diff --git a/Assets/Settings/Editor/User/URSEditorUserSettings.asset b/Assets/Settings/Editor/User/URSEditorUserSettings.asset deleted file mode 100644 index 973fd3f..0000000 --- a/Assets/Settings/Editor/User/URSEditorUserSettings.asset +++ /dev/null @@ -1,20 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!114 &11400000 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 0} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 0} - m_Name: URSEditorUserSettings - m_EditorClassIdentifier: Assembly-CSharp-Editor::URSEditorUserSettings - BuildVersionCode: 1.0.0 - CopyToStreamTargetVersion: 1.0.0 - BuildChannel: default_channel - AppId: AppId - AppToChannelRouter: - Items: [] diff --git a/Assets/URS/Animation/Editor/AnimationClipUtil.cs b/Assets/URS/Animation/Editor/AnimationClipUtil.cs index 069acdd..58c3f04 100644 --- a/Assets/URS/Animation/Editor/AnimationClipUtil.cs +++ b/Assets/URS/Animation/Editor/AnimationClipUtil.cs @@ -26,7 +26,7 @@ Hope this helps and please comment with any questions. Thanks! using UnityEditor; using System.IO; using System.Collections.Generic; -using static DG.DemiEditor.DeGUIKey; +//using static DG.DemiEditor.DeGUIKey; public class SpiteAnimationClip : ScriptableWizard { diff --git a/Assets/URS/AssetPipeline/Editor/Interface/TreeViews/AssetSearchTableItem.cs b/Assets/URS/AssetPipeline/Editor/Interface/TreeViews/AssetSearchTableItem.cs index 7c80ab9..fac6eed 100644 --- a/Assets/URS/AssetPipeline/Editor/Interface/TreeViews/AssetSearchTableItem.cs +++ b/Assets/URS/AssetPipeline/Editor/Interface/TreeViews/AssetSearchTableItem.cs @@ -101,7 +101,7 @@ public void UpdateProfileState() } enabledProcessorCount++; - if (!userData.HasProcessor(processor)) + if (!processor.IsConfigOK(userData.GetAssetImporter()) ||!userData.HasProcessor(processor)) { missingProcessors.Add($"Processor: {processor.GetName()}\nFilter: {filter.file.pattern}"); } diff --git a/Assets/URS/AssetPipeline/Editor/Interface/TreeViews/ImportProfileAssetTableItem.cs b/Assets/URS/AssetPipeline/Editor/Interface/TreeViews/ImportProfileAssetTableItem.cs index 0c6a2f7..949e1a9 100644 --- a/Assets/URS/AssetPipeline/Editor/Interface/TreeViews/ImportProfileAssetTableItem.cs +++ b/Assets/URS/AssetPipeline/Editor/Interface/TreeViews/ImportProfileAssetTableItem.cs @@ -72,7 +72,7 @@ public void UpdateProfileState() } enabledProcessorCount++; - if (!userData.HasProcessor(processor)) + if (!processor.IsConfigOK(userData.GetAssetImporter()) ||!userData.HasProcessor(processor)) { missingProcessors.Add($"Processor: {processor.GetName()}\nFilter: {filter.file.pattern}"); } diff --git a/Assets/URS/AssetPipeline/Editor/Interface/TreeViews/ImportProfileAssetTableView.cs b/Assets/URS/AssetPipeline/Editor/Interface/TreeViews/ImportProfileAssetTableView.cs index edb6156..bb0d4fe 100644 --- a/Assets/URS/AssetPipeline/Editor/Interface/TreeViews/ImportProfileAssetTableView.cs +++ b/Assets/URS/AssetPipeline/Editor/Interface/TreeViews/ImportProfileAssetTableView.cs @@ -155,6 +155,7 @@ protected override void CellGUI(Rect cellRect, int columnIndex, AssetTableItem a { var tooltip = string.Empty; GUIContent icon = null; + // Debug.LogError(" asset path "+ item.assetPath+ " item.profileState "+ item.profileState); switch (item.profileState) { case AssetProfileState.NoMatchingFilters: diff --git a/Assets/URS/AssetPipeline/Editor/PathConvention/Anchor.cs b/Assets/URS/AssetPipeline/Editor/PathConvention/Anchor.cs index 8198341..9a0ae0a 100644 --- a/Assets/URS/AssetPipeline/Editor/PathConvention/Anchor.cs +++ b/Assets/URS/AssetPipeline/Editor/PathConvention/Anchor.cs @@ -7,5 +7,6 @@ public enum Anchor End = 2, Exact = 3, AllPaths = 4, + Regex= 5, } } \ No newline at end of file diff --git a/Assets/URS/AssetPipeline/Editor/PathConvention/Template.cs b/Assets/URS/AssetPipeline/Editor/PathConvention/Template.cs index f1c120c..367115b 100644 --- a/Assets/URS/AssetPipeline/Editor/PathConvention/Template.cs +++ b/Assets/URS/AssetPipeline/Editor/PathConvention/Template.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Debug = UnityEngine.Debug; using System.Text.RegularExpressions; namespace Daihenka.AssetPipeline.NamingConvention @@ -406,6 +407,10 @@ Regex ConstructRegularExpression(string rePattern) { expression += "$"; } + if (Anchor == Anchor.Regex) + { + expression = rePattern; + } Regex compiled; try diff --git a/Assets/URS/AssetPipeline/Editor/Postprocessors/AssetImportPostprocessor.cs b/Assets/URS/AssetPipeline/Editor/Postprocessors/AssetImportPostprocessor.cs index 5fa6f8d..d46e228 100644 --- a/Assets/URS/AssetPipeline/Editor/Postprocessors/AssetImportPostprocessor.cs +++ b/Assets/URS/AssetPipeline/Editor/Postprocessors/AssetImportPostprocessor.cs @@ -35,7 +35,7 @@ static List GetProcessors(string assetPath, string[] methodNames var result = new List(s_CachedProcessors[assetPath].Count); foreach (var processor in s_CachedProcessors[assetPath]) { - if (AssetProcessor.IsForceApply(assetPath) || ((isOnDeletedAsset || !ImportProfileUserData.HasProcessor(assetPath, processor)) && processor.HasOverriddenMethods(methodNames))) + if (processor.FireOnEveryImport()|| AssetProcessor.IsForceApply(assetPath) || ((isOnDeletedAsset || !ImportProfileUserData.HasProcessor(assetPath, processor)) && processor.HasOverriddenMethods(methodNames))) { result.Add(processor); } @@ -188,6 +188,7 @@ void OnPostprocessSprites(Texture2D texture, Sprite[] sprites) void OnPostprocessTexture(Texture2D texture) { + CustomAssetImportPostprocessor.OnPostprocessTexture(assetPath, assetImporter); foreach (var processor in GetProcessors(assetPath, MethodBase.GetCurrentMethod().Name)) { processor.OnPostprocessTexture(assetPath, assetImporter as TextureImporter, texture); @@ -259,9 +260,14 @@ static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAsse AssetProcessor.SetForceApply(assetPath, false); } - foreach (var assetPath in deletedAssets) { - foreach (var processor in GetProcessors(assetPath, "OnDeletedAsset")) { - processor.OnDeletedAsset(assetPath); + foreach (var assetPath in deletedAssets) + { + if (!string.IsNullOrEmpty(assetPath)) + { + foreach (var processor in GetProcessors(assetPath, "OnDeletedAsset")) + { + processor.OnDeletedAsset(assetPath); + } } } diff --git a/Assets/URS/AssetPipeline/Editor/Postprocessors/TexturePostprocess.cs b/Assets/URS/AssetPipeline/Editor/Postprocessors/TexturePostprocess.cs new file mode 100644 index 0000000..405f1a1 --- /dev/null +++ b/Assets/URS/AssetPipeline/Editor/Postprocessors/TexturePostprocess.cs @@ -0,0 +1,193 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Text; +using Daihenka.AssetPipeline.Import; +using NinjaBeats; +using UnityEditor; +using UnityEditor.AssetImporters; +using UnityEngine; + +public class CustomAssetImportPostprocessor +{ + public const string VFXDirectoryPath = "Assets/GameResources/VFX/Texture"; + public const string VFXDirectoryPath2 = "Assets/GameResources/VFX/Scene/Texture"; + + + private static string[] Platforms = new string[] { "Android", "iOS" }; + + public static void OnPostprocessTexture(string assetPath, AssetImporter assetImporter) + { + if (assetPath == null) return; + if ((!assetPath.Contains(VFXDirectoryPath)) && (!assetPath.Contains(VFXDirectoryPath2))) return; + + var ti = assetImporter as TextureImporter; + if (ti == null) return; + + bool showWarning = false; + string message = ""; + foreach (var platform in Platforms) + { + var currentSetting = ti.GetPlatformTextureSettings(platform); + // Debug.LogError("platform.name " + platform + " tPath ? " + (tPath)); + if (currentSetting == null) + { + message += $" 没有安装{platform}的扩展 "; + showWarning = true; + } + + if (!currentSetting.overridden) + { + message += $" {platform}没有点击overrider "; + showWarning = true; + } + + if (currentSetting.overridden && currentSetting.maxTextureSize > 1024) + { + message += $" {platform}maxTextureSize 不能高于1024 "; + showWarning = true; + } + + if (currentSetting.overridden && currentSetting.format != TextureImporterFormat.ASTC_4x4 + && currentSetting.format != TextureImporterFormat.ASTC_5x5 + && currentSetting.format != TextureImporterFormat.ASTC_6x6 + && currentSetting.format != TextureImporterFormat.ASTC_8x8 + && currentSetting.format != TextureImporterFormat.ASTC_10x10 + && currentSetting.format != TextureImporterFormat.ASTC_12x12 + ) + { + message += $"{platform}format 不是astc,当前的格式是 {currentSetting.format}"; + showWarning = true; + } + } + + if (showWarning) + { + if (EditorApplication.isUpdating && EditorUtility.DisplayDialog("警告", $"特效贴图没有设置,路径{assetPath},原因 {message}", "确定")) + { + } + } + else + { + Debug.Log($"特效贴图设置OK,路径{assetPath}"); + } + } + + public delegate void CheckVFXTextureDelegate(string assetPath, string message); + + public static void CheckVFXTexture(string assetPath, CheckVFXTextureDelegate func, int preferMaxTextureSize = 1024) + { + var assetImporter = AssetImporter.GetAtPath(assetPath); + + var ti = assetImporter as TextureImporter; + + //Debug.LogError("platform.name " + tPath + " is null? " + (ti==null)); + if (ti == null) + return; + + string message = ""; + + var texture = AssetDatabase.LoadAssetAtPath(assetPath); + if (texture != null) + { + if ((texture.width & texture.width - 1) != 0 || (texture.height & texture.height - 1) != 0) + { + message += " 不是2的幂次方"; + } + } + + if (ti.isReadable) + { + message += " 不能开启Read/Write Enabled"; + } + + // if (ti.mipmapEnabled) + // { + // message += $" 不能开启mipmap"; + // } + // + // if (ti.streamingMipmaps) + // { + // message += " 不能开启mipmap串流"; + // } + + int maxTextureSize = 0; + TextureImporterFormat format = TextureImporterFormat.Automatic; + bool isFirst = true; + foreach (var platform in Platforms) + { + var currentSetting = ti.GetPlatformTextureSettings(platform); + // Debug.LogError("platform.name " + platform + " tPath ? " + (tPath)); + if (currentSetting == null) + { + message += $" 没有安装\'{platform}\'的扩展"; + } + + if (!currentSetting.overridden) + { + message += $" \'{platform}\'没有点击override"; + } + + if (currentSetting.overridden && currentSetting.maxTextureSize > preferMaxTextureSize) + { + message += $" \'{platform}\'maxTextureSize 不能高于{preferMaxTextureSize}"; + } + + if (currentSetting.overridden && currentSetting.format != TextureImporterFormat.ASTC_4x4 + && currentSetting.format != TextureImporterFormat.ASTC_5x5 + && currentSetting.format != TextureImporterFormat.ASTC_6x6 + && currentSetting.format != TextureImporterFormat.ASTC_8x8 + && currentSetting.format != TextureImporterFormat.ASTC_10x10 + && currentSetting.format != TextureImporterFormat.ASTC_12x12 + ) + { + message += $" \'{platform}\'format 不是astc ,当前的格式是 {currentSetting.format}"; + } + + if (isFirst) + { + isFirst = false; + maxTextureSize = currentSetting.maxTextureSize; + format = currentSetting.format; + } + else + { + if (maxTextureSize != currentSetting.maxTextureSize) + { + message += $" \'Android\'与\'iOS\'maxTextureSize 不一致"; + } + + if (format != currentSetting.format) + { + message += $" \'Android\'与\'iOS\'format 不一致"; + } + } + } + + func(assetPath, message); + } + + public static void CheckVFXTexture(CheckVFXTextureDelegate func) + { + var textures = AssetDatabase.FindAssets("t:Texture", new string[] { VFXDirectoryPath }); + if (textures == null) return; + //Debug.LogError("platform.name " + textures.Length); + foreach (var guid in textures) + { + var tPath = AssetDatabase.GUIDToAssetPath(guid); + CheckVFXTexture(tPath, func); + } + } + + [MenuItem("Tools/检查特效贴图设置")] + public static void CheckVFXTexture() + { + CheckVFXTexture((assetPath, message) => + { + if (!string.IsNullOrWhiteSpace(message)) + Debug.LogError($"特效贴图没有设置,路径{assetPath},原因:{message}"); + else + Debug.Log($"特效贴图设置OK,路径{assetPath}"); + }); + } +} \ No newline at end of file diff --git a/Assets/URS/Setting/Editor/Settings/ScriptableObjectSettingsProvider.cs.meta b/Assets/URS/AssetPipeline/Editor/Postprocessors/TexturePostprocess.cs.meta similarity index 83% rename from Assets/URS/Setting/Editor/Settings/ScriptableObjectSettingsProvider.cs.meta rename to Assets/URS/AssetPipeline/Editor/Postprocessors/TexturePostprocess.cs.meta index 28136c9..7976897 100644 --- a/Assets/URS/Setting/Editor/Settings/ScriptableObjectSettingsProvider.cs.meta +++ b/Assets/URS/AssetPipeline/Editor/Postprocessors/TexturePostprocess.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: c9f3529e51db83c41a2464f56cd2f310 +guid: b3a03a52035dd694a98cf194dad859f2 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/AssetPipeline/Editor/Processors/AnimCompression.cs b/Assets/URS/AssetPipeline/Editor/Processors/AnimCompression.cs index bf1540d..ee9f1be 100644 --- a/Assets/URS/AssetPipeline/Editor/Processors/AnimCompression.cs +++ b/Assets/URS/AssetPipeline/Editor/Processors/AnimCompression.cs @@ -8,20 +8,51 @@ namespace Daihenka.AssetPipeline.Processors [AssetProcessorDescription("FilterByLabel@2x", ImportAssetTypeFlag.Models)] public class AnimCompression : AssetProcessor { - [SerializeField] private ModelImporterAnimationCompression animationCompression; + [SerializeField] private ModelImporterAnimationCompression animationCompression; [SerializeField] private float animationRotationError; [SerializeField] private float animationPositionError; [SerializeField] private float animationScaleError; - + [SerializeField] private bool resampleCurve=false; + public override bool IsConfigOK (AssetImporter importer) + { + if (importer == null) return false; + var mi= importer as ModelImporter; + if (mi == null) return false; + if (!mi.importAnimation) return true; + if (mi.animationCompression != animationCompression) + { + return false; + } + if (mi.animationRotationError != animationRotationError) + { + return false; + } + if (mi.animationPositionError != animationPositionError) + { + return false; + } + if (mi.animationScaleError != animationScaleError) + { + return false; + } + if (mi.resampleCurves != resampleCurve) + { + return false; + } + return true; + } public override void OnPostprocessModel(string assetPath, ModelImporter importer, GameObject go) { - importer.animationCompression = animationCompression; - importer.animationRotationError = animationRotationError; - importer.animationPositionError = animationPositionError; - importer.animationScaleError = animationScaleError; - - ImportProfileUserData.AddOrUpdateProcessor(assetPath, this); - Debug.Log($"[{GetName()}] Preset applied for {assetPath}"); + if (importer.importAnimation&& !IsConfigOK(importer)) + { + importer.animationCompression = animationCompression; + importer.animationRotationError = animationRotationError; + importer.animationPositionError = animationPositionError; + importer.animationScaleError = animationScaleError; + importer.resampleCurves = resampleCurve; + ImportProfileUserData.AddOrUpdateProcessor(assetPath, this); + Debug.Log($"[{GetName()}] Preset applied for {assetPath}"); + } } } diff --git a/Assets/URS/AssetPipeline/Editor/Processors/ApplyPreset.cs b/Assets/URS/AssetPipeline/Editor/Processors/ApplyPreset.cs index b14ccd9..8bb716a 100644 --- a/Assets/URS/AssetPipeline/Editor/Processors/ApplyPreset.cs +++ b/Assets/URS/AssetPipeline/Editor/Processors/ApplyPreset.cs @@ -1,4 +1,5 @@ -using System.Linq; +using System; +using System.Linq; using Daihenka.AssetPipeline.Import; using UnityEditor; using UnityEditor.Presets; @@ -26,12 +27,49 @@ public override void OnPostprocess(Object asset, string assetPath) { ApplyPresetToSpriteAtlas(asset, assetPath); } + + public override void OnPostprocessTexture(string assetPath, TextureImporter importer, Texture2D tex) + { + OnPostprocessTexture(assetPath, importer); + } + + public override void OnPostprocessCubemap(string assetPath, TextureImporter importer, Cubemap texture) + { + OnPostprocessTexture(assetPath, importer); + } public override bool ShouldImport(string assetPath) { return IsForceApply(assetPath) || !ImportProfileUserData.HasProcessor(assetPath, this); } + public override bool IsConfigOK(AssetImporter importer) + { + if (importer == null || preset == null) return false; + bool isEqual= DataEquals(preset, importer); + if (isEqual) + { + return true; + } + else + { + if (importer is TextureImporter textureImporter) + { + string androidPlatform = "Android"; + string iPhonePlatform = "iPhone"; + bool isAndroidPresetOverrider = IsPresetPlatformTextureMaxSizeIsBiggerThanOrign(androidPlatform, preset, textureImporter, out var orignAndroidSetting, out var orignAndroidMaxSize,out var presetAndroidMaxSize); + bool isIPhonePresetOverrider = IsPresetPlatformTextureMaxSizeIsBiggerThanOrign(iPhonePlatform, preset, textureImporter, out var orignIPhoneSetting, out var orignIPhoneMaxSize, out var presetIPhoneMaxSize); + bool androidOk = (!isAndroidPresetOverrider) || (orignAndroidMaxSize <= presetAndroidMaxSize); + bool isIPhoneOk = (!isIPhonePresetOverrider) || (orignIPhoneMaxSize <= presetIPhoneMaxSize); + return androidOk & isIPhoneOk; + } + else + { + return true; + } + } + } + public override void OnPreprocessAsset(string assetPath, AssetImporter importer) { if (preset == null || !preset.CanBeAppliedTo(importer) || !ShouldImport(importer)) @@ -59,8 +97,24 @@ public override void OnPreprocessAsset(string assetPath, AssetImporter importer) var prevW = widthProp.intValue; var prevH = heightProp.intValue; + + string androidPlatform = "Android"; + string iPhonePlatform = "iPhone"; + bool isAndroidPresetOverrider = IsPresetPlatformTextureMaxSizeIsBiggerThanOrign(androidPlatform, preset, textureImporter, out var orignAndroidSetting, out var orignAndroidMaxSize, out var presetAndroidMaxSize); + bool isIPhonePresetOverrider = IsPresetPlatformTextureMaxSizeIsBiggerThanOrign(iPhonePlatform, preset, textureImporter, out var orignIPhoneSetting, out var orignIPhoneMaxSize, out var presetIPhoneMaxSize); preset.ApplyTo(importer); - + if (isAndroidPresetOverrider && (orignAndroidMaxSize < presetAndroidMaxSize)) + { + var currentSetting = textureImporter.GetPlatformTextureSettings(androidPlatform); + currentSetting.maxTextureSize = orignAndroidMaxSize; + textureImporter.SetPlatformTextureSettings(currentSetting); + } + if (isIPhonePresetOverrider && (orignIPhoneMaxSize < presetIPhoneMaxSize)) + { + var currentSetting = textureImporter.GetPlatformTextureSettings(iPhonePlatform); + currentSetting.maxTextureSize = orignIPhoneMaxSize; + textureImporter.SetPlatformTextureSettings(currentSetting); + } importerSo.Update(); widthProp.intValue = prevW; heightProp.intValue = prevH; @@ -113,11 +167,11 @@ void ApplyPresetToSpriteAtlas(Object asset, string assetPath) return; } - var atlas = (SpriteAtlas) asset; + var atlas = (SpriteAtlas)asset; var isVariant = atlas.isVariant; var so = new SerializedObject(atlas); var includeInBuild = so.FindProperty("m_EditorData.bindAsDefault").boolValue; - var masterAtlas = (SpriteAtlas) so.FindProperty("m_MasterAtlas").objectReferenceValue; + var masterAtlas = (SpriteAtlas)so.FindProperty("m_MasterAtlas").objectReferenceValue; var variantScale = so.FindProperty("m_EditorData.variantMultiplier").floatValue; var packables = atlas.GetPackables(); preset.ApplyTo(atlas); @@ -135,5 +189,118 @@ void ApplyPresetToSpriteAtlas(Object asset, string assetPath) Debug.Log($"[{GetName()}] Preset applied for {assetPath}"); ImportProfileUserData.AddOrUpdateProcessor(assetPath, this); } + + static bool DataEquals(Preset preset, UnityEngine.Object obj) + { + if (preset == null || obj == null) + return false; + var properties = preset.PropertyModifications; + var so = new SerializedObject(obj); + foreach (var prop in properties) + { + if (prop.propertyPath == "m_UserData" || prop.propertyPath == "m_PSDShowRemoveMatteOption") + continue; + var value = so.FindProperty(prop.propertyPath); + if (value.GetPropertyValueAsString() != prop.value) + return false; + } + + return true; + } + public bool IsPresetPlatformTextureMaxSizeIsBiggerThanOrign( + string platform, + Preset preset, + TextureImporter importer, + out TextureImporterPlatformSettings orignSetting, + out int orginTextureSize, + out int presetTetureSize) + { + var so = new SerializedObject(importer); + SerializedProperty property = so.FindProperty("m_PlatformSettings"); + string targetPresetPropertyPath = null; + bool orignHasOverride = false; + int orignMaxTextureSize = 0; + for (int i = 0; i < property.arraySize; i++) + { + SerializedProperty element = property.GetArrayElementAtIndex(i); + var buildTarget = element.FindPropertyRelative("m_BuildTarget").stringValue; + + if (buildTarget == platform) + { + targetPresetPropertyPath = element.propertyPath; + orignHasOverride = element.FindPropertyRelative("m_Overridden").boolValue; + orignMaxTextureSize = element.FindPropertyRelative("m_MaxTextureSize").intValue; + break; + } + + } + bool presetOverrider = false; + int presetMaxTextureSize = 0; + if (!string.IsNullOrEmpty(targetPresetPropertyPath)) + { + var modify = preset.PropertyModifications; + var presetOverriderPath = $"{targetPresetPropertyPath}.m_Overridden"; + var presetMaxSizePath = $"{targetPresetPropertyPath}.m_MaxTextureSize"; + foreach (var proper in modify) + { + if (proper.propertyPath == presetOverriderPath) + { + presetOverrider = (proper.value == "1"); + } + else if (proper.propertyPath == presetMaxSizePath) + { + presetMaxTextureSize = int.Parse(proper.value); + } + } + } + //Debug.LogError($"targetPresetPropertyPath {targetPresetPropertyPath} orignHasOverride {orignHasOverride} orignMaxTextureSize {orignMaxTextureSize} presetOverrider {presetOverrider} presetMaxTextureSize {presetMaxTextureSize}"); + + orginTextureSize = orignMaxTextureSize; + presetTetureSize = presetMaxTextureSize; + orignSetting = importer.GetPlatformTextureSettings(platform); + + return presetOverrider; + } + + void OnPostprocessTexture(string assetPath, TextureImporter importer) + { + if (DataEquals(preset, importer)) + return; + string androidPlatform = "Android"; + string iPhonePlatform = "iPhone"; + bool isAndroidPresetOverrider = IsPresetPlatformTextureMaxSizeIsBiggerThanOrign( + androidPlatform, + preset, + importer , + out var orignAndroidSetting, + out var orignAndroidMaxSize, + out var presetAndroidMaxSize); + bool isIPhonePresetOverrider = IsPresetPlatformTextureMaxSizeIsBiggerThanOrign( + iPhonePlatform, + preset, + importer, + out var orignIPhoneSetting, + out var orignIPhoneMaxSize, + out var presetIPhoneMaxSize); + + if (!preset.ApplyTo(importer)) + return; + if (isAndroidPresetOverrider&& (orignAndroidMaxSize{assetPath}"); + ImportProfileUserData.AddOrUpdateProcessor(assetPath, this); + } } } \ No newline at end of file diff --git a/Assets/URS/AssetPipeline/Editor/Processors/AssetProcessor.cs b/Assets/URS/AssetPipeline/Editor/Processors/AssetProcessor.cs index 79ec35d..1b18abf 100644 --- a/Assets/URS/AssetPipeline/Editor/Processors/AssetProcessor.cs +++ b/Assets/URS/AssetPipeline/Editor/Processors/AssetProcessor.cs @@ -235,6 +235,24 @@ public virtual void OnPreprocessMaterialDescription(string assetPath, AssetImpor { } + public virtual bool IsConfigOK(AssetImporter importer) + { + return true; + } + + public virtual bool FireOnEveryImport() { + + return false; + } + + public virtual void BeforeImport(string assetpath) + { + + } + public virtual void AfterImport(string assetpath) + { + + } protected string ReplaceVariables(string input, string assetPath) { if (string.IsNullOrEmpty(input)) diff --git a/Assets/URS/AssetPipeline/Editor/Processors/Inspectors/SetTextureFormatInspector.cs b/Assets/URS/AssetPipeline/Editor/Processors/Inspectors/SetTextureFormatInspector.cs index 8c65ae8..906e5bd 100644 --- a/Assets/URS/AssetPipeline/Editor/Processors/Inspectors/SetTextureFormatInspector.cs +++ b/Assets/URS/AssetPipeline/Editor/Processors/Inspectors/SetTextureFormatInspector.cs @@ -8,14 +8,17 @@ using UnityEditorInternal; using UnityEngine; using Object = UnityEngine.Object; +using NinjaBeats; +using IList = System.Collections.IList; +using NinjaBeats.ReflectionHelper; namespace Daihenka.AssetPipeline.Processors { [CustomEditor(typeof(SetTextureFormat))] internal class SetTextureFormatInspector : AssetProcessorInspector { - private static dynamic m_DummyEditor; - private dynamic m_PlatformSettings; + private static UnityEditor_TextureImporterInspector s_DummyEditor; + private static IList s_PlatformSettings; private SetTextureFormat m_Target; private readonly GUIContent GUIContent_defaultPlatform = EditorGUIUtility.TrTextContent("Default"); @@ -29,21 +32,10 @@ protected override void OnEnable() m_Target.DataToDummy(); - m_DummyEditor ??= Editor.CreateEditor(SetTextureFormat.DummyImporter, UnityEditorDynamic.Type_TextureImporterInspector); - m_PlatformSettings = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(new[] { UnityEditorDynamic.Type_BaseTextureImportPlatformSettings })); - var v = Activator.CreateInstance(UnityEditorDynamic.Type_TextureImportPlatformSettings, - UnityEditorDynamic.TextureImporterInspector.s_DefaultPlatformName, BuildTarget.StandaloneWindows, m_DummyEditor); - ((IList)m_PlatformSettings).Add((object)v); - foreach (var buildPlatform in UnityEditorDynamic.Build_BuildPlatforms.instance.GetValidPlatforms()) - { - var name = (string)UnityEditorDynamic.Reflection_BuildPlatform_name.GetValue((object)buildPlatform); - var defaultTarget = (BuildTarget)UnityEditorDynamic.Reflection_BuildPlatform_defaultTarget.GetValue((object)buildPlatform); - var vv = Activator.CreateInstance(UnityEditorDynamic.Type_TextureImportPlatformSettings, name, defaultTarget, m_DummyEditor); - ((IList)m_PlatformSettings).Add((object)vv); - } - - if (m_DummyEditor != null) - UnityEditorDynamic.Reflection_TextureImporterInspector_OnEnable.Invoke((object)m_DummyEditor, Array.Empty()); + s_DummyEditor.__self__ ??= Editor.CreateEditor(SetTextureFormat.DummyImporter, UnityEditor_TextureImporterInspector.__type__); + s_PlatformSettings ??= (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(new[] { UnityEditor_BaseTextureImportPlatformSettings.__type__ })); + + s_DummyEditor.OnEnable(); } protected void OnDisable() @@ -51,8 +43,7 @@ protected void OnDisable() if (m_Target == null) return; - if (m_DummyEditor != null) - UnityEditorDynamic.Reflection_TextureImporterInspector_OnDisable.Invoke((object)m_DummyEditor, Array.Empty()); + s_DummyEditor.OnDisable(); m_Target = null; } @@ -65,25 +56,37 @@ public override void OnInspectorGUI() serializedObject.Update(); DrawBaseProperties(); serializedObject.ApplyModifiedProperties(); - - UnityEditorDynamic.BaseTextureImportPlatformSettings.InitPlatformSettings(m_PlatformSettings); - GUILayout.Space(10f); - int selected = (int)UnityEditorDynamic.EditorGUILayout.BeginPlatformGrouping(UnityEditorDynamic.BaseTextureImportPlatformSettings.GetBuildPlayerValidPlatforms(), GUIContent_defaultPlatform, UnityEditorDynamic.EditorStyles.frameBox, (Func) (idx => + + s_PlatformSettings.Clear(); + s_PlatformSettings.AddRange(s_DummyEditor.m_PlatformSettings); + var m_PlatformSettingsArrProp = s_DummyEditor.m_PlatformSettingsArrProp; + UnityEditor_BaseTextureImportPlatformSettings.InitPlatformSettings(s_PlatformSettings); + foreach (var v in s_PlatformSettings) { - var setting = ((IList)this.m_PlatformSettings)[idx + 1]; - var model = (dynamic)UnityEditorDynamic.Reflection_TextureImportPlatformSettings_model.GetValue(setting); - var isDefault = (bool)(UnityEditorDynamic.Reflection_TextureImportPlatformSettingsData_isDefault.GetValue(model)); - var overriddenIsDifferent = (bool)(UnityEditorDynamic.Reflection_TextureImportPlatformSettingsData_overriddenIsDifferent.GetValue(model)); - var allAreOverridden = (bool)(UnityEditorDynamic.Reflection_TextureImportPlatformSettingsData_allAreOverridden.GetValue(model)); - return !isDefault && (overriddenIsDifferent || allAreOverridden); - })); + var settings = new UnityEditor_TextureImportPlatformSettings(v); + settings.CacheSerializedProperties(m_PlatformSettingsArrProp); + } + GUILayout.Space(10f); + int selected = UnityEditor_EditorGUILayout.BeginPlatformGrouping( + UnityEditor_BaseTextureImportPlatformSettings.GetBuildPlayerValidPlatforms(), + GUIContent_defaultPlatform, + UnityEditor_EditorStyles.frameBox, (Func)(idx => + { + UnityEditor_TextureImportPlatformSettings setting = new(s_PlatformSettings[idx + 1]); + var model = setting.model; + var isDefault = model.isDefault; + var overriddenIsDifferent = model.overriddenIsDifferent; + var allAreOverridden = model.allAreOverridden; + return !isDefault && (overriddenIsDifferent || allAreOverridden); + })); using (EditorGUI.ChangeCheckScope changeCheckScope = new EditorGUI.ChangeCheckScope()) { - UnityEditorDynamic.BaseTextureImportPlatformSettings.ShowPlatformSpecificSettings(m_PlatformSettings, selected); + UnityEditor_BaseTextureImportPlatformSettings.ShowPlatformSpecificSettings(s_PlatformSettings, + selected); if (changeCheckScope.changed) { Undo.RegisterCompleteObjectUndo(new UnityEngine.Object[] { this.m_Target, SetTextureFormat.DummyImporter }, "Inspector"); - UnityEditorDynamic.BaseTextureImportPlatformSettings.ApplyPlatformSettings(m_PlatformSettings); + UnityEditor_BaseTextureImportPlatformSettings.ApplyPlatformSettings(s_PlatformSettings); m_Target.DataFromDummy(); } diff --git a/Assets/URS/AssetPipeline/Editor/Processors/Inspectors/SetTextureMipmapsInspector.cs b/Assets/URS/AssetPipeline/Editor/Processors/Inspectors/SetTextureMipmapsInspector.cs new file mode 100644 index 0000000..558b8a0 --- /dev/null +++ b/Assets/URS/AssetPipeline/Editor/Processors/Inspectors/SetTextureMipmapsInspector.cs @@ -0,0 +1,26 @@ +using Daihenka.AssetPipeline.Import; +using UnityEditor; + +namespace Daihenka.AssetPipeline.Processors +{ + [CustomEditor(typeof(SetTextureMipmaps))] + internal class SetTextureMipmapsInspector : AssetProcessorInspector + { + SerializedProperty m_EnableMipmaps; + + protected override void OnEnable() + { + base.OnEnable(); + m_EnableMipmaps = serializedObject.FindProperty(nameof(SetTextureMipmaps.enableMipmaps)); + } + + public override void OnInspectorGUI() + { + serializedObject.Update(); + DrawBaseProperties(); + EditorGUILayout.PropertyField(m_EnableMipmaps); + serializedObject.ApplyModifiedProperties(); + + } + } +} \ No newline at end of file diff --git a/Assets/URS/Setting/Editor/Settings/SettingsEditor.cs.meta b/Assets/URS/AssetPipeline/Editor/Processors/Inspectors/SetTextureMipmapsInspector.cs.meta similarity index 83% rename from Assets/URS/Setting/Editor/Settings/SettingsEditor.cs.meta rename to Assets/URS/AssetPipeline/Editor/Processors/Inspectors/SetTextureMipmapsInspector.cs.meta index 6076edf..d4a59e5 100644 --- a/Assets/URS/Setting/Editor/Settings/SettingsEditor.cs.meta +++ b/Assets/URS/AssetPipeline/Editor/Processors/Inspectors/SetTextureMipmapsInspector.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 323be3a3194cab8458983cde8d8d4b21 +guid: 4cf0f85ddfaf8b043bcec9738e859e34 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/AssetPipeline/Editor/Processors/SetTextureFormat.cs b/Assets/URS/AssetPipeline/Editor/Processors/SetTextureFormat.cs index c229b74..c714c95 100644 --- a/Assets/URS/AssetPipeline/Editor/Processors/SetTextureFormat.cs +++ b/Assets/URS/AssetPipeline/Editor/Processors/SetTextureFormat.cs @@ -2,9 +2,11 @@ using System.Collections.Generic; using System.Linq; using Daihenka.AssetPipeline.Import; +using NinjaBeats; using UnityEditor; using UnityEditor.Build; using UnityEngine; +using NinjaBeats.ReflectionHelper; namespace Daihenka.AssetPipeline.Processors { @@ -20,14 +22,18 @@ public void DataToDummy() if (DummyImporter == null) return; - foreach (var platform in UnityEditorDynamic.Build_BuildPlatforms.instance.GetValidPlatforms()) + foreach (var _platform in UnityEditor_Build_BuildPlatforms.instance.GetValidPlatforms()) { - var platformName = (string)UnityEditorDynamic.Reflection_BuildPlatform_name.GetValue((object)platform); + var platform = new UnityEditor_Build_BuildPlatform(_platform); + var platformName = platform.name; var setting = m_SettingList?.Find(x => x.name == platformName); - if (setting != null) - DummyImporter.SetPlatformTextureSettings(setting); - else - DummyImporter.ClearPlatformTextureSettings(platformName); + if (setting == null) + { + setting = new TextureImporterPlatformSettings(); + setting.name = platformName; + setting.overridden = false; + } + DummyImporter.SetPlatformTextureSettings(setting); } } @@ -39,31 +45,110 @@ public void DataFromDummy() m_SettingList ??= new(); m_SettingList.Clear(); - foreach (var platform in UnityEditorDynamic.Build_BuildPlatforms.instance.GetValidPlatforms()) + foreach (var _platform in UnityEditor_Build_BuildPlatforms.instance.GetValidPlatforms()) { - var platformName = (string)UnityEditorDynamic.Reflection_BuildPlatform_name.GetValue((object)platform); + var platform = new UnityEditor_Build_BuildPlatform(_platform); + var platformName = platform.name; var setting = DummyImporter.GetPlatformTextureSettings(platformName); if (setting != null) m_SettingList.Add(setting); } + + EditorUtility.SetDirty(this); + } + + public override bool IsConfigOK(AssetImporter importer) + { + if (importer == null) return false; + var ti = importer as TextureImporter; + if (ti==null) return false; + if (m_SettingList == null || m_SettingList.Count == 0) return true; + + for (int i = 0; i < m_SettingList.Count; i++) + { + var myConfig= m_SettingList[i]; + var currentSetting = ti.GetPlatformTextureSettings(myConfig.name); + if (currentSetting == null) + { + + return false; + } + if (myConfig.overridden != currentSetting.overridden) { + return false; + } + if (myConfig.maxTextureSize < currentSetting.maxTextureSize) + { + return false; + } + if (myConfig.resizeAlgorithm != currentSetting.resizeAlgorithm) + { + return false; + } + if (myConfig.format != currentSetting.format) + { + return false; + } + if (myConfig.textureCompression != currentSetting.textureCompression) + { + return false; + } + if (myConfig.compressionQuality != currentSetting.compressionQuality) + { + return false; + } + if (myConfig.crunchedCompression != currentSetting.crunchedCompression) + { + return false; + } + if (myConfig.allowsAlphaSplitting != currentSetting.allowsAlphaSplitting) + { + return false; + } + if (myConfig.androidETC2FallbackOverride != currentSetting.androidETC2FallbackOverride) + { + return false; + } + } + return true; } - public override void OnPostprocessTexture(string assetPath, TextureImporter importer, Texture2D tex) + void OnPostprocessTexture(string assetPath, TextureImporter importer) { if (m_SettingList != null) { - foreach (var platform in UnityEditorDynamic.Build_BuildPlatforms.instance.GetValidPlatforms()) + foreach (var _platform in UnityEditor_Build_BuildPlatforms.instance.GetValidPlatforms()) { - var platformName = (string)UnityEditorDynamic.Reflection_BuildPlatform_name.GetValue((object)platform); + var platform = new UnityEditor_Build_BuildPlatform(_platform); + var platformName = platform.name; var setting = m_SettingList.Find(x => x.name == platformName); - if (setting != null) + if (setting != null) + { + var orignSetting = importer.GetPlatformTextureSettings(platformName); importer.SetPlatformTextureSettings(setting); + if (orignSetting.overridden&& orignSetting.maxTextureSize< setting.maxTextureSize) + { + var currentSetting= importer.GetPlatformTextureSettings(platformName); + currentSetting.maxTextureSize = orignSetting.maxTextureSize; + importer.SetPlatformTextureSettings(currentSetting); + } + } + } } ImportProfileUserData.AddOrUpdateProcessor(assetPath, this); Debug.Log($"[{GetName()}] Preset applied for {assetPath}"); } + + public override void OnPostprocessTexture(string assetPath, TextureImporter importer, Texture2D tex) + { + OnPostprocessTexture(assetPath, importer); + } + + public override void OnPostprocessCubemap(string assetPath, TextureImporter importer, Cubemap texture) + { + OnPostprocessTexture(assetPath, importer); + } } } \ No newline at end of file diff --git a/Assets/URS/AssetPipeline/Editor/Processors/SetTextureMipmaps.cs b/Assets/URS/AssetPipeline/Editor/Processors/SetTextureMipmaps.cs new file mode 100644 index 0000000..c196c04 --- /dev/null +++ b/Assets/URS/AssetPipeline/Editor/Processors/SetTextureMipmaps.cs @@ -0,0 +1,45 @@ +using Daihenka.AssetPipeline.Import; +using UnityEditor; +using UnityEngine; + +namespace Daihenka.AssetPipeline.Processors +{ + [AssetProcessorDescription("FilterByLabel@2x", ImportAssetTypeFlag.Textures)] + public class SetTextureMipmaps : AssetProcessor + { + [SerializeField] public bool enableMipmaps; + + public override bool IsConfigOK(AssetImporter importer) + { + if (importer == null) return false; + var ti = importer as TextureImporter; + if (ti == null) return false; + + if (ti.mipmapEnabled != enableMipmaps || ti.streamingMipmaps != enableMipmaps) + return false; + return true; + } + + void OnPostprocessTexture(string assetPath, TextureImporter importer) + { + if (importer.mipmapEnabled == enableMipmaps && importer.streamingMipmaps == enableMipmaps) + return; + + importer.mipmapEnabled = enableMipmaps; + importer.streamingMipmaps = enableMipmaps; + + ImportProfileUserData.AddOrUpdateProcessor(assetPath, this); + Debug.Log($"[{GetName()}] Preset applied for {assetPath}"); + } + + public override void OnPostprocessTexture(string assetPath, TextureImporter importer, Texture2D tex) + { + OnPostprocessTexture(assetPath, importer); + } + + public override void OnPostprocessCubemap(string assetPath, TextureImporter importer, Cubemap texture) + { + OnPostprocessTexture(assetPath, importer); + } + } +} \ No newline at end of file diff --git a/Assets/URS/Setting/Editor/Settings/SettingsExtensions.cs.meta b/Assets/URS/AssetPipeline/Editor/Processors/SetTextureMipmaps.cs.meta similarity index 83% rename from Assets/URS/Setting/Editor/Settings/SettingsExtensions.cs.meta rename to Assets/URS/AssetPipeline/Editor/Processors/SetTextureMipmaps.cs.meta index e64b4d5..a61f54b 100644 --- a/Assets/URS/Setting/Editor/Settings/SettingsExtensions.cs.meta +++ b/Assets/URS/AssetPipeline/Editor/Processors/SetTextureMipmaps.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: a46514642dffa76419c41cb7f63b2134 +guid: c610b5c40b622d448a1aecd79243a513 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/AssetPipeline/Editor/Profiles/Import/AssetFilter.cs b/Assets/URS/AssetPipeline/Editor/Profiles/Import/AssetFilter.cs index 68c5d23..75b3f11 100644 --- a/Assets/URS/AssetPipeline/Editor/Profiles/Import/AssetFilter.cs +++ b/Assets/URS/AssetPipeline/Editor/Profiles/Import/AssetFilter.cs @@ -26,7 +26,7 @@ public bool IsMatch(string assetPath, bool mustBeEnabled = true) var isValidFileExtension = assetType.IsValidFileExtension(assetPath, otherAssetExtensions); var isNotExcluded = IsValidSubPath(dirname) && !IsExcludedFile(filename); var isFileValid = file.IsValid && file.IsMatch(filename); - + // Debug.LogError("assetPath "+ assetPath+" isEnabled " + isEnabled+ " isValidFileExtension "+ isValidFileExtension+ " isNotExcluded "+ isNotExcluded+ " isFileValid "+ isFileValid); return isEnabled && isValidFileExtension && isNotExcluded && isFileValid; } diff --git a/Assets/URS/AssetPipeline/Editor/Profiles/Import/ImportProfileUserData.cs b/Assets/URS/AssetPipeline/Editor/Profiles/Import/ImportProfileUserData.cs index 59ee414..151f24f 100644 --- a/Assets/URS/AssetPipeline/Editor/Profiles/Import/ImportProfileUserData.cs +++ b/Assets/URS/AssetPipeline/Editor/Profiles/Import/ImportProfileUserData.cs @@ -75,6 +75,7 @@ public ImportProfileUserData(string assetPath) ParseUserData(); } + public AssetImporter GetAssetImporter() { return m_Importer; } void ParseUserData() { GetImporterJson(); diff --git a/Assets/URS/AssetPipeline/Editor/Reflection/UnityEditorDynamic.cs b/Assets/URS/AssetPipeline/Editor/Reflection/UnityEditorDynamic.cs index 3178390..c175545 100644 --- a/Assets/URS/AssetPipeline/Editor/Reflection/UnityEditorDynamic.cs +++ b/Assets/URS/AssetPipeline/Editor/Reflection/UnityEditorDynamic.cs @@ -9,50 +9,11 @@ internal static class UnityEditorDynamic { public static readonly Assembly UnityEditorAssembly; public static readonly dynamic EditorGUIUtility; - public static readonly dynamic EditorGUILayout; - public static readonly dynamic EditorStyles; - public static readonly dynamic Build_BuildPlatforms; - public static readonly Type Type_TextureImporterInspector; - public static readonly dynamic TextureImporterInspector; - public static readonly Type Type_TextureImportPlatformSettings; - public static readonly dynamic TextureImportPlatformSettings; - public static readonly Type Type_TextureImportPlatformSettingsData; - public static readonly Type Type_BaseTextureImportPlatformSettings; - public static readonly dynamic BaseTextureImportPlatformSettings; - public static FieldInfo Reflection_Editor_m_Targets; - public static MethodInfo Reflection_TextureImporterInspector_OnEnable; - public static MethodInfo Reflection_TextureImporterInspector_OnDisable; - public static FieldInfo Reflection_BuildPlatform_name; - public static FieldInfo Reflection_BuildPlatform_defaultTarget; - public static PropertyInfo Reflection_TextureImportPlatformSettings_model; - - public static PropertyInfo Reflection_TextureImportPlatformSettingsData_isDefault; - public static PropertyInfo Reflection_TextureImportPlatformSettingsData_overriddenIsDifferent; - public static PropertyInfo Reflection_TextureImportPlatformSettingsData_allAreOverridden; - + static UnityEditorDynamic() { UnityEditorAssembly = typeof(Editor).Assembly; EditorGUIUtility = typeof(EditorGUIUtility).AsDynamicType(); - EditorGUILayout = typeof(EditorGUILayout).AsDynamicType(); - EditorStyles = typeof(EditorStyles).AsDynamicType(); - Build_BuildPlatforms = typeof(UnityEditor.Build.BuildPlayerProcessor).Assembly?.GetType("UnityEditor.Build.BuildPlatforms").AsDynamicType(); - Type_TextureImporterInspector = UnityEditorAssembly.GetType("UnityEditor.TextureImporterInspector"); - TextureImporterInspector = Type_TextureImporterInspector.AsDynamicType(); - Type_TextureImportPlatformSettings = UnityEditorAssembly.GetType("UnityEditor.TextureImportPlatformSettings"); - TextureImportPlatformSettings = Type_TextureImportPlatformSettings.AsDynamicType(); - Type_TextureImportPlatformSettingsData = UnityEditorAssembly.GetType("UnityEditor.TextureImportPlatformSettingsData"); - Type_BaseTextureImportPlatformSettings = UnityEditorAssembly.GetType("UnityEditor.BaseTextureImportPlatformSettings"); - BaseTextureImportPlatformSettings = Type_BaseTextureImportPlatformSettings.AsDynamicType(); - Reflection_Editor_m_Targets = typeof(Editor).GetField("m_Targets", (BindingFlags)(-1)); - Reflection_TextureImporterInspector_OnEnable = Type_TextureImporterInspector.GetMethod("OnEnable", (BindingFlags)(-1)); - Reflection_TextureImporterInspector_OnDisable = Type_TextureImporterInspector.GetMethod("OnDisable", (BindingFlags)(-1)); - Reflection_BuildPlatform_name = typeof(UnityEditor.Build.BuildPlayerProcessor).Assembly.GetType("UnityEditor.Build.BuildPlatform").GetField("name", (BindingFlags)(-1)); - Reflection_BuildPlatform_defaultTarget = typeof(UnityEditor.Build.BuildPlayerProcessor).Assembly.GetType("UnityEditor.Build.BuildPlatform").GetField("defaultTarget", (BindingFlags)(-1)); - Reflection_TextureImportPlatformSettings_model = Type_TextureImportPlatformSettings.GetProperty("model", (BindingFlags)(-1)); - Reflection_TextureImportPlatformSettingsData_isDefault = Type_TextureImportPlatformSettingsData.GetProperty("isDefault", (BindingFlags)(-1)); - Reflection_TextureImportPlatformSettingsData_overriddenIsDifferent = Type_TextureImportPlatformSettingsData.GetProperty("overriddenIsDifferent", (BindingFlags)(-1)); - Reflection_TextureImportPlatformSettingsData_allAreOverridden = Type_TextureImportPlatformSettingsData.GetProperty("allAreOverridden", (BindingFlags)(-1)); } } diff --git a/Assets/URS/AssetPipeline/Editor/Utility/AssetImportPipeline.cs b/Assets/URS/AssetPipeline/Editor/Utility/AssetImportPipeline.cs index 9326753..e90b91f 100644 --- a/Assets/URS/AssetPipeline/Editor/Utility/AssetImportPipeline.cs +++ b/Assets/URS/AssetPipeline/Editor/Utility/AssetImportPipeline.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.IO; using System.Linq; using Daihenka.AssetPipeline.Import; @@ -28,7 +29,7 @@ public static class AssetImportPipeline {ImportAssetType.Other, (Texture2D) UnityEditorDynamic.EditorGUIUtility.FindTextureByType(typeof(TextAsset))}, }; - internal static string GetAssetType(string assetPath) + public static string GetAssetType(string assetPath) { var extension = Path.GetExtension(assetPath).ToLowerInvariant(); switch (extension) @@ -346,7 +347,7 @@ static void OnUpdate() } } - [MenuItem("Assets/Asset Pipeline/Force Apply Processors")] + [MenuItem("Assets/资产管理工具(Asset Pipeline)/Force Apply Processors")] static void ForceApplyProcessors() { foreach (var obj in Selection.objects) @@ -357,7 +358,7 @@ static void ForceApplyProcessors() } } - [MenuItem("Assets/Asset Pipeline/Force Apply Processors", true)] + [MenuItem("Assets/资产管理工具(Asset Pipeline)/Force Apply Processors", true)] static bool ValidateForceApplyProcessors() { return Selection.objects.Length > 0; @@ -388,5 +389,96 @@ public static List GetProcessorsForAsset(string assetPath) return processors; } + + static bool ApplyAssets(string assetPath) + { + bool result = false; + foreach (var profile in AssetImportProfile.AllProfiles) + { + if (!profile || !profile.enabled) + continue; + if (!profile.IsMatch(assetPath)) + continue; + + foreach (var filter in profile.assetFilters) + { + if (!filter || !filter.enabled) + continue; + if (!filter.IsMatch(assetPath)) + continue; + var userData = new ImportProfileUserData(assetPath); + foreach (var processor in filter.assetProcessors) + { + if (!processor || !processor.enabled) + continue; + if (!processor.IsConfigOK(userData.GetAssetImporter()) || !userData.HasProcessor(processor)|| processor.FireOnEveryImport()) + { + AssetProcessor.SetForceApply(assetPath, true); + processor.BeforeImport(assetPath); + AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); + processor.AfterImport(assetPath); + AssetProcessor.SetForceApply(assetPath, false); + result = true; + } + } + } + } + return result; + } + + [MenuItem("Tools/资产管理工具(Asset Pipeline)/一键处理资产")] + static void DealWithAsset() + { + try + { + AssetImportProfile.InvalidateCachedProfiles(); + var paths = AssetDatabase.GetAllAssetPaths(); + var profiles = AssetImportProfile.AllProfiles; + var length = profiles.Length; + + for (int index=0; index < paths.Length;index++) + { + var assetPath = paths[index]; + EditorUtility.DisplayProgressBar("一键处理资产", assetPath, (float)(index + 1) / (float)paths.Length); + if (!assetPath.StartsWith("Assets/GameResources") && !assetPath.StartsWith("Assets/Scenes")) { + continue; + } + for (int i = 0; i < profiles.Length; i++) + { + var profile = profiles[i]; + if (!profile || !profile.enabled) + continue; + if (!profile.IsMatch(assetPath)) + continue; + + foreach (var filter in profile.assetFilters) + { + if (!filter || !filter.enabled) + continue; + if (!filter.IsMatch(assetPath)) + continue; + var userData = new ImportProfileUserData(assetPath); + foreach (var processor in filter.assetProcessors) + { + if (!processor || !processor.enabled) + continue; + if (!processor.IsConfigOK(userData.GetAssetImporter()) || !userData.HasProcessor(processor) || processor.FireOnEveryImport()) + { + AssetProcessor.SetForceApply(assetPath, true); + processor.BeforeImport(assetPath); + AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); + processor.AfterImport(assetPath); + AssetProcessor.SetForceApply(assetPath, false); + } + } + } + } + } + } + finally + { + EditorUtility.ClearProgressBar(); + } + } } } \ No newline at end of file diff --git a/Assets/URS/AssetPipeline/Editor/Utility/SerializedPropertyUtility.cs b/Assets/URS/AssetPipeline/Editor/Utility/SerializedPropertyUtility.cs index d0d1868..78db819 100644 --- a/Assets/URS/AssetPipeline/Editor/Utility/SerializedPropertyUtility.cs +++ b/Assets/URS/AssetPipeline/Editor/Utility/SerializedPropertyUtility.cs @@ -150,7 +150,7 @@ internal static object GetPropertyValue(this SerializedProperty prop) case SerializedPropertyType.Rect: return prop.rectValue; case SerializedPropertyType.ArraySize: - return prop.arraySize; + return prop.intValue; case SerializedPropertyType.Character: return (char) prop.intValue; case SerializedPropertyType.AnimationCurve: diff --git a/Assets/URS/AssetPipeline/Editor/Windows/AssetSearchWindow.cs b/Assets/URS/AssetPipeline/Editor/Windows/AssetSearchWindow.cs index 51127bf..e36ab6e 100644 --- a/Assets/URS/AssetPipeline/Editor/Windows/AssetSearchWindow.cs +++ b/Assets/URS/AssetPipeline/Editor/Windows/AssetSearchWindow.cs @@ -7,7 +7,7 @@ namespace Daihenka.AssetPipeline { internal class AssetSearchWindow : EditorWindow { - [MenuItem("Tools/Asset Pipeline/Asset Search")] + [MenuItem("Tools/资产管理工具(Asset Pipeline)/Asset Search")] static void ShowWindow() { GetWindow("Asset Search", typeof(ImportProfilesWindow)).Show(); diff --git a/Assets/URS/AssetPipeline/Editor/Windows/ImportProfileWindow.cs b/Assets/URS/AssetPipeline/Editor/Windows/ImportProfileWindow.cs index 05f08de..ff58962 100644 --- a/Assets/URS/AssetPipeline/Editor/Windows/ImportProfileWindow.cs +++ b/Assets/URS/AssetPipeline/Editor/Windows/ImportProfileWindow.cs @@ -263,28 +263,35 @@ Rect DrawFilterRow(Rect r, AssetFilter assetFilter, AssetFilter aboveFilter, Ass if (assetFilter.showOptions) { - EditorGUI.DrawRect(new Rect(r.x, rect.y - 5, r.width, EditorGUIUtility.singleLineHeight + 8), ColorPalette.BackgroundLight); - EditorGUI.DrawRect(new Rect(r.x, rect.y + EditorGUIUtility.singleLineHeight + 8, r.width, 1), ColorPalette.DarkLineColor); - EditorGUI.LabelField(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), "Filter Options", DaiGUIStyles.boldLabel); - rect.y += EditorGUIUtility.singleLineHeight + 2; - rowHeight += EditorGUIUtility.singleLineHeight + 2; - - filterSo.Update(); - var fileExclusionsList = GetCachedFileExclusionsList(assetFilter); - var fileExclusionsListHeight = fileExclusionsList.GetHeight(); - EditorGUI.DrawRect(new Rect(r.x, rect.y - 3, r.width, fileExclusionsListHeight + 6), ColorPalette.BackgroundLight); - fileExclusionsList.DoList(new Rect(rect.x, rect.y, rect.width - 10, fileExclusionsListHeight)); - rect.y += fileExclusionsListHeight + 6; - rowHeight += fileExclusionsListHeight + 6; - filterSo.ApplyModifiedProperties(); - - var subPathsList = GetCachedSubPathsList(assetFilter); - var subPathsListHeight = subPathsList.GetHeight(); - EditorGUI.DrawRect(new Rect(r.x, rect.y - 3, r.width, subPathsListHeight + 6), ColorPalette.BackgroundLight); - EditorGUI.DrawRect(new Rect(r.x, rect.y + subPathsListHeight + 3, r.width, 1), ColorPalette.DarkLineColor); - subPathsList.DoList(new Rect(rect.x, rect.y, rect.width - 10, subPathsListHeight)); - rect.y += subPathsListHeight + 6; - rowHeight += subPathsListHeight + 6; + using (var check = new EditorGUI.ChangeCheckScope()) + { + + EditorGUI.DrawRect(new Rect(r.x, rect.y - 5, r.width, EditorGUIUtility.singleLineHeight + 8), ColorPalette.BackgroundLight); + EditorGUI.DrawRect(new Rect(r.x, rect.y + EditorGUIUtility.singleLineHeight + 8, r.width, 1), ColorPalette.DarkLineColor); + EditorGUI.LabelField(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), "Filter Options", DaiGUIStyles.boldLabel); + rect.y += EditorGUIUtility.singleLineHeight + 2; + rowHeight += EditorGUIUtility.singleLineHeight + 2; + + filterSo.Update(); + var fileExclusionsList = GetCachedFileExclusionsList(assetFilter); + var fileExclusionsListHeight = fileExclusionsList.GetHeight(); + EditorGUI.DrawRect(new Rect(r.x, rect.y - 3, r.width, fileExclusionsListHeight + 6), ColorPalette.BackgroundLight); + fileExclusionsList.DoList(new Rect(rect.x, rect.y, rect.width - 10, fileExclusionsListHeight)); + rect.y += fileExclusionsListHeight + 6; + rowHeight += fileExclusionsListHeight + 6; + filterSo.ApplyModifiedProperties(); + + var subPathsList = GetCachedSubPathsList(assetFilter); + var subPathsListHeight = subPathsList.GetHeight(); + EditorGUI.DrawRect(new Rect(r.x, rect.y - 3, r.width, subPathsListHeight + 6), ColorPalette.BackgroundLight); + EditorGUI.DrawRect(new Rect(r.x, rect.y + subPathsListHeight + 3, r.width, 1), ColorPalette.DarkLineColor); + subPathsList.DoList(new Rect(rect.x, rect.y, rect.width - 10, subPathsListHeight)); + rect.y += subPathsListHeight + 6; + rowHeight += subPathsListHeight + 6; + + if (check.changed) + EditorUtility.SetDirty(assetFilter); + } } EditorGUI.LabelField(rect, "Processors", DaiGUIStyles.boldLabel); diff --git a/Assets/URS/AssetPipeline/Editor/Windows/ImportProfilesWindow.cs b/Assets/URS/AssetPipeline/Editor/Windows/ImportProfilesWindow.cs index dce906b..ef61f83 100644 --- a/Assets/URS/AssetPipeline/Editor/Windows/ImportProfilesWindow.cs +++ b/Assets/URS/AssetPipeline/Editor/Windows/ImportProfilesWindow.cs @@ -32,7 +32,7 @@ static ImportProfilesWindow Window ImportProfileTableView m_TreeView; readonly HashSet m_WaitForAssetDeletion = new HashSet(); - [MenuItem("Tools/Asset Pipeline/Import Profiles")] + [MenuItem("Tools/资产管理工具(Asset Pipeline)/Import Profiles")] public static void ShowWindow() { if (!s_Window) diff --git a/Assets/URS/AssetPipeline/Editor/com.daihenka.assetpipeline.editor.asmdef b/Assets/URS/AssetPipeline/Editor/com.daihenka.assetpipeline.editor.asmdef index c871e2c..4414186 100644 --- a/Assets/URS/AssetPipeline/Editor/com.daihenka.assetpipeline.editor.asmdef +++ b/Assets/URS/AssetPipeline/Editor/com.daihenka.assetpipeline.editor.asmdef @@ -1,9 +1,11 @@ { "name": "com.daihenka.assetpipeline.editor", + "rootNamespace": "", "references": [ "GUID:c5af582b9939f4e4292be3495c687a04", "GUID:343deaaf83e0cee4ca978e7df0b80d21", - "GUID:2bafac87e7f4b9b418d9448d219b01ab" + "GUID:2bafac87e7f4b9b418d9448d219b01ab", + "GUID:81c4d37d6b16ed2428ad2691b45fb45a" ], "includePlatforms": [ "Editor" diff --git a/Assets/URS/Best HTTP/Examples/HTTP/AssetBundleSample.cs b/Assets/URS/Best HTTP/Examples/HTTP/AssetBundleSample.cs index a66289c..c9ac1bf 100644 --- a/Assets/URS/Best HTTP/Examples/HTTP/AssetBundleSample.cs +++ b/Assets/URS/Best HTTP/Examples/HTTP/AssetBundleSample.cs @@ -162,6 +162,7 @@ IEnumerator DownloadAssetBundle() break; } + this.request = null; this._downloadButton.enabled = true; } diff --git a/Assets/URS/Best HTTP/Examples/SampleSelector.unity b/Assets/URS/Best HTTP/Examples/SampleSelector.unity index b31a281..0f16fa0 100644 --- a/Assets/URS/Best HTTP/Examples/SampleSelector.unity +++ b/Assets/URS/Best HTTP/Examples/SampleSelector.unity @@ -54,7 +54,7 @@ LightmapSettings: m_EnableBakedLightmaps: 1 m_EnableRealtimeLightmaps: 1 m_LightmapEditorSettings: - serializedVersion: 10 + serializedVersion: 12 m_Resolution: 2 m_BakeResolution: 40 m_AtlasSize: 1024 @@ -62,6 +62,7 @@ LightmapSettings: m_AOMaxDistance: 1 m_CompAOExponent: 1 m_CompAOExponentDirect: 0 + m_ExtractAmbientOcclusion: 0 m_Padding: 2 m_LightmapParameters: {fileID: 0} m_LightmapsBakeMode: 1 @@ -76,10 +77,16 @@ LightmapSettings: m_PVRDirectSampleCount: 32 m_PVRSampleCount: 512 m_PVRBounces: 2 + m_PVREnvironmentSampleCount: 512 + m_PVREnvironmentReferencePointCount: 2048 + m_PVRFilteringMode: 2 + m_PVRDenoiserTypeDirect: 0 + m_PVRDenoiserTypeIndirect: 0 + m_PVRDenoiserTypeAO: 0 m_PVRFilterTypeDirect: 0 m_PVRFilterTypeIndirect: 0 m_PVRFilterTypeAO: 0 - m_PVRFilteringMode: 1 + m_PVREnvironmentMIS: 0 m_PVRCulling: 1 m_PVRFilteringGaussRadiusDirect: 1 m_PVRFilteringGaussRadiusIndirect: 5 @@ -87,7 +94,9 @@ LightmapSettings: m_PVRFilteringAtrousPositionSigmaDirect: 0.5 m_PVRFilteringAtrousPositionSigmaIndirect: 2 m_PVRFilteringAtrousPositionSigmaAO: 1 - m_ShowResolutionOverlay: 1 + m_ExportTrainingData: 0 + m_TrainingDataDestination: TrainingData + m_LightProbeSampleCountMultiplier: 4 m_LightingDataAsset: {fileID: 0} m_UseShadowmask: 1 --- !u!196 &4 @@ -158,17 +167,16 @@ MonoBehaviour: m_GameObject: {fileID: 92191008} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 0.5} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 14 @@ -225,9 +233,9 @@ RectTransform: m_Father: {fileID: 1791343486} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_AnchorMin: {x: 0, y: 1} - m_AnchorMax: {x: 0, y: 1} - m_AnchoredPosition: {x: 209.875, y: -33.25} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 209.875, y: 0} m_SizeDelta: {x: 409.75, y: 0} m_Pivot: {x: 0.5, y: 0.5} --- !u!114 &99079546 @@ -239,7 +247,7 @@ MonoBehaviour: m_GameObject: {fileID: 99079544} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1741964061, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 3245ec927659c4140ac4f8d17403cc18, type: 3} m_Name: m_EditorClassIdentifier: m_HorizontalFit: 0 @@ -253,7 +261,7 @@ MonoBehaviour: m_GameObject: {fileID: 99079544} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -405508275, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 30649d3a9faa99c48a7b1166b86bf2a0, type: 3} m_Name: m_EditorClassIdentifier: m_Padding: @@ -267,6 +275,8 @@ MonoBehaviour: m_ChildForceExpandHeight: 0 m_ChildControlWidth: 1 m_ChildControlHeight: 1 + m_ChildScaleWidth: 0 + m_ChildScaleHeight: 0 --- !u!1 &109104420 GameObject: m_ObjectHideFlags: 0 @@ -313,17 +323,16 @@ MonoBehaviour: m_GameObject: {fileID: 109104420} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 14 @@ -392,17 +401,16 @@ MonoBehaviour: m_GameObject: {fileID: 123556534} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 @@ -412,6 +420,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &123556537 CanvasRenderer: m_ObjectHideFlags: 0 @@ -466,17 +475,16 @@ MonoBehaviour: m_GameObject: {fileID: 180224809} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0, g: 0, b: 0, a: 1} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 14 @@ -535,9 +543,9 @@ RectTransform: m_Father: {fileID: 989819535} m_RootOrder: 2 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_AnchorMin: {x: 0, y: 1} - m_AnchorMax: {x: 0, y: 1} - m_AnchoredPosition: {x: 62.75, y: -27.5} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 62.75, y: 0} m_SizeDelta: {x: 125.5, y: 0} m_Pivot: {x: 0.5, y: 0.5} --- !u!114 &268882191 @@ -549,7 +557,7 @@ MonoBehaviour: m_GameObject: {fileID: 268882189} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1297475563, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Script: {fileID: 11500000, guid: 59f8146938fff824cb5fd77236b75775, type: 3} m_Name: m_EditorClassIdentifier: m_Padding: @@ -563,6 +571,8 @@ MonoBehaviour: m_ChildForceExpandHeight: 0 m_ChildControlWidth: 1 m_ChildControlHeight: 1 + m_ChildScaleWidth: 0 + m_ChildScaleHeight: 0 --- !u!114 &268882192 MonoBehaviour: m_ObjectHideFlags: 0 @@ -572,7 +582,7 @@ MonoBehaviour: m_GameObject: {fileID: 268882189} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1741964061, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Script: {fileID: 11500000, guid: 3245ec927659c4140ac4f8d17403cc18, type: 3} m_Name: m_EditorClassIdentifier: m_HorizontalFit: 0 @@ -586,7 +596,7 @@ MonoBehaviour: m_GameObject: {fileID: 268882189} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1392445389, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Script: {fileID: 11500000, guid: 4e29b1a8efbd4b44bb3f3716e73f07ff, type: 3} m_Name: m_EditorClassIdentifier: m_Navigation: @@ -600,25 +610,26 @@ MonoBehaviour: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} + m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} m_ColorMultiplier: 1 m_FadeDuration: 0.1 m_SpriteState: m_HighlightedSprite: {fileID: 0} m_PressedSprite: {fileID: 0} + m_SelectedSprite: {fileID: 0} m_DisabledSprite: {fileID: 0} m_AnimationTriggers: m_NormalTrigger: Normal m_HighlightedTrigger: Highlighted m_PressedTrigger: Pressed + m_SelectedTrigger: Highlighted m_DisabledTrigger: Disabled m_Interactable: 1 m_TargetGraphic: {fileID: 0} m_OnClick: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.Button+ButtonClickedEvent, UnityEngine.UI, Version=1.0.0.0, - Culture=neutral, PublicKeyToken=null --- !u!222 &268882194 CanvasRenderer: m_ObjectHideFlags: 0 @@ -680,8 +691,8 @@ RectTransform: m_Father: {fileID: 673663373} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_AnchorMin: {x: 0, y: 1} - m_AnchorMax: {x: 0, y: 1} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} m_AnchoredPosition: {x: 609.875, y: 0} m_SizeDelta: {x: 380.25, y: 0} m_Pivot: {x: 0.5, y: 1} @@ -709,7 +720,7 @@ MonoBehaviour: m_GameObject: {fileID: 274715337} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1741964061, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 3245ec927659c4140ac4f8d17403cc18, type: 3} m_Name: m_EditorClassIdentifier: m_HorizontalFit: 0 @@ -723,7 +734,7 @@ MonoBehaviour: m_GameObject: {fileID: 274715337} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1297475563, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 59f8146938fff824cb5fd77236b75775, type: 3} m_Name: m_EditorClassIdentifier: m_Padding: @@ -737,6 +748,8 @@ MonoBehaviour: m_ChildForceExpandHeight: 1 m_ChildControlWidth: 1 m_ChildControlHeight: 1 + m_ChildScaleWidth: 0 + m_ChildScaleHeight: 0 --- !u!114 &274715342 MonoBehaviour: m_ObjectHideFlags: 0 @@ -746,17 +759,16 @@ MonoBehaviour: m_GameObject: {fileID: 274715337} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 0.39215687} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 @@ -766,6 +778,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &274715343 CanvasRenderer: m_ObjectHideFlags: 0 @@ -820,17 +833,16 @@ MonoBehaviour: m_GameObject: {fileID: 281814071} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 @@ -840,6 +852,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &281814074 CanvasRenderer: m_ObjectHideFlags: 0 @@ -894,17 +907,16 @@ MonoBehaviour: m_GameObject: {fileID: 286163886} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0, g: 0.08965492, b: 1, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 10 @@ -973,17 +985,16 @@ MonoBehaviour: m_GameObject: {fileID: 361562339} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 9 @@ -1052,17 +1063,16 @@ MonoBehaviour: m_GameObject: {fileID: 394847335} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 14 @@ -1121,9 +1131,9 @@ RectTransform: m_Father: {fileID: 989819535} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_AnchorMin: {x: 0, y: 1} - m_AnchorMax: {x: 0, y: 1} - m_AnchoredPosition: {x: 62.75, y: -16.5} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 62.75, y: 0} m_SizeDelta: {x: 125.5, y: 0} m_Pivot: {x: 0.5, y: 0.5} --- !u!114 &441052175 @@ -1135,7 +1145,7 @@ MonoBehaviour: m_GameObject: {fileID: 441052173} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1297475563, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Script: {fileID: 11500000, guid: 59f8146938fff824cb5fd77236b75775, type: 3} m_Name: m_EditorClassIdentifier: m_Padding: @@ -1149,6 +1159,8 @@ MonoBehaviour: m_ChildForceExpandHeight: 0 m_ChildControlWidth: 1 m_ChildControlHeight: 1 + m_ChildScaleWidth: 0 + m_ChildScaleHeight: 0 --- !u!114 &441052176 MonoBehaviour: m_ObjectHideFlags: 0 @@ -1158,7 +1170,7 @@ MonoBehaviour: m_GameObject: {fileID: 441052173} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1741964061, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Script: {fileID: 11500000, guid: 3245ec927659c4140ac4f8d17403cc18, type: 3} m_Name: m_EditorClassIdentifier: m_HorizontalFit: 0 @@ -1172,7 +1184,7 @@ MonoBehaviour: m_GameObject: {fileID: 441052173} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1392445389, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Script: {fileID: 11500000, guid: 4e29b1a8efbd4b44bb3f3716e73f07ff, type: 3} m_Name: m_EditorClassIdentifier: m_Navigation: @@ -1186,25 +1198,26 @@ MonoBehaviour: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} + m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} m_ColorMultiplier: 1 m_FadeDuration: 0.1 m_SpriteState: m_HighlightedSprite: {fileID: 0} m_PressedSprite: {fileID: 0} + m_SelectedSprite: {fileID: 0} m_DisabledSprite: {fileID: 0} m_AnimationTriggers: m_NormalTrigger: Normal m_HighlightedTrigger: Highlighted m_PressedTrigger: Pressed + m_SelectedTrigger: Highlighted m_DisabledTrigger: Disabled m_Interactable: 1 m_TargetGraphic: {fileID: 0} m_OnClick: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.Button+ButtonClickedEvent, UnityEngine.UI, Version=1.0.0.0, - Culture=neutral, PublicKeyToken=null --- !u!222 &441052178 CanvasRenderer: m_ObjectHideFlags: 0 @@ -1273,17 +1286,16 @@ MonoBehaviour: m_GameObject: {fileID: 474993161} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 14 @@ -1352,17 +1364,16 @@ MonoBehaviour: m_GameObject: {fileID: 518778556} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 0} m_Type: 0 m_PreserveAspect: 0 @@ -1372,6 +1383,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &518778559 CanvasRenderer: m_ObjectHideFlags: 0 @@ -1427,17 +1439,16 @@ MonoBehaviour: m_GameObject: {fileID: 526013463} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 12 @@ -1469,7 +1480,7 @@ MonoBehaviour: m_GameObject: {fileID: 526013463} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1679637790, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 306cc8c2b49d7114eaa3623786fc2126, type: 3} m_Name: m_EditorClassIdentifier: m_IgnoreLayout: 0 @@ -1522,9 +1533,9 @@ RectTransform: m_Father: {fileID: 1125716479} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_AnchorMin: {x: 0, y: 1} - m_AnchorMax: {x: 0, y: 1} - m_AnchoredPosition: {x: 400, y: -20} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 400, y: 0} m_SizeDelta: {x: 800, y: 0} m_Pivot: {x: 0.5, y: 0.5} --- !u!114 &566278119 @@ -1536,17 +1547,16 @@ MonoBehaviour: m_GameObject: {fileID: 566278117} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 0.39215687} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 @@ -1556,6 +1566,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &566278120 CanvasRenderer: m_ObjectHideFlags: 0 @@ -1573,7 +1584,7 @@ MonoBehaviour: m_GameObject: {fileID: 566278117} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1679637790, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 306cc8c2b49d7114eaa3623786fc2126, type: 3} m_Name: m_EditorClassIdentifier: m_IgnoreLayout: 0 @@ -1593,7 +1604,7 @@ MonoBehaviour: m_GameObject: {fileID: 566278117} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -405508275, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 30649d3a9faa99c48a7b1166b86bf2a0, type: 3} m_Name: m_EditorClassIdentifier: m_Padding: @@ -1607,6 +1618,8 @@ MonoBehaviour: m_ChildForceExpandHeight: 1 m_ChildControlWidth: 1 m_ChildControlHeight: 0 + m_ChildScaleWidth: 0 + m_ChildScaleHeight: 0 --- !u!114 &566278123 MonoBehaviour: m_ObjectHideFlags: 0 @@ -1616,7 +1629,7 @@ MonoBehaviour: m_GameObject: {fileID: 566278117} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1741964061, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 3245ec927659c4140ac4f8d17403cc18, type: 3} m_Name: m_EditorClassIdentifier: m_HorizontalFit: 0 @@ -1667,17 +1680,16 @@ MonoBehaviour: m_GameObject: {fileID: 614976412} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 14 @@ -1729,9 +1741,10 @@ Camera: m_ClearFlags: 2 m_BackGroundColor: {r: 0.5943396, g: 0.4121917, b: 0.3448291, a: 0} m_projectionMatrixMode: 1 + m_GateFitMode: 2 + m_FOVAxisMode: 0 m_SensorSize: {x: 36, y: 24} m_LensShift: {x: 0, y: 0} - m_GateFitMode: 2 m_FocalLength: 50 m_NormalizedViewPortRect: serializedVersion: 2 @@ -1808,9 +1821,9 @@ RectTransform: m_Father: {fileID: 1125716479} m_RootOrder: 1 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} - m_AnchorMin: {x: 0, y: 1} - m_AnchorMax: {x: 0, y: 1} - m_AnchoredPosition: {x: 400, y: -40} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 400, y: 0} m_SizeDelta: {x: 800, y: 0} m_Pivot: {x: 0.5, y: 1} --- !u!114 &673663374 @@ -1822,7 +1835,7 @@ MonoBehaviour: m_GameObject: {fileID: 673663372} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1679637790, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 306cc8c2b49d7114eaa3623786fc2126, type: 3} m_Name: m_EditorClassIdentifier: m_IgnoreLayout: 0 @@ -1842,7 +1855,7 @@ MonoBehaviour: m_GameObject: {fileID: 673663372} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1741964061, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 3245ec927659c4140ac4f8d17403cc18, type: 3} m_Name: m_EditorClassIdentifier: m_HorizontalFit: 0 @@ -1856,7 +1869,7 @@ MonoBehaviour: m_GameObject: {fileID: 673663372} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -405508275, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 30649d3a9faa99c48a7b1166b86bf2a0, type: 3} m_Name: m_EditorClassIdentifier: m_Padding: @@ -1870,6 +1883,8 @@ MonoBehaviour: m_ChildForceExpandHeight: 1 m_ChildControlWidth: 1 m_ChildControlHeight: 1 + m_ChildScaleWidth: 0 + m_ChildScaleHeight: 0 --- !u!1 &675661191 GameObject: m_ObjectHideFlags: 0 @@ -1916,7 +1931,7 @@ MonoBehaviour: m_GameObject: {fileID: 675661191} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1741964061, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 3245ec927659c4140ac4f8d17403cc18, type: 3} m_Name: m_EditorClassIdentifier: m_HorizontalFit: 0 @@ -1930,7 +1945,7 @@ MonoBehaviour: m_GameObject: {fileID: 675661191} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1297475563, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 59f8146938fff824cb5fd77236b75775, type: 3} m_Name: m_EditorClassIdentifier: m_Padding: @@ -1944,6 +1959,8 @@ MonoBehaviour: m_ChildForceExpandHeight: 1 m_ChildControlWidth: 1 m_ChildControlHeight: 0 + m_ChildScaleWidth: 0 + m_ChildScaleHeight: 0 --- !u!1 &681609604 GameObject: m_ObjectHideFlags: 0 @@ -1993,7 +2010,7 @@ MonoBehaviour: m_GameObject: {fileID: 681609604} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1367256648, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 1aa08ab6e0800fa44ae55d278d1423e3, type: 3} m_Name: m_EditorClassIdentifier: m_Content: {fileID: 1998443256} @@ -2014,8 +2031,6 @@ MonoBehaviour: m_OnValueChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.ScrollRect+ScrollRectEvent, UnityEngine.UI, Version=1.0.0.0, - Culture=neutral, PublicKeyToken=null --- !u!114 &681609607 MonoBehaviour: m_ObjectHideFlags: 0 @@ -2025,17 +2040,16 @@ MonoBehaviour: m_GameObject: {fileID: 681609604} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 @@ -2045,6 +2059,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &681609608 CanvasRenderer: m_ObjectHideFlags: 0 @@ -2099,17 +2114,16 @@ MonoBehaviour: m_GameObject: {fileID: 786810448} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 14 @@ -2178,17 +2192,16 @@ MonoBehaviour: m_GameObject: {fileID: 817140412} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 14 @@ -2259,7 +2272,7 @@ MonoBehaviour: m_GameObject: {fileID: 819822691} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1741964061, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 3245ec927659c4140ac4f8d17403cc18, type: 3} m_Name: m_EditorClassIdentifier: m_HorizontalFit: 0 @@ -2273,7 +2286,7 @@ MonoBehaviour: m_GameObject: {fileID: 819822691} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -405508275, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 30649d3a9faa99c48a7b1166b86bf2a0, type: 3} m_Name: m_EditorClassIdentifier: m_Padding: @@ -2287,6 +2300,8 @@ MonoBehaviour: m_ChildForceExpandHeight: 0 m_ChildControlWidth: 1 m_ChildControlHeight: 1 + m_ChildScaleWidth: 0 + m_ChildScaleHeight: 0 --- !u!1 &826516844 GameObject: m_ObjectHideFlags: 0 @@ -2369,17 +2384,16 @@ MonoBehaviour: m_GameObject: {fileID: 836020846} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 14 @@ -2453,7 +2467,7 @@ MonoBehaviour: m_GameObject: {fileID: 893967394} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1741964061, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 3245ec927659c4140ac4f8d17403cc18, type: 3} m_Name: m_EditorClassIdentifier: m_HorizontalFit: 0 @@ -2467,7 +2481,7 @@ MonoBehaviour: m_GameObject: {fileID: 893967394} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1297475563, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 59f8146938fff824cb5fd77236b75775, type: 3} m_Name: m_EditorClassIdentifier: m_Padding: @@ -2481,6 +2495,8 @@ MonoBehaviour: m_ChildForceExpandHeight: 0 m_ChildControlWidth: 1 m_ChildControlHeight: 1 + m_ChildScaleWidth: 0 + m_ChildScaleHeight: 0 --- !u!114 &893967398 MonoBehaviour: m_ObjectHideFlags: 0 @@ -2490,7 +2506,7 @@ MonoBehaviour: m_GameObject: {fileID: 893967394} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1392445389, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 4e29b1a8efbd4b44bb3f3716e73f07ff, type: 3} m_Name: m_EditorClassIdentifier: m_Navigation: @@ -2504,17 +2520,20 @@ MonoBehaviour: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} + m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} m_ColorMultiplier: 1 m_FadeDuration: 0.1 m_SpriteState: m_HighlightedSprite: {fileID: 0} m_PressedSprite: {fileID: 0} + m_SelectedSprite: {fileID: 0} m_DisabledSprite: {fileID: 0} m_AnimationTriggers: m_NormalTrigger: Normal m_HighlightedTrigger: Highlighted m_PressedTrigger: Pressed + m_SelectedTrigger: Highlighted m_DisabledTrigger: Disabled m_Interactable: 1 m_TargetGraphic: {fileID: 893967399} @@ -2532,8 +2551,6 @@ MonoBehaviour: m_StringArgument: m_BoolArgument: 0 m_CallState: 2 - m_TypeName: UnityEngine.UI.Button+ButtonClickedEvent, UnityEngine.UI, Version=1.0.0.0, - Culture=neutral, PublicKeyToken=null --- !u!114 &893967399 MonoBehaviour: m_ObjectHideFlags: 0 @@ -2543,17 +2560,16 @@ MonoBehaviour: m_GameObject: {fileID: 893967394} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 @@ -2563,6 +2579,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &893967400 CanvasRenderer: m_ObjectHideFlags: 0 @@ -2580,7 +2597,7 @@ MonoBehaviour: m_GameObject: {fileID: 893967394} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1679637790, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Script: {fileID: 11500000, guid: 306cc8c2b49d7114eaa3623786fc2126, type: 3} m_Name: m_EditorClassIdentifier: m_IgnoreLayout: 0 @@ -2637,17 +2654,16 @@ MonoBehaviour: m_GameObject: {fileID: 974336252} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 @@ -2657,6 +2673,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &974336255 CanvasRenderer: m_ObjectHideFlags: 0 @@ -2711,17 +2728,16 @@ MonoBehaviour: m_GameObject: {fileID: 977577634} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 14 @@ -2795,7 +2811,7 @@ MonoBehaviour: m_GameObject: {fileID: 985743122} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1679637790, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 306cc8c2b49d7114eaa3623786fc2126, type: 3} m_Name: m_EditorClassIdentifier: m_IgnoreLayout: 0 @@ -2815,17 +2831,16 @@ MonoBehaviour: m_GameObject: {fileID: 985743122} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 0.392} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 @@ -2835,6 +2850,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &985743126 CanvasRenderer: m_ObjectHideFlags: 0 @@ -2852,7 +2868,7 @@ MonoBehaviour: m_GameObject: {fileID: 985743122} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1367256648, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 1aa08ab6e0800fa44ae55d278d1423e3, type: 3} m_Name: m_EditorClassIdentifier: m_Content: {fileID: 675661192} @@ -2873,8 +2889,6 @@ MonoBehaviour: m_OnValueChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.ScrollRect+ScrollRectEvent, UnityEngine.UI, Version=1.0.0.0, - Culture=neutral, PublicKeyToken=null --- !u!1 &989819534 GameObject: m_ObjectHideFlags: 0 @@ -2924,7 +2938,7 @@ MonoBehaviour: m_GameObject: {fileID: 989819534} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1741964061, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Script: {fileID: 11500000, guid: 3245ec927659c4140ac4f8d17403cc18, type: 3} m_Name: m_EditorClassIdentifier: m_HorizontalFit: 2 @@ -2938,7 +2952,7 @@ MonoBehaviour: m_GameObject: {fileID: 989819534} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1297475563, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Script: {fileID: 11500000, guid: 59f8146938fff824cb5fd77236b75775, type: 3} m_Name: m_EditorClassIdentifier: m_Padding: @@ -2952,6 +2966,8 @@ MonoBehaviour: m_ChildForceExpandHeight: 0 m_ChildControlWidth: 1 m_ChildControlHeight: 1 + m_ChildScaleWidth: 0 + m_ChildScaleHeight: 0 --- !u!1 &1065300029 GameObject: m_ObjectHideFlags: 0 @@ -2998,17 +3014,16 @@ MonoBehaviour: m_GameObject: {fileID: 1065300029} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 14 @@ -3094,7 +3109,7 @@ MonoBehaviour: m_GameObject: {fileID: 1125716475} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1297475563, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 59f8146938fff824cb5fd77236b75775, type: 3} m_Name: m_EditorClassIdentifier: m_Padding: @@ -3108,6 +3123,8 @@ MonoBehaviour: m_ChildForceExpandHeight: 0 m_ChildControlWidth: 1 m_ChildControlHeight: 1 + m_ChildScaleWidth: 0 + m_ChildScaleHeight: 0 --- !u!223 &1125716478 Canvas: m_ObjectHideFlags: 0 @@ -3160,7 +3177,7 @@ MonoBehaviour: m_GameObject: {fileID: 1125716475} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1301386320, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: dc42784cf147c0c48a680349fa168899, type: 3} m_Name: m_EditorClassIdentifier: m_IgnoreReversedGraphics: 1 @@ -3177,7 +3194,7 @@ MonoBehaviour: m_GameObject: {fileID: 1125716475} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1980459831, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 0cd44c1031e13a943bb63640046fad76, type: 3} m_Name: m_EditorClassIdentifier: m_UiScaleMode: 1 @@ -3238,17 +3255,16 @@ MonoBehaviour: m_GameObject: {fileID: 1163983579} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10917, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 @@ -3258,6 +3274,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &1163983582 CanvasRenderer: m_ObjectHideFlags: 0 @@ -3275,7 +3292,7 @@ MonoBehaviour: m_GameObject: {fileID: 1163983579} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -1200242548, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 31a19414c41e5ae4aae2af33fee712f6, type: 3} m_Name: m_EditorClassIdentifier: m_ShowMaskGraphic: 0 @@ -3327,17 +3344,16 @@ MonoBehaviour: m_GameObject: {fileID: 1222947056} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 0.392} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 @@ -3347,6 +3363,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &1222947059 CanvasRenderer: m_ObjectHideFlags: 0 @@ -3364,7 +3381,7 @@ MonoBehaviour: m_GameObject: {fileID: 1222947056} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1679637790, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 306cc8c2b49d7114eaa3623786fc2126, type: 3} m_Name: m_EditorClassIdentifier: m_IgnoreLayout: 0 @@ -3384,7 +3401,7 @@ MonoBehaviour: m_GameObject: {fileID: 1222947056} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1297475563, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 59f8146938fff824cb5fd77236b75775, type: 3} m_Name: m_EditorClassIdentifier: m_Padding: @@ -3398,6 +3415,8 @@ MonoBehaviour: m_ChildForceExpandHeight: 0 m_ChildControlWidth: 1 m_ChildControlHeight: 1 + m_ChildScaleWidth: 0 + m_ChildScaleHeight: 0 --- !u!1 &1237646588 GameObject: m_ObjectHideFlags: 0 @@ -3446,7 +3465,7 @@ MonoBehaviour: m_GameObject: {fileID: 1237646588} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -2061169968, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 2a4db7a114972834c8e4117be1d82ba3, type: 3} m_Name: m_EditorClassIdentifier: m_Navigation: @@ -3460,17 +3479,20 @@ MonoBehaviour: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} + m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} m_ColorMultiplier: 1 m_FadeDuration: 0.1 m_SpriteState: m_HighlightedSprite: {fileID: 0} m_PressedSprite: {fileID: 0} + m_SelectedSprite: {fileID: 0} m_DisabledSprite: {fileID: 0} m_AnimationTriggers: m_NormalTrigger: Normal m_HighlightedTrigger: Highlighted m_PressedTrigger: Pressed + m_SelectedTrigger: Highlighted m_DisabledTrigger: Disabled m_Interactable: 1 m_TargetGraphic: {fileID: 974336254} @@ -3482,8 +3504,6 @@ MonoBehaviour: m_OnValueChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.Scrollbar+ScrollEvent, UnityEngine.UI, Version=1.0.0.0, - Culture=neutral, PublicKeyToken=null --- !u!114 &1237646591 MonoBehaviour: m_ObjectHideFlags: 0 @@ -3493,17 +3513,16 @@ MonoBehaviour: m_GameObject: {fileID: 1237646588} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 @@ -3513,6 +3532,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &1237646592 CanvasRenderer: m_ObjectHideFlags: 0 @@ -3567,17 +3587,16 @@ MonoBehaviour: m_GameObject: {fileID: 1246318029} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 14 @@ -3650,7 +3669,7 @@ MonoBehaviour: m_GameObject: {fileID: 1248407390} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 575553740, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: d199490a83bb2b844b9695cbf13b01ef, type: 3} m_Name: m_EditorClassIdentifier: m_Navigation: @@ -3664,17 +3683,20 @@ MonoBehaviour: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} + m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} m_ColorMultiplier: 1 m_FadeDuration: 0.1 m_SpriteState: m_HighlightedSprite: {fileID: 0} m_PressedSprite: {fileID: 0} + m_SelectedSprite: {fileID: 0} m_DisabledSprite: {fileID: 0} m_AnimationTriggers: m_NormalTrigger: Normal m_HighlightedTrigger: Highlighted m_PressedTrigger: Pressed + m_SelectedTrigger: Highlighted m_DisabledTrigger: Disabled m_Interactable: 1 m_TargetGraphic: {fileID: 1248407393} @@ -3702,13 +3724,9 @@ MonoBehaviour: m_StringArgument: m_BoolArgument: 0 m_CallState: 2 - m_TypeName: UnityEngine.UI.InputField+SubmitEvent, UnityEngine.UI, Version=1.0.0.0, - Culture=neutral, PublicKeyToken=null m_OnValueChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.InputField+OnChangeEvent, UnityEngine.UI, Version=1.0.0.0, - Culture=neutral, PublicKeyToken=null m_CaretColor: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_CustomCaretColor: 0 m_SelectionColor: {r: 0.65882355, g: 0.80784315, b: 1, a: 0.7529412} @@ -3725,17 +3743,16 @@ MonoBehaviour: m_GameObject: {fileID: 1248407390} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10911, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 @@ -3745,6 +3762,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &1248407394 CanvasRenderer: m_ObjectHideFlags: 0 @@ -3762,7 +3780,7 @@ MonoBehaviour: m_GameObject: {fileID: 1248407390} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1679637790, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 306cc8c2b49d7114eaa3623786fc2126, type: 3} m_Name: m_EditorClassIdentifier: m_IgnoreLayout: 0 @@ -3880,7 +3898,7 @@ MonoBehaviour: m_GameObject: {fileID: 1287029237} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1679637790, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 306cc8c2b49d7114eaa3623786fc2126, type: 3} m_Name: m_EditorClassIdentifier: m_IgnoreLayout: 0 @@ -3900,7 +3918,7 @@ MonoBehaviour: m_GameObject: {fileID: 1287029237} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -405508275, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 30649d3a9faa99c48a7b1166b86bf2a0, type: 3} m_Name: m_EditorClassIdentifier: m_Padding: @@ -3914,6 +3932,8 @@ MonoBehaviour: m_ChildForceExpandHeight: 1 m_ChildControlWidth: 1 m_ChildControlHeight: 1 + m_ChildScaleWidth: 0 + m_ChildScaleHeight: 0 --- !u!114 &1287029242 MonoBehaviour: m_ObjectHideFlags: 0 @@ -3923,17 +3943,16 @@ MonoBehaviour: m_GameObject: {fileID: 1287029237} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 0.392} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 @@ -3943,6 +3962,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &1287029243 CanvasRenderer: m_ObjectHideFlags: 0 @@ -3997,17 +4017,16 @@ MonoBehaviour: m_GameObject: {fileID: 1453990608} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 10 @@ -4078,7 +4097,7 @@ MonoBehaviour: m_GameObject: {fileID: 1476244621} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1741964061, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 3245ec927659c4140ac4f8d17403cc18, type: 3} m_Name: m_EditorClassIdentifier: m_HorizontalFit: 0 @@ -4092,7 +4111,7 @@ MonoBehaviour: m_GameObject: {fileID: 1476244621} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -405508275, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 30649d3a9faa99c48a7b1166b86bf2a0, type: 3} m_Name: m_EditorClassIdentifier: m_Padding: @@ -4106,6 +4125,8 @@ MonoBehaviour: m_ChildForceExpandHeight: 0 m_ChildControlWidth: 1 m_ChildControlHeight: 1 + m_ChildScaleWidth: 0 + m_ChildScaleHeight: 0 --- !u!1 &1501798572 GameObject: m_ObjectHideFlags: 0 @@ -4133,7 +4154,7 @@ MonoBehaviour: m_GameObject: {fileID: 1501798572} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1077351063, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 4f231c4fb786f3946a6b90b886c48677, type: 3} m_Name: m_EditorClassIdentifier: m_HorizontalAxis: Horizontal @@ -4152,7 +4173,7 @@ MonoBehaviour: m_GameObject: {fileID: 1501798572} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -619905303, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 76c392e42b5098c458856cdf6ecaaaa1, type: 3} m_Name: m_EditorClassIdentifier: m_FirstSelected: {fileID: 0} @@ -4220,7 +4241,7 @@ MonoBehaviour: m_GameObject: {fileID: 1510314135} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -2061169968, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 2a4db7a114972834c8e4117be1d82ba3, type: 3} m_Name: m_EditorClassIdentifier: m_Navigation: @@ -4234,17 +4255,20 @@ MonoBehaviour: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} + m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} m_ColorMultiplier: 1 m_FadeDuration: 0.1 m_SpriteState: m_HighlightedSprite: {fileID: 0} m_PressedSprite: {fileID: 0} + m_SelectedSprite: {fileID: 0} m_DisabledSprite: {fileID: 0} m_AnimationTriggers: m_NormalTrigger: Normal m_HighlightedTrigger: Highlighted m_PressedTrigger: Pressed + m_SelectedTrigger: Highlighted m_DisabledTrigger: Disabled m_Interactable: 1 m_TargetGraphic: {fileID: 123556536} @@ -4256,8 +4280,6 @@ MonoBehaviour: m_OnValueChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.Scrollbar+ScrollEvent, UnityEngine.UI, Version=1.0.0.0, - Culture=neutral, PublicKeyToken=null --- !u!114 &1510314138 MonoBehaviour: m_ObjectHideFlags: 0 @@ -4267,17 +4289,16 @@ MonoBehaviour: m_GameObject: {fileID: 1510314135} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 @@ -4287,6 +4308,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &1510314139 CanvasRenderer: m_ObjectHideFlags: 0 @@ -4341,17 +4363,16 @@ MonoBehaviour: m_GameObject: {fileID: 1517813666} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 14 @@ -4424,7 +4445,7 @@ MonoBehaviour: m_GameObject: {fileID: 1602849058} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1297475563, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Script: {fileID: 11500000, guid: 59f8146938fff824cb5fd77236b75775, type: 3} m_Name: m_EditorClassIdentifier: m_Padding: @@ -4438,6 +4459,8 @@ MonoBehaviour: m_ChildForceExpandHeight: 0 m_ChildControlWidth: 1 m_ChildControlHeight: 1 + m_ChildScaleWidth: 0 + m_ChildScaleHeight: 0 --- !u!114 &1602849061 MonoBehaviour: m_ObjectHideFlags: 0 @@ -4447,7 +4470,7 @@ MonoBehaviour: m_GameObject: {fileID: 1602849058} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1741964061, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Script: {fileID: 11500000, guid: 3245ec927659c4140ac4f8d17403cc18, type: 3} m_Name: m_EditorClassIdentifier: m_HorizontalFit: 0 @@ -4461,7 +4484,7 @@ MonoBehaviour: m_GameObject: {fileID: 1602849058} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1392445389, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Script: {fileID: 11500000, guid: 4e29b1a8efbd4b44bb3f3716e73f07ff, type: 3} m_Name: m_EditorClassIdentifier: m_Navigation: @@ -4475,25 +4498,26 @@ MonoBehaviour: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} + m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} m_ColorMultiplier: 1 m_FadeDuration: 0.1 m_SpriteState: m_HighlightedSprite: {fileID: 0} m_PressedSprite: {fileID: 0} + m_SelectedSprite: {fileID: 0} m_DisabledSprite: {fileID: 0} m_AnimationTriggers: m_NormalTrigger: Normal m_HighlightedTrigger: Highlighted m_PressedTrigger: Pressed + m_SelectedTrigger: Highlighted m_DisabledTrigger: Disabled m_Interactable: 1 m_TargetGraphic: {fileID: 0} m_OnClick: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.Button+ButtonClickedEvent, UnityEngine.UI, Version=1.0.0.0, - Culture=neutral, PublicKeyToken=null --- !u!222 &1602849063 CanvasRenderer: m_ObjectHideFlags: 0 @@ -4567,7 +4591,7 @@ MonoBehaviour: m_GameObject: {fileID: 1720255537} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1679637790, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 306cc8c2b49d7114eaa3623786fc2126, type: 3} m_Name: m_EditorClassIdentifier: m_IgnoreLayout: 0 @@ -4587,7 +4611,7 @@ MonoBehaviour: m_GameObject: {fileID: 1720255537} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 853051423, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 0d0b652f32a2cc243917e4028fa0f046, type: 3} m_Name: m_EditorClassIdentifier: m_Navigation: @@ -4601,17 +4625,20 @@ MonoBehaviour: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} + m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} m_ColorMultiplier: 1 m_FadeDuration: 0.1 m_SpriteState: m_HighlightedSprite: {fileID: 0} m_PressedSprite: {fileID: 0} + m_SelectedSprite: {fileID: 0} m_DisabledSprite: {fileID: 0} m_AnimationTriggers: m_NormalTrigger: Normal m_HighlightedTrigger: Highlighted m_PressedTrigger: Pressed + m_SelectedTrigger: Highlighted m_DisabledTrigger: Disabled m_Interactable: 1 m_TargetGraphic: {fileID: 1720255541} @@ -4649,8 +4676,7 @@ MonoBehaviour: m_StringArgument: m_BoolArgument: 0 m_CallState: 2 - m_TypeName: UnityEngine.UI.Dropdown+DropdownEvent, UnityEngine.UI, Version=1.0.0.0, - Culture=neutral, PublicKeyToken=null + m_AlphaFadeSpeed: 0.15 --- !u!114 &1720255541 MonoBehaviour: m_ObjectHideFlags: 0 @@ -4660,17 +4686,16 @@ MonoBehaviour: m_GameObject: {fileID: 1720255537} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 @@ -4680,6 +4705,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &1720255542 CanvasRenderer: m_ObjectHideFlags: 0 @@ -4736,17 +4762,16 @@ MonoBehaviour: m_GameObject: {fileID: 1778320393} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10917, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 @@ -4756,6 +4781,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &1778320396 CanvasRenderer: m_ObjectHideFlags: 0 @@ -4773,7 +4799,7 @@ MonoBehaviour: m_GameObject: {fileID: 1778320393} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -1200242548, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 31a19414c41e5ae4aae2af33fee712f6, type: 3} m_Name: m_EditorClassIdentifier: m_ShowMaskGraphic: 0 @@ -4853,7 +4879,7 @@ MonoBehaviour: m_GameObject: {fileID: 1791343485} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1741964061, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 3245ec927659c4140ac4f8d17403cc18, type: 3} m_Name: m_EditorClassIdentifier: m_HorizontalFit: 0 @@ -4867,7 +4893,7 @@ MonoBehaviour: m_GameObject: {fileID: 1791343485} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1297475563, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 59f8146938fff824cb5fd77236b75775, type: 3} m_Name: m_EditorClassIdentifier: m_Padding: @@ -4881,6 +4907,8 @@ MonoBehaviour: m_ChildForceExpandHeight: 1 m_ChildControlWidth: 1 m_ChildControlHeight: 1 + m_ChildScaleWidth: 0 + m_ChildScaleHeight: 0 --- !u!114 &1791343491 MonoBehaviour: m_ObjectHideFlags: 0 @@ -4890,17 +4918,16 @@ MonoBehaviour: m_GameObject: {fileID: 1791343485} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 0.39215687} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 @@ -4910,6 +4937,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!1 &1792220204 GameObject: m_ObjectHideFlags: 0 @@ -4958,7 +4986,7 @@ MonoBehaviour: m_GameObject: {fileID: 1792220204} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -2061169968, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 2a4db7a114972834c8e4117be1d82ba3, type: 3} m_Name: m_EditorClassIdentifier: m_Navigation: @@ -4972,17 +5000,20 @@ MonoBehaviour: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} + m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} m_ColorMultiplier: 1 m_FadeDuration: 0.1 m_SpriteState: m_HighlightedSprite: {fileID: 0} m_PressedSprite: {fileID: 0} + m_SelectedSprite: {fileID: 0} m_DisabledSprite: {fileID: 0} m_AnimationTriggers: m_NormalTrigger: Normal m_HighlightedTrigger: Highlighted m_PressedTrigger: Pressed + m_SelectedTrigger: Highlighted m_DisabledTrigger: Disabled m_Interactable: 1 m_TargetGraphic: {fileID: 281814073} @@ -4994,8 +5025,6 @@ MonoBehaviour: m_OnValueChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.Scrollbar+ScrollEvent, UnityEngine.UI, Version=1.0.0.0, - Culture=neutral, PublicKeyToken=null --- !u!114 &1792220207 MonoBehaviour: m_ObjectHideFlags: 0 @@ -5005,17 +5034,16 @@ MonoBehaviour: m_GameObject: {fileID: 1792220204} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10907, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 @@ -5025,6 +5053,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &1792220208 CanvasRenderer: m_ObjectHideFlags: 0 @@ -5081,7 +5110,7 @@ MonoBehaviour: m_GameObject: {fileID: 1795126381} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1741964061, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 3245ec927659c4140ac4f8d17403cc18, type: 3} m_Name: m_EditorClassIdentifier: m_HorizontalFit: 0 @@ -5095,7 +5124,7 @@ MonoBehaviour: m_GameObject: {fileID: 1795126381} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -405508275, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 30649d3a9faa99c48a7b1166b86bf2a0, type: 3} m_Name: m_EditorClassIdentifier: m_Padding: @@ -5109,6 +5138,8 @@ MonoBehaviour: m_ChildForceExpandHeight: 0 m_ChildControlWidth: 1 m_ChildControlHeight: 1 + m_ChildScaleWidth: 0 + m_ChildScaleHeight: 0 --- !u!1 &1859417307 GameObject: m_ObjectHideFlags: 0 @@ -5155,17 +5186,16 @@ MonoBehaviour: m_GameObject: {fileID: 1859417307} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10915, guid: 0000000000000000f000000000000000, type: 0} m_Type: 0 m_PreserveAspect: 0 @@ -5175,6 +5205,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &1859417310 CanvasRenderer: m_ObjectHideFlags: 0 @@ -5231,7 +5262,7 @@ MonoBehaviour: m_GameObject: {fileID: 1881588353} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 2109663825, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 9085046f02f69544eb97fd06b6048fe2, type: 3} m_Name: m_EditorClassIdentifier: m_Navigation: @@ -5245,17 +5276,20 @@ MonoBehaviour: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} + m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} m_ColorMultiplier: 1 m_FadeDuration: 0.1 m_SpriteState: m_HighlightedSprite: {fileID: 0} m_PressedSprite: {fileID: 0} + m_SelectedSprite: {fileID: 0} m_DisabledSprite: {fileID: 0} m_AnimationTriggers: m_NormalTrigger: Normal m_HighlightedTrigger: Highlighted m_PressedTrigger: Pressed + m_SelectedTrigger: Highlighted m_DisabledTrigger: Disabled m_Interactable: 1 m_TargetGraphic: {fileID: 518778558} @@ -5265,8 +5299,6 @@ MonoBehaviour: onValueChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.Toggle+ToggleEvent, UnityEngine.UI, Version=1.0.0.0, - Culture=neutral, PublicKeyToken=null m_IsOn: 1 --- !u!1 &1902271795 GameObject: @@ -5314,17 +5346,16 @@ MonoBehaviour: m_GameObject: {fileID: 1902271795} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0, g: 0.08965492, b: 1, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 10 @@ -5393,17 +5424,16 @@ MonoBehaviour: m_GameObject: {fileID: 1964866601} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10901, guid: 0000000000000000f000000000000000, type: 0} m_Type: 0 m_PreserveAspect: 0 @@ -5413,6 +5443,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &1964866604 CanvasRenderer: m_ObjectHideFlags: 0 @@ -5539,17 +5570,16 @@ MonoBehaviour: m_GameObject: {fileID: 2001181084} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 10 @@ -5618,17 +5648,16 @@ MonoBehaviour: m_GameObject: {fileID: 2032247218} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0, g: 0.08965492, b: 1, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 10 @@ -5702,7 +5731,7 @@ MonoBehaviour: m_GameObject: {fileID: 2060017214} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1741964061, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 3245ec927659c4140ac4f8d17403cc18, type: 3} m_Name: m_EditorClassIdentifier: m_HorizontalFit: 0 @@ -5716,7 +5745,7 @@ MonoBehaviour: m_GameObject: {fileID: 2060017214} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1297475563, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 59f8146938fff824cb5fd77236b75775, type: 3} m_Name: m_EditorClassIdentifier: m_Padding: @@ -5730,6 +5759,8 @@ MonoBehaviour: m_ChildForceExpandHeight: 0 m_ChildControlWidth: 1 m_ChildControlHeight: 1 + m_ChildScaleWidth: 0 + m_ChildScaleHeight: 0 --- !u!114 &2060017218 MonoBehaviour: m_ObjectHideFlags: 0 @@ -5739,7 +5770,7 @@ MonoBehaviour: m_GameObject: {fileID: 2060017214} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1392445389, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 4e29b1a8efbd4b44bb3f3716e73f07ff, type: 3} m_Name: m_EditorClassIdentifier: m_Navigation: @@ -5753,17 +5784,20 @@ MonoBehaviour: m_NormalColor: {r: 1, g: 1, b: 1, a: 1} m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} + m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} m_ColorMultiplier: 1 m_FadeDuration: 0.1 m_SpriteState: m_HighlightedSprite: {fileID: 0} m_PressedSprite: {fileID: 0} + m_SelectedSprite: {fileID: 0} m_DisabledSprite: {fileID: 0} m_AnimationTriggers: m_NormalTrigger: Normal m_HighlightedTrigger: Highlighted m_PressedTrigger: Pressed + m_SelectedTrigger: Highlighted m_DisabledTrigger: Disabled m_Interactable: 1 m_TargetGraphic: {fileID: 2060017219} @@ -5781,8 +5815,6 @@ MonoBehaviour: m_StringArgument: m_BoolArgument: 0 m_CallState: 2 - m_TypeName: UnityEngine.UI.Button+ButtonClickedEvent, UnityEngine.UI, Version=1.0.0.0, - Culture=neutral, PublicKeyToken=null --- !u!114 &2060017219 MonoBehaviour: m_ObjectHideFlags: 0 @@ -5792,17 +5824,16 @@ MonoBehaviour: m_GameObject: {fileID: 2060017214} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: -765806418, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 1, g: 1, b: 1, a: 1} m_RaycastTarget: 1 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} m_Type: 1 m_PreserveAspect: 0 @@ -5812,6 +5843,7 @@ MonoBehaviour: m_FillClockwise: 1 m_FillOrigin: 0 m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 --- !u!222 &2060017220 CanvasRenderer: m_ObjectHideFlags: 0 @@ -5829,7 +5861,7 @@ MonoBehaviour: m_GameObject: {fileID: 2060017214} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1679637790, guid: f70555f144d8491a825f0804e09c671c, type: 3} + m_Script: {fileID: 11500000, guid: 306cc8c2b49d7114eaa3623786fc2126, type: 3} m_Name: m_EditorClassIdentifier: m_IgnoreLayout: 0 @@ -5885,7 +5917,7 @@ MonoBehaviour: m_GameObject: {fileID: 2062856653} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 1679637790, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 306cc8c2b49d7114eaa3623786fc2126, type: 3} m_Name: m_EditorClassIdentifier: m_IgnoreLayout: 0 @@ -5942,17 +5974,16 @@ MonoBehaviour: m_GameObject: {fileID: 2080431525} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0, g: 0, b: 0, a: 1} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 14 @@ -6021,17 +6052,16 @@ MonoBehaviour: m_GameObject: {fileID: 2080744764} m_Enabled: 1 m_EditorHideFlags: 0 - m_Script: {fileID: 708705254, guid: f5f67c52d1564df4a8936ccd202a3bd8, type: 3} + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} m_Name: m_EditorClassIdentifier: m_Material: {fileID: 0} m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} m_RaycastTarget: 0 + m_Maskable: 1 m_OnCullStateChanged: m_PersistentCalls: m_Calls: [] - m_TypeName: UnityEngine.UI.MaskableGraphic+CullStateChangedEvent, UnityEngine.UI, - Version=1.0.0.0, Culture=neutral, PublicKeyToken=null m_FontData: m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} m_FontSize: 9 diff --git a/Assets/URS/Best HTTP/Examples/SignalRCore/Encoders/JsonDotNetEncoder.cs b/Assets/URS/Best HTTP/Examples/SignalRCore/Encoders/JsonDotNetEncoder.cs index f555697..8a24086 100644 --- a/Assets/URS/Best HTTP/Examples/SignalRCore/Encoders/JsonDotNetEncoder.cs +++ b/Assets/URS/Best HTTP/Examples/SignalRCore/Encoders/JsonDotNetEncoder.cs @@ -6,23 +6,33 @@ namespace BestHTTP.SignalRCore.Encoders { public sealed class JsonDotNetEncoder : BestHTTP.SignalRCore.IEncoder { + Newtonsoft.Json.JsonSerializerSettings _settings; + + public JsonDotNetEncoder() + { } + + public JsonDotNetEncoder(Newtonsoft.Json.JsonSerializerSettings settings) + { + this._settings = settings; + } + public object ConvertTo(Type toType, object obj) { - string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj); + string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj, this._settings); - return Newtonsoft.Json.JsonConvert.DeserializeObject(json, toType); + return Newtonsoft.Json.JsonConvert.DeserializeObject(json, toType, this._settings); } public T DecodeAs(BufferSegment buffer) { using (var reader = new System.IO.StreamReader(new System.IO.MemoryStream(buffer.Data, buffer.Offset, buffer.Count))) using (var jsonReader = new Newtonsoft.Json.JsonTextReader(reader)) - return new Newtonsoft.Json.JsonSerializer().Deserialize(jsonReader); + return Newtonsoft.Json.JsonSerializer.CreateDefault(this._settings).Deserialize(jsonReader); } public BufferSegment Encode(T value) { - var json = Newtonsoft.Json.JsonConvert.SerializeObject(value); + var json = Newtonsoft.Json.JsonConvert.SerializeObject(value, this._settings); int len = System.Text.Encoding.UTF8.GetByteCount(json); byte[] buffer = BufferPool.Get(len + 1, true); diff --git a/Assets/URS/Best HTTP/Examples/SocketIO3/ChatSample.prefab b/Assets/URS/Best HTTP/Examples/SocketIO3/ChatSample.prefab index 80605b2..cc98c8f 100644 --- a/Assets/URS/Best HTTP/Examples/SocketIO3/ChatSample.prefab +++ b/Assets/URS/Best HTTP/Examples/SocketIO3/ChatSample.prefab @@ -507,7 +507,7 @@ MonoBehaviour: m_TargetGraphic: {fileID: 114760470429517008} m_HandleRect: {fileID: 224189678256422720} m_Direction: 2 - m_Value: 1 + m_Value: 0 m_Size: 1 m_NumberOfSteps: 0 m_OnValueChanged: @@ -788,8 +788,8 @@ MonoBehaviour: m_TargetGraphic: {fileID: 114780823094611374} m_HandleRect: {fileID: 224288845495672020} m_Direction: 0 - m_Value: 0.5 - m_Size: 0 + m_Value: 0 + m_Size: 1 m_NumberOfSteps: 0 m_OnValueChanged: m_PersistentCalls: diff --git a/Assets/URS/Best HTTP/Examples/SocketIO3/Parsers/JsonDotNetParser.cs b/Assets/URS/Best HTTP/Examples/SocketIO3/Parsers/JsonDotNetParser.cs new file mode 100644 index 0000000..178499a --- /dev/null +++ b/Assets/URS/Best HTTP/Examples/SocketIO3/Parsers/JsonDotNetParser.cs @@ -0,0 +1,562 @@ +#if !BESTHTTP_DISABLE_SOCKETIO && BESTHTTP_SOCKETIO_ENABLE_NEWTONSOFT_JSON_DOTNET_ENCODER + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +using BestHTTP.PlatformSupport.Memory; +using BestHTTP.SocketIO3.Events; + +using Newtonsoft.Json; + +namespace BestHTTP.SocketIO3.Parsers +{ + public sealed class JsonDotNetParser : IParser + { + private IncomingPacket PacketWithAttachment = IncomingPacket.Empty; + private JsonSerializerSettings _settings; + + public JsonDotNetParser() + { } + + public JsonDotNetParser(JsonSerializerSettings settings) + { + this._settings = settings; + } + + private int ToInt(char ch) + { + int charValue = Convert.ToInt32(ch); + int num = charValue - '0'; + if (num < 0 || num > 9) + return -1; + + return num; + } + + public IncomingPacket Parse(SocketManager manager, string from) + { + int idx = 0; + var transportEvent = (TransportEventTypes)ToInt(from[idx++]); + var socketIOEvent = SocketIOEventTypes.Unknown; + var nsp = string.Empty; + var id = -1; + var payload = string.Empty; + int attachments = 0; + + if (from.Length > idx && ToInt(from[idx]) >= 0) + socketIOEvent = (SocketIOEventTypes)ToInt(from[idx++]); + else + socketIOEvent = SocketIOEventTypes.Unknown; + + // Parse Attachment + if (socketIOEvent == SocketIOEventTypes.BinaryEvent || socketIOEvent == SocketIOEventTypes.BinaryAck) + { + int endIdx = from.IndexOf('-', idx); + if (endIdx == -1) + endIdx = from.Length; + + int.TryParse(from.Substring(idx, endIdx - idx), out attachments); + + idx = endIdx + 1; + } + + // Parse Namespace + if (from.Length > idx && from[idx] == '/') + { + int endIdx = from.IndexOf(',', idx); + if (endIdx == -1) + endIdx = from.Length; + + nsp = from.Substring(idx, endIdx - idx); + idx = endIdx + 1; + } + else + nsp = "/"; + + // Parse Id + if (from.Length > idx && ToInt(from[idx]) >= 0) + { + int startIdx = idx++; + while (from.Length > idx && ToInt(from[idx]) >= 0) + idx++; + + int.TryParse(from.Substring(startIdx, idx - startIdx), out id); + } + + // What left is the payload data + if (from.Length > idx) + payload = from.Substring(idx); + else + payload = string.Empty; + + var packet = new IncomingPacket(transportEvent, socketIOEvent, nsp, id); + packet.AttachementCount = attachments; + + string eventName = packet.EventName; + object[] args = null; + + switch (socketIOEvent) + { + case SocketIOEventTypes.Unknown: + packet.DecodedArg = payload; + break; + + case SocketIOEventTypes.Connect: + // No Data | Object + if (!string.IsNullOrEmpty(payload)) + (eventName, args) = ReadData(manager, packet, payload); + break; + + case SocketIOEventTypes.Disconnect: + // No Data + break; + + case SocketIOEventTypes.Error: + // String | Object + (eventName, args) = ReadData(manager, packet, payload); + break; + + case SocketIOEventTypes.BinaryAck: + // Save payload until all attachments arrive + if (packet.AttachementCount > 0) + packet.DecodedArg = payload; + break; + + default: + // Array + (eventName, args) = ReadData(manager, packet, payload); + // Save payload until all attachments arrive + if (packet.AttachementCount > 0) + packet.DecodedArg = payload; + break; + } + + packet.EventName = eventName; + + if (args != null) + { + if (args.Length == 1) + packet.DecodedArg = args[0]; + else + packet.DecodedArgs = args; + } + + if (packet.AttachementCount > 0) + { + PacketWithAttachment = packet; + return IncomingPacket.Empty; + } + + return packet; + } + + public IncomingPacket MergeAttachements(SocketManager manager, IncomingPacket packet) + { + string payload = packet.DecodedArg as string; + packet.DecodedArg = null; + + string placeholderFormat = "{{\"_placeholder\":true,\"num\":{0}}}"; + + for (int i = 0; i < packet.Attachements.Count; ++i) + { + string placeholder = string.Format(placeholderFormat, i); + BufferSegment data = packet.Attachements[i]; + + payload = payload.Replace(placeholder, "\"" + Convert.ToBase64String(data.Data, data.Offset, data.Count) + "\""); + } + + (string eventName, object[] args) = ReadData(manager, packet, payload); + + packet.EventName = eventName; + + if (args != null) + { + if (args.Length == 1) + packet.DecodedArg = args[0]; + else + packet.DecodedArgs = args; + } + + return packet; + } + + private (string, object[]) ReadData(SocketManager manager, IncomingPacket packet, string payload) + { + Socket socket = manager.GetSocket(packet.Namespace); + + string eventName = packet.EventName; + Subscription subscription = socket.GetSubscription(eventName); + + object[] args = null; + + switch (packet.SocketIOEvent) + { + case SocketIOEventTypes.Unknown: + // TODO: Error? + break; + + case SocketIOEventTypes.Connect: + // No Data | Object + using (var strReader = new System.IO.StringReader(payload)) + using (var txtReader = new JsonTextReader(strReader)) + args = ReadParameters(socket, subscription, txtReader); + break; + + case SocketIOEventTypes.Disconnect: + // No Data + break; + + case SocketIOEventTypes.Error: + // String | Object + switch (payload[0]) + { + case '{': + using (var strReader = new System.IO.StringReader(payload)) + using (var txtReader = new JsonTextReader(strReader)) + args = ReadParameters(socket, subscription, txtReader); + break; + + default: + args = new object[] { new Error(payload) }; + break; + + } + break; + + case SocketIOEventTypes.Ack: + case SocketIOEventTypes.BinaryAck: + eventName = IncomingPacket.GenerateAcknowledgementNameFromId(packet.Id); + subscription = socket.GetSubscription(eventName); + + args = ReadParameters(socket, subscription, JsonConvert.DeserializeObject>(payload, this._settings), 0); + + break; + + default: + // Array + + List array = JsonConvert.DeserializeObject>(payload, this._settings); + + if (array.Count > 0) + { + eventName = array[0].ToString(); + subscription = socket.GetSubscription(eventName); + } + + if (packet.AttachementCount == 0 || packet.Attachements != null) + { + try + { + args = ReadParameters(socket, subscription, array, 1); + } + catch (Exception ex) + { + HTTPManager.Logger.Exception("DefaultJsonParser", string.Format("ReadParameters with eventName: {0}", eventName), ex); + } + } + + break; + } + + return (eventName, args); + } + + private object[] ReadParameters(Socket socket, Subscription subscription, List array, int startIdx) + { + object[] args = null; + + if (array.Count > startIdx) + { + var desc = subscription != null ? subscription.callbacks.FirstOrDefault() : default(CallbackDescriptor); + int paramCount = desc.ParamTypes != null ? desc.ParamTypes.Length : 0; + + int arrayIdx = startIdx; + if (paramCount > 0) + { + args = new object[paramCount]; + + for (int i = 0; i < desc.ParamTypes.Length; ++i) + { + Type type = desc.ParamTypes[i]; + + if (type == typeof(Socket)) + args[i] = socket; + else if (type == typeof(SocketManager)) + args[i] = socket.Manager; + else if (type == typeof(Placeholder)) + args[i] = new Placeholder(); + else + args[i] = ConvertTo(desc.ParamTypes[i], array[arrayIdx++]); + } + } + } + + return args; + } + + public object ConvertTo(Type toType, object obj) + { + if (obj == null) + return null; + +#if NETFX_CORE + TypeInfo objType = obj.GetType().GetTypeInfo(); +#else + Type objType = obj.GetType(); +#endif + +#if NETFX_CORE + TypeInfo typeInfo = toType.GetTypeInfo(); +#endif + +#if NETFX_CORE + if (typeInfo.IsEnum) +#else + if (toType.IsEnum) +#endif + return Enum.Parse(toType, obj.ToString(), true); + +#if NETFX_CORE + if (typeInfo.IsPrimitive) +#else + if (toType.IsPrimitive) +#endif + return Convert.ChangeType(obj, toType); + + if (toType == typeof(string)) + return obj.ToString(); + +#if NETFX_CORE + if (typeInfo.IsGenericType && toType.Name == "Nullable`1") + return Convert.ChangeType(obj, toType.GenericTypeArguments[0]); +#else + if (toType.IsGenericType && toType.Name == "Nullable`1") + return Convert.ChangeType(obj, toType.GetGenericArguments()[0]); +#endif + +#if NETFX_CORE + if (objType.Equals(typeInfo)) +#else + if (objType.Equals(toType)) +#endif + return obj; + + if (toType == typeof(byte[]) && objType == typeof(string)) + return Convert.FromBase64String(obj.ToString()); + + return JsonConvert.DeserializeObject(JsonConvert.SerializeObject(obj, this._settings), toType, this._settings); + } + + private object[] ReadParameters(Socket socket, Subscription subscription, JsonTextReader reader) + { + var desc = subscription != null ? subscription.callbacks.FirstOrDefault() : default(CallbackDescriptor); + int paramCount = desc.ParamTypes != null ? desc.ParamTypes.Length : 0; + object[] args = null; + + if (paramCount > 0) + { + args = new object[paramCount]; + + for (int i = 0; i < desc.ParamTypes.Length; ++i) + { + Type type = desc.ParamTypes[i]; + + if (type == typeof(Socket)) + args[i] = socket; + else if (type == typeof(SocketManager)) + args[i] = socket.Manager; + else + { + args[i] = JsonSerializer.CreateDefault(this._settings).Deserialize(reader, type); + } + } + } + + return args; + } + + public IncomingPacket Parse(SocketManager manager, BufferSegment data, TransportEventTypes transportEvent = TransportEventTypes.Unknown) + { + IncomingPacket packet = IncomingPacket.Empty; + + if (PacketWithAttachment.Attachements == null) + PacketWithAttachment.Attachements = new List(PacketWithAttachment.AttachementCount); + PacketWithAttachment.Attachements.Add(data); + + if (PacketWithAttachment.Attachements.Count == PacketWithAttachment.AttachementCount) + { + packet = manager.Parser.MergeAttachements(manager, PacketWithAttachment); + PacketWithAttachment = IncomingPacket.Empty; + } + + return packet; + } + + public OutgoingPacket CreateOutgoing(TransportEventTypes transportEvent, string payload) + { + return new OutgoingPacket { Payload = "" + (char)('0' + (byte)transportEvent) + payload }; + } + + private StringBuilder builder = new StringBuilder(); + public OutgoingPacket CreateOutgoing(Socket socket, SocketIOEventTypes socketIOEvent, int id, string name, object arg) + { + return CreateOutgoing(socket, socketIOEvent, id, name, arg != null ? new object[] { arg } : null); + } + + private int GetBinaryCount(object[] args) + { + if (args == null || args.Length == 0) + return 0; + + int count = 0; + for (int i = 0; i < args.Length; ++i) + if (args[i] is byte[]) + count++; + + return count; + } + public OutgoingPacket CreateOutgoing(Socket socket, SocketIOEventTypes socketIOEvent, int id, string name, object[] args) + { + builder.Length = 0; + List attachements = null; + + switch (socketIOEvent) + { + case SocketIOEventTypes.Ack: + if (GetBinaryCount(args) > 0) + { + attachements = CreatePlaceholders(args); + socketIOEvent = SocketIOEventTypes.BinaryAck; + } + break; + + case SocketIOEventTypes.Event: + if (GetBinaryCount(args) > 0) + { + attachements = CreatePlaceholders(args); + socketIOEvent = SocketIOEventTypes.BinaryEvent; + } + break; + } + + builder.Append(((int)TransportEventTypes.Message).ToString()); + builder.Append(((int)socketIOEvent).ToString()); + + if (socketIOEvent == SocketIOEventTypes.BinaryEvent || socketIOEvent == SocketIOEventTypes.BinaryAck) + { + builder.Append(attachements.Count.ToString()); + builder.Append('-'); + } + + // Add the namespace. If there is any other then the root nsp ("/") + // then we have to add a trailing "," if we have more data. + bool nspAdded = false; + if (socket.Namespace != "/") + { + builder.Append(socket.Namespace); + nspAdded = true; + } + + // ack id, if any + if (id >= 0) + { + if (nspAdded) + { + builder.Append(','); + nspAdded = false; + } + + builder.Append(id.ToString()); + } + + // payload + switch (socketIOEvent) + { + case SocketIOEventTypes.Connect: + // No Data | Object + if (args != null && args.Length > 0) + { + if (nspAdded) builder.Append(','); + + builder.Append(JsonConvert.SerializeObject(args[0], this._settings)); + } + break; + + case SocketIOEventTypes.Disconnect: + // No Data + break; + + case SocketIOEventTypes.Error: + // String | Object + if (args != null && args.Length > 0) + { + if (nspAdded) builder.Append(','); + + builder.Append(JsonConvert.SerializeObject(args[0], this._settings)); + } + break; + + case SocketIOEventTypes.Ack: + case SocketIOEventTypes.BinaryAck: + if (nspAdded) builder.Append(','); + + if (args != null && args.Length > 0) + { + builder.Append(JsonConvert.SerializeObject(args[0], this._settings)); + } + else + builder.Append("[]"); + break; + + default: + if (nspAdded) builder.Append(','); + + // Array + builder.Append('['); + if (!string.IsNullOrEmpty(name)) + { + builder.Append('\"'); + builder.Append(name); + builder.Append('\"'); + } + + if (args != null && args.Length > 0) + { + builder.Append(','); + + var argsJson = JsonConvert.SerializeObject(args, this._settings); + builder.Append(argsJson, 1, argsJson.Length - 2); + } + + builder.Append(']'); + break; + } + + return new OutgoingPacket { Payload = builder.ToString(), Attachements = attachements }; + } + + private List CreatePlaceholders(object[] args) + { + List attachements = null; + + for (int i = 0; i < args.Length; ++i) + { + var binary = args[i] as byte[]; + if (binary != null) + { + if (attachements == null) + attachements = new List(); + attachements.Add(binary); + + args[i] = new Placeholder { _placeholder = true, num = attachements.Count - 1 }; + } + } + + return attachements; + } + } +} + +#endif diff --git a/Assets/URS/Setting/Runtime/Settings/Settings.cs.meta b/Assets/URS/Best HTTP/Examples/SocketIO3/Parsers/JsonDotNetParser.cs.meta similarity index 83% rename from Assets/URS/Setting/Runtime/Settings/Settings.cs.meta rename to Assets/URS/Best HTTP/Examples/SocketIO3/Parsers/JsonDotNetParser.cs.meta index bd03ec8..9607310 100644 --- a/Assets/URS/Setting/Runtime/Settings/Settings.cs.meta +++ b/Assets/URS/Best HTTP/Examples/SocketIO3/Parsers/JsonDotNetParser.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 60d9c864478b32844af990a726ef479f +guid: c1b1e9a202e74ba4089e4aa518f64109 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Examples/SocketIO3/Parsers/MsgPackParser.cs b/Assets/URS/Best HTTP/Examples/SocketIO3/Parsers/MsgPackParser.cs index 5e9f2af..78b56de 100644 --- a/Assets/URS/Best HTTP/Examples/SocketIO3/Parsers/MsgPackParser.cs +++ b/Assets/URS/Best HTTP/Examples/SocketIO3/Parsers/MsgPackParser.cs @@ -4,7 +4,6 @@ using System.Linq; using BestHTTP.PlatformSupport.Memory; -using BestHTTP.SignalRCore.Encoders; using BestHTTP.SocketIO3.Events; using GameDevWare.Serialization; @@ -15,6 +14,10 @@ namespace BestHTTP.SocketIO3.Parsers { public sealed class MsgPackParser : IParser { + // Variables to calculate an average buffer size to start with in CreateOutgoing + ulong sumLength; + uint count; + /// /// Custom function instead of char.GetNumericValue, as it throws an error under WebGL using the new 4.x runtime. /// It will return the value of the char if it's a numeric one, otherwise -1. @@ -213,12 +216,12 @@ private void SkipData(IJsonReader reader, SocketIOEventTypes type) default: // Array - SkipArray(reader, false); + SkipArray(reader, false, true); break; } } - private object[] ReadParameters(Socket socket, Subscription subscription, IJsonReader reader) + private object[] ReadParameters(Socket socket, Subscription subscription, IJsonReader reader, bool isInArray) { var desc = subscription != null ? subscription.callbacks.FirstOrDefault() : default(CallbackDescriptor); int paramCount = desc.ParamTypes != null ? desc.ParamTypes.Length : 0; @@ -240,6 +243,18 @@ private object[] ReadParameters(Socket socket, Subscription subscription, IJsonR args[i] = reader.ReadValue(desc.ParamTypes[i]); } } + else + { + if (isInArray) + { + if (reader.Token != JsonToken.EndOfArray) + SkipArray(reader, true, false); + } + else + { + SkipObject(reader); + } + } return args; } @@ -261,7 +276,7 @@ private object[] ReadParameters(Socket socket, Subscription subscription, IJsonR case SocketIOEventTypes.Connect: // No Data | Object - args = ReadParameters(socket, subscription, reader); + args = ReadParameters(socket, subscription, reader, false); //SkipObject(reader); break; @@ -278,9 +293,9 @@ private object[] ReadParameters(Socket socket, Subscription subscription, IJsonR break; case JsonToken.BeginObject: - args = ReadParameters(socket, subscription, reader); - if (subscription == null && args == null) - SkipObject(reader); + args = ReadParameters(socket, subscription, reader, false); + //if (subscription == null && args == null) + // SkipObject(reader); break; } break; @@ -291,7 +306,7 @@ private object[] ReadParameters(Socket socket, Subscription subscription, IJsonR reader.ReadArrayBegin(); - args = ReadParameters(socket, subscription, reader); + args = ReadParameters(socket, subscription, reader, true); reader.ReadArrayEnd(); break; @@ -303,7 +318,7 @@ private object[] ReadParameters(Socket socket, Subscription subscription, IJsonR subscription = socket.GetSubscription(eventName); - args = ReadParameters(socket, subscription, reader); + args = ReadParameters(socket, subscription, reader, true); reader.ReadArrayEnd(); break; @@ -312,7 +327,7 @@ private object[] ReadParameters(Socket socket, Subscription subscription, IJsonR return (eventName, args); } - private void SkipArray(IJsonReader reader, bool alreadyStarted) + private void SkipArray(IJsonReader reader, bool alreadyStarted, bool readFinalArrayToken) { if (!alreadyStarted) reader.ReadArrayBegin(); @@ -326,7 +341,9 @@ private void SkipArray(IJsonReader reader, bool alreadyStarted) case JsonToken.BeginArray: arrayBegins++; break; case JsonToken.EndOfArray: arrayBegins--; break; } - reader.NextToken(); + + if (readFinalArrayToken || arrayBegins >= 1) + reader.NextToken(); } } @@ -358,7 +375,9 @@ public OutgoingPacket CreateOutgoing(Socket socket, SocketIOEventTypes socketIOE public OutgoingPacket CreateOutgoing(Socket socket, SocketIOEventTypes socketIOEvent, int id, string name, object[] args) { - var memBuffer = BufferPool.Get(256, true); + var memBufferTargetLength = count == 0 ? 256 : Math.Max(256, (sumLength / count) / 2); + + var memBuffer = BufferPool.Get((long)memBufferTargetLength, true); var stream = new BestHTTP.Extensions.BufferPoolMemoryStream(memBuffer, 0, memBuffer.Length, true, true, false, true); var buffer = BufferPool.Get(MsgPackWriter.DEFAULT_BUFFER_SIZE, true); @@ -437,9 +456,17 @@ public OutgoingPacket CreateOutgoing(Socket socket, SocketIOEventTypes socketIOE if (!string.IsNullOrEmpty(name)) writer.Write(name); - - foreach (var arg in args) - writer.WriteValue(arg, arg.GetType()); + + if (args != null && args.Length > 0) + { + foreach (var arg in args) + { + if (arg != null) + writer.WriteValue(arg, arg.GetType()); + else + writer.WriteNull(); + } + } writer.WriteArrayEnd(); break; @@ -455,6 +482,16 @@ public OutgoingPacket CreateOutgoing(Socket socket, SocketIOEventTypes socketIOE int length = (int)stream.Position; buffer = stream.GetBuffer(); + + sumLength += (ulong)length; + count++; + + if(sumLength >= int.MaxValue) + { + sumLength /= count; + count = 1; + } + return new OutgoingPacket { PayloadData = new BufferSegment(buffer, 0, length) }; } } diff --git a/Assets/URS/Best HTTP/Examples/Websocket/WebSocketSample.cs b/Assets/URS/Best HTTP/Examples/Websocket/WebSocketSample.cs index f583f84..92b3657 100644 --- a/Assets/URS/Best HTTP/Examples/Websocket/WebSocketSample.cs +++ b/Assets/URS/Best HTTP/Examples/Websocket/WebSocketSample.cs @@ -70,7 +70,7 @@ public void OnConnectButton() #if !UNITY_WEBGL || UNITY_EDITOR this.webSocket.StartPingThread = true; -#if !BESTHTTP_DISABLE_PROXY +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) if (HTTPManager.Proxy != null) this.webSocket.OnInternalRequestCreated = (ws, internalRequest) => internalRequest.Proxy = new HTTPProxy(HTTPManager.Proxy.Address, HTTPManager.Proxy.Credentials, false); #endif diff --git a/Assets/Settings/Editor/User.meta b/Assets/URS/Best HTTP/Plugins/Android.meta similarity index 77% rename from Assets/Settings/Editor/User.meta rename to Assets/URS/Best HTTP/Plugins/Android.meta index e549402..165c000 100644 --- a/Assets/Settings/Editor/User.meta +++ b/Assets/URS/Best HTTP/Plugins/Android.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 9222aeb3c73fedd47ac509382cfff0df +guid: 00074d6d9db5c82418d3de6cd69eb2a7 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Assets/URS/Best HTTP/Plugins/Android/ProxyFinder.java b/Assets/URS/Best HTTP/Plugins/Android/ProxyFinder.java new file mode 100644 index 0000000..e87cd42 --- /dev/null +++ b/Assets/URS/Best HTTP/Plugins/Android/ProxyFinder.java @@ -0,0 +1,35 @@ +package com.besthttp.proxy; + +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.URI; +import java.util.Iterator; +import java.util.List; + +public class ProxyFinder { + + public static String FindFor(String uriStr) { + try { + System.setProperty("java.net.useSystemProxies","true"); + + List proxies = ProxySelector.getDefault().select(new URI(uriStr)); + + for (Iterator iter = proxies.iterator(); iter.hasNext(); ) { + Proxy proxy = iter.next(); + + InetSocketAddress addr = (InetSocketAddress)proxy.address(); + + if(addr == null) { + // no op + } else { + return String.format("%s://%s:%s", proxy.type(), addr.getHostName(), addr.getPort()); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + return null; + } +} diff --git a/Assets/URS/Best HTTP/Plugins/Android/ProxyFinder.java.meta b/Assets/URS/Best HTTP/Plugins/Android/ProxyFinder.java.meta new file mode 100644 index 0000000..2a9e907 --- /dev/null +++ b/Assets/URS/Best HTTP/Plugins/Android/ProxyFinder.java.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: d58fbdd72f22ed9419414fb4e267c62b +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Android: Android + second: + enabled: 1 + settings: {} + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/Authentication/Digest.cs b/Assets/URS/Best HTTP/Source/Authentication/Digest.cs index 0bd476a..396acf2 100644 --- a/Assets/URS/Best HTTP/Source/Authentication/Digest.cs +++ b/Assets/URS/Best HTTP/Source/Authentication/Digest.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; namespace BestHTTP.Authentication @@ -215,7 +215,7 @@ public string GenerateResponseHeader(HTTPRequest request, Credentials credential if (entityBody == null) entityBody = BufferPool.NoData; //string.Empty.GetASCIIBytes(); - string HA2 = string.Format("{0}:{1}:{2}", method, uri, entityBody.CalculateMD5Hash()).CalculateMD5Hash(); + string HA2 = string.Format("{0}:{1}:{2}", method, uri, new BufferSegment(entityBody, 0, entityBody.Length).CalculateMD5Hash()).CalculateMD5Hash(); response = string.Format("{0}:{1}:{2}:{3}:{4}:{5}", HA1, Nonce, ncvalue, cnonce, qop, HA2).CalculateMD5Hash(); } @@ -278,4 +278,4 @@ public bool IsUriProtected(Uri uri) return true; } } -} \ No newline at end of file +} diff --git a/Assets/URS/Best HTTP/Source/Caching/HTTPCacheFileInfo.cs b/Assets/URS/Best HTTP/Source/Caching/HTTPCacheFileInfo.cs index 79702ce..ef73c11 100644 --- a/Assets/URS/Best HTTP/Source/Caching/HTTPCacheFileInfo.cs +++ b/Assets/URS/Best HTTP/Source/Caching/HTTPCacheFileInfo.cs @@ -396,19 +396,18 @@ public System.IO.Stream GetBodyStream(out int length) return stream; } - internal HTTPResponse ReadResponseTo(HTTPRequest request) + internal void ReadResponseTo(HTTPRequest request) { if (!IsExists()) - return null; + return; LastAccess = DateTime.UtcNow; using (Stream stream = HTTPManager.IOService.CreateFileStream(GetPath(), FileStreamModes.OpenRead)) { - var response = new HTTPResponse(request, stream, request.UseStreaming, true); - response.CacheFileInfo = this; - response.Receive(BodyLength); - return response; + request.Response = new HTTPResponse(request, stream, request.UseStreaming, true); + request.Response.CacheFileInfo = this; + request.Response.Receive(BodyLength); } } diff --git a/Assets/URS/Best HTTP/Source/Caching/HTTPCacheService.cs b/Assets/URS/Best HTTP/Source/Caching/HTTPCacheService.cs index 14f2088..5c79d36 100644 --- a/Assets/URS/Best HTTP/Source/Caching/HTTPCacheService.cs +++ b/Assets/URS/Best HTTP/Source/Caching/HTTPCacheService.cs @@ -274,10 +274,10 @@ public static HTTPCacheFileInfo GetEntity(Uri uri) return info; } - internal static HTTPResponse GetFullResponse(HTTPRequest request) + internal static void GetFullResponse(HTTPRequest request) { if (!IsSupported) - return null; + return; CheckSetup(); @@ -286,9 +286,9 @@ internal static HTTPResponse GetFullResponse(HTTPRequest request) using (new ReadLock(rwLock)) { if (!library.TryGetValue(request.CurrentUri, out info)) - return null; + return; - return info.ReadResponseTo(request); + info.ReadResponseTo(request); } } diff --git a/Assets/URS/Best HTTP/Source/Connections/BufferedReadNetworkStream.cs b/Assets/URS/Best HTTP/Source/Connections/BufferedReadNetworkStream.cs index b654695..e6e0619 100644 --- a/Assets/URS/Best HTTP/Source/Connections/BufferedReadNetworkStream.cs +++ b/Assets/URS/Best HTTP/Source/Connections/BufferedReadNetworkStream.cs @@ -57,6 +57,7 @@ public BufferedReadNetworkStream(Stream stream, int bufferSize) { this.innerStream = stream; this.readStream = new ReadOnlyBufferedStream(stream, bufferSize); + IncrementCurrentConnections(); } @@ -93,10 +94,24 @@ public override void Close() if (this.innerStream != null) { - this.innerStream.Close(); - this.innerStream = null; + lock (this) + { + if (this.innerStream != null) + { + DecrementCurrentConnections(); + + var stream = this.innerStream; + this.innerStream = null; + + stream.Close(); + } - DecrementCurrentConnections(); + if (this.readStream != null) + { + this.readStream.Close(); + this.readStream = null; + } + } } } } diff --git a/Assets/URS/Best HTTP/Source/Connections/ConnectionHelper.cs b/Assets/URS/Best HTTP/Source/Connections/ConnectionHelper.cs index 38fb3ef..1798c89 100644 --- a/Assets/URS/Best HTTP/Source/Connections/ConnectionHelper.cs +++ b/Assets/URS/Best HTTP/Source/Connections/ConnectionHelper.cs @@ -90,6 +90,7 @@ public static void HandleResponse(string context, HTTPRequest request, out bool goto default; } +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) case 407: { if (request.Proxy == null) @@ -99,10 +100,12 @@ public static void HandleResponse(string context, HTTPRequest request, out bool goto default; } +#endif // Redirected case 301: // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.2 case 302: // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3 + case 303: // "See Other" case 307: // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.8 case 308: // http://tools.ietf.org/html/rfc7238 { @@ -287,13 +290,14 @@ public static bool TryLoadAllFromCache(string context, HTTPRequest request, Logg if (HTTPManager.Logger.Level == Logger.Loglevels.All) HTTPManager.Logger.Verbose("ConnectionHelper", string.Format("[{0}] - TryLoadAllFromCache - whole response loading from cache", context), loggingContext1, loggingContext2, loggingContext3); - request.Response = HTTPCacheService.GetFullResponse(request); + HTTPCacheService.GetFullResponse(request); if (request.Response != null) return true; } catch { + request.Response = null; HTTPManager.Logger.Verbose("ConnectionHelper", string.Format("[{0}] - TryLoadAllFromCache - failed to load content!", context), loggingContext1, loggingContext2, loggingContext3); HTTPCacheService.DeleteEntity(request.CurrentUri); } diff --git a/Assets/URS/Best HTTP/Source/Connections/HTTP1Handler.cs b/Assets/URS/Best HTTP/Source/Connections/HTTP1Handler.cs index f0fd1cd..0399cef 100644 --- a/Assets/URS/Best HTTP/Source/Connections/HTTP1Handler.cs +++ b/Assets/URS/Best HTTP/Source/Connections/HTTP1Handler.cs @@ -2,6 +2,7 @@ using System; using BestHTTP.Core; using BestHTTP.Logger; +using BestHTTP.PlatformSupport.Threading; #if !BESTHTTP_DISABLE_CACHING using BestHTTP.Caching; @@ -37,7 +38,7 @@ public void RunHandler() { HTTPManager.Logger.Information("HTTP1Handler", string.Format("[{0}] started processing request '{1}'", this, this.conn.CurrentRequest.CurrentUri.ToString()), this.Context, this.conn.CurrentRequest.Context); - System.Threading.Thread.CurrentThread.Name = "BestHTTP.HTTP1 R&W"; + ThreadedRunner.SetThreadName("BestHTTP.HTTP1 R&W"); HTTPConnectionStates proposedConnectionState = HTTPConnectionStates.Processing; @@ -115,7 +116,7 @@ public void RunHandler() exceptionMessage = "null"; else { - System.Text.StringBuilder sb = new System.Text.StringBuilder(); + System.Text.StringBuilder sb = PlatformSupport.Text.StringBuilderPool.Get(1); Exception exception = e; int counter = 1; @@ -129,7 +130,7 @@ public void RunHandler() sb.AppendLine(); } - exceptionMessage = sb.ToString(); + exceptionMessage = PlatformSupport.Text.StringBuilderPool.ReleaseAndGrab(sb); } HTTPManager.Logger.Verbose("HTTP1Handler", exceptionMessage, this.Context, this.conn.CurrentRequest.Context); diff --git a/Assets/URS/Best HTTP/Source/Connections/HTTP2/FramesAsStreamView.cs b/Assets/URS/Best HTTP/Source/Connections/HTTP2/FramesAsStreamView.cs index ff3de58..d3c8b90 100644 --- a/Assets/URS/Best HTTP/Source/Connections/HTTP2/FramesAsStreamView.cs +++ b/Assets/URS/Best HTTP/Source/Connections/HTTP2/FramesAsStreamView.cs @@ -7,7 +7,7 @@ namespace BestHTTP.Connections.HTTP2 { - interface IFrameDataView : IDisposable + public interface IFrameDataView : IDisposable { long Length { get; } long Position { get; } @@ -17,7 +17,7 @@ interface IFrameDataView : IDisposable int Read(byte[] buffer, int offset, int count); } - abstract class CommonFrameView : IFrameDataView + public abstract class CommonFrameView : IFrameDataView { public long Length { get; protected set; } public long Position { get; protected set; } @@ -74,14 +74,15 @@ public virtual int ReadByte() public virtual void Dispose() { for (int i = 0; i < this.frames.Count; ++i) - if (this.frames[i].Payload != null && !this.frames[i].DontUseMemPool) + //if (this.frames[i].Payload != null && !this.frames[i].DontUseMemPool) BufferPool.Release(this.frames[i].Payload); this.frames.Clear(); } public override string ToString() { - var sb = new System.Text.StringBuilder("[CommonFrameView "); + var sb = PlatformSupport.Text.StringBuilderPool.Get(this.frames.Count + 2); + sb.Append("[CommonFrameView "); for (int i = 0; i < this.frames.Count; ++i) { sb.AppendFormat("{0} Payload: {1}\n", this.frames[i], this.frames[i].PayloadAsHex()); @@ -89,11 +90,11 @@ public override string ToString() sb.Append("]"); - return sb.ToString(); + return PlatformSupport.Text.StringBuilderPool.ReleaseAndGrab(sb); } } - sealed class HeaderFrameView : CommonFrameView + public sealed class HeaderFrameView : CommonFrameView { public override void AddFrame(HTTP2FrameHeaderAndPayload frame) { @@ -149,7 +150,7 @@ protected override bool AdvanceFrame() } } - sealed class DataFrameView : CommonFrameView + public sealed class DataFrameView : CommonFrameView { public override void AddFrame(HTTP2FrameHeaderAndPayload frame) { @@ -182,7 +183,7 @@ protected override bool AdvanceFrame() } } - sealed class FramesAsStreamView : Stream + public sealed class FramesAsStreamView : Stream { public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } diff --git a/Assets/URS/Best HTTP/Source/Connections/HTTP2/HPACKEncoder.cs b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HPACKEncoder.cs index 073d61b..b91404a 100644 --- a/Assets/URS/Best HTTP/Source/Connections/HTTP2/HPACKEncoder.cs +++ b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HPACKEncoder.cs @@ -36,7 +36,7 @@ public void Encode(HTTP2Stream context, HTTPRequest request, Queue { if (header.Equals("connection", StringComparison.OrdinalIgnoreCase) || - header.Equals("te", StringComparison.OrdinalIgnoreCase) || + (header.Equals("te", StringComparison.OrdinalIgnoreCase) && !values.Contains("trailers") && values.Count <= 1) || header.Equals("host", StringComparison.OrdinalIgnoreCase) || header.Equals("keep-alive", StringComparison.OrdinalIgnoreCase) || header.StartsWith("proxy-", StringComparison.OrdinalIgnoreCase)) @@ -295,9 +295,11 @@ private string DecodeString(Stream stream) stream.Read(buffer, 0, (int)stringLength); + var result = System.Text.Encoding.UTF8.GetString(buffer, 0, (int)stringLength); + BufferPool.Release(buffer); - return System.Text.Encoding.UTF8.GetString(buffer, 0, (int)stringLength); + return result; } else { @@ -305,7 +307,7 @@ private string DecodeString(Stream stream) byte currentByte = (byte)stream.ReadByte(); byte bitIdx = 0; // 0..7 - using (BufferPoolMemoryStream bufferStream = new BufferPoolMemoryStream()) + using (BufferPoolMemoryStream bufferStream = new BufferPoolMemoryStream((int)(stringLength * 1.5f))) { do { @@ -333,12 +335,10 @@ private string DecodeString(Stream stream) } } while (stringLength > 0); - byte[] buffer = bufferStream.ToArray(true); + byte[] buffer = bufferStream.GetBuffer(); string result = System.Text.Encoding.UTF8.GetString(buffer, 0, (int)bufferStream.Length); - BufferPool.Release(buffer); - return result; } } diff --git a/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2FrameHelper.cs b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2FrameHelper.cs index 2578de7..65dd9bd 100644 --- a/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2FrameHelper.cs +++ b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2FrameHelper.cs @@ -251,7 +251,15 @@ public static HTTP2FrameHeaderAndPayload ReadHeader(Stream stream) { byte[] buffer = BufferPool.Get(9, true); - StreamRead(stream, buffer, 0, 9); + try + { + StreamRead(stream, buffer, 0, 9); + } + catch + { + BufferPool.Release(buffer); + throw; + } HTTP2FrameHeaderAndPayload header = new HTTP2FrameHeaderAndPayload(); @@ -263,7 +271,16 @@ public static HTTP2FrameHeaderAndPayload ReadHeader(Stream stream) BufferPool.Release(buffer); header.Payload = BufferPool.Get(header.PayloadLength, true); - StreamRead(stream, header.Payload, 0, header.PayloadLength); + + try + { + StreamRead(stream, header.Payload, 0, header.PayloadLength); + } + catch + { + BufferPool.Release(header.Payload); + throw; + } return header; } diff --git a/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2Frames.cs b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2Frames.cs index d3d6050..0d75ea7 100644 --- a/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2Frames.cs +++ b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2Frames.cs @@ -85,13 +85,15 @@ public struct HTTP2FrameHeaderAndPayload public override string ToString() { - return string.Format("[HTTP2FrameHeaderAndPayload Length: {0}, Type: {1}, Flags: {2}, StreamId: {3}, PayloadOffset: {4}, DontUseMemPool: {5}]", - this.PayloadLength, this.Type, this.Flags.ToBinaryStr(), this.StreamId, this.PayloadOffset, this.DontUseMemPool); + return string.Format("[HTTP2FrameHeaderAndPayload Length: {0}, Type: {1}, Flags: {2}, StreamId: {3}, PayloadOffset: {4}, DontUseMemPool: {5}, Payload: {6}]", + this.PayloadLength, this.Type, this.Flags.ToBinaryStr(), this.StreamId, this.PayloadOffset, this.DontUseMemPool, + this.Payload == null ? BufferSegment.Empty : new BufferSegment(this.Payload, (int)this.PayloadOffset, (int)this.PayloadLength)); } public string PayloadAsHex() { - System.Text.StringBuilder sb = new System.Text.StringBuilder("[", (int)this.PayloadLength + 1); + System.Text.StringBuilder sb = PlatformSupport.Text.StringBuilderPool.Get((int)this.PayloadLength + 2); + sb.Append("["); if (this.Payload != null && this.PayloadLength > 0) { uint idx = this.PayloadOffset; @@ -101,7 +103,7 @@ public string PayloadAsHex() } sb.Append("]"); - return sb.ToString(); + return PlatformSupport.Text.StringBuilderPool.ReleaseAndGrab(sb); } } @@ -122,12 +124,14 @@ public override string ToString() string settings = null; if (this.Settings != null) { - System.Text.StringBuilder sb = new System.Text.StringBuilder("["); + System.Text.StringBuilder sb = PlatformSupport.Text.StringBuilderPool.Get(this.Settings.Count + 2); + + sb.Append("["); foreach (var kvp in this.Settings) sb.AppendFormat("[{0}: {1}]", kvp.Key, kvp.Value); sb.Append("]"); - settings = sb.ToString(); + settings = PlatformSupport.Text.StringBuilderPool.ReleaseAndGrab(sb); } return string.Format("[HTTP2SettingsFrame Header: {0}, Flags: {1}, Settings: {2}]", this.Header.ToString(), this.Flags, settings ?? "Empty"); diff --git a/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2Handler.cs b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2Handler.cs index 081b061..1dd714a 100644 --- a/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2Handler.cs +++ b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2Handler.cs @@ -10,6 +10,7 @@ using BestHTTP.Core; using BestHTTP.PlatformSupport.Memory; using BestHTTP.Logger; +using BestHTTP.PlatformSupport.Threading; namespace BestHTTP.Connections.HTTP2 { @@ -96,14 +97,14 @@ public void Process(HTTPRequest request) public void SignalRunnerThread() { - this.newFrameSignal.Set(); + this.newFrameSignal?.Set(); } public void RunHandler() { HTTPManager.Logger.Information("HTTP2Handler", "Processing thread up and running!", this.Context); - Thread.CurrentThread.Name = "BestHTTP.HTTP2 Process"; + ThreadedRunner.SetThreadName("BestHTTP.HTTP2 Process"); PlatformSupport.Threading.ThreadedRunner.RunLongLiving(ReadThread); @@ -175,7 +176,7 @@ public void RunHandler() // lastInteraction lastInteraction + MaxIdleTime var sendPingAt = this.lastPingSent + this.pingFrequency; - var timeoutAt = this.lastPingSent + HTTPManager.HTTP2Settings.Timeout; + var timeoutAt = this.waitingForPingAck != 0 ? this.lastPingSent + HTTPManager.HTTP2Settings.Timeout : DateTime.MaxValue; var nextPingInteraction = sendPingAt < timeoutAt ? sendPingAt : timeoutAt; var disconnectByIdleAt = this.lastInteraction + HTTPManager.HTTP2Settings.MaxIdleTime; @@ -185,6 +186,16 @@ public void RunHandler() wait = (int)Math.Min(wait, this.MaxGoAwayWaitTime.TotalMilliseconds); + TimeSpan nextStreamInteraction = TimeSpan.MaxValue; + for (int i = 0; i < this.clientInitiatedStreams.Count; i++) + { + var streamInteraction = this.clientInitiatedStreams[i].NextInteraction; + if (streamInteraction < nextStreamInteraction) + nextStreamInteraction = streamInteraction; + } + + wait = (int)Math.Min(wait, nextStreamInteraction.TotalMilliseconds); + if (wait >= 1) { if (HTTPManager.Logger.Level <= Logger.Loglevels.All) @@ -255,6 +266,8 @@ public void RunHandler() this.outgoingFrames.Add(frame); } + + BufferPool.Release(pingFrame.OpaqueData); break; case HTTP2FrameTypes.WINDOW_UPDATE: @@ -268,7 +281,7 @@ public void RunHandler() HTTPManager.Logger.Information("HTTP2Handler", "Received GOAWAY frame: " + goAwayFrame.ToString(), this.Context); - string msg = string.Format("Server closing the connection! Error code: {0} ({1})", goAwayFrame.Error, goAwayFrame.ErrorCode); + string msg = string.Format("Server closing the connection! Error code: {0} ({1}) Additonal Debug Data: {2}", goAwayFrame.Error, goAwayFrame.ErrorCode, new BufferSegment(goAwayFrame.AdditionalDebugData, 0, (int)goAwayFrame.AdditionalDebugDataLength)); for (int i = 0; i < this.clientInitiatedStreams.Count; ++i) this.clientInitiatedStreams[i].Abort(msg); this.clientInitiatedStreams.Clear(); @@ -276,7 +289,9 @@ public void RunHandler() // set the running flag to false, so the thread can exit this.isRunning = false; - this.conn.State = HTTPConnectionStates.Closed; + BufferPool.Release(goAwayFrame.AdditionalDebugData); + + //this.conn.State = HTTPConnectionStates.Closed; break; case HTTP2FrameTypes.ALT_SVC: @@ -301,12 +316,19 @@ public void RunHandler() HTTPRequest request; while (this.clientInitiatedStreams.Count < maxConcurrentStreams && this.requestQueue.TryDequeue(out request)) { - // create a new stream - var newStream = new HTTP2Stream((UInt32)Interlocked.Add(ref LastStreamId, 2), this, this.settings, this.HPACKEncoder); + HTTP2Stream newStream = null; +#if !BESTHTTP_DISABLE_WEBSOCKET + if (request.Tag is WebSocket.OverHTTP2) + { + newStream = new HTTP2WebSocketStream((UInt32)Interlocked.Add(ref LastStreamId, 2), this, this.settings, this.HPACKEncoder); + } + else +#endif + { + newStream = new HTTP2Stream((UInt32)Interlocked.Add(ref LastStreamId, 2), this, this.settings, this.HPACKEncoder); + } - // process the request newStream.Assign(request); - this.clientInitiatedStreams.Add(newStream); } } @@ -363,7 +385,8 @@ public void RunHandler() { HTTPManager.Logger.Information("HTTP2Handler", "No GoAway frame received back. Really quitting now!", this.Context); this.isRunning = false; - conn.State = HTTPConnectionStates.Closed; + + //conn.State = HTTPConnectionStates.Closed; } uint streamWindowUpdates = 0; @@ -428,6 +451,9 @@ public void RunHandler() bufferedStream.Write(buffer.Data, 0, buffer.Length); bufferedStream.Write(frame.Payload, (int)frame.PayloadOffset, (int)frame.PayloadLength); + + if (!frame.DontUseMemPool) + BufferPool.Release(frame.Payload); } } // while (this.isRunning) @@ -438,7 +464,7 @@ public void RunHandler() catch (Exception ex) { // Log out the exception if it's a non-expected one. - if (this.ShutdownType == ShutdownTypes.Running && this.goAwaySentAt == DateTime.MaxValue && HTTPManager.IsQuitting) + if (this.ShutdownType == ShutdownTypes.Running && this.goAwaySentAt == DateTime.MaxValue && !HTTPManager.IsQuitting) HTTPManager.Logger.Exception("HTTP2Handler", "Sender thread", ex, this.Context); } finally @@ -485,7 +511,7 @@ private void ReadThread() { try { - Thread.CurrentThread.Name = "BestHTTP.HTTP2 Read"; + ThreadedRunner.SetThreadName("BestHTTP.HTTP2 Read"); HTTPManager.Logger.Information("HTTP2Handler", "Reader thread up and running!", this.Context); while (this.isRunning) @@ -528,10 +554,16 @@ private void ReadThread() HTTPManager.Logger.Verbose("HTTP2Handler", string.Format("Latency: {0:F2}ms, RTT buffer: {1}", this.Latency, this.rtts.ToString()), this.Context); } + + BufferPool.Release(pingFrame.OpaqueData); break; case HTTP2FrameTypes.GOAWAY: // Just exit from this thread. The processing thread will handle the frame too. + + // Risking a double release here if the processing thread also consumed the goaway frame + //if (Volatile.Read(ref this.threadExitCount) > 0) + // BufferPool.Release(header.Payload); return; } } @@ -555,15 +587,24 @@ private void TryToCleanup() // First thread closing notifies the ConnectionEventHelper int counter = Interlocked.Increment(ref this.threadExitCount); - if (counter == 1) - ConnectionEventHelper.EnqueueConnectionEvent(new ConnectionEventInfo(this.conn, HTTPConnectionStates.Closed)); - - // Last thread closes the AutoResetEvent - if (counter == 2) + switch(counter) { - if (this.newFrameSignal != null) - this.newFrameSignal.Close(); - this.newFrameSignal = null; + case 1: + ConnectionEventHelper.EnqueueConnectionEvent(new ConnectionEventInfo(this.conn, HTTPConnectionStates.Closed)); + break; + + // Last thread closes the AutoResetEvent + case 2: + if (this.newFrameSignal != null) + this.newFrameSignal.Close(); + this.newFrameSignal = null; + + while (this.newFrames.TryDequeue(out var frame)) + BufferPool.Release(frame.Payload); + break; + default: + HTTPManager.Logger.Warning("HTTP2Handler", String.Format("TryToCleanup - counter is {0}!", counter)); + break; } } diff --git a/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2PluginSettings.cs b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2PluginSettings.cs index fe0fd30..ea8b1c0 100644 --- a/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2PluginSettings.cs +++ b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2PluginSettings.cs @@ -56,7 +56,7 @@ public sealed class HTTP2PluginSettings /// /// Time between two ping messages. /// - public TimeSpan PingFrequency = TimeSpan.FromSeconds(5); + public TimeSpan PingFrequency = TimeSpan.FromSeconds(30); /// /// Timeout to receive a ping acknowledgement from the server. If no ack reveived in this time the connection will be treated as broken. @@ -68,6 +68,9 @@ public sealed class HTTP2PluginSettings /// public bool EnableConnectProtocol = false; + /// + /// Settings for WebSockets over HTTP/2 (RFC 8441) + /// public WebSocketOverHTTP2Settings WebSocketOverHTTP2Settings = new WebSocketOverHTTP2Settings(); } } diff --git a/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2Response.cs b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2Response.cs index e97a4ef..f1b1885 100644 --- a/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2Response.cs +++ b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2Response.cs @@ -13,7 +13,12 @@ public sealed class HTTP2Response : HTTPResponse { // For progress report public long ExpectedContentLength { get; private set; } - public bool IsCompressed { get; private set; } + public bool HasContentEncoding { get => !string.IsNullOrEmpty(this.contentEncoding); } + + private string contentEncoding = null; + + bool isPrepared; + private Decompression.IDecompressor decompressor; public HTTP2Response(HTTPRequest request, bool isFromCache) : base(request, isFromCache) @@ -38,9 +43,9 @@ internal void AddHeaders(List> headers) } else { - if (!this.IsCompressed && header.Key.Equals("content-encoding", StringComparison.OrdinalIgnoreCase)) + if (!this.HasContentEncoding && header.Key.Equals("content-encoding", StringComparison.OrdinalIgnoreCase)) { - this.IsCompressed = true; + this.contentEncoding = header.Value; } else if (base.baseRequest.OnDownloadProgress != null && header.Key.Equals("content-length", StringComparison.OrdinalIgnoreCase)) { @@ -72,13 +77,20 @@ internal void AddHeaders(List> headers) internal void AddData(Stream stream) { - if (this.IsCompressed) + if (this.HasContentEncoding) { - using (var decoderStream = new Decompression.Zlib.GZipStream(stream, Decompression.Zlib.CompressionMode.Decompress)) + Stream decoderStream = Decompression.DecompressorFactory.GetDecoderStream(stream, this.contentEncoding); + + if (decoderStream == null) + { + base.Data = new byte[stream.Length]; + stream.Read(base.Data, 0, (int)stream.Length); + } + else { using (var ms = new BufferPoolMemoryStream((int)stream.Length)) { - var buf = BufferPool.Get(8 * 1024, true); + var buf = BufferPool.Get(HTTPResponse.MinReadBufferSize, true); int byteCount = 0; while ((byteCount = decoderStream.Read(buf, 0, buf.Length)) > 0) @@ -88,18 +100,18 @@ internal void AddData(Stream stream) base.Data = ms.ToArray(); } + + decoderStream.Dispose(); } } else { - base.Data = BufferPool.Get(stream.Length, false); + base.Data = new byte[stream.Length]; stream.Read(base.Data, 0, (int)stream.Length); } } - bool isPrepared; - private Decompression.GZipDecompressor decompressor; - + internal void ProcessData(byte[] payload, int payloadLength) { if (!this.isPrepared) @@ -108,10 +120,10 @@ internal void ProcessData(byte[] payload, int payloadLength) base.BeginReceiveStreamFragments(); } - if (this.IsCompressed) + if (this.HasContentEncoding) { if (this.decompressor == null) - this.decompressor = new Decompression.GZipDecompressor(0); + this.decompressor = Decompression.DecompressorFactory.GetDecompressor(this.contentEncoding, this.Context); var result = this.decompressor.Decompress(payload, 0, payloadLength, true, true); base.FeedStreamFragment(result.Data, 0, result.Length); diff --git a/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2Stream.cs b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2Stream.cs index e39d675..01d0a66 100644 --- a/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2Stream.cs +++ b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2Stream.cs @@ -46,21 +46,21 @@ public enum HTTP2StreamStates Closed } - public sealed class HTTP2Stream + public class HTTP2Stream { public UInt32 Id { get; private set; } public HTTP2StreamStates State { get { return this._state; } - private set { + protected set { var oldState = this._state; this._state = value; if (oldState != this._state) { - this.lastStateChangedAt = DateTime.Now; + //this.lastStateChangedAt = DateTime.Now; HTTPManager.Logger.Information("HTTP2Stream", string.Format("[{0}] State changed from {1} to {2}", this.Id, oldState, this._state), this.Context, this.AssignedRequest.Context, this.parent.Context); } @@ -68,13 +68,13 @@ private set { } private HTTP2StreamStates _state; - private DateTime lastStateChangedAt; - //private TimeSpan TimeSpentInCurrentState { get { return DateTime.Now - this.lastStateChangedAt; } } + //protected DateTime lastStateChangedAt; + //protected TimeSpan TimeSpentInCurrentState { get { return DateTime.Now - this.lastStateChangedAt; } } /// /// This flag is checked by the connection to decide whether to do a new processing-frame sending round before sleeping until new data arrives /// - public bool HasFrameToSend + public virtual bool HasFrameToSend { get { @@ -84,41 +84,46 @@ public bool HasFrameToSend } } - public HTTPRequest AssignedRequest { get; private set; } + /// + /// Next interaction scheduled by the stream relative to *now*. Its default is TimeSpan.MaxValue == no interaction. + /// + public virtual TimeSpan NextInteraction { get; } = TimeSpan.MaxValue; - public LoggingContext Context { get; private set; } + public HTTPRequest AssignedRequest { get; protected set; } - private bool isStreamedDownload; - private uint downloaded; + public LoggingContext Context { get; protected set; } - private HTTPRequest.UploadStreamInfo uploadStreamInfo; + protected bool isStreamedDownload; + protected uint downloaded; - private HTTP2SettingsManager settings; - private HPACKEncoder encoder; + protected HTTPRequest.UploadStreamInfo uploadStreamInfo; + + protected HTTP2SettingsManager settings; + protected HPACKEncoder encoder; // Outgoing frames. The stream will send one frame per Process call, but because one step might be able to // generate more than one frames, we use a list. - private Queue outgoing = new Queue(); + protected Queue outgoing = new Queue(); - private Queue incomingFrames = new Queue(); + protected Queue incomingFrames = new Queue(); - private FramesAsStreamView headerView; - private FramesAsStreamView dataView; + protected FramesAsStreamView headerView; + protected FramesAsStreamView dataView; - private UInt32 localWindow; - private Int64 remoteWindow; + protected UInt32 localWindow; + protected Int64 remoteWindow; - private uint windowUpdateThreshold; + protected uint windowUpdateThreshold; - private UInt32 sentData; + protected UInt32 sentData; - private bool isRSTFrameSent; - private bool isEndSTRReceived; + protected bool isRSTFrameSent; + protected bool isEndSTRReceived; - private HTTP2Response response; + protected HTTP2Response response; - private HTTP2Handler parent; - private int lastReadCount; + protected HTTP2Handler parent; + protected int lastReadCount; /// /// Constructor to create a client stream. @@ -140,7 +145,7 @@ public HTTP2Stream(UInt32 id, HTTP2Handler parentHandler, HTTP2SettingsManager r this.Context.Add("id", id); } - public void Assign(HTTPRequest request) + public virtual void Assign(HTTPRequest request) { if (request.IsRedirected) request.Timing.Add(TimingEventNames.Queued_For_Redirection); @@ -234,7 +239,7 @@ public void Abort(string msg) this.Removed(); } - private void ProcessIncomingFrames(List outgoingFrames) + protected void ProcessIncomingFrames(List outgoingFrames) { UInt32 windowUpdate = 0; @@ -289,6 +294,9 @@ private void ProcessIncomingFrames(List outgoingFram HTTPManager.Logger.Exception("HTTP2Stream", string.Format("[{0}] ProcessIncomingFrames - Header Frames: {1}, Encoder: {2}", this.Id, this.headerView.ToString(), this.encoder.ToString()), ex, this.Context, this.AssignedRequest.Context, this.parent.Context); } + this.headerView.Close(); + this.headerView = null; + this.AssignedRequest.Timing.Add(TimingEventNames.Headers); if (this.isRSTFrameSent) @@ -302,9 +310,6 @@ private void ProcessIncomingFrames(List outgoingFram this.response.AddHeaders(headers); - this.headerView.Close(); - this.headerView = null; - if (this.isEndSTRReceived) { // If there's any trailing header, no data frame has an END_STREAM flag @@ -324,69 +329,7 @@ private void ProcessIncomingFrames(List outgoingFram break; case HTTP2FrameTypes.DATA: - if (this.State != HTTP2StreamStates.HalfClosedLocal && this.State != HTTP2StreamStates.Open) - { - // ERROR! - continue; - } - - this.downloaded += frame.PayloadLength; - - if (this.isStreamedDownload && frame.Payload != null && frame.PayloadLength > 0) - this.response.ProcessData(frame.Payload, (int)frame.PayloadLength); - - // frame's buffer will be released by the frames view - frame.DontUseMemPool = !this.isStreamedDownload; - - if (this.dataView == null && !this.isStreamedDownload) - this.dataView = new FramesAsStreamView(new DataFrameView()); - - if (!this.isStreamedDownload) - this.dataView.AddFrame(frame); - - // Track received data, and if necessary(local window getting too low), send a window update frame - if (this.localWindow < frame.PayloadLength) - { - HTTPManager.Logger.Error("HTTP2Stream", string.Format("[{0}] Frame's PayloadLength ({1:N0}) is larger then local window ({2:N0}). Frame: {3}", this.Id, frame.PayloadLength, this.localWindow, frame), this.Context, this.AssignedRequest.Context, this.parent.Context); - } - else - this.localWindow -= frame.PayloadLength; - - if ((frame.Flags & (byte)HTTP2DataFlags.END_STREAM) != 0) - this.isEndSTRReceived = true; - - // Window update logic. - // 1.) We could use a logic to only send window update(s) after a threshold is reached. - // When the initial window size is high enough to contain the whole or most of the result, - // sending back two window updates (connection and stream) after every data frame is pointless. - // 2.) On the other hand, window updates are cheap and works even when initial window size is low. - // ( - if (this.isEndSTRReceived || this.localWindow <= this.windowUpdateThreshold) - windowUpdate += this.settings.MySettings[HTTP2Settings.INITIAL_WINDOW_SIZE] - this.localWindow - windowUpdate; - - if (this.isEndSTRReceived) - { - if (this.isStreamedDownload) - this.response.FinishProcessData(); - - HTTPManager.Logger.Information("HTTP2Stream", string.Format("[{0}] All data arrived, data length: {1:N0}", this.Id, this.downloaded), this.Context, this.AssignedRequest.Context, this.parent.Context); - - // create a short living thread to process the downloaded data: - PlatformSupport.Threading.ThreadedRunner.RunShortLiving(FinishRequest, this, this.dataView); - - this.dataView = null; - - if (this.State == HTTP2StreamStates.HalfClosedLocal) - this.State = HTTP2StreamStates.Closed; - else - this.State = HTTP2StreamStates.HalfClosedRemote; - } - else if (this.AssignedRequest.OnDownloadProgress != null) - RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(this.AssignedRequest, - RequestEvents.DownloadProgress, - downloaded, - this.response.ExpectedContentLength)); - + ProcessIncomingDATAFrame(ref frame, ref windowUpdate); break; case HTTP2FrameTypes.WINDOW_UPDATE: @@ -421,7 +364,7 @@ private void ProcessIncomingFrames(List outgoingFram BufferPool.Release(frame.Payload); } - if (windowUpdate > 0) + if (windowUpdate > 0 && this.State != HTTP2StreamStates.Closed) { if (HTTPManager.Logger.Level <= Logger.Loglevels.All) HTTPManager.Logger.Information("HTTP2Stream", string.Format("[{0}] Sending window update: {1:N0}, current window: {2:N0}, initial window size: {3:N0}", this.Id, windowUpdate, this.localWindow, this.settings.MySettings[HTTP2Settings.INITIAL_WINDOW_SIZE]), this.Context, this.AssignedRequest.Context, this.parent.Context); @@ -432,7 +375,73 @@ private void ProcessIncomingFrames(List outgoingFram } } - private void ProcessState(List outgoingFrames) + protected virtual void ProcessIncomingDATAFrame(ref HTTP2FrameHeaderAndPayload frame, ref uint windowUpdate) + { + if (this.State != HTTP2StreamStates.HalfClosedLocal && this.State != HTTP2StreamStates.Open) + { + // ERROR! + return; + } + + this.downloaded += frame.PayloadLength; + + if (this.isStreamedDownload && frame.Payload != null && frame.PayloadLength > 0) + this.response.ProcessData(frame.Payload, (int)frame.PayloadLength); + + // frame's buffer will be released by the frames view + frame.DontUseMemPool = !this.isStreamedDownload; + + if (this.dataView == null && !this.isStreamedDownload) + this.dataView = new FramesAsStreamView(new DataFrameView()); + + if (!this.isStreamedDownload) + this.dataView.AddFrame(frame); + + // Track received data, and if necessary(local window getting too low), send a window update frame + if (this.localWindow < frame.PayloadLength) + { + HTTPManager.Logger.Error("HTTP2Stream", string.Format("[{0}] Frame's PayloadLength ({1:N0}) is larger then local window ({2:N0}). Frame: {3}", this.Id, frame.PayloadLength, this.localWindow, frame), this.Context, this.AssignedRequest.Context, this.parent.Context); + } + else + this.localWindow -= frame.PayloadLength; + + if ((frame.Flags & (byte)HTTP2DataFlags.END_STREAM) != 0) + this.isEndSTRReceived = true; + + // Window update logic. + // 1.) We could use a logic to only send window update(s) after a threshold is reached. + // When the initial window size is high enough to contain the whole or most of the result, + // sending back two window updates (connection and stream) after every data frame is pointless. + // 2.) On the other hand, window updates are cheap and works even when initial window size is low. + // ( + if (this.isEndSTRReceived || this.localWindow <= this.windowUpdateThreshold) + windowUpdate += this.settings.MySettings[HTTP2Settings.INITIAL_WINDOW_SIZE] - this.localWindow - windowUpdate; + + if (this.isEndSTRReceived) + { + if (this.isStreamedDownload) + this.response.FinishProcessData(); + + HTTPManager.Logger.Information("HTTP2Stream", string.Format("[{0}] All data arrived, data length: {1:N0}", this.Id, this.downloaded), this.Context, this.AssignedRequest.Context, this.parent.Context); + + // create a short living thread to process the downloaded data: + PlatformSupport.Threading.ThreadedRunner.RunShortLiving(FinishRequest, this, this.dataView); + + this.dataView = null; + + if (this.State == HTTP2StreamStates.HalfClosedLocal) + this.State = HTTP2StreamStates.Closed; + else + this.State = HTTP2StreamStates.HalfClosedRemote; + } + else if (this.AssignedRequest.OnDownloadProgress != null) + RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(this.AssignedRequest, + RequestEvents.DownloadProgress, + downloaded, + this.response.ExpectedContentLength)); + } + + protected void ProcessState(List outgoingFrames) { switch (this.State) { @@ -473,76 +482,80 @@ private void ProcessState(List outgoingFrames) break; case HTTP2StreamStates.Open: - // remote Window can be negative! See https://httpwg.org/specs/rfc7540.html#InitialWindowSize - if (this.remoteWindow <= 0) - { - HTTPManager.Logger.Information("HTTP2Stream", string.Format("[{0}] Skipping data sending as remote Window is {1}!", this.Id, this.remoteWindow), this.Context, this.AssignedRequest.Context, this.parent.Context); - return; - } + ProcessOpenState(outgoingFrames); + //HTTPManager.Logger.Information("HTTP2Stream", string.Format("[{0}] New DATA frame created! remoteWindow: {1:N0}", this.Id, this.remoteWindow), this.Context, this.AssignedRequest.Context, this.parent.Context); + break; - // This step will send one frame per OpenState call. + case HTTP2StreamStates.HalfClosedLocal: + break; - Int64 maxFrameSize = Math.Min(this.remoteWindow, this.settings.RemoteSettings[HTTP2Settings.MAX_FRAME_SIZE]); + case HTTP2StreamStates.HalfClosedRemote: + break; - HTTP2FrameHeaderAndPayload frame = new HTTP2FrameHeaderAndPayload(); - frame.Type = HTTP2FrameTypes.DATA; - frame.StreamId = this.Id; + case HTTP2StreamStates.Closed: + break; + } + } - frame.Payload = BufferPool.Get(maxFrameSize, true); + protected virtual void ProcessOpenState(List outgoingFrames) + { + // remote Window can be negative! See https://httpwg.org/specs/rfc7540.html#InitialWindowSize + if (this.remoteWindow <= 0) + { + HTTPManager.Logger.Information("HTTP2Stream", string.Format("[{0}] Skipping data sending as remote Window is {1}!", this.Id, this.remoteWindow), this.Context, this.AssignedRequest.Context, this.parent.Context); + return; + } - // Expect a readCount of zero if it's end of the stream. But, to enable non-blocking scenario to wait for data, going to treat a negative value as no data. - this.lastReadCount = this.uploadStreamInfo.Stream.Read(frame.Payload, 0, (int)Math.Min(maxFrameSize, int.MaxValue)); - if (this.lastReadCount <= 0) - { - BufferPool.Release(frame.Payload); - frame.Payload = null; - frame.PayloadLength = 0; + // This step will send one frame per OpenState call. - if (this.lastReadCount < 0) - break; - } - else - frame.PayloadLength = (UInt32)this.lastReadCount; + Int64 maxFrameSize = Math.Min(HTTPRequest.UploadChunkSize, Math.Min(this.remoteWindow, this.settings.RemoteSettings[HTTP2Settings.MAX_FRAME_SIZE])); - frame.PayloadOffset = 0; - frame.DontUseMemPool = false; + HTTP2FrameHeaderAndPayload frame = new HTTP2FrameHeaderAndPayload(); + frame.Type = HTTP2FrameTypes.DATA; + frame.StreamId = this.Id; - if (this.lastReadCount <= 0) - { - this.uploadStreamInfo.Stream.Dispose(); - this.uploadStreamInfo = new HTTPRequest.UploadStreamInfo(); + frame.Payload = BufferPool.Get(maxFrameSize, true); - frame.Flags = (byte)(HTTP2DataFlags.END_STREAM); + // Expect a readCount of zero if it's end of the stream. But, to enable non-blocking scenario to wait for data, going to treat a negative value as no data. + this.lastReadCount = this.uploadStreamInfo.Stream.Read(frame.Payload, 0, (int)Math.Min(maxFrameSize, int.MaxValue)); + if (this.lastReadCount <= 0) + { + BufferPool.Release(frame.Payload); + frame.Payload = null; + frame.PayloadLength = 0; - this.State = HTTP2StreamStates.HalfClosedLocal; + if (this.lastReadCount < 0) + return; + } + else + frame.PayloadLength = (UInt32)this.lastReadCount; - this.AssignedRequest.Timing.Add(TimingEventNames.Request_Sent); - } + frame.PayloadOffset = 0; + frame.DontUseMemPool = false; - this.outgoing.Enqueue(frame); + if (this.lastReadCount <= 0) + { + this.uploadStreamInfo.Stream.Dispose(); + this.uploadStreamInfo = new HTTPRequest.UploadStreamInfo(); - this.remoteWindow -= frame.PayloadLength; + frame.Flags = (byte)(HTTP2DataFlags.END_STREAM); - this.sentData += frame.PayloadLength; + this.State = HTTP2StreamStates.HalfClosedLocal; - if (this.AssignedRequest.OnUploadProgress != null) - RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(this.AssignedRequest, RequestEvents.UploadProgress, this.sentData, this.uploadStreamInfo.Length)); + this.AssignedRequest.Timing.Add(TimingEventNames.Request_Sent); + } - //HTTPManager.Logger.Information("HTTP2Stream", string.Format("[{0}] New DATA frame created! remoteWindow: {1:N0}", this.Id, this.remoteWindow), this.Context, this.AssignedRequest.Context, this.parent.Context); - break; + this.outgoing.Enqueue(frame); - case HTTP2StreamStates.HalfClosedLocal: - break; + this.remoteWindow -= frame.PayloadLength; - case HTTP2StreamStates.HalfClosedRemote: - break; + this.sentData += frame.PayloadLength; - case HTTP2StreamStates.Closed: - break; - } + if (this.AssignedRequest.OnUploadProgress != null) + RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(this.AssignedRequest, RequestEvents.UploadProgress, this.sentData, this.uploadStreamInfo.Length)); } - private void OnRemoteSettingChanged(HTTP2SettingsRegistry registry, HTTP2Settings setting, uint oldValue, uint newValue) + protected void OnRemoteSettingChanged(HTTP2SettingsRegistry registry, HTTP2Settings setting, uint oldValue, uint newValue) { switch (setting) { @@ -578,37 +591,44 @@ private void OnRemoteSettingChanged(HTTP2SettingsRegistry registry, HTTP2Setting } } - private static void FinishRequest(HTTP2Stream stream, FramesAsStreamView dataStream) + protected static void FinishRequest(HTTP2Stream stream, FramesAsStreamView dataStream) { - if (dataStream != null) + try { - try - { - stream.response.AddData(dataStream); - } - finally + if (dataStream != null) { - dataStream.Close(); + try + { + stream.response.AddData(dataStream); + } + finally + { + dataStream.Close(); + } } - } - stream.AssignedRequest.Timing.Add(TimingEventNames.Response_Received); + stream.AssignedRequest.Timing.Add(TimingEventNames.Response_Received); - bool resendRequest; - HTTPConnectionStates proposedConnectionStates; // ignored - KeepAliveHeader keepAliveHeader = null; // ignored + bool resendRequest; + HTTPConnectionStates proposedConnectionStates; // ignored + KeepAliveHeader keepAliveHeader = null; // ignored - ConnectionHelper.HandleResponse("HTTP2Stream", stream.AssignedRequest, out resendRequest, out proposedConnectionStates, ref keepAliveHeader, stream.Context, stream.AssignedRequest.Context); + ConnectionHelper.HandleResponse("HTTP2Stream", stream.AssignedRequest, out resendRequest, out proposedConnectionStates, ref keepAliveHeader, stream.Context, stream.AssignedRequest.Context); - if (resendRequest && !stream.AssignedRequest.IsCancellationRequested) - RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(stream.AssignedRequest, RequestEvents.Resend)); - else if (stream.AssignedRequest.State == HTTPRequestStates.Processing && !stream.AssignedRequest.IsCancellationRequested) - stream.AssignedRequest.State = HTTPRequestStates.Finished; - else + if (resendRequest && !stream.AssignedRequest.IsCancellationRequested) + RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(stream.AssignedRequest, RequestEvents.Resend)); + else if (stream.AssignedRequest.State == HTTPRequestStates.Processing && !stream.AssignedRequest.IsCancellationRequested) + stream.AssignedRequest.State = HTTPRequestStates.Finished; + else + { + // Already set in HTTPRequest's Abort(). + //if (stream.AssignedRequest.State == HTTPRequestStates.Processing && stream.AssignedRequest.IsCancellationRequested) + // stream.AssignedRequest.State = stream.AssignedRequest.IsTimedOut ? HTTPRequestStates.TimedOut : HTTPRequestStates.Aborted; + } + } + catch(Exception ex) { - // Already set in HTTPRequest's Abort(). - //if (stream.AssignedRequest.State == HTTPRequestStates.Processing && stream.AssignedRequest.IsCancellationRequested) - // stream.AssignedRequest.State = stream.AssignedRequest.IsTimedOut ? HTTPRequestStates.TimedOut : HTTPRequestStates.Aborted; + HTTPManager.Logger.Exception("HTTP2Stream", "FinishRequest", ex, stream.AssignedRequest.Context); } } diff --git a/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2WebSocketStream.cs b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2WebSocketStream.cs new file mode 100644 index 0000000..440b923 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2WebSocketStream.cs @@ -0,0 +1,185 @@ +#if (!UNITY_WEBGL || UNITY_EDITOR) && !BESTHTTP_DISABLE_ALTERNATE_SSL && !BESTHTTP_DISABLE_HTTP2 && !BESTHTTP_DISABLE_WEBSOCKET +using System; +using System.Collections.Generic; + +using BestHTTP.Extensions; +using BestHTTP.PlatformSupport.Memory; +using BestHTTP.WebSocket; + +namespace BestHTTP.Connections.HTTP2 +{ + public sealed class HTTP2WebSocketStream : HTTP2Stream + { + public override bool HasFrameToSend + { + get + { + // Don't let the connection sleep until + return this.outgoing.Count > 0 || // we already booked at least one frame in advance + (this.State == HTTP2StreamStates.Open && + this.remoteWindow > 0 && + this.lastReadCount > 0 && + (this.overHTTP2.frames.Count > 0 || this.chunkQueue.Count > 0)); // we are in the middle of sending request data + } + } + + public override TimeSpan NextInteraction => this.overHTTP2.GetNextInteraction(); + + private OverHTTP2 overHTTP2; + + // local list of websocket header-data pairs + private List> chunkQueue = new List>(); + + public HTTP2WebSocketStream(uint id, HTTP2Handler parentHandler, HTTP2SettingsManager registry, HPACKEncoder hpackEncoder) : base(id, parentHandler, registry, hpackEncoder) + { + } + + public override void Assign(HTTPRequest request) + { + base.Assign(request); + + this.overHTTP2 = request.Tag as OverHTTP2; + this.overHTTP2.SetHTTP2Handler(this.parent); + } + + protected override void ProcessIncomingDATAFrame(ref HTTP2FrameHeaderAndPayload frame, ref uint windowUpdate) + { + try + { + if (this.State != HTTP2StreamStates.HalfClosedLocal && this.State != HTTP2StreamStates.Open) + { + // ERROR! + return; + } + + this.downloaded += frame.PayloadLength; + + this.overHTTP2.OnReadThread(frame.Payload.AsBuffer((int)frame.PayloadOffset, (int)frame.PayloadLength)); + + // frame's buffer will be released later + frame.DontUseMemPool = true; + + // Track received data, and if necessary(local window getting too low), send a window update frame + if (this.localWindow < frame.PayloadLength) + { + HTTPManager.Logger.Error(nameof(HTTP2WebSocketStream), string.Format("[{0}] Frame's PayloadLength ({1:N0}) is larger then local window ({2:N0}). Frame: {3}", this.Id, frame.PayloadLength, this.localWindow, frame), this.Context, this.AssignedRequest.Context, this.parent.Context); + } + else + this.localWindow -= frame.PayloadLength; + + if ((frame.Flags & (byte)HTTP2DataFlags.END_STREAM) != 0) + this.isEndSTRReceived = true; + + if (this.isEndSTRReceived) + { + HTTPManager.Logger.Information(nameof(HTTP2WebSocketStream), string.Format("[{0}] All data arrived, data length: {1:N0}", this.Id, this.downloaded), this.Context, this.AssignedRequest.Context, this.parent.Context); + + // create a short living thread to process the downloaded data: + PlatformSupport.Threading.ThreadedRunner.RunShortLiving(FinishRequest, this, this.dataView); + + this.dataView = null; + + if (this.State == HTTP2StreamStates.HalfClosedLocal) + this.State = HTTP2StreamStates.Closed; + else + this.State = HTTP2StreamStates.HalfClosedRemote; + } + + if (this.isEndSTRReceived || this.localWindow <= this.windowUpdateThreshold) + windowUpdate += this.settings.MySettings[HTTP2Settings.INITIAL_WINDOW_SIZE] - this.localWindow - windowUpdate; + } + catch (Exception ex) + { + HTTPManager.Logger.Exception(nameof(HTTP2WebSocketStream), nameof(ProcessIncomingDATAFrame), ex, this.parent.Context); + } + } + + protected override void ProcessOpenState(List outgoingFrames) + { + try + { + // remote Window can be negative! See https://httpwg.org/specs/rfc7540.html#InitialWindowSize + if (this.remoteWindow <= 0) + { + HTTPManager.Logger.Information(nameof(HTTP2WebSocketStream), string.Format("[{0}] Skipping data sending as remote Window is {1}!", this.Id, this.remoteWindow), this.Context, this.AssignedRequest.Context, this.parent.Context); + return; + } + + this.overHTTP2.PreReadCallback(); + + Int64 maxFragmentSize = Math.Min(BestHTTP.WebSocket.WebSocket.MaxFragmentSize, this.settings.RemoteSettings[HTTP2Settings.MAX_FRAME_SIZE]); + Int64 maxFrameSize = Math.Min(maxFragmentSize, this.remoteWindow); + + if (chunkQueue.Count == 0) + { + if (this.overHTTP2.frames.TryDequeue(out var frame)) + { + this.overHTTP2._bufferedAmount -= (int)frame.Data.Count; + + frame.WriteTo((header, data) => chunkQueue.Add(new KeyValuePair(header, data)), (uint)maxFragmentSize, false, this.Context); + } + } + + while (this.remoteWindow >= 6 && chunkQueue.Count > 0) + { + var kvp = chunkQueue[0]; + + BufferSegment header = kvp.Key; + BufferSegment data = kvp.Value; + + int minBytes = header.Count; + int maxBytes = minBytes + data.Count; + + // remote window is less than the minimum we have to send, or + // the frame has data but we have space only to send the websocket header + if (this.remoteWindow < minBytes || (maxBytes > minBytes && this.remoteWindow == minBytes)) + return; + + HTTP2FrameHeaderAndPayload headerFrame = new HTTP2FrameHeaderAndPayload(); + headerFrame.Type = HTTP2FrameTypes.DATA; + headerFrame.StreamId = this.Id; + headerFrame.PayloadOffset = (uint)header.Offset; + headerFrame.PayloadLength = (uint)header.Count; + headerFrame.Payload = header.Data; + headerFrame.DontUseMemPool = false; + + if (data.Count > 0) + { + HTTP2FrameHeaderAndPayload dataFrame = new HTTP2FrameHeaderAndPayload(); + dataFrame.Type = HTTP2FrameTypes.DATA; + dataFrame.StreamId = this.Id; + + var buff = data.Slice(data.Offset, (int)Math.Min(data.Count, maxFrameSize)); + dataFrame.PayloadOffset = (uint)buff.Offset; + dataFrame.PayloadLength = (uint)buff.Count; + dataFrame.Payload = buff.Data; + + data = data.Slice(buff.Offset + buff.Count); + if (data.Count == 0) + chunkQueue.RemoveAt(0); + else + chunkQueue[0] = new KeyValuePair(header, data); + + // release the buffer only with the final frame and with the final frame's last data chunk + bool isLast = (header.Data[header.Offset] & 0x7F) != 0 && chunkQueue.Count == 0; + headerFrame.DontUseMemPool = dataFrame.DontUseMemPool = !isLast; + + this.outgoing.Enqueue(headerFrame); + this.outgoing.Enqueue(dataFrame); + } + else + { + this.outgoing.Enqueue(headerFrame); + chunkQueue.RemoveAt(0); + } + } + } + catch (Exception ex) + { + HTTPManager.Logger.Exception(nameof(HTTP2WebSocketStream), nameof(ProcessOpenState), ex, this.parent.Context); + } + } + } +} + +#endif diff --git a/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2WebSocketStream.cs.meta b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2WebSocketStream.cs.meta new file mode 100644 index 0000000..a7181e4 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HTTP2WebSocketStream.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 70dfdb0b300f8494cbfe6474037178d8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/Connections/HTTP2/HeaderTable.cs b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HeaderTable.cs index 9efa32a..a5e6909 100644 --- a/Assets/URS/Best HTTP/Source/Connections/HTTP2/HeaderTable.cs +++ b/Assets/URS/Best HTTP/Source/Connections/HTTP2/HeaderTable.cs @@ -183,14 +183,15 @@ private void EvictEntries(uint newHeaderSize) public override string ToString() { - System.Text.StringBuilder sb = new System.Text.StringBuilder("[HeaderTable "); + System.Text.StringBuilder sb = PlatformSupport.Text.StringBuilderPool.Get(this.DynamicTable.Count + 3); + sb.Append("[HeaderTable "); sb.AppendFormat("DynamicTable count: {0}, DynamicTableSize: {1}, MaxDynamicTableSize: {2}, ", this.DynamicTable.Count, this.DynamicTableSize, this.MaxDynamicTableSize); foreach(var kvp in this.DynamicTable) sb.AppendFormat("\"{0}\": \"{1}\", ", kvp.Key, kvp.Value); sb.Append("]"); - return sb.ToString(); + return PlatformSupport.Text.StringBuilderPool.ReleaseAndGrab(sb); } } } diff --git a/Assets/URS/Best HTTP/Source/Connections/HTTPConnection.cs b/Assets/URS/Best HTTP/Source/Connections/HTTPConnection.cs index eced4c8..52535b0 100644 --- a/Assets/URS/Best HTTP/Source/Connections/HTTPConnection.cs +++ b/Assets/URS/Best HTTP/Source/Connections/HTTPConnection.cs @@ -63,20 +63,30 @@ public override bool TestConnection() try { #if !BESTHTTP_DISABLE_ALTERNATE_SSL - if (this.connector.Client.Available > 0) + TlsStream stream = (this.connector?.Stream as TlsStream); + if (stream != null && stream.Protocol != null) { - TlsStream stream = (this.connector.Stream as TlsStream); - if (stream != null) + bool locked = stream.Protocol.TryEnterApplicationDataLock(0); + try { - try + if (locked && this.connector.Client.Available > 0) { - var available = stream.Protocol.TestApplicationData(); - return !stream.Protocol.IsClosed; - } - catch { - return false; + try + { + var available = stream.Protocol.TestApplicationData(); + return !stream.Protocol.IsClosed; + } + catch + { + return false; + } } } + finally + { + if (locked) + stream.Protocol.ExitApplicationDataLock(); + } } #endif diff --git a/Assets/URS/Best HTTP/Source/Connections/TCPConnector.cs b/Assets/URS/Best HTTP/Source/Connections/TCPConnector.cs index bfb9d24..0718a4b 100644 --- a/Assets/URS/Best HTTP/Source/Connections/TCPConnector.cs +++ b/Assets/URS/Best HTTP/Source/Connections/TCPConnector.cs @@ -10,6 +10,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls; using BestHTTP.Connections.TLS; +using System.Threading; #endif #if NETFX_CORE @@ -19,7 +20,7 @@ using TcpClient = BestHTTP.PlatformSupport.TcpClient.WinRT.TcpClient; //Disable CD4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call. -#pragma warning disable 4014 + #pragma warning disable 4014 #else using TcpClient = BestHTTP.PlatformSupport.TcpClient.General.TcpClient; using System.Security.Cryptography.X509Certificates; @@ -48,7 +49,7 @@ public void Connect(HTTPRequest request) string negotiatedProtocol = HTTPProtocolFactory.W3C_HTTP1; Uri uri = -#if !BESTHTTP_DISABLE_PROXY +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) request.HasProxy ? request.Proxy.Address : #endif request.CurrentUri; @@ -184,7 +185,7 @@ public void Connect(HTTPRequest request) /*if (Stream.CanTimeout) Stream.ReadTimeout = Stream.WriteTimeout = (int)Request.Timeout.TotalMilliseconds;*/ -#if !BESTHTTP_DISABLE_PROXY +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) if (request.HasProxy) { try @@ -284,7 +285,36 @@ public void Connect(HTTPRequest request) }); if (!sslStream.IsAuthenticated) + { +#if !BESTHTTP_DISABLE_HTTP2 && !BESTHTTP_DISABLE_ALTERNATE_SSL && false + List protocols = new List(); + SupportedProtocols protocol = HTTPProtocolFactory.GetProtocolFromUri(request.CurrentUri); + if (protocol == SupportedProtocols.HTTP && request.IsKeepAlive) + { + // http/2 over tls (https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids) + protocols.Add(new SslApplicationProtocol(HTTPProtocolFactory.W3C_HTTP2)); + } + protocols.Add(new SslApplicationProtocol(HTTPProtocolFactory.W3C_HTTP1)); + + SslClientAuthenticationOptions options = new SslClientAuthenticationOptions(); + options.ApplicationProtocols = protocols; + options.TargetHost = request.CurrentUri.Host; + var task = sslStream.AuthenticateAsClientAsync(options, default(System.Threading.CancellationToken)); + task.Wait(); + + try + { + negotiatedProtocol = System.Text.Encoding.UTF8.GetString(sslStream.NegotiatedApplicationProtocol.Protocol.Span); + } + catch (Exception ex) + { + HTTPManager.Logger.Exception(nameof(TCPConnector), "Accessing SslStream's NegotiatedApplicationProtocol throwed an exception, falling back using HTTP/1.1", ex, request.Context); + negotiatedProtocol = HTTPProtocolFactory.W3C_HTTP1; + } +#else sslStream.AuthenticateAsClient(request.CurrentUri.Host); +#endif + } Stream = sslStream; #else Stream = Client.GetStream(); @@ -314,6 +344,17 @@ public void Close() Stream = null; } + try + { + if (TopmostStream != null) + TopmostStream.Close(); + } + catch { } + finally + { + TopmostStream = null; + } + try { Client.Close(); diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/AbstractTls13Client.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/AbstractTls13Client.cs index 31d0bb1..637bbfc 100644 --- a/Assets/URS/Best HTTP/Source/Connections/TLS/AbstractTls13Client.cs +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/AbstractTls13Client.cs @@ -65,8 +65,8 @@ protected AbstractTls13Client(HTTPRequest request, List sniServerNam // (Abstract)TLSClient facing functions protected override ProtocolVersion[] GetSupportedVersions() => ProtocolVersion.TLSv13.DownTo(ProtocolVersion.TLSv12); - protected override IList GetProtocolNames() => this._protocols; - protected override IList GetSniServerNames() => this._sniServerNames; + protected override IList GetProtocolNames() => this._protocols; + protected override IList GetSniServerNames() => this._sniServerNames; protected override int[] GetSupportedCipherSuites() { HTTPManager.Logger.Information(nameof(AbstractTls13Client), $"{nameof(GetSupportedCipherSuites)}", this.Context); @@ -165,7 +165,7 @@ public override void NotifySessionToResume(TlsSession session) base.NotifySessionToResume(session); } - public override void ProcessServerExtensions(IDictionary serverExtensions) + public override void ProcessServerExtensions(IDictionary serverExtensions) { HTTPManager.Logger.Information(nameof(AbstractTls13Client), $"{nameof(ProcessServerExtensions)}", this.Context); diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/FastTlsCrypto.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/FastTlsCrypto.cs index 35dc88a..182b773 100644 --- a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/FastTlsCrypto.cs +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/FastTlsCrypto.cs @@ -71,17 +71,18 @@ public override TlsCipher CreateCipher(TlsCryptoParameters cryptoParams, int enc { // NOTE: Ignores macAlgorithm //return CreateCipher_Aes_Ccm(cryptoParams, 16, 16); - FastTlsAeadCipherImpl encrypt = new FastTlsAeadCipherImpl(CreateAeadBlockCipher_Aes_Ccm(), true); - FastTlsAeadCipherImpl decrypt = new FastTlsAeadCipherImpl(CreateAeadBlockCipher_Aes_Ccm(), false); - + FastTlsAeadCipherImpl encrypt = new FastTlsAeadCipherImpl(CreateAeadCipher_Aes_Ccm(), true); + FastTlsAeadCipherImpl decrypt = new FastTlsAeadCipherImpl(CreateAeadCipher_Aes_Ccm(), false); + return new FastTlsAeadCipher(cryptoParams, encrypt, decrypt, 16, 16, TlsAeadCipher.AEAD_CCM); + } case EncryptionAlgorithm.AES_128_CCM_8: { // NOTE: Ignores macAlgorithm //return CreateCipher_Aes_Ccm(cryptoParams, 16, 8); - FastTlsAeadCipherImpl encrypt = new FastTlsAeadCipherImpl(CreateAeadBlockCipher_Aes_Ccm(), true); - FastTlsAeadCipherImpl decrypt = new FastTlsAeadCipherImpl(CreateAeadBlockCipher_Aes_Ccm(), false); + FastTlsAeadCipherImpl encrypt = new FastTlsAeadCipherImpl(CreateAeadCipher_Aes_Ccm(), true); + FastTlsAeadCipherImpl decrypt = new FastTlsAeadCipherImpl(CreateAeadCipher_Aes_Ccm(), false); return new FastTlsAeadCipher(cryptoParams, encrypt, decrypt, 16, 8, TlsAeadCipher.AEAD_CCM); } @@ -89,8 +90,8 @@ public override TlsCipher CreateCipher(TlsCryptoParameters cryptoParams, int enc { // NOTE: Ignores macAlgorithm //return CreateCipher_Aes_Ccm(cryptoParams, 32, 16); - FastTlsAeadCipherImpl encrypt = new FastTlsAeadCipherImpl(CreateAeadBlockCipher_Aes_Ccm(), true); - FastTlsAeadCipherImpl decrypt = new FastTlsAeadCipherImpl(CreateAeadBlockCipher_Aes_Ccm(), false); + FastTlsAeadCipherImpl encrypt = new FastTlsAeadCipherImpl(CreateAeadCipher_Aes_Ccm(), true); + FastTlsAeadCipherImpl decrypt = new FastTlsAeadCipherImpl(CreateAeadCipher_Aes_Ccm(), false); return new FastTlsAeadCipher(cryptoParams, encrypt, decrypt, 32, 16, TlsAeadCipher.AEAD_CCM); } @@ -98,8 +99,8 @@ public override TlsCipher CreateCipher(TlsCryptoParameters cryptoParams, int enc { // NOTE: Ignores macAlgorithm //return CreateCipher_Aes_Ccm(cryptoParams, 32, 8); - FastTlsAeadCipherImpl encrypt = new FastTlsAeadCipherImpl(CreateAeadBlockCipher_Aes_Ccm(), true); - FastTlsAeadCipherImpl decrypt = new FastTlsAeadCipherImpl(CreateAeadBlockCipher_Aes_Ccm(), false); + FastTlsAeadCipherImpl encrypt = new FastTlsAeadCipherImpl(CreateAeadCipher_Aes_Ccm(), true); + FastTlsAeadCipherImpl decrypt = new FastTlsAeadCipherImpl(CreateAeadCipher_Aes_Ccm(), false); return new FastTlsAeadCipher(cryptoParams, encrypt, decrypt, 32, 8, TlsAeadCipher.AEAD_CCM); } @@ -108,8 +109,8 @@ public override TlsCipher CreateCipher(TlsCryptoParameters cryptoParams, int enc { // NOTE: Ignores macAlgorithm //return CreateCipher_Aes_Gcm(cryptoParams, 16, 16); - FastTlsAeadCipherImpl encrypt = new FastTlsAeadCipherImpl(CreateAeadBlockCipher_Aes_Gcm(), true); - FastTlsAeadCipherImpl decrypt = new FastTlsAeadCipherImpl(CreateAeadBlockCipher_Aes_Gcm(), false); + FastTlsAeadCipherImpl encrypt = new FastTlsAeadCipherImpl(CreateAeadCipher_Aes_Gcm(), true); + FastTlsAeadCipherImpl decrypt = new FastTlsAeadCipherImpl(CreateAeadCipher_Aes_Gcm(), false); return new FastTlsAeadCipher(cryptoParams, encrypt, decrypt, 16, 16, TlsAeadCipher.AEAD_GCM); } @@ -118,8 +119,8 @@ public override TlsCipher CreateCipher(TlsCryptoParameters cryptoParams, int enc { // NOTE: Ignores macAlgorithm //return CreateCipher_Aes_Gcm(cryptoParams, 32, 16); - FastTlsAeadCipherImpl encrypt = new FastTlsAeadCipherImpl(CreateAeadBlockCipher_Aes_Gcm(), true); - FastTlsAeadCipherImpl decrypt = new FastTlsAeadCipherImpl(CreateAeadBlockCipher_Aes_Gcm(), false); + FastTlsAeadCipherImpl encrypt = new FastTlsAeadCipherImpl(CreateAeadCipher_Aes_Gcm(), true); + FastTlsAeadCipherImpl decrypt = new FastTlsAeadCipherImpl(CreateAeadCipher_Aes_Gcm(), false); return new FastTlsAeadCipher(cryptoParams, encrypt, decrypt, 32, 16, TlsAeadCipher.AEAD_GCM); } @@ -135,12 +136,12 @@ protected override IBlockCipher CreateAesEngine() return new FastAesEngine(); } - protected override IAeadBlockCipher CreateCcmMode(IBlockCipher engine) + protected override IAeadCipher CreateCcmMode(IBlockCipher engine) { return new FastCcmBlockCipher(engine); } - protected override IAeadBlockCipher CreateGcmMode(IBlockCipher engine) + protected override IAeadCipher CreateGcmMode(IBlockCipher engine) { // TODO Consider allowing custom configuration of multiplier return new FastGcmBlockCipher(engine); diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/BurstTables8kGcmMultiplier.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/BurstTables8kGcmMultiplier.cs new file mode 100644 index 0000000..ef20e5c --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/BurstTables8kGcmMultiplier.cs @@ -0,0 +1,150 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.Runtime.CompilerServices; + +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes.Gcm; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; + +#if BESTHTTP_WITH_BURST +using Unity.Burst; +using Unity.Collections.LowLevel.Unsafe; +#endif + +namespace BestHTTP.Connections.TLS.Crypto.Impl +{ + [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] +#if BESTHTTP_WITH_BURST + [BurstCompile] +#endif + public sealed class BurstTables8kGcmMultiplier //: IGcmMultiplier + { + private byte[] H; + private GcmUtilities.FieldElement[][] T; + + public void Init(byte[] H) + { + if (T == null) + { + T = new GcmUtilities.FieldElement[2][]; + } + else if (Arrays.AreEqual(this.H, H)) + { + return; + } + + if (this.H == null) + this.H = Arrays.Clone(H); + else + { + if (this.H.Length != H.Length) + Array.Resize(ref this.H, H.Length); + + Array.Copy(H, this.H, H.Length); + } + + for (int i = 0; i < 2; ++i) + { + if (T[i] == null) + T[i] = new GcmUtilities.FieldElement[256]; + + GcmUtilities.FieldElement[] t = T[i]; + + // t[0] = 0 + + if (i == 0) + { + // t[1] = H.p^7 + GcmUtilities.AsFieldElement(this.H, out t[1]); + GcmUtilities.MultiplyP7(ref t[1]); + } + else + { + // t[1] = T[i-1][1].p^8 + GcmUtilities.MultiplyP8(ref T[i - 1][1], out t[1]); + } + + for (int n = 1; n < 128; ++n) + { + // t[2.n] = t[n].p^-1 + GcmUtilities.DivideP(ref t[n], out t[n << 1]); + + // t[2.n + 1] = t[2.n] + t[1] + GcmUtilities.Xor(ref t[n << 1], ref t[1], out t[(n << 1) + 1]); + } + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void MultiplyH(byte[] x) + { + fixed (byte* px = x) + fixed (GcmUtilities.FieldElement* pT0 = this.T[0]) + fixed (GcmUtilities.FieldElement* pT1 = this.T[1]) + MultiplyHImpl(px, pT0, pT1); + } + +#if BESTHTTP_WITH_BURST + [BurstCompile] +#endif + private static unsafe void MultiplyHImpl( +#if BESTHTTP_WITH_BURST + [NoAlias] +#endif + byte* px, +#if BESTHTTP_WITH_BURST + [NoAlias] +#endif + GcmUtilities.FieldElement* pT0, +#if BESTHTTP_WITH_BURST + [NoAlias] +#endif + GcmUtilities.FieldElement* pT1) + { + int vPos = px[15]; + int uPos = px[14]; + ulong z1 = pT0[uPos].n1 ^ pT1[vPos].n1; + ulong z0 = pT0[uPos].n0 ^ pT1[vPos].n0; + + for (int i = 12; i >= 0; i -= 2) + { + vPos = px[i + 1]; + uPos = px[i]; + + ulong c = z1 << 48; + z1 = pT0[uPos].n1 ^ pT1[vPos].n1 ^ ((z1 >> 16) | (z0 << 48)); + z0 = pT0[uPos].n0 ^ pT1[vPos].n0 ^ (z0 >> 16) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); + } + + //GcmUtilities.AsBytes(z0, z1, x); + + //UInt32_To_BE((uint)(n >> 32), bs, off); + uint n = (uint)(z0 >> 32); + px[0] = (byte)(n >> 24); + px[1] = (byte)(n >> 16); + px[2] = (byte)(n >> 8); + px[3] = (byte)(n); + //UInt32_To_BE((uint)(n), bs, off + 4); + n = (uint)(z0); + px[4] = (byte)(n >> 24); + px[5] = (byte)(n >> 16); + px[6] = (byte)(n >> 8); + px[7] = (byte)(n); + + n = (uint)(z1 >> 32); + px[8] = (byte)(n >> 24); + px[9] = (byte)(n >> 16); + px[10] = (byte)(n >> 8); + px[11] = (byte)(n); + //UInt32_To_BE((uint)(n), bs, off + 4); + n = (uint)(z1); + px[12] = (byte)(n >> 24); + px[13] = (byte)(n >> 16); + px[14] = (byte)(n >> 8); + px[15] = (byte)(n); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/BurstTables8kGcmMultiplier.cs.meta b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/BurstTables8kGcmMultiplier.cs.meta new file mode 100644 index 0000000..2f778c6 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/BurstTables8kGcmMultiplier.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5e88c42789588844893c08f62978218b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastAesEngine.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastAesEngine.cs index 6059322..3f4174a 100644 --- a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastAesEngine.cs +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastAesEngine.cs @@ -11,7 +11,7 @@ namespace BestHTTP.Connections.TLS.Crypto.Impl { /** - * an implementation of the AES (Rijndael)), from FIPS-197. + * an implementation of the AES (Rijndael), from FIPS-197. *

* For further details see: http://csrc.nist.gov/encryption/aes/. * @@ -19,29 +19,22 @@ namespace BestHTTP.Connections.TLS.Crypto.Impl * 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 + * 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 + * 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), + * 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 contents of the first. * - * The slowest version uses no static tables at all and computes the values in each round + * 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 + * This file contains the middle performance version with 2Kbytes of static tables for round precomputation. *

*/ - /// - /// Unfortunately this class has a few side channel issues. - /// In an environment where encryption/decryption may be closely observed it should not be used. - /// - - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] + [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] public sealed class FastAesEngine : IBlockCipher @@ -184,174 +177,6 @@ public sealed class FastAesEngine 0x3a16162c }; - private static readonly uint[] T1 = - { - 0x6363c6a5, 0x7c7cf884, 0x7777ee99, 0x7b7bf68d, 0xf2f2ff0d, - 0x6b6bd6bd, 0x6f6fdeb1, 0xc5c59154, 0x30306050, 0x01010203, - 0x6767cea9, 0x2b2b567d, 0xfefee719, 0xd7d7b562, 0xabab4de6, - 0x7676ec9a, 0xcaca8f45, 0x82821f9d, 0xc9c98940, 0x7d7dfa87, - 0xfafaef15, 0x5959b2eb, 0x47478ec9, 0xf0f0fb0b, 0xadad41ec, - 0xd4d4b367, 0xa2a25ffd, 0xafaf45ea, 0x9c9c23bf, 0xa4a453f7, - 0x7272e496, 0xc0c09b5b, 0xb7b775c2, 0xfdfde11c, 0x93933dae, - 0x26264c6a, 0x36366c5a, 0x3f3f7e41, 0xf7f7f502, 0xcccc834f, - 0x3434685c, 0xa5a551f4, 0xe5e5d134, 0xf1f1f908, 0x7171e293, - 0xd8d8ab73, 0x31316253, 0x15152a3f, 0x0404080c, 0xc7c79552, - 0x23234665, 0xc3c39d5e, 0x18183028, 0x969637a1, 0x05050a0f, - 0x9a9a2fb5, 0x07070e09, 0x12122436, 0x80801b9b, 0xe2e2df3d, - 0xebebcd26, 0x27274e69, 0xb2b27fcd, 0x7575ea9f, 0x0909121b, - 0x83831d9e, 0x2c2c5874, 0x1a1a342e, 0x1b1b362d, 0x6e6edcb2, - 0x5a5ab4ee, 0xa0a05bfb, 0x5252a4f6, 0x3b3b764d, 0xd6d6b761, - 0xb3b37dce, 0x2929527b, 0xe3e3dd3e, 0x2f2f5e71, 0x84841397, - 0x5353a6f5, 0xd1d1b968, 0x00000000, 0xededc12c, 0x20204060, - 0xfcfce31f, 0xb1b179c8, 0x5b5bb6ed, 0x6a6ad4be, 0xcbcb8d46, - 0xbebe67d9, 0x3939724b, 0x4a4a94de, 0x4c4c98d4, 0x5858b0e8, - 0xcfcf854a, 0xd0d0bb6b, 0xefefc52a, 0xaaaa4fe5, 0xfbfbed16, - 0x434386c5, 0x4d4d9ad7, 0x33336655, 0x85851194, 0x45458acf, - 0xf9f9e910, 0x02020406, 0x7f7ffe81, 0x5050a0f0, 0x3c3c7844, - 0x9f9f25ba, 0xa8a84be3, 0x5151a2f3, 0xa3a35dfe, 0x404080c0, - 0x8f8f058a, 0x92923fad, 0x9d9d21bc, 0x38387048, 0xf5f5f104, - 0xbcbc63df, 0xb6b677c1, 0xdadaaf75, 0x21214263, 0x10102030, - 0xffffe51a, 0xf3f3fd0e, 0xd2d2bf6d, 0xcdcd814c, 0x0c0c1814, - 0x13132635, 0xececc32f, 0x5f5fbee1, 0x979735a2, 0x444488cc, - 0x17172e39, 0xc4c49357, 0xa7a755f2, 0x7e7efc82, 0x3d3d7a47, - 0x6464c8ac, 0x5d5dbae7, 0x1919322b, 0x7373e695, 0x6060c0a0, - 0x81811998, 0x4f4f9ed1, 0xdcdca37f, 0x22224466, 0x2a2a547e, - 0x90903bab, 0x88880b83, 0x46468cca, 0xeeeec729, 0xb8b86bd3, - 0x1414283c, 0xdedea779, 0x5e5ebce2, 0x0b0b161d, 0xdbdbad76, - 0xe0e0db3b, 0x32326456, 0x3a3a744e, 0x0a0a141e, 0x494992db, - 0x06060c0a, 0x2424486c, 0x5c5cb8e4, 0xc2c29f5d, 0xd3d3bd6e, - 0xacac43ef, 0x6262c4a6, 0x919139a8, 0x959531a4, 0xe4e4d337, - 0x7979f28b, 0xe7e7d532, 0xc8c88b43, 0x37376e59, 0x6d6ddab7, - 0x8d8d018c, 0xd5d5b164, 0x4e4e9cd2, 0xa9a949e0, 0x6c6cd8b4, - 0x5656acfa, 0xf4f4f307, 0xeaeacf25, 0x6565caaf, 0x7a7af48e, - 0xaeae47e9, 0x08081018, 0xbaba6fd5, 0x7878f088, 0x25254a6f, - 0x2e2e5c72, 0x1c1c3824, 0xa6a657f1, 0xb4b473c7, 0xc6c69751, - 0xe8e8cb23, 0xdddda17c, 0x7474e89c, 0x1f1f3e21, 0x4b4b96dd, - 0xbdbd61dc, 0x8b8b0d86, 0x8a8a0f85, 0x7070e090, 0x3e3e7c42, - 0xb5b571c4, 0x6666ccaa, 0x484890d8, 0x03030605, 0xf6f6f701, - 0x0e0e1c12, 0x6161c2a3, 0x35356a5f, 0x5757aef9, 0xb9b969d0, - 0x86861791, 0xc1c19958, 0x1d1d3a27, 0x9e9e27b9, 0xe1e1d938, - 0xf8f8eb13, 0x98982bb3, 0x11112233, 0x6969d2bb, 0xd9d9a970, - 0x8e8e0789, 0x949433a7, 0x9b9b2db6, 0x1e1e3c22, 0x87871592, - 0xe9e9c920, 0xcece8749, 0x5555aaff, 0x28285078, 0xdfdfa57a, - 0x8c8c038f, 0xa1a159f8, 0x89890980, 0x0d0d1a17, 0xbfbf65da, - 0xe6e6d731, 0x424284c6, 0x6868d0b8, 0x414182c3, 0x999929b0, - 0x2d2d5a77, 0x0f0f1e11, 0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6, - 0x16162c3a - }; - - private static readonly uint[] T2 = - { - 0x63c6a563, 0x7cf8847c, 0x77ee9977, 0x7bf68d7b, 0xf2ff0df2, - 0x6bd6bd6b, 0x6fdeb16f, 0xc59154c5, 0x30605030, 0x01020301, - 0x67cea967, 0x2b567d2b, 0xfee719fe, 0xd7b562d7, 0xab4de6ab, - 0x76ec9a76, 0xca8f45ca, 0x821f9d82, 0xc98940c9, 0x7dfa877d, - 0xfaef15fa, 0x59b2eb59, 0x478ec947, 0xf0fb0bf0, 0xad41ecad, - 0xd4b367d4, 0xa25ffda2, 0xaf45eaaf, 0x9c23bf9c, 0xa453f7a4, - 0x72e49672, 0xc09b5bc0, 0xb775c2b7, 0xfde11cfd, 0x933dae93, - 0x264c6a26, 0x366c5a36, 0x3f7e413f, 0xf7f502f7, 0xcc834fcc, - 0x34685c34, 0xa551f4a5, 0xe5d134e5, 0xf1f908f1, 0x71e29371, - 0xd8ab73d8, 0x31625331, 0x152a3f15, 0x04080c04, 0xc79552c7, - 0x23466523, 0xc39d5ec3, 0x18302818, 0x9637a196, 0x050a0f05, - 0x9a2fb59a, 0x070e0907, 0x12243612, 0x801b9b80, 0xe2df3de2, - 0xebcd26eb, 0x274e6927, 0xb27fcdb2, 0x75ea9f75, 0x09121b09, - 0x831d9e83, 0x2c58742c, 0x1a342e1a, 0x1b362d1b, 0x6edcb26e, - 0x5ab4ee5a, 0xa05bfba0, 0x52a4f652, 0x3b764d3b, 0xd6b761d6, - 0xb37dceb3, 0x29527b29, 0xe3dd3ee3, 0x2f5e712f, 0x84139784, - 0x53a6f553, 0xd1b968d1, 0x00000000, 0xedc12ced, 0x20406020, - 0xfce31ffc, 0xb179c8b1, 0x5bb6ed5b, 0x6ad4be6a, 0xcb8d46cb, - 0xbe67d9be, 0x39724b39, 0x4a94de4a, 0x4c98d44c, 0x58b0e858, - 0xcf854acf, 0xd0bb6bd0, 0xefc52aef, 0xaa4fe5aa, 0xfbed16fb, - 0x4386c543, 0x4d9ad74d, 0x33665533, 0x85119485, 0x458acf45, - 0xf9e910f9, 0x02040602, 0x7ffe817f, 0x50a0f050, 0x3c78443c, - 0x9f25ba9f, 0xa84be3a8, 0x51a2f351, 0xa35dfea3, 0x4080c040, - 0x8f058a8f, 0x923fad92, 0x9d21bc9d, 0x38704838, 0xf5f104f5, - 0xbc63dfbc, 0xb677c1b6, 0xdaaf75da, 0x21426321, 0x10203010, - 0xffe51aff, 0xf3fd0ef3, 0xd2bf6dd2, 0xcd814ccd, 0x0c18140c, - 0x13263513, 0xecc32fec, 0x5fbee15f, 0x9735a297, 0x4488cc44, - 0x172e3917, 0xc49357c4, 0xa755f2a7, 0x7efc827e, 0x3d7a473d, - 0x64c8ac64, 0x5dbae75d, 0x19322b19, 0x73e69573, 0x60c0a060, - 0x81199881, 0x4f9ed14f, 0xdca37fdc, 0x22446622, 0x2a547e2a, - 0x903bab90, 0x880b8388, 0x468cca46, 0xeec729ee, 0xb86bd3b8, - 0x14283c14, 0xdea779de, 0x5ebce25e, 0x0b161d0b, 0xdbad76db, - 0xe0db3be0, 0x32645632, 0x3a744e3a, 0x0a141e0a, 0x4992db49, - 0x060c0a06, 0x24486c24, 0x5cb8e45c, 0xc29f5dc2, 0xd3bd6ed3, - 0xac43efac, 0x62c4a662, 0x9139a891, 0x9531a495, 0xe4d337e4, - 0x79f28b79, 0xe7d532e7, 0xc88b43c8, 0x376e5937, 0x6ddab76d, - 0x8d018c8d, 0xd5b164d5, 0x4e9cd24e, 0xa949e0a9, 0x6cd8b46c, - 0x56acfa56, 0xf4f307f4, 0xeacf25ea, 0x65caaf65, 0x7af48e7a, - 0xae47e9ae, 0x08101808, 0xba6fd5ba, 0x78f08878, 0x254a6f25, - 0x2e5c722e, 0x1c38241c, 0xa657f1a6, 0xb473c7b4, 0xc69751c6, - 0xe8cb23e8, 0xdda17cdd, 0x74e89c74, 0x1f3e211f, 0x4b96dd4b, - 0xbd61dcbd, 0x8b0d868b, 0x8a0f858a, 0x70e09070, 0x3e7c423e, - 0xb571c4b5, 0x66ccaa66, 0x4890d848, 0x03060503, 0xf6f701f6, - 0x0e1c120e, 0x61c2a361, 0x356a5f35, 0x57aef957, 0xb969d0b9, - 0x86179186, 0xc19958c1, 0x1d3a271d, 0x9e27b99e, 0xe1d938e1, - 0xf8eb13f8, 0x982bb398, 0x11223311, 0x69d2bb69, 0xd9a970d9, - 0x8e07898e, 0x9433a794, 0x9b2db69b, 0x1e3c221e, 0x87159287, - 0xe9c920e9, 0xce8749ce, 0x55aaff55, 0x28507828, 0xdfa57adf, - 0x8c038f8c, 0xa159f8a1, 0x89098089, 0x0d1a170d, 0xbf65dabf, - 0xe6d731e6, 0x4284c642, 0x68d0b868, 0x4182c341, 0x9929b099, - 0x2d5a772d, 0x0f1e110f, 0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb, - 0x162c3a16 - }; - - private static readonly uint[] T3 = - { - 0xc6a56363, 0xf8847c7c, 0xee997777, 0xf68d7b7b, 0xff0df2f2, - 0xd6bd6b6b, 0xdeb16f6f, 0x9154c5c5, 0x60503030, 0x02030101, - 0xcea96767, 0x567d2b2b, 0xe719fefe, 0xb562d7d7, 0x4de6abab, - 0xec9a7676, 0x8f45caca, 0x1f9d8282, 0x8940c9c9, 0xfa877d7d, - 0xef15fafa, 0xb2eb5959, 0x8ec94747, 0xfb0bf0f0, 0x41ecadad, - 0xb367d4d4, 0x5ffda2a2, 0x45eaafaf, 0x23bf9c9c, 0x53f7a4a4, - 0xe4967272, 0x9b5bc0c0, 0x75c2b7b7, 0xe11cfdfd, 0x3dae9393, - 0x4c6a2626, 0x6c5a3636, 0x7e413f3f, 0xf502f7f7, 0x834fcccc, - 0x685c3434, 0x51f4a5a5, 0xd134e5e5, 0xf908f1f1, 0xe2937171, - 0xab73d8d8, 0x62533131, 0x2a3f1515, 0x080c0404, 0x9552c7c7, - 0x46652323, 0x9d5ec3c3, 0x30281818, 0x37a19696, 0x0a0f0505, - 0x2fb59a9a, 0x0e090707, 0x24361212, 0x1b9b8080, 0xdf3de2e2, - 0xcd26ebeb, 0x4e692727, 0x7fcdb2b2, 0xea9f7575, 0x121b0909, - 0x1d9e8383, 0x58742c2c, 0x342e1a1a, 0x362d1b1b, 0xdcb26e6e, - 0xb4ee5a5a, 0x5bfba0a0, 0xa4f65252, 0x764d3b3b, 0xb761d6d6, - 0x7dceb3b3, 0x527b2929, 0xdd3ee3e3, 0x5e712f2f, 0x13978484, - 0xa6f55353, 0xb968d1d1, 0x00000000, 0xc12ceded, 0x40602020, - 0xe31ffcfc, 0x79c8b1b1, 0xb6ed5b5b, 0xd4be6a6a, 0x8d46cbcb, - 0x67d9bebe, 0x724b3939, 0x94de4a4a, 0x98d44c4c, 0xb0e85858, - 0x854acfcf, 0xbb6bd0d0, 0xc52aefef, 0x4fe5aaaa, 0xed16fbfb, - 0x86c54343, 0x9ad74d4d, 0x66553333, 0x11948585, 0x8acf4545, - 0xe910f9f9, 0x04060202, 0xfe817f7f, 0xa0f05050, 0x78443c3c, - 0x25ba9f9f, 0x4be3a8a8, 0xa2f35151, 0x5dfea3a3, 0x80c04040, - 0x058a8f8f, 0x3fad9292, 0x21bc9d9d, 0x70483838, 0xf104f5f5, - 0x63dfbcbc, 0x77c1b6b6, 0xaf75dada, 0x42632121, 0x20301010, - 0xe51affff, 0xfd0ef3f3, 0xbf6dd2d2, 0x814ccdcd, 0x18140c0c, - 0x26351313, 0xc32fecec, 0xbee15f5f, 0x35a29797, 0x88cc4444, - 0x2e391717, 0x9357c4c4, 0x55f2a7a7, 0xfc827e7e, 0x7a473d3d, - 0xc8ac6464, 0xbae75d5d, 0x322b1919, 0xe6957373, 0xc0a06060, - 0x19988181, 0x9ed14f4f, 0xa37fdcdc, 0x44662222, 0x547e2a2a, - 0x3bab9090, 0x0b838888, 0x8cca4646, 0xc729eeee, 0x6bd3b8b8, - 0x283c1414, 0xa779dede, 0xbce25e5e, 0x161d0b0b, 0xad76dbdb, - 0xdb3be0e0, 0x64563232, 0x744e3a3a, 0x141e0a0a, 0x92db4949, - 0x0c0a0606, 0x486c2424, 0xb8e45c5c, 0x9f5dc2c2, 0xbd6ed3d3, - 0x43efacac, 0xc4a66262, 0x39a89191, 0x31a49595, 0xd337e4e4, - 0xf28b7979, 0xd532e7e7, 0x8b43c8c8, 0x6e593737, 0xdab76d6d, - 0x018c8d8d, 0xb164d5d5, 0x9cd24e4e, 0x49e0a9a9, 0xd8b46c6c, - 0xacfa5656, 0xf307f4f4, 0xcf25eaea, 0xcaaf6565, 0xf48e7a7a, - 0x47e9aeae, 0x10180808, 0x6fd5baba, 0xf0887878, 0x4a6f2525, - 0x5c722e2e, 0x38241c1c, 0x57f1a6a6, 0x73c7b4b4, 0x9751c6c6, - 0xcb23e8e8, 0xa17cdddd, 0xe89c7474, 0x3e211f1f, 0x96dd4b4b, - 0x61dcbdbd, 0x0d868b8b, 0x0f858a8a, 0xe0907070, 0x7c423e3e, - 0x71c4b5b5, 0xccaa6666, 0x90d84848, 0x06050303, 0xf701f6f6, - 0x1c120e0e, 0xc2a36161, 0x6a5f3535, 0xaef95757, 0x69d0b9b9, - 0x17918686, 0x9958c1c1, 0x3a271d1d, 0x27b99e9e, 0xd938e1e1, - 0xeb13f8f8, 0x2bb39898, 0x22331111, 0xd2bb6969, 0xa970d9d9, - 0x07898e8e, 0x33a79494, 0x2db69b9b, 0x3c221e1e, 0x15928787, - 0xc920e9e9, 0x8749cece, 0xaaff5555, 0x50782828, 0xa57adfdf, - 0x038f8c8c, 0x59f8a1a1, 0x09808989, 0x1a170d0d, 0x65dabfbf, - 0xd731e6e6, 0x84c64242, 0xd0b86868, 0x82c34141, 0x29b09999, - 0x5a772d2d, 0x1e110f0f, 0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb, - 0x2c3a1616 - }; - private static readonly uint[] Tinv0 = { 0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b, @@ -408,174 +233,6 @@ public sealed class FastAesEngine 0x4257b8d0 }; - private static readonly uint[] Tinv1 = - { - 0xa7f45150, 0x65417e53, 0xa4171ac3, 0x5e273a96, 0x6bab3bcb, - 0x459d1ff1, 0x58faacab, 0x03e34b93, 0xfa302055, 0x6d76adf6, - 0x76cc8891, 0x4c02f525, 0xd7e54ffc, 0xcb2ac5d7, 0x44352680, - 0xa362b58f, 0x5ab1de49, 0x1bba2567, 0x0eea4598, 0xc0fe5de1, - 0x752fc302, 0xf04c8112, 0x97468da3, 0xf9d36bc6, 0x5f8f03e7, - 0x9c921595, 0x7a6dbfeb, 0x595295da, 0x83bed42d, 0x217458d3, - 0x69e04929, 0xc8c98e44, 0x89c2756a, 0x798ef478, 0x3e58996b, - 0x71b927dd, 0x4fe1beb6, 0xad88f017, 0xac20c966, 0x3ace7db4, - 0x4adf6318, 0x311ae582, 0x33519760, 0x7f536245, 0x7764b1e0, - 0xae6bbb84, 0xa081fe1c, 0x2b08f994, 0x68487058, 0xfd458f19, - 0x6cde9487, 0xf87b52b7, 0xd373ab23, 0x024b72e2, 0x8f1fe357, - 0xab55662a, 0x28ebb207, 0xc2b52f03, 0x7bc5869a, 0x0837d3a5, - 0x872830f2, 0xa5bf23b2, 0x6a0302ba, 0x8216ed5c, 0x1ccf8a2b, - 0xb479a792, 0xf207f3f0, 0xe2694ea1, 0xf4da65cd, 0xbe0506d5, - 0x6234d11f, 0xfea6c48a, 0x532e349d, 0x55f3a2a0, 0xe18a0532, - 0xebf6a475, 0xec830b39, 0xef6040aa, 0x9f715e06, 0x106ebd51, - 0x8a213ef9, 0x06dd963d, 0x053eddae, 0xbde64d46, 0x8d5491b5, - 0x5dc47105, 0xd406046f, 0x155060ff, 0xfb981924, 0xe9bdd697, - 0x434089cc, 0x9ed96777, 0x42e8b0bd, 0x8b890788, 0x5b19e738, - 0xeec879db, 0x0a7ca147, 0x0f427ce9, 0x1e84f8c9, 0x00000000, - 0x86800983, 0xed2b3248, 0x70111eac, 0x725a6c4e, 0xff0efdfb, - 0x38850f56, 0xd5ae3d1e, 0x392d3627, 0xd90f0a64, 0xa65c6821, - 0x545b9bd1, 0x2e36243a, 0x670a0cb1, 0xe757930f, 0x96eeb4d2, - 0x919b1b9e, 0xc5c0804f, 0x20dc61a2, 0x4b775a69, 0x1a121c16, - 0xba93e20a, 0x2aa0c0e5, 0xe0223c43, 0x171b121d, 0x0d090e0b, - 0xc78bf2ad, 0xa8b62db9, 0xa91e14c8, 0x19f15785, 0x0775af4c, - 0xdd99eebb, 0x607fa3fd, 0x2601f79f, 0xf5725cbc, 0x3b6644c5, - 0x7efb5b34, 0x29438b76, 0xc623cbdc, 0xfcedb668, 0xf1e4b863, - 0xdc31d7ca, 0x85634210, 0x22971340, 0x11c68420, 0x244a857d, - 0x3dbbd2f8, 0x32f9ae11, 0xa129c76d, 0x2f9e1d4b, 0x30b2dcf3, - 0x52860dec, 0xe3c177d0, 0x16b32b6c, 0xb970a999, 0x489411fa, - 0x64e94722, 0x8cfca8c4, 0x3ff0a01a, 0x2c7d56d8, 0x903322ef, - 0x4e4987c7, 0xd138d9c1, 0xa2ca8cfe, 0x0bd49836, 0x81f5a6cf, - 0xde7aa528, 0x8eb7da26, 0xbfad3fa4, 0x9d3a2ce4, 0x9278500d, - 0xcc5f6a9b, 0x467e5462, 0x138df6c2, 0xb8d890e8, 0xf7392e5e, - 0xafc382f5, 0x805d9fbe, 0x93d0697c, 0x2dd56fa9, 0x1225cfb3, - 0x99acc83b, 0x7d1810a7, 0x639ce86e, 0xbb3bdb7b, 0x7826cd09, - 0x18596ef4, 0xb79aec01, 0x9a4f83a8, 0x6e95e665, 0xe6ffaa7e, - 0xcfbc2108, 0xe815efe6, 0x9be7bad9, 0x366f4ace, 0x099fead4, - 0x7cb029d6, 0xb2a431af, 0x233f2a31, 0x94a5c630, 0x66a235c0, - 0xbc4e7437, 0xca82fca6, 0xd090e0b0, 0xd8a73315, 0x9804f14a, - 0xdaec41f7, 0x50cd7f0e, 0xf691172f, 0xd64d768d, 0xb0ef434d, - 0x4daacc54, 0x0496e4df, 0xb5d19ee3, 0x886a4c1b, 0x1f2cc1b8, - 0x5165467f, 0xea5e9d04, 0x358c015d, 0x7487fa73, 0x410bfb2e, - 0x1d67b35a, 0xd2db9252, 0x5610e933, 0x47d66d13, 0x61d79a8c, - 0x0ca1377a, 0x14f8598e, 0x3c13eb89, 0x27a9ceee, 0xc961b735, - 0xe51ce1ed, 0xb1477a3c, 0xdfd29c59, 0x73f2553f, 0xce141879, - 0x37c773bf, 0xcdf753ea, 0xaafd5f5b, 0x6f3ddf14, 0xdb447886, - 0xf3afca81, 0xc468b93e, 0x3424382c, 0x40a3c25f, 0xc31d1672, - 0x25e2bc0c, 0x493c288b, 0x950dff41, 0x01a83971, 0xb30c08de, - 0xe4b4d89c, 0xc1566490, 0x84cb7b61, 0xb632d570, 0x5c6c4874, - 0x57b8d042 - }; - - private static readonly uint[] Tinv2 = - { - 0xf45150a7, 0x417e5365, 0x171ac3a4, 0x273a965e, 0xab3bcb6b, - 0x9d1ff145, 0xfaacab58, 0xe34b9303, 0x302055fa, 0x76adf66d, - 0xcc889176, 0x02f5254c, 0xe54ffcd7, 0x2ac5d7cb, 0x35268044, - 0x62b58fa3, 0xb1de495a, 0xba25671b, 0xea45980e, 0xfe5de1c0, - 0x2fc30275, 0x4c8112f0, 0x468da397, 0xd36bc6f9, 0x8f03e75f, - 0x9215959c, 0x6dbfeb7a, 0x5295da59, 0xbed42d83, 0x7458d321, - 0xe0492969, 0xc98e44c8, 0xc2756a89, 0x8ef47879, 0x58996b3e, - 0xb927dd71, 0xe1beb64f, 0x88f017ad, 0x20c966ac, 0xce7db43a, - 0xdf63184a, 0x1ae58231, 0x51976033, 0x5362457f, 0x64b1e077, - 0x6bbb84ae, 0x81fe1ca0, 0x08f9942b, 0x48705868, 0x458f19fd, - 0xde94876c, 0x7b52b7f8, 0x73ab23d3, 0x4b72e202, 0x1fe3578f, - 0x55662aab, 0xebb20728, 0xb52f03c2, 0xc5869a7b, 0x37d3a508, - 0x2830f287, 0xbf23b2a5, 0x0302ba6a, 0x16ed5c82, 0xcf8a2b1c, - 0x79a792b4, 0x07f3f0f2, 0x694ea1e2, 0xda65cdf4, 0x0506d5be, - 0x34d11f62, 0xa6c48afe, 0x2e349d53, 0xf3a2a055, 0x8a0532e1, - 0xf6a475eb, 0x830b39ec, 0x6040aaef, 0x715e069f, 0x6ebd5110, - 0x213ef98a, 0xdd963d06, 0x3eddae05, 0xe64d46bd, 0x5491b58d, - 0xc471055d, 0x06046fd4, 0x5060ff15, 0x981924fb, 0xbdd697e9, - 0x4089cc43, 0xd967779e, 0xe8b0bd42, 0x8907888b, 0x19e7385b, - 0xc879dbee, 0x7ca1470a, 0x427ce90f, 0x84f8c91e, 0x00000000, - 0x80098386, 0x2b3248ed, 0x111eac70, 0x5a6c4e72, 0x0efdfbff, - 0x850f5638, 0xae3d1ed5, 0x2d362739, 0x0f0a64d9, 0x5c6821a6, - 0x5b9bd154, 0x36243a2e, 0x0a0cb167, 0x57930fe7, 0xeeb4d296, - 0x9b1b9e91, 0xc0804fc5, 0xdc61a220, 0x775a694b, 0x121c161a, - 0x93e20aba, 0xa0c0e52a, 0x223c43e0, 0x1b121d17, 0x090e0b0d, - 0x8bf2adc7, 0xb62db9a8, 0x1e14c8a9, 0xf1578519, 0x75af4c07, - 0x99eebbdd, 0x7fa3fd60, 0x01f79f26, 0x725cbcf5, 0x6644c53b, - 0xfb5b347e, 0x438b7629, 0x23cbdcc6, 0xedb668fc, 0xe4b863f1, - 0x31d7cadc, 0x63421085, 0x97134022, 0xc6842011, 0x4a857d24, - 0xbbd2f83d, 0xf9ae1132, 0x29c76da1, 0x9e1d4b2f, 0xb2dcf330, - 0x860dec52, 0xc177d0e3, 0xb32b6c16, 0x70a999b9, 0x9411fa48, - 0xe9472264, 0xfca8c48c, 0xf0a01a3f, 0x7d56d82c, 0x3322ef90, - 0x4987c74e, 0x38d9c1d1, 0xca8cfea2, 0xd498360b, 0xf5a6cf81, - 0x7aa528de, 0xb7da268e, 0xad3fa4bf, 0x3a2ce49d, 0x78500d92, - 0x5f6a9bcc, 0x7e546246, 0x8df6c213, 0xd890e8b8, 0x392e5ef7, - 0xc382f5af, 0x5d9fbe80, 0xd0697c93, 0xd56fa92d, 0x25cfb312, - 0xacc83b99, 0x1810a77d, 0x9ce86e63, 0x3bdb7bbb, 0x26cd0978, - 0x596ef418, 0x9aec01b7, 0x4f83a89a, 0x95e6656e, 0xffaa7ee6, - 0xbc2108cf, 0x15efe6e8, 0xe7bad99b, 0x6f4ace36, 0x9fead409, - 0xb029d67c, 0xa431afb2, 0x3f2a3123, 0xa5c63094, 0xa235c066, - 0x4e7437bc, 0x82fca6ca, 0x90e0b0d0, 0xa73315d8, 0x04f14a98, - 0xec41f7da, 0xcd7f0e50, 0x91172ff6, 0x4d768dd6, 0xef434db0, - 0xaacc544d, 0x96e4df04, 0xd19ee3b5, 0x6a4c1b88, 0x2cc1b81f, - 0x65467f51, 0x5e9d04ea, 0x8c015d35, 0x87fa7374, 0x0bfb2e41, - 0x67b35a1d, 0xdb9252d2, 0x10e93356, 0xd66d1347, 0xd79a8c61, - 0xa1377a0c, 0xf8598e14, 0x13eb893c, 0xa9ceee27, 0x61b735c9, - 0x1ce1ede5, 0x477a3cb1, 0xd29c59df, 0xf2553f73, 0x141879ce, - 0xc773bf37, 0xf753eacd, 0xfd5f5baa, 0x3ddf146f, 0x447886db, - 0xafca81f3, 0x68b93ec4, 0x24382c34, 0xa3c25f40, 0x1d1672c3, - 0xe2bc0c25, 0x3c288b49, 0x0dff4195, 0xa8397101, 0x0c08deb3, - 0xb4d89ce4, 0x566490c1, 0xcb7b6184, 0x32d570b6, 0x6c48745c, - 0xb8d04257 - }; - - private static readonly uint[] Tinv3 = - { - 0x5150a7f4, 0x7e536541, 0x1ac3a417, 0x3a965e27, 0x3bcb6bab, - 0x1ff1459d, 0xacab58fa, 0x4b9303e3, 0x2055fa30, 0xadf66d76, - 0x889176cc, 0xf5254c02, 0x4ffcd7e5, 0xc5d7cb2a, 0x26804435, - 0xb58fa362, 0xde495ab1, 0x25671bba, 0x45980eea, 0x5de1c0fe, - 0xc302752f, 0x8112f04c, 0x8da39746, 0x6bc6f9d3, 0x03e75f8f, - 0x15959c92, 0xbfeb7a6d, 0x95da5952, 0xd42d83be, 0x58d32174, - 0x492969e0, 0x8e44c8c9, 0x756a89c2, 0xf478798e, 0x996b3e58, - 0x27dd71b9, 0xbeb64fe1, 0xf017ad88, 0xc966ac20, 0x7db43ace, - 0x63184adf, 0xe582311a, 0x97603351, 0x62457f53, 0xb1e07764, - 0xbb84ae6b, 0xfe1ca081, 0xf9942b08, 0x70586848, 0x8f19fd45, - 0x94876cde, 0x52b7f87b, 0xab23d373, 0x72e2024b, 0xe3578f1f, - 0x662aab55, 0xb20728eb, 0x2f03c2b5, 0x869a7bc5, 0xd3a50837, - 0x30f28728, 0x23b2a5bf, 0x02ba6a03, 0xed5c8216, 0x8a2b1ccf, - 0xa792b479, 0xf3f0f207, 0x4ea1e269, 0x65cdf4da, 0x06d5be05, - 0xd11f6234, 0xc48afea6, 0x349d532e, 0xa2a055f3, 0x0532e18a, - 0xa475ebf6, 0x0b39ec83, 0x40aaef60, 0x5e069f71, 0xbd51106e, - 0x3ef98a21, 0x963d06dd, 0xddae053e, 0x4d46bde6, 0x91b58d54, - 0x71055dc4, 0x046fd406, 0x60ff1550, 0x1924fb98, 0xd697e9bd, - 0x89cc4340, 0x67779ed9, 0xb0bd42e8, 0x07888b89, 0xe7385b19, - 0x79dbeec8, 0xa1470a7c, 0x7ce90f42, 0xf8c91e84, 0x00000000, - 0x09838680, 0x3248ed2b, 0x1eac7011, 0x6c4e725a, 0xfdfbff0e, - 0x0f563885, 0x3d1ed5ae, 0x3627392d, 0x0a64d90f, 0x6821a65c, - 0x9bd1545b, 0x243a2e36, 0x0cb1670a, 0x930fe757, 0xb4d296ee, - 0x1b9e919b, 0x804fc5c0, 0x61a220dc, 0x5a694b77, 0x1c161a12, - 0xe20aba93, 0xc0e52aa0, 0x3c43e022, 0x121d171b, 0x0e0b0d09, - 0xf2adc78b, 0x2db9a8b6, 0x14c8a91e, 0x578519f1, 0xaf4c0775, - 0xeebbdd99, 0xa3fd607f, 0xf79f2601, 0x5cbcf572, 0x44c53b66, - 0x5b347efb, 0x8b762943, 0xcbdcc623, 0xb668fced, 0xb863f1e4, - 0xd7cadc31, 0x42108563, 0x13402297, 0x842011c6, 0x857d244a, - 0xd2f83dbb, 0xae1132f9, 0xc76da129, 0x1d4b2f9e, 0xdcf330b2, - 0x0dec5286, 0x77d0e3c1, 0x2b6c16b3, 0xa999b970, 0x11fa4894, - 0x472264e9, 0xa8c48cfc, 0xa01a3ff0, 0x56d82c7d, 0x22ef9033, - 0x87c74e49, 0xd9c1d138, 0x8cfea2ca, 0x98360bd4, 0xa6cf81f5, - 0xa528de7a, 0xda268eb7, 0x3fa4bfad, 0x2ce49d3a, 0x500d9278, - 0x6a9bcc5f, 0x5462467e, 0xf6c2138d, 0x90e8b8d8, 0x2e5ef739, - 0x82f5afc3, 0x9fbe805d, 0x697c93d0, 0x6fa92dd5, 0xcfb31225, - 0xc83b99ac, 0x10a77d18, 0xe86e639c, 0xdb7bbb3b, 0xcd097826, - 0x6ef41859, 0xec01b79a, 0x83a89a4f, 0xe6656e95, 0xaa7ee6ff, - 0x2108cfbc, 0xefe6e815, 0xbad99be7, 0x4ace366f, 0xead4099f, - 0x29d67cb0, 0x31afb2a4, 0x2a31233f, 0xc63094a5, 0x35c066a2, - 0x7437bc4e, 0xfca6ca82, 0xe0b0d090, 0x3315d8a7, 0xf14a9804, - 0x41f7daec, 0x7f0e50cd, 0x172ff691, 0x768dd64d, 0x434db0ef, - 0xcc544daa, 0xe4df0496, 0x9ee3b5d1, 0x4c1b886a, 0xc1b81f2c, - 0x467f5165, 0x9d04ea5e, 0x015d358c, 0xfa737487, 0xfb2e410b, - 0xb35a1d67, 0x9252d2db, 0xe9335610, 0x6d1347d6, 0x9a8c61d7, - 0x377a0ca1, 0x598e14f8, 0xeb893c13, 0xceee27a9, 0xb735c961, - 0xe1ede51c, 0x7a3cb147, 0x9c59dfd2, 0x553f73f2, 0x1879ce14, - 0x73bf37c7, 0x53eacdf7, 0x5f5baafd, 0xdf146f3d, 0x7886db44, - 0xca81f3af, 0xb93ec468, 0x382c3424, 0xc25f40a3, 0x1672c31d, - 0xbc0c25e2, 0x288b493c, 0xff41950d, 0x397101a8, 0x08deb30c, - 0xd89ce4b4, 0x6490c156, 0x7b6184cb, 0xd570b632, 0x48745c6c, - 0xd04257b8 - }; - private static uint Shift(uint r, int shift) { return (r >> shift) | (r << (32 - shift)); @@ -784,9 +441,10 @@ private uint[][] GenerateWorkingKey(byte[] key, bool forEncryption) private int ROUNDS; private uint[][] WorkingKey; - private uint C0, C1, C2, C3; private bool forEncryption; + private byte[] s; + private const int BLOCK_SIZE = 16; /** @@ -804,19 +462,16 @@ public FastAesEngine() * @exception ArgumentException if the parameters argument is * inappropriate. */ - public void Init( - bool forEncryption, - ICipherParameters parameters) + public void Init(bool forEncryption, ICipherParameters parameters) { - NoCopyKeyParameter keyParameter = parameters as NoCopyKeyParameter; - - if (keyParameter == null) + if (!(parameters is KeyParameter keyParameter)) throw new ArgumentException("invalid parameter passed to AES init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); WorkingKey = GenerateWorkingKey(keyParameter.GetKey(), forEncryption); this.forEncryption = forEncryption; + this.s = /*Arrays.Clone*/(forEncryption ? S : Si); } public string AlgorithmName @@ -824,195 +479,459 @@ public string AlgorithmName get { return "AES"; } } - public bool IsPartialBlockOkay - { - get { return false; } - } - public int GetBlockSize() { return BLOCK_SIZE; } - public unsafe int ProcessBlock( - byte[] input, - int inOff, - byte[] output, - int outOff) + public int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { - fixed (byte* pinput = input) - { - uint* puintinput = (uint*)&pinput[inOff]; + if (WorkingKey == null) + throw new InvalidOperationException("AES engine not initialised"); - C0 = puintinput[0]; - C1 = puintinput[1]; - C2 = puintinput[2]; - C3 = puintinput[3]; + Check.DataLength(input, inOff, 16, "input buffer too short"); + Check.OutputLength(output, outOff, 16, "output buffer too short"); - inOff += 16; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + if (forEncryption) + { + EncryptBlock(input.AsSpan(inOff), output.AsSpan(outOff), WorkingKey); } + else + { + DecryptBlock(input.AsSpan(inOff), output.AsSpan(outOff), WorkingKey); + } +#else + if (forEncryption) + { + EncryptBlock(input, inOff, output, outOff, WorkingKey); + } + else + { + DecryptBlock(input, inOff, output, outOff, WorkingKey); + } +#endif + + return BLOCK_SIZE; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public unsafe int ProcessBlock(ReadOnlySpan input, Span output) + { + if (WorkingKey == null) + throw new InvalidOperationException("AES engine not initialised"); + + Check.DataLength(input, 16, "input buffer too short"); + Check.OutputLength(output, 16, "output buffer too short"); if (forEncryption) { - uint[][] KW = WorkingKey; - uint[] kw = KW[0]; - uint t0 = this.C0 ^ kw[0]; - uint t1 = this.C1 ^ kw[1]; - uint t2 = this.C2 ^ kw[2]; + //EncryptBlock(input, output, WorkingKey); + + uint C0 = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(input); + uint C1 = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(input[4..]); + uint C2 = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(input[8..]); + uint C3 = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(input[12..]); - uint r0, r1, r2, r3 = this.C3 ^ kw[3]; + uint[] kw = WorkingKey[0]; + uint t0 = C0 ^ kw[0]; + uint t1 = C1 ^ kw[1]; + uint t2 = C2 ^ kw[2]; + + uint r0, r1, r2, r3 = C3 ^ kw[3]; int r = 1; - fixed (uint* pT0 = T0, pT1 = T1, pT2 = T2, pT3 = T3) + uint tmp1, tmp2, tmp3; + uint shift1, shift2, shift3; + + fixed (uint* pT0 = T0) { while (r < ROUNDS - 1) { - kw = KW[r++]; + kw = WorkingKey[r++]; fixed (uint* pkw = kw) { - r0 = pT0[t0 & 255] ^ pT1[(t1 >> 8) & 255] ^ pT2[(t2 >> 16) & 255] ^ pT3[r3 >> 24] ^ pkw[0]; - r1 = pT0[t1 & 255] ^ pT1[(t2 >> 8) & 255] ^ pT2[(r3 >> 16) & 255] ^ pT3[t0 >> 24] ^ pkw[1]; - r2 = pT0[t2 & 255] ^ pT1[(r3 >> 8) & 255] ^ pT2[(t0 >> 16) & 255] ^ pT3[t1 >> 24] ^ pkw[2]; - r3 = pT0[r3 & 255] ^ pT1[(t0 >> 8) & 255] ^ pT2[(t1 >> 16) & 255] ^ pT3[t2 >> 24] ^ pkw[3]; + tmp1 = pT0[(t1 >> 8) & 255]; tmp2 = pT0[(t2 >> 16) & 255]; tmp3 = pT0[(r3 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + r0 = pT0[t0 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[0]; + + tmp1 = pT0[(t2 >> 8) & 255]; tmp2 = pT0[(r3 >> 16) & 255]; tmp3 = pT0[(t0 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + r1 = pT0[t1 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[1]; + + tmp1 = pT0[(r3 >> 8) & 255]; tmp2 = pT0[(t0 >> 16) & 255]; tmp3 = pT0[(t1 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + r2 = pT0[t2 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[2]; + + tmp1 = pT0[(t0 >> 8) & 255]; tmp2 = pT0[(t1 >> 16) & 255]; tmp3 = pT0[(t2 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + r3 = pT0[r3 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[3]; } - kw = KW[r++]; + kw = WorkingKey[r++]; + fixed (uint* pkw = kw) { - t0 = pT0[r0 & 255] ^ pT1[(r1 >> 8) & 255] ^ pT2[(r2 >> 16) & 255] ^ pT3[r3 >> 24] ^ pkw[0]; - t1 = pT0[r1 & 255] ^ pT1[(r2 >> 8) & 255] ^ pT2[(r3 >> 16) & 255] ^ pT3[r0 >> 24] ^ pkw[1]; - t2 = pT0[r2 & 255] ^ pT1[(r3 >> 8) & 255] ^ pT2[(r0 >> 16) & 255] ^ pT3[r1 >> 24] ^ pkw[2]; - r3 = pT0[r3 & 255] ^ pT1[(r0 >> 8) & 255] ^ pT2[(r1 >> 16) & 255] ^ pT3[r2 >> 24] ^ pkw[3]; + tmp1 = pT0[(r1 >> 8) & 255]; tmp2 = pT0[(r2 >> 16) & 255]; tmp3 = pT0[(r3 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + t0 = pT0[r0 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[0]; + + tmp1 = pT0[(r2 >> 8) & 255]; tmp2 = pT0[(r3 >> 16) & 255]; tmp3 = pT0[(r0 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + t1 = pT0[r1 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[1]; + + tmp1 = pT0[(r3 >> 8) & 255]; tmp2 = pT0[(r0 >> 16) & 255]; tmp3 = pT0[(r1 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + t2 = pT0[r2 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[2]; + + tmp1 = pT0[(r0 >> 8) & 255]; tmp2 = pT0[(r1 >> 16) & 255]; tmp3 = pT0[(r2 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + r3 = pT0[r3 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[3]; } } - kw = KW[r++]; + kw = WorkingKey[r++]; fixed (uint* pkw = kw) { - r0 = pT0[t0 & 255] ^ pT1[(t1 >> 8) & 255] ^ pT2[(t2 >> 16) & 255] ^ pT3[r3 >> 24] ^ pkw[0]; - r1 = pT0[t1 & 255] ^ pT1[(t2 >> 8) & 255] ^ pT2[(r3 >> 16) & 255] ^ pT3[t0 >> 24] ^ pkw[1]; - r2 = pT0[t2 & 255] ^ pT1[(r3 >> 8) & 255] ^ pT2[(t0 >> 16) & 255] ^ pT3[t1 >> 24] ^ pkw[2]; - r3 = pT0[r3 & 255] ^ pT1[(t0 >> 8) & 255] ^ pT2[(t1 >> 16) & 255] ^ pT3[t2 >> 24] ^ pkw[3]; - } + tmp1 = pT0[(t1 >> 8) & 255]; tmp2 = pT0[(t2 >> 16) & 255]; tmp3 = pT0[(r3 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + r0 = pT0[t0 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[0]; - // the final round's table is a simple function of S so we don't use a whole other four tables for it + tmp1 = pT0[(t2 >> 8) & 255]; tmp2 = pT0[(r3 >> 16) & 255]; tmp3 = pT0[(t0 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + r1 = pT0[t1 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[1]; - kw = KW[r]; - fixed (uint* pkw = kw) - fixed (byte* pS = S) - { - this.C0 = (uint)pS[r0 & 255] ^ (((uint)pS[(r1 >> 8) & 255]) << 8) ^ (((uint)pS[(r2 >> 16) & 255]) << 16) ^ (((uint)pS[r3 >> 24]) << 24) ^ pkw[0]; - this.C1 = (uint)pS[r1 & 255] ^ (((uint)pS[(r2 >> 8) & 255]) << 8) ^ (((uint)pS[(r3 >> 16) & 255]) << 16) ^ (((uint)pS[r0 >> 24]) << 24) ^ pkw[1]; - this.C2 = (uint)pS[r2 & 255] ^ (((uint)pS[(r3 >> 8) & 255]) << 8) ^ (((uint)pS[(r0 >> 16) & 255]) << 16) ^ (((uint)pS[r1 >> 24]) << 24) ^ pkw[2]; - this.C3 = (uint)pS[r3 & 255] ^ (((uint)pS[(r0 >> 8) & 255]) << 8) ^ (((uint)pS[(r1 >> 16) & 255]) << 16) ^ (((uint)pS[r2 >> 24]) << 24) ^ pkw[3]; + tmp1 = pT0[(r3 >> 8) & 255]; tmp2 = pT0[(t0 >> 16) & 255]; tmp3 = pT0[(t1 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + r2 = pT0[t2 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[2]; + + tmp1 = pT0[(t0 >> 8) & 255]; tmp2 = pT0[(t1 >> 16) & 255]; tmp3 = pT0[(t2 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + r3 = pT0[r3 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[3]; } } + + // the final round's table is a simple function of S so we don't use a whole other four tables for it + + kw = WorkingKey[r]; + fixed (uint* pkw = kw) + fixed (byte* pS = S) + fixed (byte* ps = s) + { + C0 = (uint)pS[r0 & 255] ^ (((uint)pS[(r1 >> 8) & 255]) << 8) ^ (((uint)ps[(r2 >> 16) & 255]) << 16) ^ (((uint)ps[(r3 >> 24) & 255]) << 24) ^ pkw[0]; + C1 = (uint)ps[r1 & 255] ^ (((uint)pS[(r2 >> 8) & 255]) << 8) ^ (((uint)pS[(r3 >> 16) & 255]) << 16) ^ (((uint)ps[(r0 >> 24) & 255]) << 24) ^ pkw[1]; + C2 = (uint)ps[r2 & 255] ^ (((uint)pS[(r3 >> 8) & 255]) << 8) ^ (((uint)pS[(r0 >> 16) & 255]) << 16) ^ (((uint)pS[(r1 >> 24) & 255]) << 24) ^ pkw[2]; + C3 = (uint)ps[r3 & 255] ^ (((uint)ps[(r0 >> 8) & 255]) << 8) ^ (((uint)ps[(r1 >> 16) & 255]) << 16) ^ (((uint)pS[(r2 >> 24) & 255]) << 24) ^ pkw[3]; + } + + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(output, C0); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(output[4..], C1); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(output[8..], C2); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(output[12..], C3); } else { - uint[][] KW = WorkingKey; - uint[] kw = KW[ROUNDS]; - uint t0 = this.C0 ^ kw[0]; - uint t1 = this.C1 ^ kw[1]; - uint t2 = this.C2 ^ kw[2]; + //DecryptBlock(input, output, WorkingKey); + + uint C0 = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(input); + uint C1 = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(input[4..]); + uint C2 = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(input[8..]); + uint C3 = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(input[12..]); - uint r0, r1, r2, r3 = this.C3 ^ kw[3]; + uint[] kw = WorkingKey[ROUNDS]; + uint t0 = C0 ^ kw[0]; + uint t1 = C1 ^ kw[1]; + uint t2 = C2 ^ kw[2]; + + uint r0, r1, r2, r3 = C3 ^ kw[3]; int r = ROUNDS - 1; - fixed (uint* pTinv0 = Tinv0, pTinv1 = Tinv1, pTinv2 = Tinv2, pTinv3 = Tinv3) + + uint tmp1, tmp2, tmp3; + uint shift1, shift2, shift3; + + fixed (uint* pTinv0 = Tinv0) { while (r > 1) { - kw = KW[r--]; + kw = WorkingKey[r--]; fixed (uint* pkw = kw) { - r0 = pTinv0[t0 & 255] ^ pTinv1[(r3 >> 8) & 255] ^ pTinv2[(t2 >> 16) & 255] ^ pTinv3[t1 >> 24] ^ pkw[0]; - r1 = pTinv0[t1 & 255] ^ pTinv1[(t0 >> 8) & 255] ^ pTinv2[(r3 >> 16) & 255] ^ pTinv3[t2 >> 24] ^ pkw[1]; - r2 = pTinv0[t2 & 255] ^ pTinv1[(t1 >> 8) & 255] ^ pTinv2[(t0 >> 16) & 255] ^ pTinv3[r3 >> 24] ^ pkw[2]; - r3 = pTinv0[r3 & 255] ^ pTinv1[(t2 >> 8) & 255] ^ pTinv2[(t1 >> 16) & 255] ^ pTinv3[t0 >> 24] ^ pkw[3]; + tmp1 = pTinv0[(r3 >> 8) & 255]; tmp2 = pTinv0[(t2 >> 16) & 255]; tmp3 = pTinv0[(t1 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + r0 = pTinv0[t0 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[0]; + + tmp1 = pTinv0[(t0 >> 8) & 255]; tmp2 = pTinv0[(r3 >> 16) & 255]; tmp3 = pTinv0[(t2 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + r1 = pTinv0[t1 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[1]; + + tmp1 = pTinv0[(t1 >> 8) & 255]; tmp2 = pTinv0[(t0 >> 16) & 255]; tmp3 = pTinv0[(r3 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + r2 = pTinv0[t2 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[2]; + + tmp1 = pTinv0[(t2 >> 8) & 255]; tmp2 = pTinv0[(t1 >> 16) & 255]; tmp3 = pTinv0[(t0 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + r3 = pTinv0[r3 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[3]; } - kw = KW[r--]; + kw = WorkingKey[r--]; + fixed (uint* pkw = kw) { - t0 = pTinv0[r0 & 255] ^ pTinv1[(r3 >> 8) & 255] ^ pTinv2[(r2 >> 16) & 255] ^ pTinv3[r1 >> 24] ^ pkw[0]; - t1 = pTinv0[r1 & 255] ^ pTinv1[(r0 >> 8) & 255] ^ pTinv2[(r3 >> 16) & 255] ^ pTinv3[r2 >> 24] ^ pkw[1]; - t2 = pTinv0[r2 & 255] ^ pTinv1[(r1 >> 8) & 255] ^ pTinv2[(r0 >> 16) & 255] ^ pTinv3[r3 >> 24] ^ pkw[2]; - r3 = pTinv0[r3 & 255] ^ pTinv1[(r2 >> 8) & 255] ^ pTinv2[(r1 >> 16) & 255] ^ pTinv3[r0 >> 24] ^ pkw[3]; + tmp1 = pTinv0[(r3 >> 8) & 255]; tmp2 = pTinv0[(r2 >> 16) & 255]; tmp3 = pTinv0[(r1 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + t0 = pTinv0[r0 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[0]; + + tmp1 = pTinv0[(r0 >> 8) & 255]; tmp2 = pTinv0[(r3 >> 16) & 255]; tmp3 = pTinv0[(r2 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + t1 = pTinv0[r1 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[1]; + + tmp1 = pTinv0[(r1 >> 8) & 255]; tmp2 = pTinv0[(r0 >> 16) & 255]; tmp3 = pTinv0[(r3 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + t2 = pTinv0[r2 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[2]; + + tmp1 = pTinv0[(r2 >> 8) & 255]; tmp2 = pTinv0[(r1 >> 16) & 255]; tmp3 = pTinv0[(r0 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + r3 = pTinv0[r3 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[3]; } } - kw = KW[1]; + kw = WorkingKey[1]; + fixed (uint* pkw = kw) { - r0 = pTinv0[t0 & 255] ^ pTinv1[(r3 >> 8) & 255] ^ pTinv2[(t2 >> 16) & 255] ^ pTinv3[t1 >> 24] ^ pkw[0]; - r1 = pTinv0[t1 & 255] ^ pTinv1[(t0 >> 8) & 255] ^ pTinv2[(r3 >> 16) & 255] ^ pTinv3[t2 >> 24] ^ pkw[1]; - r2 = pTinv0[t2 & 255] ^ pTinv1[(t1 >> 8) & 255] ^ pTinv2[(t0 >> 16) & 255] ^ pTinv3[r3 >> 24] ^ pkw[2]; - r3 = pTinv0[r3 & 255] ^ pTinv1[(t2 >> 8) & 255] ^ pTinv2[(t1 >> 16) & 255] ^ pTinv3[t0 >> 24] ^ pkw[3]; - } + tmp1 = pTinv0[(r3 >> 8) & 255]; tmp2 = pTinv0[(t2 >> 16) & 255]; tmp3 = pTinv0[(t1 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + r0 = pTinv0[t0 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[0]; - // the final round's table is a simple function of Si so we don't use a whole other four tables for it + tmp1 = pTinv0[(t0 >> 8) & 255]; tmp2 = pTinv0[(r3 >> 16) & 255]; tmp3 = pTinv0[(t2 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + r1 = pTinv0[t1 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[1]; - kw = KW[0]; - fixed (uint* pkw = kw) - fixed (byte* pSi = Si) - { - this.C0 = (uint)pSi[r0 & 255] ^ (((uint)pSi[(r3 >> 8) & 255]) << 8) ^ (((uint)pSi[(r2 >> 16) & 255]) << 16) ^ (((uint)pSi[r1 >> 24]) << 24) ^ pkw[0]; - this.C1 = (uint)pSi[r1 & 255] ^ (((uint)pSi[(r0 >> 8) & 255]) << 8) ^ (((uint)pSi[(r3 >> 16) & 255]) << 16) ^ (((uint)pSi[r2 >> 24]) << 24) ^ pkw[1]; - this.C2 = (uint)pSi[r2 & 255] ^ (((uint)pSi[(r1 >> 8) & 255]) << 8) ^ (((uint)pSi[(r0 >> 16) & 255]) << 16) ^ (((uint)pSi[r3 >> 24]) << 24) ^ pkw[2]; - this.C3 = (uint)pSi[r3 & 255] ^ (((uint)pSi[(r2 >> 8) & 255]) << 8) ^ (((uint)pSi[(r1 >> 16) & 255]) << 16) ^ (((uint)pSi[r0 >> 24]) << 24) ^ pkw[3]; + tmp1 = pTinv0[(t1 >> 8) & 255]; tmp2 = pTinv0[(t0 >> 16) & 255]; tmp3 = pTinv0[(r3 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + r2 = pTinv0[t2 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[2]; + + tmp1 = pTinv0[(t2 >> 8) & 255]; tmp2 = pTinv0[(t1 >> 16) & 255]; tmp3 = pTinv0[(t0 >> 24) & 255]; + shift1 = (tmp1 >> 24) | (tmp1 << 8); shift2 = (tmp2 >> 16) | (tmp2 << 16); shift3 = (tmp3 >> 8) | (tmp3 << 24); + r3 = pTinv0[r3 & 255] ^ shift1 ^ shift2 ^ shift3 ^ pkw[3]; } } - } + // the final round's table is a simple function of Si so we don't use a whole other four tables for it - fixed (byte* poutput = output) - { - uint* puintOutput = (uint*)&poutput[outOff]; + kw = WorkingKey[0]; + fixed (uint* pkw = kw) + fixed(byte* pSi = Si) + fixed (byte* ps = s) + { + C0 = (uint)pSi[r0 & 255] ^ (((uint)ps[(r3 >> 8) & 255]) << 8) ^ (((uint)ps[(r2 >> 16) & 255]) << 16) ^ (((uint)pSi[(r1 >> 24) & 255]) << 24) ^ pkw[0]; + C1 = (uint)ps[r1 & 255] ^ (((uint)ps[(r0 >> 8) & 255]) << 8) ^ (((uint)pSi[(r3 >> 16) & 255]) << 16) ^ (((uint)ps[(r2 >> 24) & 255]) << 24) ^ pkw[1]; + C2 = (uint)ps[r2 & 255] ^ (((uint)pSi[(r1 >> 8) & 255]) << 8) ^ (((uint)pSi[(r0 >> 16) & 255]) << 16) ^ (((uint)ps[(r3 >> 24) & 255]) << 24) ^ pkw[2]; + C3 = (uint)pSi[r3 & 255] ^ (((uint)ps[(r2 >> 8) & 255]) << 8) ^ (((uint)ps[(r1 >> 16) & 255]) << 16) ^ (((uint)ps[(r0 >> 24) & 255]) << 24) ^ pkw[3]; + } - puintOutput[0] = C0; - puintOutput[1] = C1; - puintOutput[2] = C2; - puintOutput[3] = C3; + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(output, C0); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(output[4..], C1); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(output[8..], C2); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(output[12..], C3); } return BLOCK_SIZE; } +#endif - public void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void EncryptBlock(ReadOnlySpan input, Span output, uint[][] KW) { + uint C0 = Pack.LE_To_UInt32(input); + uint C1 = Pack.LE_To_UInt32(input[4..]); + uint C2 = Pack.LE_To_UInt32(input[8..]); + uint C3 = Pack.LE_To_UInt32(input[12..]); + + uint[] kw = KW[0]; + uint t0 = C0 ^ kw[0]; + uint t1 = C1 ^ kw[1]; + uint t2 = C2 ^ kw[2]; + + uint r0, r1, r2, r3 = C3 ^ kw[3]; + int r = 1; + while (r < ROUNDS - 1) + { + kw = KW[r++]; + r0 = T0[t0 & 255] ^ Shift(T0[(t1 >> 8) & 255], 24) ^ Shift(T0[(t2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0]; + r1 = T0[t1 & 255] ^ Shift(T0[(t2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(t0 >> 24) & 255], 8) ^ kw[1]; + r2 = T0[t2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(t0 >> 16) & 255], 16) ^ Shift(T0[(t1 >> 24) & 255], 8) ^ kw[2]; + r3 = T0[r3 & 255] ^ Shift(T0[(t0 >> 8) & 255], 24) ^ Shift(T0[(t1 >> 16) & 255], 16) ^ Shift(T0[(t2 >> 24) & 255], 8) ^ kw[3]; + kw = KW[r++]; + t0 = T0[r0 & 255] ^ Shift(T0[(r1 >> 8) & 255], 24) ^ Shift(T0[(r2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0]; + t1 = T0[r1 & 255] ^ Shift(T0[(r2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(r0 >> 24) & 255], 8) ^ kw[1]; + t2 = T0[r2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(r0 >> 16) & 255], 16) ^ Shift(T0[(r1 >> 24) & 255], 8) ^ kw[2]; + r3 = T0[r3 & 255] ^ Shift(T0[(r0 >> 8) & 255], 24) ^ Shift(T0[(r1 >> 16) & 255], 16) ^ Shift(T0[(r2 >> 24) & 255], 8) ^ kw[3]; + } + + kw = KW[r++]; + r0 = T0[t0 & 255] ^ Shift(T0[(t1 >> 8) & 255], 24) ^ Shift(T0[(t2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0]; + r1 = T0[t1 & 255] ^ Shift(T0[(t2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(t0 >> 24) & 255], 8) ^ kw[1]; + r2 = T0[t2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(t0 >> 16) & 255], 16) ^ Shift(T0[(t1 >> 24) & 255], 8) ^ kw[2]; + r3 = T0[r3 & 255] ^ Shift(T0[(t0 >> 8) & 255], 24) ^ Shift(T0[(t1 >> 16) & 255], 16) ^ Shift(T0[(t2 >> 24) & 255], 8) ^ kw[3]; + + // the final round's table is a simple function of S so we don't use a whole other four tables for it + + kw = KW[r]; + C0 = (uint)S[r0 & 255] ^ (((uint)S[(r1 >> 8) & 255]) << 8) ^ (((uint)s[(r2 >> 16) & 255]) << 16) ^ (((uint)s[(r3 >> 24) & 255]) << 24) ^ kw[0]; + C1 = (uint)s[r1 & 255] ^ (((uint)S[(r2 >> 8) & 255]) << 8) ^ (((uint)S[(r3 >> 16) & 255]) << 16) ^ (((uint)s[(r0 >> 24) & 255]) << 24) ^ kw[1]; + C2 = (uint)s[r2 & 255] ^ (((uint)S[(r3 >> 8) & 255]) << 8) ^ (((uint)S[(r0 >> 16) & 255]) << 16) ^ (((uint)S[(r1 >> 24) & 255]) << 24) ^ kw[2]; + C3 = (uint)s[r3 & 255] ^ (((uint)s[(r0 >> 8) & 255]) << 8) ^ (((uint)s[(r1 >> 16) & 255]) << 16) ^ (((uint)S[(r2 >> 24) & 255]) << 24) ^ kw[3]; + + Pack.UInt32_To_LE(C0, output); + Pack.UInt32_To_LE(C1, output[4..]); + Pack.UInt32_To_LE(C2, output[8..]); + Pack.UInt32_To_LE(C3, output[12..]); } - private unsafe void UnPackBlock( - byte[] input, - int inOff) + private void DecryptBlock(ReadOnlySpan input, Span output, uint[][] KW) { - fixed (byte* poutput = input) + uint C0 = Pack.LE_To_UInt32(input); + uint C1 = Pack.LE_To_UInt32(input[4..]); + uint C2 = Pack.LE_To_UInt32(input[8..]); + uint C3 = Pack.LE_To_UInt32(input[12..]); + + uint[] kw = KW[ROUNDS]; + uint t0 = C0 ^ kw[0]; + uint t1 = C1 ^ kw[1]; + uint t2 = C2 ^ kw[2]; + + uint r0, r1, r2, r3 = C3 ^ kw[3]; + int r = ROUNDS - 1; + while (r > 1) { - uint* puintoutput = (uint*)&poutput[inOff]; + kw = KW[r--]; + r0 = Tinv0[t0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(t2 >> 16) & 255], 16) ^ Shift(Tinv0[(t1 >> 24) & 255], 8) ^ kw[0]; + r1 = Tinv0[t1 & 255] ^ Shift(Tinv0[(t0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(t2 >> 24) & 255], 8) ^ kw[1]; + r2 = Tinv0[t2 & 255] ^ Shift(Tinv0[(t1 >> 8) & 255], 24) ^ Shift(Tinv0[(t0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2]; + r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(t2 >> 8) & 255], 24) ^ Shift(Tinv0[(t1 >> 16) & 255], 16) ^ Shift(Tinv0[(t0 >> 24) & 255], 8) ^ kw[3]; + kw = KW[r--]; + t0 = Tinv0[r0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(r2 >> 16) & 255], 16) ^ Shift(Tinv0[(r1 >> 24) & 255], 8) ^ kw[0]; + t1 = Tinv0[r1 & 255] ^ Shift(Tinv0[(r0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(r2 >> 24) & 255], 8) ^ kw[1]; + t2 = Tinv0[r2 & 255] ^ Shift(Tinv0[(r1 >> 8) & 255], 24) ^ Shift(Tinv0[(r0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2]; + r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(r2 >> 8) & 255], 24) ^ Shift(Tinv0[(r1 >> 16) & 255], 16) ^ Shift(Tinv0[(r0 >> 24) & 255], 8) ^ kw[3]; + } - C0 = puintoutput[0]; - C1 = puintoutput[1]; - C2 = puintoutput[2]; - C3 = puintoutput[3]; + kw = KW[1]; + r0 = Tinv0[t0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(t2 >> 16) & 255], 16) ^ Shift(Tinv0[(t1 >> 24) & 255], 8) ^ kw[0]; + r1 = Tinv0[t1 & 255] ^ Shift(Tinv0[(t0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(t2 >> 24) & 255], 8) ^ kw[1]; + r2 = Tinv0[t2 & 255] ^ Shift(Tinv0[(t1 >> 8) & 255], 24) ^ Shift(Tinv0[(t0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2]; + r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(t2 >> 8) & 255], 24) ^ Shift(Tinv0[(t1 >> 16) & 255], 16) ^ Shift(Tinv0[(t0 >> 24) & 255], 8) ^ kw[3]; - inOff += 16; - } + // the final round's table is a simple function of Si so we don't use a whole other four tables for it + + kw = KW[0]; + C0 = (uint)Si[r0 & 255] ^ (((uint)s[(r3 >> 8) & 255]) << 8) ^ (((uint)s[(r2 >> 16) & 255]) << 16) ^ (((uint)Si[(r1 >> 24) & 255]) << 24) ^ kw[0]; + C1 = (uint)s[r1 & 255] ^ (((uint)s[(r0 >> 8) & 255]) << 8) ^ (((uint)Si[(r3 >> 16) & 255]) << 16) ^ (((uint)s[(r2 >> 24) & 255]) << 24) ^ kw[1]; + C2 = (uint)s[r2 & 255] ^ (((uint)Si[(r1 >> 8) & 255]) << 8) ^ (((uint)Si[(r0 >> 16) & 255]) << 16) ^ (((uint)s[(r3 >> 24) & 255]) << 24) ^ kw[2]; + C3 = (uint)Si[r3 & 255] ^ (((uint)s[(r2 >> 8) & 255]) << 8) ^ (((uint)s[(r1 >> 16) & 255]) << 16) ^ (((uint)s[(r0 >> 24) & 255]) << 24) ^ kw[3]; + + Pack.UInt32_To_LE(C0, output); + Pack.UInt32_To_LE(C1, output[4..]); + Pack.UInt32_To_LE(C2, output[8..]); + Pack.UInt32_To_LE(C3, output[12..]); + } +#else + private void EncryptBlock(byte[] input, int inOff, byte[] output, int outOff, uint[][] KW) + { + FastAesEngineHelper.EncryptBlock(input, inOff, output, outOff, KW, ROUNDS, T0, S, s); + //uint C0 = Pack.LE_To_UInt32(input, inOff + 0); + //uint C1 = Pack.LE_To_UInt32(input, inOff + 4); + //uint C2 = Pack.LE_To_UInt32(input, inOff + 8); + //uint C3 = Pack.LE_To_UInt32(input, inOff + 12); + // + //uint[] kw = KW[0]; + //uint t0 = C0 ^ kw[0]; + //uint t1 = C1 ^ kw[1]; + //uint t2 = C2 ^ kw[2]; + // + //uint r0, r1, r2, r3 = C3 ^ kw[3]; + //int r = 1; + //while (r < ROUNDS - 1) + //{ + // kw = KW[r++]; + // r0 = T0[t0 & 255] ^ Shift(T0[(t1 >> 8) & 255], 24) ^ Shift(T0[(t2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0]; + // r1 = T0[t1 & 255] ^ Shift(T0[(t2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(t0 >> 24) & 255], 8) ^ kw[1]; + // r2 = T0[t2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(t0 >> 16) & 255], 16) ^ Shift(T0[(t1 >> 24) & 255], 8) ^ kw[2]; + // r3 = T0[r3 & 255] ^ Shift(T0[(t0 >> 8) & 255], 24) ^ Shift(T0[(t1 >> 16) & 255], 16) ^ Shift(T0[(t2 >> 24) & 255], 8) ^ kw[3]; + // kw = KW[r++]; + // t0 = T0[r0 & 255] ^ Shift(T0[(r1 >> 8) & 255], 24) ^ Shift(T0[(r2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0]; + // t1 = T0[r1 & 255] ^ Shift(T0[(r2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(r0 >> 24) & 255], 8) ^ kw[1]; + // t2 = T0[r2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(r0 >> 16) & 255], 16) ^ Shift(T0[(r1 >> 24) & 255], 8) ^ kw[2]; + // r3 = T0[r3 & 255] ^ Shift(T0[(r0 >> 8) & 255], 24) ^ Shift(T0[(r1 >> 16) & 255], 16) ^ Shift(T0[(r2 >> 24) & 255], 8) ^ kw[3]; + //} + // + //kw = KW[r++]; + //r0 = T0[t0 & 255] ^ Shift(T0[(t1 >> 8) & 255], 24) ^ Shift(T0[(t2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0]; + //r1 = T0[t1 & 255] ^ Shift(T0[(t2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(t0 >> 24) & 255], 8) ^ kw[1]; + //r2 = T0[t2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(t0 >> 16) & 255], 16) ^ Shift(T0[(t1 >> 24) & 255], 8) ^ kw[2]; + //r3 = T0[r3 & 255] ^ Shift(T0[(t0 >> 8) & 255], 24) ^ Shift(T0[(t1 >> 16) & 255], 16) ^ Shift(T0[(t2 >> 24) & 255], 8) ^ kw[3]; + // + //// the final round's table is a simple function of S so we don't use a whole other four tables for it + // + //kw = KW[r]; + //C0 = (uint)S[r0 & 255] ^ (((uint)S[(r1 >> 8) & 255]) << 8) ^ (((uint)s[(r2 >> 16) & 255]) << 16) ^ (((uint)s[(r3 >> 24) & 255]) << 24) ^ kw[0]; + //C1 = (uint)s[r1 & 255] ^ (((uint)S[(r2 >> 8) & 255]) << 8) ^ (((uint)S[(r3 >> 16) & 255]) << 16) ^ (((uint)s[(r0 >> 24) & 255]) << 24) ^ kw[1]; + //C2 = (uint)s[r2 & 255] ^ (((uint)S[(r3 >> 8) & 255]) << 8) ^ (((uint)S[(r0 >> 16) & 255]) << 16) ^ (((uint)S[(r1 >> 24) & 255]) << 24) ^ kw[2]; + //C3 = (uint)s[r3 & 255] ^ (((uint)s[(r0 >> 8) & 255]) << 8) ^ (((uint)s[(r1 >> 16) & 255]) << 16) ^ (((uint)S[(r2 >> 24) & 255]) << 24) ^ kw[3]; + // + //Pack.UInt32_To_LE(C0, output, outOff + 0); + //Pack.UInt32_To_LE(C1, output, outOff + 4); + //Pack.UInt32_To_LE(C2, output, outOff + 8); + //Pack.UInt32_To_LE(C3, output, outOff + 12); } - private unsafe void PackBlock( - byte[] output, - int outOff) + private void DecryptBlock(byte[] input, int inOff, byte[] output, int outOff, uint[][] KW) { - fixed (byte* poutput = output) + uint C0 = Pack.LE_To_UInt32(input, inOff + 0); + uint C1 = Pack.LE_To_UInt32(input, inOff + 4); + uint C2 = Pack.LE_To_UInt32(input, inOff + 8); + uint C3 = Pack.LE_To_UInt32(input, inOff + 12); + + uint[] kw = KW[ROUNDS]; + uint t0 = C0 ^ kw[0]; + uint t1 = C1 ^ kw[1]; + uint t2 = C2 ^ kw[2]; + + uint r0, r1, r2, r3 = C3 ^ kw[3]; + int r = ROUNDS - 1; + while (r > 1) { - uint* puintOutput = (uint*)&poutput[outOff]; + kw = KW[r--]; + r0 = Tinv0[t0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(t2 >> 16) & 255], 16) ^ Shift(Tinv0[(t1 >> 24) & 255], 8) ^ kw[0]; + r1 = Tinv0[t1 & 255] ^ Shift(Tinv0[(t0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(t2 >> 24) & 255], 8) ^ kw[1]; + r2 = Tinv0[t2 & 255] ^ Shift(Tinv0[(t1 >> 8) & 255], 24) ^ Shift(Tinv0[(t0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2]; + r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(t2 >> 8) & 255], 24) ^ Shift(Tinv0[(t1 >> 16) & 255], 16) ^ Shift(Tinv0[(t0 >> 24) & 255], 8) ^ kw[3]; + kw = KW[r--]; + t0 = Tinv0[r0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(r2 >> 16) & 255], 16) ^ Shift(Tinv0[(r1 >> 24) & 255], 8) ^ kw[0]; + t1 = Tinv0[r1 & 255] ^ Shift(Tinv0[(r0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(r2 >> 24) & 255], 8) ^ kw[1]; + t2 = Tinv0[r2 & 255] ^ Shift(Tinv0[(r1 >> 8) & 255], 24) ^ Shift(Tinv0[(r0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2]; + r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(r2 >> 8) & 255], 24) ^ Shift(Tinv0[(r1 >> 16) & 255], 16) ^ Shift(Tinv0[(r0 >> 24) & 255], 8) ^ kw[3]; + } - puintOutput[0] = C0; - puintOutput[1] = C1; - puintOutput[2] = C2; - puintOutput[3] = C3; + kw = KW[1]; + r0 = Tinv0[t0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(t2 >> 16) & 255], 16) ^ Shift(Tinv0[(t1 >> 24) & 255], 8) ^ kw[0]; + r1 = Tinv0[t1 & 255] ^ Shift(Tinv0[(t0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(t2 >> 24) & 255], 8) ^ kw[1]; + r2 = Tinv0[t2 & 255] ^ Shift(Tinv0[(t1 >> 8) & 255], 24) ^ Shift(Tinv0[(t0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2]; + r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(t2 >> 8) & 255], 24) ^ Shift(Tinv0[(t1 >> 16) & 255], 16) ^ Shift(Tinv0[(t0 >> 24) & 255], 8) ^ kw[3]; - outOff += 16; - } + // the final round's table is a simple function of Si so we don't use a whole other four tables for it + + kw = KW[0]; + C0 = (uint)Si[r0 & 255] ^ (((uint)s[(r3 >> 8) & 255]) << 8) ^ (((uint)s[(r2 >> 16) & 255]) << 16) ^ (((uint)Si[(r1 >> 24) & 255]) << 24) ^ kw[0]; + C1 = (uint)s[r1 & 255] ^ (((uint)s[(r0 >> 8) & 255]) << 8) ^ (((uint)Si[(r3 >> 16) & 255]) << 16) ^ (((uint)s[(r2 >> 24) & 255]) << 24) ^ kw[1]; + C2 = (uint)s[r2 & 255] ^ (((uint)Si[(r1 >> 8) & 255]) << 8) ^ (((uint)Si[(r0 >> 16) & 255]) << 16) ^ (((uint)s[(r3 >> 24) & 255]) << 24) ^ kw[2]; + C3 = (uint)Si[r3 & 255] ^ (((uint)s[(r2 >> 8) & 255]) << 8) ^ (((uint)s[(r1 >> 16) & 255]) << 16) ^ (((uint)s[(r0 >> 24) & 255]) << 24) ^ kw[3]; + + Pack.UInt32_To_LE(C0, output, outOff + 0); + Pack.UInt32_To_LE(C1, output, outOff + 4); + Pack.UInt32_To_LE(C2, output, outOff + 8); + Pack.UInt32_To_LE(C3, output, outOff + 12); } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastAesEngineHelper.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastAesEngineHelper.cs new file mode 100644 index 0000000..76f14cc --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastAesEngineHelper.cs @@ -0,0 +1,195 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +using System; + +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; + +namespace BestHTTP.Connections.TLS.Crypto.Impl +{ + internal static class FastAesEngineHelper + { + public unsafe static void EncryptBlock(byte[] input, int inOff, byte[] output, int outOff, uint[][] KW, int ROUNDS, uint[] T0, byte[] S, byte[] s) + { + uint C0 = Pack.LE_To_UInt32(input, inOff + 0); + uint C1 = Pack.LE_To_UInt32(input, inOff + 4); + uint C2 = Pack.LE_To_UInt32(input, inOff + 8); + uint C3 = Pack.LE_To_UInt32(input, inOff + 12); + + uint[] kw = KW[0]; + uint t0 = C0 ^ kw[0]; + uint t1 = C1 ^ kw[1]; + uint t2 = C2 ^ kw[2]; + + uint r0, r1, r2, r3 = C3 ^ kw[3]; + int r = 1; + + byte idx; + uint tmp1, tmp2, tmp3; + + fixed (uint* pT0 = T0) + { + while (r < ROUNDS - 1) + { + kw = KW[r++]; + + fixed (uint* pkw = kw) + { + idx = (byte)(t1 >> 8); + tmp1 = (pT0[idx] >> 24) | (pT0[idx] << 8); + + idx = (byte)(t2 >> 16); + tmp2 = (pT0[idx] >> 16) | (pT0[idx] << 16); + + idx = (byte)(r3 >> 24); + tmp3 = (pT0[idx] >> 8) | (pT0[idx] << 24); + r0 = pT0[t0 & 255] ^ tmp1 ^ tmp2 ^ tmp3 ^ pkw[0]; + + idx = (byte)(t2 >> 8); + tmp1 = (pT0[idx] >> 24) | (pT0[idx] << 8); + + idx = (byte)(r3 >> 16); + tmp2 = (pT0[idx] >> 16) | (pT0[idx] << 16); + + idx = (byte)(t0 >> 24); + tmp3 = (pT0[idx] >> 8) | (pT0[idx] << 24); + r1 = pT0[t1 & 255] ^ tmp1 ^ tmp2 ^ tmp3 ^ pkw[1]; + + idx = (byte)(r3 >> 8); + tmp1 = (pT0[idx] >> 24) | (pT0[idx] << 8); + + idx = (byte)(t0 >> 16); + tmp2 = (pT0[idx] >> 16) | (pT0[idx] << 16); + + idx = (byte)(t1 >> 24); + tmp3 = (pT0[idx] >> 8) | (pT0[idx] << 24); + + r2 = pT0[t2 & 255] ^ tmp1 ^ tmp2 ^ tmp3 ^ pkw[2]; + + idx = (byte)(t0 >> 8); + tmp1 = (pT0[idx] >> 24) | (pT0[idx] << 8); + + idx = (byte)(t1 >> 16); + tmp2 = (pT0[idx] >> 16) | (pT0[idx] << 16); + + idx = (byte)(t2 >> 24); + tmp3 = (pT0[idx] >> 8) | (pT0[idx] << 24); + + r3 = pT0[r3 & 255] ^ tmp1 ^ tmp2 ^ tmp3 ^ pkw[3]; + } + + kw = KW[r++]; + + fixed (uint* pkw = kw) + { + idx = (byte)(r1 >> 8); + tmp1 = (pT0[idx] >> 24) | (pT0[idx] << 8); + + idx = (byte)(r2 >> 16); + tmp2 = (pT0[idx] >> 16) | (pT0[idx] << 16); + + idx = (byte)(r3 >> 24); + tmp3 = (pT0[idx] >> 8) | (pT0[idx] << 24); + t0 = pT0[r0 & 255] ^ tmp1 ^ tmp2 ^ tmp3 ^ pkw[0]; + + idx = (byte)(r2 >> 8); + tmp1 = (pT0[idx] >> 24) | (pT0[idx] << 8); + + idx = (byte)(r3 >> 16); + tmp2 = (pT0[idx] >> 16) | (pT0[idx] << 16); + + idx = (byte)(r0 >> 24); + tmp3 = (pT0[idx] >> 8) | (pT0[idx] << 24); + t1 = pT0[r1 & 255] ^ tmp1 ^ tmp2 ^ tmp3 ^ pkw[1]; + + idx = (byte)(r3 >> 8); + tmp1 = (pT0[idx] >> 24) | (pT0[idx] << 8); + + idx = (byte)(r0 >> 16); + tmp2 = (pT0[idx] >> 16) | (pT0[idx] << 16); + + idx = (byte)(r1 >> 24); + tmp3 = (pT0[idx] >> 8) | (pT0[idx] << 24); + + t2 = pT0[r2 & 255] ^ tmp1 ^ tmp2 ^ tmp3 ^ pkw[2]; + + idx = (byte)(r0 >> 8); + tmp1 = (pT0[idx] >> 24) | (pT0[idx] << 8); + + idx = (byte)(r1 >> 16); + tmp2 = (pT0[idx] >> 16) | (pT0[idx] << 16); + + idx = (byte)(r2 >> 24); + tmp3 = (pT0[idx] >> 8) | (pT0[idx] << 24); + r3 = pT0[r3 & 255] ^ tmp1 ^ tmp2 ^ tmp3 ^ pkw[3]; + } + } + + kw = KW[r++]; + + fixed (uint* pkw = kw) + { + idx = (byte)(t1 >> 8); + tmp1 = (pT0[idx] >> 24) | (pT0[idx] << 8); + + idx = (byte)(t2 >> 16); + tmp2 = (pT0[idx] >> 16) | (pT0[idx] << 16); + + idx = (byte)(r3 >> 24); + tmp3 = (pT0[idx] >> 8) | (pT0[idx] << 24); + r0 = pT0[t0 & 255] ^ tmp1 ^ tmp2 ^ tmp3 ^ pkw[0]; + + idx = (byte)(t2 >> 8); + tmp1 = (pT0[idx] >> 24) | (pT0[idx] << 8); + + idx = (byte)(r3 >> 16); + tmp2 = (pT0[idx] >> 16) | (pT0[idx] << 16); + + idx = (byte)(t0 >> 24); + tmp3 = (pT0[idx] >> 8) | (pT0[idx] << 24); + + r1 = pT0[t1 & 255] ^ tmp1 ^ tmp2 ^ tmp3 ^ pkw[1]; + + idx = (byte)(r3 >> 8); + tmp1 = (pT0[idx] >> 24) | (pT0[idx] << 8); + + idx = (byte)(t0 >> 16); + tmp2 = (pT0[idx] >> 16) | (pT0[idx] << 16); + + idx = (byte)(t1 >> 24); + tmp3 = (pT0[idx] >> 8) | (pT0[idx] << 24); + + r2 = pT0[t2 & 255] ^ tmp1 ^ tmp2 ^ tmp3 ^ pkw[2]; + + idx = (byte)(t0 >> 8); + tmp1 = (pT0[idx] >> 24) | (pT0[idx] << 8); + + idx = (byte)(t1 >> 16); + tmp2 = (pT0[idx] >> 16) | (pT0[idx] << 16); + + idx = (byte)(t2 >> 24); + tmp3 = (pT0[idx] >> 8) | (pT0[idx] << 24); + + r3 = pT0[r3 & 255] ^ tmp1 ^ tmp2 ^ tmp3 ^ pkw[3]; + } + + // the final round's table is a simple function of S so we don't use a whole other four tables for it + + kw = KW[r]; + + fixed (byte* pS = S, ps = s) + fixed (uint* pkw = kw) + { + C0 = (uint)pS[(byte)r0] ^ (((uint)pS[(byte)(r1 >> 8)]) << 8) ^ (((uint)ps[(byte)(r2 >> 16)]) << 16) ^ (((uint)ps[(byte)(r3 >> 24)]) << 24) ^ pkw[0]; + C1 = (uint)ps[(byte)r1] ^ (((uint)pS[(byte)(r2 >> 8)]) << 8) ^ (((uint)pS[(byte)(r3 >> 16)]) << 16) ^ (((uint)ps[(byte)(r0 >> 24)]) << 24) ^ pkw[1]; + C2 = (uint)ps[(byte)r2] ^ (((uint)pS[(byte)(r3 >> 8)]) << 8) ^ (((uint)pS[(byte)(r0 >> 16)]) << 16) ^ (((uint)pS[(byte)(r1 >> 24)]) << 24) ^ pkw[2]; + C3 = (uint)ps[(byte)r3] ^ (((uint)ps[(byte)(r0 >> 8)]) << 8) ^ (((uint)ps[(byte)(r1 >> 16)]) << 16) ^ (((uint)pS[(byte)(r2 >> 24)]) << 24) ^ pkw[3]; + } + } + + Pack.UInt32_To_LE(C0, output, outOff + 0); + Pack.UInt32_To_LE(C1, output, outOff + 4); + Pack.UInt32_To_LE(C2, output, outOff + 8); + Pack.UInt32_To_LE(C3, output, outOff + 12); + } + } +} +#endif diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastAesEngineHelper.cs.meta b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastAesEngineHelper.cs.meta new file mode 100644 index 0000000..b86d502 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastAesEngineHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0f41ac81f5b4391419ba276b4bb78044 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastBcChaCha20Poly1305.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastBcChaCha20Poly1305.cs index 32bc2a2..e49e61c 100644 --- a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastBcChaCha20Poly1305.cs +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastBcChaCha20Poly1305.cs @@ -1,4 +1,5 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable using System; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines; @@ -28,13 +29,16 @@ public FastBcChaCha20Poly1305(bool isEncrypting) this.m_isEncrypting = isEncrypting; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + unsafe +#endif public int DoFinal(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) { if (m_isEncrypting) { int ciphertextLength = inputLength; - m_cipher.ProcessBytes(input, inputOffset, inputLength, output, outputOffset); + m_cipher.DoFinal(input, inputOffset, inputLength, output, outputOffset); int outputLength = inputLength; if (ciphertextLength != outputLength) @@ -42,14 +46,25 @@ public int DoFinal(byte[] input, int inputOffset, int inputLength, byte[] output UpdateMac(output, outputOffset, ciphertextLength); - byte[] lengths = BufferPool.Get(16, true); - Pack.UInt64_To_LE((ulong)m_additionalDataLength, lengths, 0); - Pack.UInt64_To_LE((ulong)ciphertextLength, lengths, 8); - m_mac.BlockUpdate(lengths, 0, 16); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span lengths = stackalloc byte[16]; - BufferPool.Release(lengths); + Pack.UInt64_To_LE((ulong)m_additionalDataLength, lengths); + Pack.UInt64_To_LE((ulong)ciphertextLength, lengths[8..]); - m_mac.DoFinal(output, outputOffset + ciphertextLength); + m_mac.BlockUpdate(lengths); + m_mac.DoFinal(output.AsSpan(outputOffset + ciphertextLength)); +#else + byte[] lengths = BufferPool.Get(16, true); + using (var _ = new PooledBuffer(lengths)) + { + Pack.UInt64_To_LE((ulong)m_additionalDataLength, lengths, 0); + Pack.UInt64_To_LE((ulong)ciphertextLength, lengths, 8); + + m_mac.BlockUpdate(lengths, 0, 16); + m_mac.DoFinal(output, outputOffset + ciphertextLength); + } +#endif return ciphertextLength + 16; } @@ -59,18 +74,37 @@ public int DoFinal(byte[] input, int inputOffset, int inputLength, byte[] output UpdateMac(input, inputOffset, ciphertextLength); - byte[] expectedMac = BufferPool.Get(16, true); - Pack.UInt64_To_LE((ulong)m_additionalDataLength, expectedMac, 0); - Pack.UInt64_To_LE((ulong)ciphertextLength, expectedMac, 8); - m_mac.BlockUpdate(expectedMac, 0, 16); - m_mac.DoFinal(expectedMac, 0); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span expectedMac = stackalloc byte[16]; + + Pack.UInt64_To_LE((ulong)m_additionalDataLength, expectedMac); + Pack.UInt64_To_LE((ulong)ciphertextLength, expectedMac[8..]); + + m_mac.BlockUpdate(expectedMac); + m_mac.DoFinal(expectedMac); bool badMac = !TlsUtilities.ConstantTimeAreEqual(16, expectedMac, 0, input, inputOffset + ciphertextLength); - BufferPool.Release(expectedMac); + if (badMac) throw new TlsFatalAlert(AlertDescription.bad_record_mac); +#else + byte[] expectedMac = BufferPool.Get(16, true); + using (var _ = new PooledBuffer(expectedMac)) + { + Pack.UInt64_To_LE((ulong)m_additionalDataLength, expectedMac, 0); + Pack.UInt64_To_LE((ulong)ciphertextLength, expectedMac, 8); + + m_mac.BlockUpdate(expectedMac, 0, 16); + m_mac.DoFinal(expectedMac, 0); + + bool badMac = !TlsUtilities.ConstantTimeAreEqual(16, expectedMac, 0, input, inputOffset + ciphertextLength); - m_cipher.ProcessBytes(input, inputOffset, ciphertextLength, output, outputOffset); + if (badMac) + throw new TlsFatalAlert(AlertDescription.bad_record_mac); + } +#endif + + m_cipher.DoFinal(input, inputOffset, ciphertextLength, output, outputOffset); int outputLength = ciphertextLength; if (ciphertextLength != outputLength) @@ -90,7 +124,7 @@ public void Init(byte[] nonce, int macSize, byte[] additionalData) if (nonce == null || nonce.Length != 12 || macSize != 16) throw new TlsFatalAlert(AlertDescription.internal_error); - m_cipher.Init(m_isEncrypting, new FastParametersWithIV(null, nonce)); + m_cipher.Init(m_isEncrypting, new ParametersWithIV(null, nonce)); InitMac(); if (additionalData == null) { @@ -103,30 +137,53 @@ public void Init(byte[] nonce, int macSize, byte[] additionalData) } } + public void Reset() + { + m_cipher.Reset(); + m_mac.Reset(); + } + public void SetKey(byte[] key, int keyOff, int keyLen) { - NoCopyKeyParameter cipherKey = new NoCopyKeyParameter(key, keyOff, keyLen); - m_cipher.Init(m_isEncrypting, new FastParametersWithIV(cipherKey, Zeroes, 0, 12)); + KeyParameter cipherKey = new KeyParameter(key, keyOff, keyLen); + m_cipher.Init(m_isEncrypting, new ParametersWithIV(cipherKey, Zeroes, 0, 12)); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void SetKey(ReadOnlySpan key) + { + KeyParameter cipherKey = new KeyParameter(key); + m_cipher.Init(m_isEncrypting, new ParametersWithIV(cipherKey, Zeroes[..12])); + } +#endif + + byte[] firstBlock = new byte[64]; private void InitMac() { - byte[] firstBlock = new byte[64]; m_cipher.ProcessBytes(firstBlock, 0, 64, firstBlock, 0); - m_mac.Init(new NoCopyKeyParameter(firstBlock, 0, 32)); + m_mac.Init(new KeyParameter(firstBlock, 0, 32)); Array.Clear(firstBlock, 0, firstBlock.Length); } private void UpdateMac(byte[] buf, int off, int len) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + m_mac.BlockUpdate(buf.AsSpan(off, len)); +#else m_mac.BlockUpdate(buf, off, len); +#endif int partial = len % 16; if (partial != 0) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + m_mac.BlockUpdate(Zeroes.AsSpan(0, 16 - partial)); +#else m_mac.BlockUpdate(Zeroes, 0, 16 - partial); +#endif } } } } +#pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastCbcBlockCipher.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastCbcBlockCipher.cs index cc8727d..2a29195 100644 --- a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastCbcBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastCbcBlockCipher.cs @@ -4,6 +4,7 @@ using BestHTTP.Connections.TLS.Crypto.Impl; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; namespace BestHTTP.Connections.TLS.Crypto @@ -11,12 +12,12 @@ namespace BestHTTP.Connections.TLS.Crypto /** * implements Cipher-Block-Chaining (CBC) mode on top of a simple cipher. */ - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] + + + [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] - public class FastCbcBlockCipher - : IBlockCipher + public sealed class FastCbcBlockCipher + : IBlockCipherMode { private byte[] IV, cbcV, cbcNextV; private int blockSize; @@ -44,10 +45,7 @@ public FastCbcBlockCipher( * * @return the underlying block cipher that we are wrapping. */ - public IBlockCipher GetUnderlyingCipher() - { - return cipher; - } + public IBlockCipher UnderlyingCipher => cipher; /** * Initialise the cipher and, possibly, the initialisation vector (IV). @@ -59,23 +57,18 @@ public IBlockCipher GetUnderlyingCipher() * @exception ArgumentException if the parameters argument is * inappropriate. */ - public void Init( - bool forEncryption, - ICipherParameters parameters) + public void Init(bool forEncryption, ICipherParameters parameters) { bool oldEncrypting = this.encrypting; this.encrypting = forEncryption; - if (parameters is FastParametersWithIV) + if (parameters is ParametersWithIV ivParam) { - FastParametersWithIV ivParam = (FastParametersWithIV)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); @@ -120,30 +113,28 @@ 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) + public int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { - return (encrypting) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return encrypting + ? EncryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)) + : DecryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); +#else + return encrypting ? EncryptBlock(input, inOff, output, outOff) : DecryptBlock(input, inOff, output, outOff); +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessBlock(ReadOnlySpan input, Span output) + { + return encrypting + ? EncryptBlock(input, output) + : DecryptBlock(input, output); + } +#endif + /** * reset the chaining vector back to the IV and reset the underlying * cipher. @@ -152,112 +143,85 @@ 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 unsafe int EncryptBlock( - byte[] input, - int inOff, - byte[] outBytes, - int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int EncryptBlock(ReadOnlySpan input, Span output) { - if ((inOff + blockSize) > input.Length) + Check.DataLength(input, blockSize, "input buffer too short"); + Check.OutputLength(output, blockSize, "output buffer too short"); + + for (int i = 0; i < blockSize; i++) { - throw new DataLengthException("input buffer too short"); + cbcV[i] ^= input[i]; } - /* - * XOR the cbcV and the input, - * then encrypt the cbcV - */ - //for (int i = 0; i < blockSize; i++) - //{ - // cbcV[i] ^= input[inOff + i]; - //} - fixed (byte* pinput = input, pcbcV = cbcV) + int length = cipher.ProcessBlock(cbcV, output); + + output[..blockSize].CopyTo(cbcV); + + return length; + } + + private int DecryptBlock(ReadOnlySpan input, Span output) + { + Check.DataLength(input, blockSize, "input buffer too short"); + Check.OutputLength(output, blockSize, "output buffer too short"); + + input[..blockSize].CopyTo(cbcNextV); + + int length = cipher.ProcessBlock(input, output); + + for (int i = 0; i < blockSize; i++) { - ulong* pulongInput = (ulong*)&pinput[inOff], pulongcbcV = (ulong*)pcbcV; + output[i] ^= cbcV[i]; + } + + byte[] tmp = cbcV; + cbcV = cbcNextV; + cbcNextV = tmp; + + return length; + } +#else + private int EncryptBlock(byte[] input, int inOff, byte[] outBytes, int outOff) + { + Check.DataLength(input, inOff, blockSize, "input buffer too short"); + Check.OutputLength(outBytes, outOff, blockSize, "output buffer too short"); - for (int i = 0; i < blockSize / 8; i++) - pulongcbcV[i] ^= pulongInput[i]; + 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 unsafe int DecryptBlock( - byte[] input, - int inOff, - byte[] outBytes, - int outOff) + private int DecryptBlock(byte[] input, int inOff, byte[] outBytes, int outOff) { - if ((inOff + blockSize) > input.Length) - { - throw new DataLengthException("input buffer too short"); - } + Check.DataLength(input, inOff, blockSize, "input buffer too short"); + Check.OutputLength(outBytes, outOff, blockSize, "output 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]; - //} - fixed (byte* poutBytes = outBytes, pcbcV = cbcV) + + for (int i = 0; i < blockSize; i++) { - ulong* pulongBytes = (ulong*)&poutBytes[outOff], pulongcbcV = (ulong*)pcbcV; - - for (int i = 0; i < blockSize / 8; i++) - pulongBytes[i] ^= pulongcbcV[i]; + outBytes[outOff + i] ^= cbcV[i]; } - /* - * swap the back up buffer into next position - */ - byte[] tmp; - - tmp = cbcV; + byte[] tmp = cbcV; cbcV = cbcNextV; cbcNextV = tmp; return length; } +#endif } } diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastCcmBlockCipher.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastCcmBlockCipher.cs index 5c67155..3d64838 100644 --- a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastCcmBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastCcmBlockCipher.cs @@ -11,113 +11,6 @@ namespace BestHTTP.Connections.TLS.Crypto.Impl { - public class FastSicBlockCipher - : 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 FastSicBlockCipher(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) - { - FastParametersWithIV ivParam = parameters as FastParametersWithIV; - if (ivParam == null) - throw new ArgumentException("CTR/SIC mode requires ParametersWithIV", "parameters"); - - this.IV = 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(); - } - } - /** * Implements the Counter with Cipher Block Chaining mode (CCM) detailed in * NIST Special Publication 800-38C. @@ -160,35 +53,26 @@ public FastCcmBlockCipher( * * @return the underlying block cipher that we are wrapping. */ - public virtual IBlockCipher GetUnderlyingCipher() - { - return cipher; - } + public virtual IBlockCipher UnderlyingCipher => cipher; - public virtual void Init( - bool forEncryption, - ICipherParameters parameters) + public virtual void Init(bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; ICipherParameters cipherParameters; - if (parameters is FastAeadParameters) + if (parameters is AeadParameters aeadParameters) { - AeadParameters param = (AeadParameters)parameters; - - nonce = param.GetNonce(); - initialAssociatedText = param.GetAssociatedText(); - macSize = GetMacSize(forEncryption, param.MacSize); - cipherParameters = param.Key; + nonce = aeadParameters.GetNonce(); + initialAssociatedText = aeadParameters.GetAssociatedText(); + macSize = GetMacSize(forEncryption, aeadParameters.MacSize); + cipherParameters = aeadParameters.Key; } - else if (parameters is FastParametersWithIV) + else if (parameters is ParametersWithIV parametersWithIV) { - FastParametersWithIV param = (FastParametersWithIV)parameters; - - nonce = param.GetIV(); + nonce = parametersWithIV.GetIV(); initialAssociatedText = null; macSize = GetMacSize(forEncryption, 64); - cipherParameters = param.Parameters; + cipherParameters = parametersWithIV.Parameters; } else { @@ -207,10 +91,7 @@ public virtual void Init( Reset(); } - public virtual string AlgorithmName - { - get { return cipher.AlgorithmName + "/CCM"; } - } + public virtual string AlgorithmName => cipher.AlgorithmName + "/CCM"; public virtual int GetBlockSize() { @@ -228,52 +109,80 @@ public virtual void ProcessAadBytes(byte[] inBytes, int inOff, int len) associatedText.Write(inBytes, inOff, len); } - public virtual int ProcessByte( - byte input, - byte[] outBytes, - int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void ProcessAadBytes(ReadOnlySpan input) + { + // TODO: Process AAD online + associatedText.Write(input); + } +#endif + + public virtual int ProcessByte(byte input, byte[] outBytes, int outOff) + { + data.WriteByte(input); + + return 0; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessByte(byte input, Span output) { data.WriteByte(input); return 0; } +#endif - public virtual int ProcessBytes( - byte[] inBytes, - int inOff, - int inLen, - byte[] outBytes, - int outOff) + public virtual int ProcessBytes(byte[] inBytes, int inOff, int inLen, byte[] outBytes, int outOff) { - Check.DataLength(inBytes, inOff, inLen, "Input buffer too short"); + 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 NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBytes(ReadOnlySpan input, Span output) { -#if PORTABLE || NETFX_CORE - byte[] input = data.ToArray(); - int inLen = input.Length; + data.Write(input); + + return 0; + } +#endif + + public virtual int DoFinal(byte[] outBytes, int outOff) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(outBytes.AsSpan(outOff)); #else byte[] input = data.GetBuffer(); - int inLen = (int)data.Position; -#endif + int inLen = Convert.ToInt32(data.Length); int len = ProcessPacket(input, 0, inLen, outBytes, outOff); Reset(); + return len; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int DoFinal(Span output) + { + byte[] input = data.GetBuffer(); + int inLen = Convert.ToInt32(data.Length); + + int len = ProcessPacket(input.AsSpan(0, inLen), output); + + Reset(); + return len; } +#endif public virtual void Reset() { - cipher.Reset(); associatedText.SetLength(0); data.SetLength(0); } @@ -289,16 +198,14 @@ public virtual byte[] GetMac() return Arrays.CopyOfRange(macBlock, 0, macSize); } - public virtual int GetUpdateOutputSize( - int len) + public virtual int GetUpdateOutputSize(int len) { return 0; } - public virtual int GetOutputSize( - int len) + public virtual int GetOutputSize(int len) { - int totalData = (int)data.Length + len; + int totalData = Convert.ToInt32(data.Length) + len; if (forEncryption) { @@ -373,7 +280,7 @@ public virtual int ProcessPacket(byte[] input, int inOff, int inLen, byte[] outp nonce.CopyTo(iv, 1); IBlockCipher ctrCipher = new FastSicBlockCipher(cipher); - ctrCipher.Init(forEncryption, new FastParametersWithIV(keyParam, iv)); + ctrCipher.Init(forEncryption, new ParametersWithIV(keyParam, iv)); int outputLen; int inIndex = inOff; @@ -449,8 +356,106 @@ public virtual int ProcessPacket(byte[] input, int inOff, int inLen, byte[] outp return outputLen; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessPacket(ReadOnlySpan input, Span output) + { + int inLen = input.Length; + + // 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 index = 0; + Span block = stackalloc byte[BlockSize]; + + if (forEncryption) + { + outputLen = inLen + macSize; + Check.OutputLength(output, outputLen, "output buffer too short"); + + CalculateMac(input, macBlock); + + byte[] encMac = new byte[BlockSize]; + ctrCipher.ProcessBlock(macBlock, encMac); // S0 + + while (index < (inLen - BlockSize)) // S1... + { + ctrCipher.ProcessBlock(input[index..], output[index..]); + index += BlockSize; + } + + input[index..].CopyTo(block); + + ctrCipher.ProcessBlock(block, block); + + block[..(inLen - index)].CopyTo(output[index..]); + + encMac.AsSpan(0, macSize).CopyTo(output[inLen..]); + } + else + { + if (inLen < macSize) + throw new InvalidCipherTextException("data too short"); + + outputLen = inLen - macSize; + Check.OutputLength(output, outputLen, "output buffer too short"); + + input[outputLen..].CopyTo(macBlock); + + ctrCipher.ProcessBlock(macBlock, macBlock); + + for (int i = macSize; i != macBlock.Length; i++) + { + macBlock[i] = 0; + } + + while (index < (outputLen - BlockSize)) + { + ctrCipher.ProcessBlock(input[index..], output[index..]); + index += BlockSize; + } + + input[index..outputLen].CopyTo(block); + + ctrCipher.ProcessBlock(block, block); + + block[..(outputLen - index)].CopyTo(output[index..]); + + Span calculatedMacBlock = stackalloc byte[BlockSize]; + + CalculateMac(output[..outputLen], calculatedMacBlock); + + if (!Arrays.ConstantTimeAreEqual(macBlock, calculatedMacBlock)) + throw new InvalidCipherTextException("mac check in CCM failed"); + } + + return outputLen; + } +#endif + private int CalculateMac(byte[] data, int dataOff, int dataLen, byte[] macBlock) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return CalculateMac(data.AsSpan(dataOff, dataLen), macBlock); +#else IMac cMac = new CbcBlockCipherMac(cipher, macSize * 8); cMac.Init(keyParam); @@ -513,15 +518,10 @@ private int CalculateMac(byte[] data, int dataOff, int dataLen, byte[] macBlock) { cMac.BlockUpdate(initialAssociatedText, 0, initialAssociatedText.Length); } - if (associatedText.Position > 0) + if (associatedText.Length > 0) { -#if PORTABLE || NETFX_CORE - byte[] input = associatedText.ToArray(); - int len = input.Length; -#else byte[] input = associatedText.GetBuffer(); - int len = (int)associatedText.Position; -#endif + int len = Convert.ToInt32(associatedText.Length); cMac.BlockUpdate(input, 0, len); } @@ -542,8 +542,101 @@ private int CalculateMac(byte[] data, int dataOff, int dataLen, byte[] macBlock) cMac.BlockUpdate(data, dataOff, dataLen); return cMac.DoFinal(macBlock, 0); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int CalculateMac(ReadOnlySpan data, Span 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 = data.Length; + 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.Length > 0) + { + byte[] input = associatedText.GetBuffer(); + int len = Convert.ToInt32(associatedText.Length); + + 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); + + return cMac.DoFinal(macBlock); + } +#endif + private int GetMacSize(bool forEncryption, int requestedMacBits) { if (forEncryption && (requestedMacBits < 32 || requestedMacBits > 128 || 0 != (requestedMacBits & 15))) @@ -554,7 +647,8 @@ private int GetMacSize(bool forEncryption, int requestedMacBits) private int GetAssociatedTextLength() { - return (int)associatedText.Length + ((initialAssociatedText == null) ? 0 : initialAssociatedText.Length); + return Convert.ToInt32(associatedText.Length) + + (initialAssociatedText == null ? 0 : initialAssociatedText.Length); } private bool HasAssociatedText() diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaCha7539Engine.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaCha7539Engine.cs index 4d2c707..c3db600 100644 --- a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaCha7539Engine.cs +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaCha7539Engine.cs @@ -1,7 +1,10 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.CompilerServices; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; namespace BestHTTP.Connections.TLS.Crypto.Impl @@ -9,9 +12,9 @@ namespace BestHTTP.Connections.TLS.Crypto.Impl /// /// Implementation of Daniel J. Bernstein's ChaCha stream cipher. /// - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] + + + [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] public sealed class FastChaCha7539Engine : FastSalsa20Engine @@ -64,11 +67,465 @@ protected override void SetKey(byte[] keyBytes, byte[] ivBytes) protected override void GenerateKeyStream(byte[] output) { - FastChaChaEngine.ChachaCore(rounds, engineState, x); - Pack.UInt32_To_LE(x, output, 0); + FastChaChaEngineHelper.ChachaCore(rounds, engineState, output); + } + + internal void DoFinal(byte[] inBuf, int inOff, int inLen, byte[] outBuf, int outOff) + { + if (!initialised) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + if (index != 0) + throw new InvalidOperationException(AlgorithmName + " not in block-aligned state"); + + Check.DataLength(inBuf, inOff, inLen, "input buffer too short"); + Check.OutputLength(outBuf, outOff, inLen, "output buffer too short"); + + while (inLen >= 128) + { +#if BESTHTTP_WITH_BURST + FastChaCha7539EngineHelper.ProcessBlocks2(inBuf.AsSpan(inOff), outBuf.AsSpan(outOff), engineState, rounds, keyStream); +#elif NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + //ProcessBlocks2(inBuf.AsSpan(inOff), outBuf.AsSpan(outOff)); + + var input = inBuf.AsSpan(inOff); + var output = outBuf.AsSpan(outOff); + ImplProcessBlock(inBuf.AsSpan(inOff), outBuf.AsSpan(outOff)); + ImplProcessBlock(input[64..], output[64..]); +#else + ProcessBlocks2(inBuf, inOff, outBuf, outOff); +#endif + inOff += 128; + inLen -= 128; + outOff += 128; + } + + if (inLen >= 64) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ImplProcessBlock(inBuf.AsSpan(inOff), outBuf.AsSpan(outOff)); +#else + ImplProcessBlock(inBuf, inOff, outBuf, outOff); +#endif + inOff += 64; + inLen -= 64; + outOff += 64; + } + + if (inLen > 0) + { + GenerateKeyStream(keyStream); + //AdvanceCounter(); + if (++engineState[12] == 0) + throw new InvalidOperationException("attempt to increase counter past 2^32."); + + for (int i = 0; i < inLen; ++i) + { + outBuf[outOff + i] = (byte)(inBuf[i + inOff] ^ keyStream[i]); + } + } + + engineState[12] = 0; + + // TODO Prevent re-use if encrypting + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal void ProcessBlock(ReadOnlySpan input, Span output) + { + if (!initialised) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + if (LimitExceeded(64U)) + throw new MaxBytesExceededException("2^38 byte limit per IV would be exceeded; Change IV"); + + UnityEngine.Debug.Assert(index == 0); + + ImplProcessBlock(input, output); + } + + internal void ProcessBlocks2(ReadOnlySpan input, Span output) + { + if (!initialised) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + if (LimitExceeded(128U)) + throw new MaxBytesExceededException("2^38 byte limit per IV would be exceeded; Change IV"); + + UnityEngine.Debug.Assert(index == 0); + +#if NETCOREAPP3_0_OR_GREATER + if (Avx2.IsSupported) + { + ImplProcessBlocks2_X86_Avx2(rounds, engineState, input, output); + return; + } + + if (Sse2.IsSupported) + { + ImplProcessBlocks2_X86_Sse2(rounds, engineState, input, output); + return; + } +#endif + + { + ImplProcessBlock(input, output); + ImplProcessBlock(input[64..], output[64..]); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void ImplProcessBlock(ReadOnlySpan input, Span output) + { + FastChaChaEngineHelper.ChachaCore(rounds, engineState, keyStream); + + //AdvanceCounter(); + if (++engineState[12] == 0) + throw new InvalidOperationException("attempt to increase counter past 2^32."); + + FastChaChaEngineHelper.ImplProcessBlock(input, output, keyStream); + } +#else + internal void ProcessBlock(byte[] inBytes, int inOff, byte[] outBytes, int outOff) + { + if (!initialised) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + if (LimitExceeded(64U)) + throw new MaxBytesExceededException("2^38 byte limit per IV would be exceeded; Change IV"); + + UnityEngine.Debug.Assert(index == 0); + + ImplProcessBlock(inBytes, inOff, outBytes, outOff); + } + + internal void ProcessBlocks2(byte[] inBytes, int inOff, byte[] outBytes, int outOff) + { + if (!initialised) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + if (LimitExceeded(128U)) + throw new MaxBytesExceededException("2^38 byte limit per IV would be exceeded; Change IV"); + + UnityEngine.Debug.Assert(index == 0); + + { + ImplProcessBlock(inBytes, inOff, outBytes, outOff); + ImplProcessBlock(inBytes, inOff + 64, outBytes, outOff + 64); + } + } + +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif + internal void ImplProcessBlock(byte[] inBuf, int inOff, byte[] outBuf, int outOff) + { + ChaChaEngine.ChachaCore(rounds, engineState, keyStream); + AdvanceCounter(); + + for (int i = 0; i < 64; ++i) + { + outBuf[outOff + i] = (byte)(keyStream[i] ^ inBuf[inOff + i]); } } +#endif + +#if NETCOREAPP3_0_OR_GREATER + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void ImplProcessBlocks2_X86_Avx2(int rounds, uint[] state, ReadOnlySpan input, + Span output) + { + if (!Avx2.IsSupported) + throw new PlatformNotSupportedException(); + + Debug.Assert(rounds % 2 == 0); + Debug.Assert(state.Length >= 16); + Debug.Assert(input.Length >= 128); + Debug.Assert(output.Length >= 128); + + var t0 = Load128_UInt32(state.AsSpan()); + var t1 = Load128_UInt32(state.AsSpan(4)); + var t2 = Load128_UInt32(state.AsSpan(8)); + var t3 = Load128_UInt32(state.AsSpan(12)); + ++state[12]; + var t4 = Load128_UInt32(state.AsSpan(12)); + ++state[12]; + + var x0 = Vector256.Create(t0, t0); + var x1 = Vector256.Create(t1, t1); + var x2 = Vector256.Create(t2, t2); + var x3 = Vector256.Create(t3, t4); + + var v0 = x0; + var v1 = x1; + var v2 = x2; + var v3 = x3; + + for (int i = rounds; i > 0; i -= 2) + { + v0 = Avx2.Add(v0, v1); + v3 = Avx2.Xor(v3, v0); + v3 = Avx2.Xor(Avx2.ShiftLeftLogical(v3, 16), Avx2.ShiftRightLogical(v3, 16)); + v2 = Avx2.Add(v2, v3); + v1 = Avx2.Xor(v1, v2); + v1 = Avx2.Xor(Avx2.ShiftLeftLogical(v1, 12), Avx2.ShiftRightLogical(v1, 20)); + v0 = Avx2.Add(v0, v1); + v3 = Avx2.Xor(v3, v0); + v3 = Avx2.Xor(Avx2.ShiftLeftLogical(v3, 8), Avx2.ShiftRightLogical(v3, 24)); + v2 = Avx2.Add(v2, v3); + v1 = Avx2.Xor(v1, v2); + v1 = Avx2.Xor(Avx2.ShiftLeftLogical(v1, 7), Avx2.ShiftRightLogical(v1, 25)); + + v1 = Avx2.Shuffle(v1, 0x39); + v2 = Avx2.Shuffle(v2, 0x4E); + v3 = Avx2.Shuffle(v3, 0x93); + + v0 = Avx2.Add(v0, v1); + v3 = Avx2.Xor(v3, v0); + v3 = Avx2.Xor(Avx2.ShiftLeftLogical(v3, 16), Avx2.ShiftRightLogical(v3, 16)); + v2 = Avx2.Add(v2, v3); + v1 = Avx2.Xor(v1, v2); + v1 = Avx2.Xor(Avx2.ShiftLeftLogical(v1, 12), Avx2.ShiftRightLogical(v1, 20)); + v0 = Avx2.Add(v0, v1); + v3 = Avx2.Xor(v3, v0); + v3 = Avx2.Xor(Avx2.ShiftLeftLogical(v3, 8), Avx2.ShiftRightLogical(v3, 24)); + v2 = Avx2.Add(v2, v3); + v1 = Avx2.Xor(v1, v2); + v1 = Avx2.Xor(Avx2.ShiftLeftLogical(v1, 7), Avx2.ShiftRightLogical(v1, 25)); + + v1 = Avx2.Shuffle(v1, 0x93); + v2 = Avx2.Shuffle(v2, 0x4E); + v3 = Avx2.Shuffle(v3, 0x39); + } + + v0 = Avx2.Add(v0, x0); + v1 = Avx2.Add(v1, x1); + v2 = Avx2.Add(v2, x2); + v3 = Avx2.Add(v3, x3); + + var n0 = Avx2.Permute2x128(v0, v1, 0x20).AsByte(); + var n1 = Avx2.Permute2x128(v2, v3, 0x20).AsByte(); + var n2 = Avx2.Permute2x128(v0, v1, 0x31).AsByte(); + var n3 = Avx2.Permute2x128(v2, v3, 0x31).AsByte(); + + n0 = Avx2.Xor(n0, Load256_Byte(input)); + n1 = Avx2.Xor(n1, Load256_Byte(input[0x20..])); + n2 = Avx2.Xor(n2, Load256_Byte(input[0x40..])); + n3 = Avx2.Xor(n3, Load256_Byte(input[0x60..])); + + Store256_Byte(n0, output); + Store256_Byte(n1, output[0x20..]); + Store256_Byte(n2, output[0x40..]); + Store256_Byte(n3, output[0x60..]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void ImplProcessBlocks2_X86_Sse2(int rounds, uint[] state, ReadOnlySpan input, + Span output) + { + if (!Sse2.IsSupported) + throw new PlatformNotSupportedException(); + + Debug.Assert(rounds % 2 == 0); + Debug.Assert(state.Length >= 16); + Debug.Assert(input.Length >= 128); + Debug.Assert(output.Length >= 128); + + var x0 = Load128_UInt32(state.AsSpan()); + var x1 = Load128_UInt32(state.AsSpan(4)); + var x2 = Load128_UInt32(state.AsSpan(8)); + var x3 = Load128_UInt32(state.AsSpan(12)); + ++state[12]; + + var v0 = x0; + var v1 = x1; + var v2 = x2; + var v3 = x3; + + for (int i = rounds; i > 0; i -= 2) + { + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 16), Sse2.ShiftRightLogical(v3, 16)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 12), Sse2.ShiftRightLogical(v1, 20)); + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 8), Sse2.ShiftRightLogical(v3, 24)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 7), Sse2.ShiftRightLogical(v1, 25)); + + v1 = Sse2.Shuffle(v1, 0x39); + v2 = Sse2.Shuffle(v2, 0x4E); + v3 = Sse2.Shuffle(v3, 0x93); + + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 16), Sse2.ShiftRightLogical(v3, 16)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 12), Sse2.ShiftRightLogical(v1, 20)); + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 8), Sse2.ShiftRightLogical(v3, 24)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 7), Sse2.ShiftRightLogical(v1, 25)); + + v1 = Sse2.Shuffle(v1, 0x93); + v2 = Sse2.Shuffle(v2, 0x4E); + v3 = Sse2.Shuffle(v3, 0x39); + } + + v0 = Sse2.Add(v0, x0); + v1 = Sse2.Add(v1, x1); + v2 = Sse2.Add(v2, x2); + v3 = Sse2.Add(v3, x3); + + var n0 = Load128_Byte(input); + var n1 = Load128_Byte(input[0x10..]); + var n2 = Load128_Byte(input[0x20..]); + var n3 = Load128_Byte(input[0x30..]); + + n0 = Sse2.Xor(n0, v0.AsByte()); + n1 = Sse2.Xor(n1, v1.AsByte()); + n2 = Sse2.Xor(n2, v2.AsByte()); + n3 = Sse2.Xor(n3, v3.AsByte()); + + Store128_Byte(n0, output); + Store128_Byte(n1, output[0x10..]); + Store128_Byte(n2, output[0x20..]); + Store128_Byte(n3, output[0x30..]); + + x3 = Load128_UInt32(state.AsSpan(12)); + ++state[12]; + + v0 = x0; + v1 = x1; + v2 = x2; + v3 = x3; + + for (int i = rounds; i > 0; i -= 2) + { + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 16), Sse2.ShiftRightLogical(v3, 16)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 12), Sse2.ShiftRightLogical(v1, 20)); + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 8), Sse2.ShiftRightLogical(v3, 24)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 7), Sse2.ShiftRightLogical(v1, 25)); + + v1 = Sse2.Shuffle(v1, 0x39); + v2 = Sse2.Shuffle(v2, 0x4E); + v3 = Sse2.Shuffle(v3, 0x93); + + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 16), Sse2.ShiftRightLogical(v3, 16)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 12), Sse2.ShiftRightLogical(v1, 20)); + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 8), Sse2.ShiftRightLogical(v3, 24)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 7), Sse2.ShiftRightLogical(v1, 25)); + + v1 = Sse2.Shuffle(v1, 0x93); + v2 = Sse2.Shuffle(v2, 0x4E); + v3 = Sse2.Shuffle(v3, 0x39); + } + + v0 = Sse2.Add(v0, x0); + v1 = Sse2.Add(v1, x1); + v2 = Sse2.Add(v2, x2); + v3 = Sse2.Add(v3, x3); + + n0 = Load128_Byte(input[0x40..]); + n1 = Load128_Byte(input[0x50..]); + n2 = Load128_Byte(input[0x60..]); + n3 = Load128_Byte(input[0x70..]); + + n0 = Sse2.Xor(n0, v0.AsByte()); + n1 = Sse2.Xor(n1, v1.AsByte()); + n2 = Sse2.Xor(n2, v2.AsByte()); + n3 = Sse2.Xor(n3, v3.AsByte()); + + Store128_Byte(n0, output[0x40..]); + Store128_Byte(n1, output[0x50..]); + Store128_Byte(n2, output[0x60..]); + Store128_Byte(n3, output[0x70..]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector128 Load128_Byte(ReadOnlySpan t) + { + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 16) + return MemoryMarshal.Read>(t); + + return Vector128.Create( + BinaryPrimitives.ReadUInt64LittleEndian(t[..8]), + BinaryPrimitives.ReadUInt64LittleEndian(t[8..]) + ).AsByte(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector128 Load128_UInt32(ReadOnlySpan t) + { + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 16) + return MemoryMarshal.Read>(MemoryMarshal.AsBytes(t)); + + return Vector128.Create(t[0], t[1], t[2], t[3]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector256 Load256_Byte(ReadOnlySpan t) + { + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 32) + return MemoryMarshal.Read>(t); + + return Vector256.Create( + BinaryPrimitives.ReadUInt64LittleEndian(t[ 0.. 8]), + BinaryPrimitives.ReadUInt64LittleEndian(t[ 8..16]), + BinaryPrimitives.ReadUInt64LittleEndian(t[16..24]), + BinaryPrimitives.ReadUInt64LittleEndian(t[24..32]) + ).AsByte(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Store128_Byte(Vector128 s, Span t) + { + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 16) + { + MemoryMarshal.Write(t, ref s); + return; + } + + var u = s.AsUInt64(); + BinaryPrimitives.WriteUInt64LittleEndian(t[..8], u.GetElement(0)); + BinaryPrimitives.WriteUInt64LittleEndian(t[8..], u.GetElement(1)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Store256_Byte(Vector256 s, Span t) + { + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 32) + { + MemoryMarshal.Write(t, ref s); + return; + } + + var u = s.AsUInt64(); + BinaryPrimitives.WriteUInt64LittleEndian(t[ 0.. 8], u.GetElement(0)); + BinaryPrimitives.WriteUInt64LittleEndian(t[ 8..16], u.GetElement(1)); + BinaryPrimitives.WriteUInt64LittleEndian(t[16..24], u.GetElement(2)); + BinaryPrimitives.WriteUInt64LittleEndian(t[24..32], u.GetElement(3)); + } +#endif + } +} #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaCha7539EngineHelper.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaCha7539EngineHelper.cs new file mode 100644 index 0000000..db7dccd --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaCha7539EngineHelper.cs @@ -0,0 +1,484 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) && BESTHTTP_WITH_BURST +using System; +using System.Runtime.CompilerServices; + +using Unity.Burst; + +using Unity.Burst.Intrinsics; + +using static Unity.Burst.Intrinsics.X86; +using static Unity.Burst.Intrinsics.Arm; + +// https://github.com/sschoener/burst-simd-exercises/blob/main/Assets/Examples/2-sum-small-numbers-sse3/SumSmallNumbers_SSE3.cs +// https://github.com/jratcliff63367/sse2neon/blob/master/SSE2NEON.h#L789 + +namespace BestHTTP.Connections.TLS.Crypto.Impl +{ + [BurstCompile] + public unsafe static class FastChaCha7539EngineHelper + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ProcessBlocks2(ReadOnlySpan input, Span output, uint[] state, int rounds, byte[] keyStream) + { + fixed (byte* pinput = input) + fixed (byte* poutput = output) + fixed (uint* pstate = state) + fixed(byte* pkeyStream = keyStream) + ProcessBlocks2Impl(pinput, input.Length, poutput, output.Length, pstate, state.Length, rounds, pkeyStream); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + [BurstCompile(CompileSynchronously = true)] + private static void ProcessBlocks2Impl([NoAlias] byte* input, int inputLen, [NoAlias] byte* output, int outLen, [NoAlias] uint* state, int stateLen, int rounds, [NoAlias] byte* keyStream) + { + if (Avx2.IsAvx2Supported) + { + var t0 = new v128(state[0], state[1], state[2], state[3]); //Load128_UInt32(state.AsSpan()); + var t1 = new v128(state[4], state[5], state[6], state[7]); //Load128_UInt32(state.AsSpan(4)); + var t2 = new v128(state[8], state[9], state[10], state[11]); //Load128_UInt32(state.AsSpan(8)); + var t3 = new v128(state[12], state[13], state[14], state[15]); //Load128_UInt32(state.AsSpan(12)); + ++state[12]; + var t4 = new v128(state[12], state[13], state[14], state[15]); //Load128_UInt32(state.AsSpan(12)); + ++state[12]; + + var x0 = new v256(t0, t0); //Vector256.Create(t0, t0); + var x1 = new v256(t1, t1); //Vector256.Create(t1, t1); + var x2 = new v256(t2, t2); //Vector256.Create(t2, t2); + var x3 = new v256(t3, t4); //Vector256.Create(t3, t4); + + var v0 = x0; + var v1 = x1; + var v2 = x2; + var v3 = x3; + + for (int i = rounds; i > 0; i -= 2) + { + v0 = Avx2.mm256_add_epi32(v0, v1); + v3 = Avx2.mm256_xor_si256(v3, v0); + v3 = Avx2.mm256_xor_si256(Avx2.mm256_slli_epi32(v3, 16), Avx2.mm256_srli_epi32(v3, 16)); + v2 = Avx2.mm256_add_epi32(v2, v3); + v1 = Avx2.mm256_xor_si256(v1, v2); + v1 = Avx2.mm256_xor_si256(Avx2.mm256_slli_epi32(v1, 12), Avx2.mm256_srli_epi32(v1, 20)); + v0 = Avx2.mm256_add_epi32(v0, v1); + v3 = Avx2.mm256_xor_si256(v3, v0); + v3 = Avx2.mm256_xor_si256(Avx2.mm256_slli_epi32(v3, 8), Avx2.mm256_srli_epi32(v3, 24)); + v2 = Avx2.mm256_add_epi32(v2, v3); + v1 = Avx2.mm256_xor_si256(v1, v2); + v1 = Avx2.mm256_xor_si256(Avx2.mm256_slli_epi32(v1, 7), Avx2.mm256_srli_epi32(v1, 25)); + + v1 = Avx2.mm256_shuffle_epi32(v1, 0x39); + v2 = Avx2.mm256_shuffle_epi32(v2, 0x4E); + v3 = Avx2.mm256_shuffle_epi32(v3, 0x93); + + v0 = Avx2.mm256_add_epi32(v0, v1); + v3 = Avx2.mm256_xor_si256(v3, v0); + v3 = Avx2.mm256_xor_si256(Avx2.mm256_slli_epi32(v3, 16), Avx2.mm256_srli_epi32(v3, 16)); + v2 = Avx2.mm256_add_epi32(v2, v3); + v1 = Avx2.mm256_xor_si256(v1, v2); + v1 = Avx2.mm256_xor_si256(Avx2.mm256_slli_epi32(v1, 12), Avx2.mm256_srli_epi32(v1, 20)); + v0 = Avx2.mm256_add_epi32(v0, v1); + v3 = Avx2.mm256_xor_si256(v3, v0); + v3 = Avx2.mm256_xor_si256(Avx2.mm256_slli_epi32(v3, 8), Avx2.mm256_srli_epi32(v3, 24)); + v2 = Avx2.mm256_add_epi32(v2, v3); + v1 = Avx2.mm256_xor_si256(v1, v2); + v1 = Avx2.mm256_xor_si256(Avx2.mm256_slli_epi32(v1, 7), Avx2.mm256_srli_epi32(v1, 25)); + + v1 = Avx2.mm256_shuffle_epi32(v1, 0x93); + v2 = Avx2.mm256_shuffle_epi32(v2, 0x4E); + v3 = Avx2.mm256_shuffle_epi32(v3, 0x39); + } + + v0 = Avx2.mm256_add_epi32(v0, x0); + v1 = Avx2.mm256_add_epi32(v1, x1); + v2 = Avx2.mm256_add_epi32(v2, x2); + v3 = Avx2.mm256_add_epi32(v3, x3); + + var n0 = Avx2.mm256_permute2x128_si256(v0, v1, 0x20); + var n1 = Avx2.mm256_permute2x128_si256(v2, v3, 0x20); + var n2 = Avx2.mm256_permute2x128_si256(v0, v1, 0x31); + var n3 = Avx2.mm256_permute2x128_si256(v2, v3, 0x31); + + ulong* uInput = (ulong*)input; + n0 = Avx2.mm256_xor_si256(n0, new v256(uInput[0], uInput[1], uInput[2], uInput[3])); // Load256_Byte(input) + n1 = Avx2.mm256_xor_si256(n1, new v256(uInput[4], uInput[5], uInput[6], uInput[7])); // Load256_Byte(input[0x20..]) + n2 = Avx2.mm256_xor_si256(n2, new v256(uInput[8], uInput[9], uInput[10], uInput[11])); // Load256_Byte(input[0x40..]) + n3 = Avx2.mm256_xor_si256(n3, new v256(uInput[12], uInput[13], uInput[14], uInput[15])); // Load256_Byte(input[0x60..]) + + ulong* uOutput = (ulong*)output; + uOutput[0] = n0.ULong0; uOutput[1] = n0.ULong1; uOutput[2] = n0.ULong2; uOutput[3] = n0.ULong3; //Store256_Byte(n0, output); + uOutput[4] = n1.ULong0; uOutput[5] = n1.ULong1; uOutput[6] = n1.ULong2; uOutput[7] = n1.ULong3; //Store256_Byte(n1, output[0x20..]); + uOutput[8] = n2.ULong0; uOutput[9] = n2.ULong1; uOutput[10] = n2.ULong2; uOutput[11] = n2.ULong3; //Store256_Byte(n2, output[0x40..]); + uOutput[12] = n3.ULong0; uOutput[13] = n3.ULong1; uOutput[14] = n3.ULong2; uOutput[15] = n3.ULong3; //Store256_Byte(n3, output[0x60..]); + } + else if (Sse2.IsSse2Supported) + { + var x0 = Sse2.loadu_si128(state); //new v128(state[0], state[1], state[2], state[3]); //Load128_UInt32(state.AsSpan()); + var x1 = Sse2.loadu_si128(state + 4); //new v128(state[4], state[5], state[6], state[7]); //Load128_UInt32(state.AsSpan(4)); + var x2 = Sse2.loadu_si128(state + 8); //new v128(state[8], state[9], state[10], state[11]); //Load128_UInt32(state.AsSpan(8)); + var x3 = Sse2.loadu_si128(state + 12); //new v128(state[12], state[13], state[14], state[15]); //Load128_UInt32(state.AsSpan(12)); + ++state[12]; + + var v0 = x0; + var v1 = x1; + var v2 = x2; + var v3 = x3; + + for (int i = rounds; i > 0; i -= 2) + { + v0 = Sse2.add_epi32(v0, v1); + v3 = Sse2.xor_si128(v3, v0); + v3 = Sse2.xor_si128(Sse2.slli_epi32(v3, 16), Sse2.srli_epi32(v3, 16)); + v2 = Sse2.add_epi32(v2, v3); + v1 = Sse2.xor_si128(v1, v2); + v1 = Sse2.xor_si128(Sse2.slli_epi32(v1, 12), Sse2.srli_epi32(v1, 20)); + v0 = Sse2.add_epi32(v0, v1); + v3 = Sse2.xor_si128(v3, v0); + v3 = Sse2.xor_si128(Sse2.slli_epi32(v3, 8), Sse2.srli_epi32(v3, 24)); + v2 = Sse2.add_epi32(v2, v3); + v1 = Sse2.xor_si128(v1, v2); + v1 = Sse2.xor_si128(Sse2.slli_epi32(v1, 7), Sse2.srli_epi32(v1, 25)); + + v1 = Sse2.shuffle_epi32(v1, 0x39); + v2 = Sse2.shuffle_epi32(v2, 0x4E); + v3 = Sse2.shuffle_epi32(v3, 0x93); + + v0 = Sse2.add_epi32(v0, v1); + v3 = Sse2.xor_si128(v3, v0); + v3 = Sse2.xor_si128(Sse2.slli_epi32(v3, 16), Sse2.srli_epi32(v3, 16)); + v2 = Sse2.add_epi32(v2, v3); + v1 = Sse2.xor_si128(v1, v2); + v1 = Sse2.xor_si128(Sse2.slli_epi32(v1, 12), Sse2.srli_epi32(v1, 20)); + v0 = Sse2.add_epi32(v0, v1); + v3 = Sse2.xor_si128(v3, v0); + v3 = Sse2.xor_si128(Sse2.slli_epi32(v3, 8), Sse2.srli_epi32(v3, 24)); + v2 = Sse2.add_epi32(v2, v3); + v1 = Sse2.xor_si128(v1, v2); + v1 = Sse2.xor_si128(Sse2.slli_epi32(v1, 7), Sse2.srli_epi32(v1, 25)); + + v1 = Sse2.shuffle_epi32(v1, 0x93); + v2 = Sse2.shuffle_epi32(v2, 0x4E); + v3 = Sse2.shuffle_epi32(v3, 0x39); + } + + v0 = Sse2.add_epi32(v0, x0); + v1 = Sse2.add_epi32(v1, x1); + v2 = Sse2.add_epi32(v2, x2); + v3 = Sse2.add_epi32(v3, x3); + + var n0 = Sse2.loadu_si128(input + 0x00); //Load128_Byte(input); + var n1 = Sse2.loadu_si128(input + 0x10); //Load128_Byte(input[0x10..]); + var n2 = Sse2.loadu_si128(input + 0x20); //Load128_Byte(input[0x20..]); + var n3 = Sse2.loadu_si128(input + 0x30); //Load128_Byte(input[0x30..]); + + n0 = Sse2.xor_si128(n0, v0); + n1 = Sse2.xor_si128(n1, v1); + n2 = Sse2.xor_si128(n2, v2); + n3 = Sse2.xor_si128(n3, v3); + + Sse2.storeu_si128(output + 0x00, n0); //Store128_Byte(n0, output); + Sse2.storeu_si128(output + 0x10, n1); //Store128_Byte(n1, output[0x10..]); + Sse2.storeu_si128(output + 0x20, n2); //Store128_Byte(n2, output[0x20..]); + Sse2.storeu_si128(output + 0x30, n3); //Store128_Byte(n3, output[0x30..]); + + + x3 = Sse2.loadu_si128(state + 12); // Load128_UInt32(state.AsSpan(12)); + ++state[12]; + + v0 = x0; + v1 = x1; + v2 = x2; + v3 = x3; + + for (int i = rounds; i > 0; i -= 2) + { + v0 = Sse2.add_epi32(v0, v1); + v3 = Sse2.xor_si128(v3, v0); + v3 = Sse2.xor_si128(Sse2.slli_epi32(v3, 16), Sse2.srli_epi32(v3, 16)); + v2 = Sse2.add_epi32(v2, v3); + v1 = Sse2.xor_si128(v1, v2); + v1 = Sse2.xor_si128(Sse2.slli_epi32(v1, 12), Sse2.srli_epi32(v1, 20)); + v0 = Sse2.add_epi32(v0, v1); + v3 = Sse2.xor_si128(v3, v0); + v3 = Sse2.xor_si128(Sse2.slli_epi32(v3, 8), Sse2.srli_epi32(v3, 24)); + v2 = Sse2.add_epi32(v2, v3); + v1 = Sse2.xor_si128(v1, v2); + v1 = Sse2.xor_si128(Sse2.slli_epi32(v1, 7), Sse2.srli_epi32(v1, 25)); + + v1 = Sse2.shuffle_epi32(v1, 0x39); + v2 = Sse2.shuffle_epi32(v2, 0x4E); + v3 = Sse2.shuffle_epi32(v3, 0x93); + + v0 = Sse2.add_epi32(v0, v1); + v3 = Sse2.xor_si128(v3, v0); + v3 = Sse2.xor_si128(Sse2.slli_epi32(v3, 16), Sse2.srli_epi32(v3, 16)); + v2 = Sse2.add_epi32(v2, v3); + v1 = Sse2.xor_si128(v1, v2); + v1 = Sse2.xor_si128(Sse2.slli_epi32(v1, 12), Sse2.srli_epi32(v1, 20)); + v0 = Sse2.add_epi32(v0, v1); + v3 = Sse2.xor_si128(v3, v0); + v3 = Sse2.xor_si128(Sse2.slli_epi32(v3, 8), Sse2.srli_epi32(v3, 24)); + v2 = Sse2.add_epi32(v2, v3); + v1 = Sse2.xor_si128(v1, v2); + v1 = Sse2.xor_si128(Sse2.slli_epi32(v1, 7), Sse2.srli_epi32(v1, 25)); + + v1 = Sse2.shuffle_epi32(v1, 0x93); + v2 = Sse2.shuffle_epi32(v2, 0x4E); + v3 = Sse2.shuffle_epi32(v3, 0x39); + } + + v0 = Sse2.add_epi32(v0, x0); + v1 = Sse2.add_epi32(v1, x1); + v2 = Sse2.add_epi32(v2, x2); + v3 = Sse2.add_epi32(v3, x3); + + n0 = Sse2.loadu_si128(input + 0x40); //Load128_Byte(input[0x40..]); + n1 = Sse2.loadu_si128(input + 0x50); //Load128_Byte(input[0x50..]); + n2 = Sse2.loadu_si128(input + 0x60); //Load128_Byte(input[0x60..]); + n3 = Sse2.loadu_si128(input + 0x70); //Load128_Byte(input[0x70..]); + + n0 = Sse2.xor_si128(n0, v0); + n1 = Sse2.xor_si128(n1, v1); + n2 = Sse2.xor_si128(n2, v2); + n3 = Sse2.xor_si128(n3, v3); + + Sse2.storeu_si128(output + 0x40, n0); //Store128_Byte(n0, output[0x40..]); + Sse2.storeu_si128(output + 0x50, n1); //Store128_Byte(n1, output[0x50..]); + Sse2.storeu_si128(output + 0x60, n2); //Store128_Byte(n2, output[0x60..]); + Sse2.storeu_si128(output + 0x70, n3); //Store128_Byte(n3, output[0x70..]); + } + else if (Neon.IsNeonSupported) + { + var x0 = Neon.vld1q_u32(state); //new v128(state[0], state[1], state[2], state[3]); //Load128_UInt32(state.AsSpan()); + var x1 = Neon.vld1q_u32(state + 4); //new v128(state[4], state[5], state[6], state[7]); //Load128_UInt32(state.AsSpan(4)); + var x2 = Neon.vld1q_u32(state + 8); //new v128(state[8], state[9], state[10], state[11]); //Load128_UInt32(state.AsSpan(8)); + var x3 = Neon.vld1q_u32(state + 12); + ++state[12]; + + var v0 = x0; + var v1 = x1; + var v2 = x2; + var v3 = x3; + + for (int i = rounds; i > 0; i -= 2) + { + v0 = Neon.vaddq_u32(v0, v1); + v3 = Neon.veorq_u32(v3, v0); + v3 = Neon.veorq_u32(Neon.vshlq_n_u32(v3, 16), Neon.vshrq_n_u32(v3, 16)); + v2 = Neon.vaddq_u32(v2, v3); + v1 = Neon.veorq_u32(v1, v2); + v1 = Neon.veorq_u32(Neon.vshlq_n_u32(v1, 12), Neon.vshrq_n_u32(v1, 20)); + v0 = Neon.vaddq_u32(v0, v1); + v3 = Neon.veorq_u32(v3, v0); + v3 = Neon.veorq_u32(Neon.vshlq_n_u32(v3, 8), Neon.vshrq_n_u32(v3, 24)); + v2 = Neon.vaddq_u32(v2, v3); + v1 = Neon.veorq_u32(v1, v2); + v1 = Neon.veorq_u32(Neon.vshlq_n_u32(v1, 7), Neon.vshrq_n_u32(v1, 25)); + + ///*v1 = */Neon_shuffle_epi32(v1, 0x39, out v1); + v128 ret; + ret = Neon.vmovq_n_u32(Neon.vgetq_lane_u32(v1, (0x39) & 0x3)); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v1, ((0x39) >> 2) & 0x3), ret, 1); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v1, ((0x39) >> 4) & 0x3), ret, 2); + v1 = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v1, ((0x39) >> 6) & 0x3), ret, 3); + + ///*v2 = */Neon_shuffle_epi32(v2, 0x4E, out v2); + ret = Neon.vmovq_n_u32(Neon.vgetq_lane_u32(v2, (0x4E) & 0x3)); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v2, ((0x4E) >> 2) & 0x3), ret, 1); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v2, ((0x4E) >> 4) & 0x3), ret, 2); + v2 = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v2, ((0x4E) >> 6) & 0x3), ret, 3); + + ///*v3 = */Neon_shuffle_epi32(v3, 0x93, out v3); + ret = Neon.vmovq_n_u32(Neon.vgetq_lane_u32(v3, (0x93) & 0x3)); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v3, ((0x93) >> 2) & 0x3), ret, 1); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v3, ((0x93) >> 4) & 0x3), ret, 2); + v3 = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v3, ((0x93) >> 6) & 0x3), ret, 3); + + v0 = Neon.vaddq_u32(v0, v1); + v3 = Neon.veorq_u32(v3, v0); + v3 = Neon.veorq_u32(Neon.vshlq_n_u32(v3, 16), Neon.vshrq_n_u32(v3, 16)); + v2 = Neon.vaddq_u32(v2, v3); + v1 = Neon.veorq_u32(v1, v2); + v1 = Neon.veorq_u32(Neon.vshlq_n_u32(v1, 12), Neon.vshrq_n_u32(v1, 20)); + v0 = Neon.vaddq_u32(v0, v1); + v3 = Neon.veorq_u32(v3, v0); + v3 = Neon.veorq_u32(Neon.vshlq_n_u32(v3, 8), Neon.vshrq_n_u32(v3, 24)); + v2 = Neon.vaddq_u32(v2, v3); + v1 = Neon.veorq_u32(v1, v2); + v1 = Neon.veorq_u32(Neon.vshlq_n_u32(v1, 7), Neon.vshrq_n_u32(v1, 25)); + + ///*v1 = */Neon_shuffle_epi32(v1, 0x93, out v1); + ret = Neon.vmovq_n_u32(Neon.vgetq_lane_u32(v1, (0x93) & 0x3)); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v1, ((0x93) >> 2) & 0x3), ret, 1); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v1, ((0x93) >> 4) & 0x3), ret, 2); + v1 = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v1, ((0x93) >> 6) & 0x3), ret, 3); + + ///*v2 = */Neon_shuffle_epi32(v2, 0x4E, out v2); + ret = Neon.vmovq_n_u32(Neon.vgetq_lane_u32(v2, (0x4E) & 0x3)); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v2, ((0x4E) >> 2) & 0x3), ret, 1); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v2, ((0x4E) >> 4) & 0x3), ret, 2); + v2 = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v2, ((0x4E) >> 6) & 0x3), ret, 3); + + ///*v3 = */Neon_shuffle_epi32(v3, 0x39, out v3); + ret = Neon.vmovq_n_u32(Neon.vgetq_lane_u32(v3, (0x39) & 0x3)); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v3, ((0x39) >> 2) & 0x3), ret, 1); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v3, ((0x39) >> 4) & 0x3), ret, 2); + v3 = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v3, ((0x39) >> 6) & 0x3), ret, 3); + } + + v0 = Neon.vaddq_u32(v0, x0); + v1 = Neon.vaddq_u32(v1, x1); + v2 = Neon.vaddq_u32(v2, x2); + v3 = Neon.vaddq_u32(v3, x3); + + var n0 = Neon.vld1q_u32((uint*)(input + 0x00)); //Load128_Byte(input); + var n1 = Neon.vld1q_u32((uint*)(input + 0x10)); //Load128_Byte(input[0x10..]); + var n2 = Neon.vld1q_u32((uint*)(input + 0x20)); //Load128_Byte(input[0x20..]); + var n3 = Neon.vld1q_u32((uint*)(input + 0x30)); //Load128_Byte(input[0x30..]); + + n0 = Neon.veorq_u32(n0, v0); + n1 = Neon.veorq_u32(n1, v1); + n2 = Neon.veorq_u32(n2, v2); + n3 = Neon.veorq_u32(n3, v3); + + Neon.vst1q_u32((uint*)(output + 0x00), n0); //Store128_Byte(n0, output); + Neon.vst1q_u32((uint*)(output + 0x10), n1); //Store128_Byte(n1, output[0x10..]); + Neon.vst1q_u32((uint*)(output + 0x20), n2); //Store128_Byte(n2, output[0x20..]); + Neon.vst1q_u32((uint*)(output + 0x30), n3); //Store128_Byte(n3, output[0x30..]); + + + x3 = Neon.vld1q_u32(state + 12); // Load128_UInt32(state.AsSpan(12)); + ++state[12]; + + v0 = x0; + v1 = x1; + v2 = x2; + v3 = x3; + + for (int i = rounds; i > 0; i -= 2) + { + v0 = Neon.vaddq_u32(v0, v1); + v3 = Neon.veorq_u32(v3, v0); + v3 = Neon.veorq_u32(Neon.vshlq_n_u32(v3, 16), Neon.vshrq_n_u32(v3, 16)); + v2 = Neon.vaddq_u32(v2, v3); + v1 = Neon.veorq_u32(v1, v2); + v1 = Neon.veorq_u32(Neon.vshlq_n_u32(v1, 12), Neon.vshrq_n_u32(v1, 20)); + v0 = Neon.vaddq_u32(v0, v1); + v3 = Neon.veorq_u32(v3, v0); + v3 = Neon.veorq_u32(Neon.vshlq_n_u32(v3, 8), Neon.vshrq_n_u32(v3, 24)); + v2 = Neon.vaddq_u32(v2, v3); + v1 = Neon.veorq_u32(v1, v2); + v1 = Neon.veorq_u32(Neon.vshlq_n_u32(v1, 7), Neon.vshrq_n_u32(v1, 25)); + + ///*v1 = */Neon_shuffle_epi32(v1, 0x39, out v1); + v128 ret; + ret = Neon.vmovq_n_u32(Neon.vgetq_lane_u32(v1, (0x39) & 0x3)); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v1, ((0x39) >> 2) & 0x3), ret, 1); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v1, ((0x39) >> 4) & 0x3), ret, 2); + v1 = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v1, ((0x39) >> 6) & 0x3), ret, 3); + + ///*v2 = */Neon_shuffle_epi32(v2, 0x4E, out v2); + ret = Neon.vmovq_n_u32(Neon.vgetq_lane_u32(v2, (0x4E) & 0x3)); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v2, ((0x4E) >> 2) & 0x3), ret, 1); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v2, ((0x4E) >> 4) & 0x3), ret, 2); + v2 = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v2, ((0x4E) >> 6) & 0x3), ret, 3); + + ///*v3 = */Neon_shuffle_epi32(v3, 0x93, out v3); + ret = Neon.vmovq_n_u32(Neon.vgetq_lane_u32(v3, (0x93) & 0x3)); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v3, ((0x93) >> 2) & 0x3), ret, 1); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v3, ((0x93) >> 4) & 0x3), ret, 2); + v3 = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v3, ((0x93) >> 6) & 0x3), ret, 3); + + v0 = Neon.vaddq_u32(v0, v1); + v3 = Neon.veorq_u32(v3, v0); + v3 = Neon.veorq_u32(Neon.vshlq_n_u32(v3, 16), Neon.vshrq_n_u32(v3, 16)); + v2 = Neon.vaddq_u32(v2, v3); + v1 = Neon.veorq_u32(v1, v2); + v1 = Neon.veorq_u32(Neon.vshlq_n_u32(v1, 12), Neon.vshrq_n_u32(v1, 20)); + v0 = Neon.vaddq_u32(v0, v1); + v3 = Neon.veorq_u32(v3, v0); + v3 = Neon.veorq_u32(Neon.vshlq_n_u32(v3, 8), Neon.vshrq_n_u32(v3, 24)); + v2 = Neon.vaddq_u32(v2, v3); + v1 = Neon.veorq_u32(v1, v2); + v1 = Neon.veorq_u32(Neon.vshlq_n_u32(v1, 7), Neon.vshrq_n_u32(v1, 25)); + + ///*v1 = */Neon_shuffle_epi32(v1, 0x93, out v1); + ret = Neon.vmovq_n_u32(Neon.vgetq_lane_u32(v1, (0x93) & 0x3)); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v1, ((0x93) >> 2) & 0x3), ret, 1); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v1, ((0x93) >> 4) & 0x3), ret, 2); + v1 = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v1, ((0x93) >> 6) & 0x3), ret, 3); + + ///*v2 = */Neon_shuffle_epi32(v2, 0x4E, out v2); + ret = Neon.vmovq_n_u32(Neon.vgetq_lane_u32(v2, (0x4E) & 0x3)); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v2, ((0x4E) >> 2) & 0x3), ret, 1); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v2, ((0x4E) >> 4) & 0x3), ret, 2); + v2 = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v2, ((0x4E) >> 6) & 0x3), ret, 3); + + ///*v3 = */Neon_shuffle_epi32(v3, 0x39, out v3); + ret = Neon.vmovq_n_u32(Neon.vgetq_lane_u32(v3, (0x39) & 0x3)); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v3, ((0x39) >> 2) & 0x3), ret, 1); + ret = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v3, ((0x39) >> 4) & 0x3), ret, 2); + v3 = Neon.vsetq_lane_u32(Neon.vgetq_lane_u32(v3, ((0x39) >> 6) & 0x3), ret, 3); + } + + v0 = Neon.vaddq_u32(v0, x0); + v1 = Neon.vaddq_u32(v1, x1); + v2 = Neon.vaddq_u32(v2, x2); + v3 = Neon.vaddq_u32(v3, x3); + + n0 = Neon.vld1q_u32((uint*)(input + 0x40)); //Load128_Byte(input[0x40..]); + n1 = Neon.vld1q_u32((uint*)(input + 0x50)); //Load128_Byte(input[0x50..]); + n2 = Neon.vld1q_u32((uint*)(input + 0x60)); //Load128_Byte(input[0x60..]); + n3 = Neon.vld1q_u32((uint*)(input + 0x70)); //Load128_Byte(input[0x70..]); + + n0 = Neon.veorq_u32(n0, v0); + n1 = Neon.veorq_u32(n1, v1); + n2 = Neon.veorq_u32(n2, v2); + n3 = Neon.veorq_u32(n3, v3); + + Neon.vst1q_u32((uint*)(output + 0x40), n0); //Store128_Byte(n0, output[0x40..]); + Neon.vst1q_u32((uint*)(output + 0x50), n1); //Store128_Byte(n1, output[0x50..]); + Neon.vst1q_u32((uint*)(output + 0x60), n2); //Store128_Byte(n2, output[0x60..]); + Neon.vst1q_u32((uint*)(output + 0x70), n3); //Store128_Byte(n3, output[0x70..]); + } + else + { + // Inlined to two ImplProcessBlock calls: + //ImplProcessBlock(input, output); + //ImplProcessBlock(input[64..], output[64..]); + + FastChaChaEngineHelper.ChachaCoreImpl(rounds, state, keyStream); + ++state[12]; + ulong* pulinput = (ulong*)input; + ulong* puloutput = (ulong*)output; + ulong* pulkeyStream = (ulong*)keyStream; + + puloutput[0] = pulkeyStream[0] ^ pulinput[0]; + puloutput[1] = pulkeyStream[1] ^ pulinput[1]; + puloutput[2] = pulkeyStream[2] ^ pulinput[2]; + puloutput[3] = pulkeyStream[3] ^ pulinput[3]; + + puloutput[4] = pulkeyStream[4] ^ pulinput[4]; + puloutput[5] = pulkeyStream[5] ^ pulinput[5]; + puloutput[6] = pulkeyStream[6] ^ pulinput[6]; + puloutput[7] = pulkeyStream[7] ^ pulinput[7]; + + FastChaChaEngineHelper.ChachaCoreImpl(rounds, state, keyStream); + ++state[12]; + + pulinput = (ulong*)&input[64]; + puloutput = (ulong*)&output[64]; + + puloutput[0] = pulkeyStream[0] ^ pulinput[0]; + puloutput[1] = pulkeyStream[1] ^ pulinput[1]; + puloutput[2] = pulkeyStream[2] ^ pulinput[2]; + puloutput[3] = pulkeyStream[3] ^ pulinput[3]; + + puloutput[4] = pulkeyStream[4] ^ pulinput[4]; + puloutput[5] = pulkeyStream[5] ^ pulinput[5]; + puloutput[6] = pulkeyStream[6] ^ pulinput[6]; + puloutput[7] = pulkeyStream[7] ^ pulinput[7]; + } + } + } +} +#endif diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaCha7539EngineHelper.cs.meta b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaCha7539EngineHelper.cs.meta new file mode 100644 index 0000000..1446ced --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaCha7539EngineHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f659fd4b1e907e64c82229d4a0b83341 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaChaEngine.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaChaEngine.cs index d109dfd..be575d5 100644 --- a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaChaEngine.cs +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaChaEngine.cs @@ -1,6 +1,14 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Diagnostics; +#if NETCOREAPP3_0_OR_GREATER +using System.Buffers.Binary; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -10,9 +18,9 @@ namespace BestHTTP.Connections.TLS.Crypto.Impl /// /// Implementation of Daniel J. Bernstein's ChaCha stream cipher. /// - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] + + + [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] public sealed class FastChaChaEngine : FastSalsa20Engine @@ -71,95 +79,170 @@ protected override void SetKey(byte[] keyBytes, byte[] ivBytes) protected override void GenerateKeyStream(byte[] output) { - ChachaCore(rounds, engineState, x); - Pack.UInt32_To_LE(x, output, 0); + //ChachaCore(rounds, engineState, output); + FastChaChaEngineHelper.ChachaCore(rounds, engineState, output); } - /// - /// ChaCha function. - /// - /// The number of ChaCha rounds to execute - /// The input words. - /// The ChaCha state to modify. - internal static void ChachaCore(int rounds, uint[] input, uint[] x) + internal static void ChachaCore(int rounds, uint[] input, byte[] output) { - if (input.Length != 16) - throw new ArgumentException(); - if (x.Length != 16) - throw new ArgumentException(); - if (rounds % 2 != 0) - throw new ArgumentException("Number of rounds must be even"); - - uint x00 = input[0]; - uint x01 = input[1]; - uint x02 = input[2]; - uint x03 = input[3]; - uint x04 = input[4]; - uint x05 = input[5]; - uint x06 = input[6]; - uint x07 = input[7]; - uint x08 = input[8]; - uint x09 = input[9]; - uint x10 = input[10]; - uint x11 = input[11]; - uint x12 = input[12]; - uint x13 = input[13]; - uint x14 = input[14]; - uint x15 = input[15]; - - for (int i = rounds; i > 0; i -= 2) + Debug.Assert(rounds % 2 == 0); + Debug.Assert(input.Length >= 16); + Debug.Assert(output.Length >= 64); + +#if NETCOREAPP3_0_OR_GREATER + if (Sse2.IsSupported) + { + var x0 = Load128_UInt32(input.AsSpan()); + var x1 = Load128_UInt32(input.AsSpan(4)); + var x2 = Load128_UInt32(input.AsSpan(8)); + var x3 = Load128_UInt32(input.AsSpan(12)); + + var v0 = x0; + var v1 = x1; + var v2 = x2; + var v3 = x3; + + for (int i = rounds; i > 0; i -= 2) + { + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 16), Sse2.ShiftRightLogical(v3, 16)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 12), Sse2.ShiftRightLogical(v1, 20)); + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 8), Sse2.ShiftRightLogical(v3, 24)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 7), Sse2.ShiftRightLogical(v1, 25)); + + v1 = Sse2.Shuffle(v1, 0x39); + v2 = Sse2.Shuffle(v2, 0x4E); + v3 = Sse2.Shuffle(v3, 0x93); + + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 16), Sse2.ShiftRightLogical(v3, 16)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 12), Sse2.ShiftRightLogical(v1, 20)); + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 8), Sse2.ShiftRightLogical(v3, 24)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 7), Sse2.ShiftRightLogical(v1, 25)); + + v1 = Sse2.Shuffle(v1, 0x93); + v2 = Sse2.Shuffle(v2, 0x4E); + v3 = Sse2.Shuffle(v3, 0x39); + } + + v0 = Sse2.Add(v0, x0); + v1 = Sse2.Add(v1, x1); + v2 = Sse2.Add(v2, x2); + v3 = Sse2.Add(v3, x3); + + Store128_UInt32(v0, output.AsSpan()); + Store128_UInt32(v1, output.AsSpan(0x10)); + Store128_UInt32(v2, output.AsSpan(0x20)); + Store128_UInt32(v3, output.AsSpan(0x30)); + return; + } +#endif + { - x00 += x04; x12 = Integers.RotateLeft(x12 ^ x00, 16); - x08 += x12; x04 = Integers.RotateLeft(x04 ^ x08, 12); - x00 += x04; x12 = Integers.RotateLeft(x12 ^ x00, 8); - x08 += x12; x04 = Integers.RotateLeft(x04 ^ x08, 7); - x01 += x05; x13 = Integers.RotateLeft(x13 ^ x01, 16); - x09 += x13; x05 = Integers.RotateLeft(x05 ^ x09, 12); - x01 += x05; x13 = Integers.RotateLeft(x13 ^ x01, 8); - x09 += x13; x05 = Integers.RotateLeft(x05 ^ x09, 7); - x02 += x06; x14 = Integers.RotateLeft(x14 ^ x02, 16); - x10 += x14; x06 = Integers.RotateLeft(x06 ^ x10, 12); - x02 += x06; x14 = Integers.RotateLeft(x14 ^ x02, 8); - x10 += x14; x06 = Integers.RotateLeft(x06 ^ x10, 7); - x03 += x07; x15 = Integers.RotateLeft(x15 ^ x03, 16); - x11 += x15; x07 = Integers.RotateLeft(x07 ^ x11, 12); - x03 += x07; x15 = Integers.RotateLeft(x15 ^ x03, 8); - x11 += x15; x07 = Integers.RotateLeft(x07 ^ x11, 7); - x00 += x05; x15 = Integers.RotateLeft(x15 ^ x00, 16); - x10 += x15; x05 = Integers.RotateLeft(x05 ^ x10, 12); - x00 += x05; x15 = Integers.RotateLeft(x15 ^ x00, 8); - x10 += x15; x05 = Integers.RotateLeft(x05 ^ x10, 7); - x01 += x06; x12 = Integers.RotateLeft(x12 ^ x01, 16); - x11 += x12; x06 = Integers.RotateLeft(x06 ^ x11, 12); - x01 += x06; x12 = Integers.RotateLeft(x12 ^ x01, 8); - x11 += x12; x06 = Integers.RotateLeft(x06 ^ x11, 7); - x02 += x07; x13 = Integers.RotateLeft(x13 ^ x02, 16); - x08 += x13; x07 = Integers.RotateLeft(x07 ^ x08, 12); - x02 += x07; x13 = Integers.RotateLeft(x13 ^ x02, 8); - x08 += x13; x07 = Integers.RotateLeft(x07 ^ x08, 7); - x03 += x04; x14 = Integers.RotateLeft(x14 ^ x03, 16); - x09 += x14; x04 = Integers.RotateLeft(x04 ^ x09, 12); - x03 += x04; x14 = Integers.RotateLeft(x14 ^ x03, 8); - x09 += x14; x04 = Integers.RotateLeft(x04 ^ x09, 7); - } + uint x00 = input[0], x01 = input[1], x02 = input[2], x03 = input[3]; + uint x04 = input[4], x05 = input[5], x06 = input[6], x07 = input[7]; + uint x08 = input[8], x09 = input[9], x10 = input[10], x11 = input[11]; + uint x12 = input[12], x13 = input[13], x14 = input[14], x15 = input[15]; + + for (int i = rounds; i > 0; i -= 2) + { + x00 += x04; x12 = Integers.RotateLeft(x12 ^ x00, 16); + x01 += x05; x13 = Integers.RotateLeft(x13 ^ x01, 16); + x02 += x06; x14 = Integers.RotateLeft(x14 ^ x02, 16); + x03 += x07; x15 = Integers.RotateLeft(x15 ^ x03, 16); + + x08 += x12; x04 = Integers.RotateLeft(x04 ^ x08, 12); + x09 += x13; x05 = Integers.RotateLeft(x05 ^ x09, 12); + x10 += x14; x06 = Integers.RotateLeft(x06 ^ x10, 12); + x11 += x15; x07 = Integers.RotateLeft(x07 ^ x11, 12); + + x00 += x04; x12 = Integers.RotateLeft(x12 ^ x00, 8); + x01 += x05; x13 = Integers.RotateLeft(x13 ^ x01, 8); + x02 += x06; x14 = Integers.RotateLeft(x14 ^ x02, 8); + x03 += x07; x15 = Integers.RotateLeft(x15 ^ x03, 8); + + x08 += x12; x04 = Integers.RotateLeft(x04 ^ x08, 7); + x09 += x13; x05 = Integers.RotateLeft(x05 ^ x09, 7); + x10 += x14; x06 = Integers.RotateLeft(x06 ^ x10, 7); + x11 += x15; x07 = Integers.RotateLeft(x07 ^ x11, 7); + x00 += x05; x15 = Integers.RotateLeft(x15 ^ x00, 16); + x01 += x06; x12 = Integers.RotateLeft(x12 ^ x01, 16); + x02 += x07; x13 = Integers.RotateLeft(x13 ^ x02, 16); + x03 += x04; x14 = Integers.RotateLeft(x14 ^ x03, 16); + + x10 += x15; x05 = Integers.RotateLeft(x05 ^ x10, 12); + x11 += x12; x06 = Integers.RotateLeft(x06 ^ x11, 12); + x08 += x13; x07 = Integers.RotateLeft(x07 ^ x08, 12); + x09 += x14; x04 = Integers.RotateLeft(x04 ^ x09, 12); + + x00 += x05; x15 = Integers.RotateLeft(x15 ^ x00, 8); + x01 += x06; x12 = Integers.RotateLeft(x12 ^ x01, 8); + x02 += x07; x13 = Integers.RotateLeft(x13 ^ x02, 8); + x03 += x04; x14 = Integers.RotateLeft(x14 ^ x03, 8); - x[0] = x00 + input[0]; - x[1] = x01 + input[1]; - x[2] = x02 + input[2]; - x[3] = x03 + input[3]; - x[4] = x04 + input[4]; - x[5] = x05 + input[5]; - x[6] = x06 + input[6]; - x[7] = x07 + input[7]; - x[8] = x08 + input[8]; - x[9] = x09 + input[9]; - x[10] = x10 + input[10]; - x[11] = x11 + input[11]; - x[12] = x12 + input[12]; - x[13] = x13 + input[13]; - x[14] = x14 + input[14]; - x[15] = x15 + input[15]; + x10 += x15; x05 = Integers.RotateLeft(x05 ^ x10, 7); + x11 += x12; x06 = Integers.RotateLeft(x06 ^ x11, 7); + x08 += x13; x07 = Integers.RotateLeft(x07 ^ x08, 7); + x09 += x14; x04 = Integers.RotateLeft(x04 ^ x09, 7); + } + + Pack.UInt32_To_LE(x00 + input[0], output, 0); + Pack.UInt32_To_LE(x01 + input[1], output, 4); + Pack.UInt32_To_LE(x02 + input[2], output, 8); + Pack.UInt32_To_LE(x03 + input[3], output, 12); + Pack.UInt32_To_LE(x04 + input[4], output, 16); + Pack.UInt32_To_LE(x05 + input[5], output, 20); + Pack.UInt32_To_LE(x06 + input[6], output, 24); + Pack.UInt32_To_LE(x07 + input[7], output, 28); + Pack.UInt32_To_LE(x08 + input[8], output, 32); + Pack.UInt32_To_LE(x09 + input[9], output, 36); + Pack.UInt32_To_LE(x10 + input[10], output, 40); + Pack.UInt32_To_LE(x11 + input[11], output, 44); + Pack.UInt32_To_LE(x12 + input[12], output, 48); + Pack.UInt32_To_LE(x13 + input[13], output, 52); + Pack.UInt32_To_LE(x14 + input[14], output, 56); + Pack.UInt32_To_LE(x15 + input[15], output, 60); + } } + +#if NETCOREAPP3_0_OR_GREATER + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector128 Load128_UInt32(ReadOnlySpan t) + { + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 16) + return MemoryMarshal.Read>(MemoryMarshal.AsBytes(t)); + + return Vector128.Create(t[0], t[1], t[2], t[3]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Store128_UInt32(Vector128 s, Span t) + { + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 16) + { + MemoryMarshal.Write(t, ref s); + return; + } + + var u = s.AsUInt64(); + BinaryPrimitives.WriteUInt64LittleEndian(t[..8], u.GetElement(0)); + BinaryPrimitives.WriteUInt64LittleEndian(t[8..], u.GetElement(1)); + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaChaEngineHelper.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaChaEngineHelper.cs new file mode 100644 index 0000000..4f17ff1 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaChaEngineHelper.cs @@ -0,0 +1,124 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +using System; +using System.Runtime.CompilerServices; + +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; + +#if BESTHTTP_WITH_BURST +using Unity.Burst; +#endif + +namespace BestHTTP.Connections.TLS.Crypto.Impl +{ +#if BESTHTTP_WITH_BURST + [Unity.Burst.BurstCompile] +#endif + internal static class FastChaChaEngineHelper + { + internal unsafe static void ChachaCore(int rounds, uint[] input, byte[] output) + { + fixed (uint* pinput = input) + fixed (byte* poutput = output) + ChachaCoreImpl(rounds, pinput, poutput); + } + +#if BESTHTTP_WITH_BURST + [Unity.Burst.BurstCompile] + [Unity.Burst.CompilerServices.SkipLocalsInit] +#endif + internal unsafe static void ChachaCoreImpl(int rounds, +#if BESTHTTP_WITH_BURST + [NoAlias] +#endif + uint* input, +#if BESTHTTP_WITH_BURST + [NoAlias] +#endif + byte* output) + { + uint* x = stackalloc uint[16]; + + for (int i = 0; i < 16; i++) + x[i] = input[i]; + + uint tmp = 0; + for (int i = rounds; i > 0; i -= 2) + { + x[00] += x[04]; tmp = x[12] ^ x[00]; x[12] = (tmp << 16) | (tmp >> -16); // Integers.RotateLeft(x[12] ^ x[00], 16); + x[01] += x[05]; tmp = x[13] ^ x[01]; x[13] = (tmp << 16) | (tmp >> -16); // Integers.RotateLeft(x[13] ^ x[01], 16); + x[02] += x[06]; tmp = x[14] ^ x[02]; x[14] = (tmp << 16) | (tmp >> -16); // Integers.RotateLeft(x[14] ^ x[02], 16); + x[03] += x[07]; tmp = x[15] ^ x[03]; x[15] = (tmp << 16) | (tmp >> -16); // Integers.RotateLeft(x[15] ^ x[03], 16); + + x[08] += x[12]; tmp = x[04] ^ x[08]; x[04] = (tmp << 12) | (tmp >> -12); // Integers.RotateLeft(x[04] ^ x[08], 12); + x[09] += x[13]; tmp = x[05] ^ x[09]; x[05] = (tmp << 12) | (tmp >> -12); // Integers.RotateLeft(x[05] ^ x[09], 12); + x[10] += x[14]; tmp = x[06] ^ x[10]; x[06] = (tmp << 12) | (tmp >> -12); // Integers.RotateLeft(x[06] ^ x[10], 12); + x[11] += x[15]; tmp = x[07] ^ x[11]; x[07] = (tmp << 12) | (tmp >> -12); // Integers.RotateLeft(x[07] ^ x[11], 12); + + x[00] += x[04]; tmp = x[12] ^ x[00]; x[12] = (tmp << 8) | (tmp >> -8); // Integers.RotateLeft(x[12] ^ x[00], 8); + x[01] += x[05]; tmp = x[13] ^ x[01]; x[13] = (tmp << 8) | (tmp >> -8); // Integers.RotateLeft(x[13] ^ x[01], 8); + x[02] += x[06]; tmp = x[14] ^ x[02]; x[14] = (tmp << 8) | (tmp >> -8); // Integers.RotateLeft(x[14] ^ x[02], 8); + x[03] += x[07]; tmp = x[15] ^ x[03]; x[15] = (tmp << 8) | (tmp >> -8); // Integers.RotateLeft(x[15] ^ x[03], 8); + + x[08] += x[12]; tmp = x[04] ^ x[08]; x[04] = (tmp << 7) | (tmp >> -7); // Integers.RotateLeft(x[04] ^ x[08], 7); + x[09] += x[13]; tmp = x[05] ^ x[09]; x[05] = (tmp << 7) | (tmp >> -7); // Integers.RotateLeft(x[05] ^ x[09], 7); + x[10] += x[14]; tmp = x[06] ^ x[10]; x[06] = (tmp << 7) | (tmp >> -7); // Integers.RotateLeft(x[06] ^ x[10], 7); + x[11] += x[15]; tmp = x[07] ^ x[11]; x[07] = (tmp << 7) | (tmp >> -7); // Integers.RotateLeft(x[07] ^ x[11], 7); + x[00] += x[05]; tmp = x[15] ^ x[00]; x[15] = (tmp << 16) | (tmp >> -16); // Integers.RotateLeft(x[15] ^ x[00], 16); + x[01] += x[06]; tmp = x[12] ^ x[01]; x[12] = (tmp << 16) | (tmp >> -16); // Integers.RotateLeft(x[12] ^ x[01], 16); + x[02] += x[07]; tmp = x[13] ^ x[02]; x[13] = (tmp << 16) | (tmp >> -16); // Integers.RotateLeft(x[13] ^ x[02], 16); + x[03] += x[04]; tmp = x[14] ^ x[03]; x[14] = (tmp << 16) | (tmp >> -16); // Integers.RotateLeft(x[14] ^ x[03], 16); + + x[10] += x[15]; tmp = x[05] ^ x[10]; x[05] = (tmp << 12) | (tmp >> -12); // Integers.RotateLeft(x[05] ^ x[10], 12); + x[11] += x[12]; tmp = x[06] ^ x[11]; x[06] = (tmp << 12) | (tmp >> -12); // Integers.RotateLeft(x[06] ^ x[11], 12); + x[08] += x[13]; tmp = x[07] ^ x[08]; x[07] = (tmp << 12) | (tmp >> -12); // Integers.RotateLeft(x[07] ^ x[08], 12); + x[09] += x[14]; tmp = x[04] ^ x[09]; x[04] = (tmp << 12) | (tmp >> -12); // Integers.RotateLeft(x[04] ^ x[09], 12); + + x[00] += x[05]; tmp = x[15] ^ x[00]; x[15] = (tmp << 8) | (tmp >> -8); // Integers.RotateLeft(x[15] ^ x[00], 8); + x[01] += x[06]; tmp = x[12] ^ x[01]; x[12] = (tmp << 8) | (tmp >> -8); // Integers.RotateLeft(x[12] ^ x[01], 8); + x[02] += x[07]; tmp = x[13] ^ x[02]; x[13] = (tmp << 8) | (tmp >> -8); // Integers.RotateLeft(x[13] ^ x[02], 8); + x[03] += x[04]; tmp = x[14] ^ x[03]; x[14] = (tmp << 8) | (tmp >> -8); // Integers.RotateLeft(x[14] ^ x[03], 8); + + x[10] += x[15]; tmp = x[05] ^ x[10]; x[05] = (tmp << 7) | (tmp >> -7); // Integers.RotateLeft(x[05] ^ x[10], 7); + x[11] += x[12]; tmp = x[06] ^ x[11]; x[06] = (tmp << 7) | (tmp >> -7); // Integers.RotateLeft(x[06] ^ x[11], 7); + x[08] += x[13]; tmp = x[07] ^ x[08]; x[07] = (tmp << 7) | (tmp >> -7); // Integers.RotateLeft(x[07] ^ x[08], 7); + x[09] += x[14]; tmp = x[04] ^ x[09]; x[04] = (tmp << 7) | (tmp >> -7); // Integers.RotateLeft(x[04] ^ x[09], 7); + } + + for (int i = 0; i < 16; i++) + { + uint n = x[i] + input[i]; + + output[(i * 4)] = (byte)n; + output[(i * 4) + 1] = (byte)(n >> 8); + output[(i * 4) + 2] = (byte)(n >> 16); + output[(i * 4) + 3] = (byte)(n >> 24); + } + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static unsafe void ImplProcessBlock(ReadOnlySpan input, Span output, byte[] keyStream) + { + fixed (byte* pinput = input) + fixed (byte* poutput = output) + fixed (byte* pkeyStream = keyStream) + { + ulong* pulinput = (ulong*)pinput; + ulong* puloutput = (ulong*)poutput; + ulong* pulkeyStream = (ulong*)pkeyStream; + + puloutput[0] = pulkeyStream[0] ^ pulinput[0]; + puloutput[1] = pulkeyStream[1] ^ pulinput[1]; + puloutput[2] = pulkeyStream[2] ^ pulinput[2]; + puloutput[3] = pulkeyStream[3] ^ pulinput[3]; + + puloutput[4] = pulkeyStream[4] ^ pulinput[4]; + puloutput[5] = pulkeyStream[5] ^ pulinput[5]; + puloutput[6] = pulkeyStream[6] ^ pulinput[6]; + puloutput[7] = pulkeyStream[7] ^ pulinput[7]; + } + } +#endif + } +} +#endif diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaChaEngineHelper.cs.meta b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaChaEngineHelper.cs.meta new file mode 100644 index 0000000..5c99dcc --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastChaChaEngineHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: be2ccde693e75344ca2f2e8f707edec4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastGcmBlockCipher.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastGcmBlockCipher.cs index fe3cb63..19af25c 100644 --- a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastGcmBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastGcmBlockCipher.cs @@ -1,6 +1,17 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.CompilerServices; + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ +using System.Buffers.Binary; +using System.Runtime.InteropServices; +#endif +#if NETCOREAPP3_0_OR_GREATER +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +#endif using BestHTTP.PlatformSupport.Memory; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; @@ -14,20 +25,36 @@ namespace BestHTTP.Connections.TLS.Crypto.Impl { /// - /// Implements the Galois/Counter mode (GCM) detailed in - /// NIST Special Publication 800-38D. + /// Implements the Galois/Counter mode (GCM) detailed in NIST Special Publication 800-38D. /// - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] + + + [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] +#if BESTHTTP_WITH_BURST + [Unity.Burst.BurstCompile] +#endif public sealed class FastGcmBlockCipher : IAeadBlockCipher { - private const int BlockSize = 16; + private static IGcmMultiplier CreateGcmMultiplier() + { +#if NETCOREAPP3_0_OR_GREATER + // TODO Prefer more tightly coupled test + if (Pclmulqdq.IsSupported) + { + return new BasicGcmMultiplier(); + } +#endif + + return new Tables8kGcmMultiplier(); + } + + public const int BlockSize = 16; byte[] ctrBlock = new byte[BlockSize]; private readonly IBlockCipher cipher; + private readonly BurstTables8kGcmMultiplier multiplier; private IGcmExponentiator exp; // These fields are set by Init and not modified by processing @@ -41,11 +68,11 @@ public sealed class FastGcmBlockCipher private byte[] J0; // These fields are modified during processing - private int bufLength; private byte[] bufBlock; private byte[] macBlock; private byte[] S, S_at, S_atPre; private byte[] counter; + private uint counter32; private uint blocksRemaining; private int bufOff; private ulong totalLength; @@ -67,20 +94,18 @@ public FastGcmBlockCipher( if (c.GetBlockSize() != BlockSize) throw new ArgumentException("cipher required with a block size of " + BlockSize + "."); - if (m != null) - throw new NotImplementedException("IGcmMultiplier"); + //if (m == null) + //{ + // m = CreateGcmMultiplier(); + //} + this.cipher = c; + this.multiplier = new BurstTables8kGcmMultiplier(); } - public string AlgorithmName - { - get { return cipher.AlgorithmName + "/GCM"; } - } + public string AlgorithmName => cipher.AlgorithmName + "/GCM"; - public IBlockCipher GetUnderlyingCipher() - { - return cipher; - } + public IBlockCipher UnderlyingCipher => cipher; public int GetBlockSize() { @@ -91,9 +116,7 @@ public int GetBlockSize() /// 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 void Init( - bool forEncryption, - ICipherParameters parameters) + public void Init(bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; //this.macBlock = null; @@ -101,12 +124,12 @@ public void Init( Array.Clear(this.macBlock, 0, this.macBlock.Length); this.initialised = true; - NoCopyKeyParameter keyParam; + KeyParameter keyParam; byte[] newNonce = null; - if (parameters is FastAeadParameters) + if (parameters is AeadParameters) { - FastAeadParameters param = (FastAeadParameters)parameters; + AeadParameters param = (AeadParameters)parameters; newNonce = param.GetNonce(); initialAssociatedText = param.GetAssociatedText(); @@ -120,23 +143,22 @@ public void Init( macSize = macSizeBits / 8; keyParam = param.Key; } - else if (parameters is FastParametersWithIV) + else if (parameters is ParametersWithIV) { - FastParametersWithIV param = (FastParametersWithIV)parameters; - + ParametersWithIV param = (ParametersWithIV)parameters; + newNonce = param.GetIV(); initialAssociatedText = null; macSize = 16; - keyParam = (NoCopyKeyParameter)param.Parameters; + keyParam = (KeyParameter)param.Parameters; } else { throw new ArgumentException("invalid parameters passed to GCM"); } - this.bufLength = forEncryption ? BlockSize : (BlockSize + macSize); - if (this.bufBlock == null || this.bufLength < this.bufBlock.Length) - BufferPool.Resize(ref this.bufBlock, this.bufLength, true, true); + int bufLength = forEncryption ? BlockSize : (BlockSize + macSize); + this.bufBlock = new byte[bufLength]; if (newNonce == null || newNonce.Length < 1) { @@ -172,14 +194,11 @@ public void Init( { cipher.Init(true, keyParam); - if (this.H == null) - this.H = new byte[BlockSize]; - else - Array.Clear(this.H, 0, BlockSize); + 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 - Tables8kGcmMultiplier_Init(H); + multiplier.Init(H); exp = null; } else if (this.H == null) @@ -187,10 +206,7 @@ public void Init( throw new ArgumentException("Key must be specified in initial init"); } - if (this.J0 == null) - this.J0 = new byte[BlockSize]; - else - Array.Clear(this.J0, 0, BlockSize); + this.J0 = new byte[BlockSize]; if (nonce.Length == 12) { @@ -200,49 +216,20 @@ public void Init( else { gHASH(J0, nonce, nonce.Length); - byte[] X = BufferPool.Get(BlockSize, false); + byte[] X = new byte[BlockSize]; Pack.UInt64_To_BE((ulong)nonce.Length * 8UL, X, 8); gHASHBlock(J0, X); - BufferPool.Release(X); } - //BufferPool.Resize(ref this.S, BlockSize, false, true); - //BufferPool.Resize(ref this.S_at, BlockSize, false, true); - //BufferPool.Resize(ref this.S_atPre, BlockSize, false, true); - //BufferPool.Resize(ref this.atBlock, BlockSize, false, true); - if (this.S == null) - this.S = new byte[BlockSize]; - else - Array.Clear(this.S, 0, this.S.Length); - - if (this.S_at == null) - this.S_at = new byte[BlockSize]; - else - Array.Clear(this.S_at, 0, this.S_at.Length); - - if (this.S_atPre == null) - this.S_atPre = new byte[BlockSize]; - else - Array.Clear(this.S_atPre, 0, this.S_atPre.Length); - - if (this.atBlock == null) - this.atBlock = new byte[BlockSize]; - else - Array.Clear(this.atBlock, 0, this.atBlock.Length); - + 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); - //BufferPool.Resize(ref this.counter, BlockSize, false, true); - if (this.counter == null) - this.counter = new byte[BlockSize]; - else - Array.Clear(this.counter, 0, this.counter.Length); - - Array.Copy(this.J0, 0, this.counter, 0, BlockSize); - + this.counter = Arrays.Clone(J0); + this.counter32 = Pack.BE_To_UInt32(counter, 12); this.blocksRemaining = uint.MaxValue - 1; // page 8, len(P) <= 2^39 - 256, 1 block used by tag this.bufOff = 0; this.totalLength = 0; @@ -260,8 +247,7 @@ public byte[] GetMac() : Arrays.Clone(macBlock); } - public int GetOutputSize( - int len) + public int GetOutputSize(int len) { int totalData = len + bufOff; @@ -273,8 +259,7 @@ public int GetOutputSize( return totalData < macSize ? 0 : totalData - macSize; } - public int GetUpdateOutputSize( - int len) + public int GetUpdateOutputSize(int len) { int totalData = len + bufOff; if (!forEncryption) @@ -304,20 +289,76 @@ public void ProcessAadByte(byte input) public void ProcessAadBytes(byte[] inBytes, int inOff, int len) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ProcessAadBytes(inBytes.AsSpan(inOff, len)); +#else + CheckStatus(); + + if (atBlockPos > 0) + { + int available = BlockSize - atBlockPos; + if (len < available) + { + Array.Copy(inBytes, inOff, atBlock, atBlockPos, len); + atBlockPos += len; + return; + } + + Array.Copy(inBytes, inOff, atBlock, atBlockPos, available); + gHASHBlock(S_at, atBlock); + atLength += BlockSize; + inOff += available; + len -= available; + //atBlockPos = 0; + } + + int inLimit = inOff + len - BlockSize; + + while (inOff <= inLimit) + { + gHASHBlock(S_at, inBytes, inOff); + atLength += BlockSize; + inOff += BlockSize; + } + + atBlockPos = BlockSize + inLimit - inOff; + Array.Copy(inBytes, inOff, atBlock, 0, atBlockPos); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void ProcessAadBytes(ReadOnlySpan input) + { CheckStatus(); - for (int i = 0; i < len; ++i) + if (atBlockPos > 0) { - atBlock[atBlockPos] = inBytes[inOff + i]; - if (++atBlockPos == BlockSize) + int available = BlockSize - atBlockPos; + if (input.Length < available) { - // Hash each block as it fills - gHASHBlock(S_at, atBlock); - atBlockPos = 0; - atLength += BlockSize; + input.CopyTo(atBlock.AsSpan(atBlockPos)); + atBlockPos += input.Length; + return; } + + input[..available].CopyTo(atBlock.AsSpan(atBlockPos)); + gHASHBlock(S_at, atBlock); + atLength += BlockSize; + input = input[available..]; + //atBlockPos = 0; + } + + while (input.Length >= BlockSize) + { + gHASHBlock(S_at, input); + atLength += BlockSize; + input = input[BlockSize..]; } + + input.CopyTo(atBlock); + atBlockPos = input.Length; } +#endif private void InitCipher() { @@ -340,23 +381,53 @@ private void InitCipher() } } - public int ProcessByte( - byte input, - byte[] output, - int outOff) + public int ProcessByte(byte input, byte[] output, int outOff) { CheckStatus(); bufBlock[bufOff] = input; - if (++bufOff == bufLength) + if (++bufOff == bufBlock.Length) { - ProcessBlock(bufBlock, 0, output, outOff); if (forEncryption) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + EncryptBlock(bufBlock, output.AsSpan(outOff)); +#else + EncryptBlock(bufBlock, 0, output, outOff); +#endif + bufOff = 0; + } + else + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + DecryptBlock(bufBlock, output.AsSpan(outOff)); +#else + DecryptBlock(bufBlock, 0, output, outOff); +#endif + Array.Copy(bufBlock, BlockSize, bufBlock, 0, macSize); + bufOff = macSize; + } + return BlockSize; + } + return 0; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessByte(byte input, Span output) + { + CheckStatus(); + + bufBlock[bufOff] = input; + if (++bufOff == bufBlock.Length) + { + if (forEncryption) + { + EncryptBlock(bufBlock, output); bufOff = 0; } else { + DecryptBlock(bufBlock, output); Array.Copy(bufBlock, BlockSize, bufBlock, 0, macSize); bufOff = macSize; } @@ -364,252 +435,414 @@ public int ProcessByte( } return 0; } +#endif - public unsafe int ProcessBytes( - byte[] input, - int inOff, - int len, - byte[] output, - int outOff) + public int ProcessBytes(byte[] input, int inOff, int len, byte[] output, int outOff) { CheckStatus(); Check.DataLength(input, inOff, len, "input buffer too short"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ProcessBytes(input.AsSpan(inOff, len), Spans.FromNullable(output, outOff)); +#else int resultLen = 0; if (forEncryption) { - if (bufOff != 0) + if (bufOff > 0) { - while (len > 0) + int available = BlockSize - bufOff; + if (len < available) { - --len; - bufBlock[bufOff] = input[inOff++]; - if (++bufOff == BlockSize) - { - ProcessBlock(bufBlock, 0, output, outOff); - bufOff = 0; - resultLen += BlockSize; - break; - } + Array.Copy(input, inOff, bufBlock, bufOff, len); + bufOff += len; + return 0; } + + Array.Copy(input, inOff, bufBlock, bufOff, available); + EncryptBlock(bufBlock, 0, output, outOff); + inOff += available; + len -= available; + resultLen = BlockSize; + //bufOff = 0; } - fixed (byte* pctrBlock = ctrBlock, pbuf = input, pS = S, poutput = output) + int inLimit1 = inOff + len - BlockSize; + int inLimit2 = inLimit1 - BlockSize; + + while (inOff <= inLimit2) { - while (len >= BlockSize) - { - // ProcessBlock(byte[] buf, int bufOff, byte[] output, int outOff) - #region ProcessBlock(buf: input, bufOff: inOff, output: output, outOff: outOff + resultLen); + EncryptBlocks2(input, inOff, output, outOff + resultLen); + inOff += BlockSize * 2; + resultLen += BlockSize * 2; + } - if (totalLength == 0) - InitCipher(); + if (inOff <= inLimit1) + { + EncryptBlock(input, inOff, output, outOff + resultLen); + inOff += BlockSize; + resultLen += BlockSize; + } - #region GetNextCtrBlock(ctrBlock); - blocksRemaining--; + bufOff = BlockSize + inLimit1 - inOff; + Array.Copy(input, inOff, bufBlock, 0, bufOff); + } + else + { + int available = bufBlock.Length - bufOff; + if (len < available) + { + Array.Copy(input, inOff, bufBlock, bufOff, len); + bufOff += len; + return 0; + } - 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; + if (bufOff >= BlockSize) + { + DecryptBlock(bufBlock, 0, output, outOff); + Array.Copy(bufBlock, BlockSize, bufBlock, 0, bufOff -= BlockSize); + resultLen = BlockSize; - cipher.ProcessBlock(counter, 0, ctrBlock, 0); - #endregion + available += BlockSize; + if (len < available) + { + Array.Copy(input, inOff, bufBlock, bufOff, len); + bufOff += len; + return resultLen; + } + } - ulong* pulongBuf = (ulong*)&pbuf[inOff]; - ulong* pulongctrBlock = (ulong*)pctrBlock; - pulongctrBlock[0] ^= pulongBuf[0]; - pulongctrBlock[1] ^= pulongBuf[1]; + int inLimit1 = inOff + len - bufBlock.Length; + int inLimit2 = inLimit1 - BlockSize; - ulong* pulongS = (ulong*)pS; - pulongS[0] ^= pulongctrBlock[0]; - pulongS[1] ^= pulongctrBlock[1]; + available = BlockSize - bufOff; + Array.Copy(input, inOff, bufBlock, bufOff, available); + DecryptBlock(bufBlock, 0, output, outOff + resultLen); + inOff += available; + resultLen += BlockSize; + //bufOff = 0; - Tables8kGcmMultiplier_MultiplyH(S); + while (inOff <= inLimit2) + { + DecryptBlocks2(input, inOff, output, outOff + resultLen); + inOff += BlockSize * 2; + resultLen += BlockSize * 2; + } - ulong* pulongoutput = (ulong*)&poutput[outOff + resultLen]; - pulongoutput[0] = pulongctrBlock[0]; - pulongoutput[1] = pulongctrBlock[1]; + if (inOff <= inLimit1) + { + DecryptBlock(input, inOff, output, outOff + resultLen); + inOff += BlockSize; + resultLen += BlockSize; + } - totalLength += BlockSize; + bufOff = bufBlock.Length + inLimit1 - inOff; + Array.Copy(input, inOff, bufBlock, 0, bufOff); + } - #endregion + return resultLen; +#endif + } - inOff += BlockSize; - len -= BlockSize; - resultLen += BlockSize; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public unsafe int ProcessBytes(ReadOnlySpan input, Span output) + { + CheckStatus(); + + int resultLen = 0; + + if (forEncryption) + { + if (bufOff > 0) + { + int available = BlockSize - bufOff; + if (input.Length < available) + { + input.CopyTo(bufBlock.AsSpan(bufOff)); + bufOff += input.Length; + return 0; } + + input[..available].CopyTo(bufBlock.AsSpan(bufOff)); + EncryptBlock(bufBlock, output); + input = input[available..]; + resultLen = BlockSize; + //bufOff = 0; } - if (len > 0) + while (input.Length >= BlockSize * 2) { - Array.Copy(input, inOff, bufBlock, 0, len); - bufOff = len; + EncryptBlocks2(input, output[resultLen..]); + input = input[(BlockSize * 2)..]; + resultLen += BlockSize * 2; } + + if (input.Length >= BlockSize) + { + EncryptBlock(input, output[resultLen..]); + input = input[BlockSize..]; + resultLen += BlockSize; + } + + bufOff = input.Length; + input.CopyTo(bufBlock); } else { - fixed (byte* pinput = input, pbufBlock = bufBlock, pctrBlock = ctrBlock, pS = S, poutput = output) + int available = bufBlock.Length - bufOff; + if (input.Length < available) { - ulong* pulongbufBlock = (ulong*)pbufBlock; + input.CopyTo(bufBlock.AsSpan(bufOff)); + bufOff += input.Length; + return 0; + } - // adjust bufOff to be on a 8 byte boundary - int adjustCount = 0; - for (int i = 0; i < len && (bufOff % 8) != 0; ++i) + if (bufOff >= BlockSize) + { + DecryptBlock(bufBlock, output); + Array.Copy(bufBlock, BlockSize, bufBlock, 0, bufOff -= BlockSize); + resultLen = BlockSize; + + available += BlockSize; + if (input.Length < available) { - pbufBlock[bufOff++] = pinput[inOff++ + i]; - adjustCount++; + input.CopyTo(bufBlock.AsSpan(bufOff)); + bufOff += input.Length; + return resultLen; + } + } - if (bufOff == bufLength) - { - ProcessBlock(bufBlock, 0, output, outOff + resultLen); + int inLimit1 = bufBlock.Length; + int inLimit2 = inLimit1 + BlockSize; - pulongbufBlock[0] = pulongbufBlock[2]; - pulongbufBlock[1] = pulongbufBlock[3]; + available = BlockSize - bufOff; + input[..available].CopyTo(bufBlock.AsSpan(bufOff)); + DecryptBlock(bufBlock, output[resultLen..]); + input = input[available..]; + resultLen += BlockSize; + //bufOff = 0; - bufOff = macSize; - resultLen += BlockSize; - } - } + while (input.Length >= inLimit2) + { + //DecryptBlocks2(input, output[resultLen..]); + + var outputSample = output[resultLen..]; - int longLen = (len - adjustCount) / 8; - if (longLen > 0) + if (totalLength == 0) { - ulong* pulonginput = (ulong*)&pinput[inOff]; + InitCipher(); + } + + Span ctrBlock = stackalloc byte[BlockSize]; - int bufLongOff = bufOff / 8; + //GetNextCtrBlock(ctrBlock); + if (blocksRemaining == 0) + throw new InvalidOperationException("Attempt to process too many blocks"); - // copy 8 bytes per cycle instead of just 1 - for (int i = 0; i < longLen; ++i) - { - pulongbufBlock[bufLongOff++] = pulonginput[i]; - bufOff += 8; + blocksRemaining--; - if (bufOff == bufLength) - { - #region ProcessBlock(buf: bufBlock, bufOff: 0, output: output, outOff: outOff + resultLen); - if (totalLength == 0) - InitCipher(); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BinaryPrimitives.WriteUInt32BigEndian(counter.AsSpan(12), ++counter32); +#else + Pack.UInt32_To_BE(++counter32, counter, 12); +#endif - #region GetNextCtrBlock(ctrBlock); - blocksRemaining--; + cipher.ProcessBlock(counter, ctrBlock); - 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; + ReadOnlySpan uInput = MemoryMarshal.Cast(input); + Span uS = MemoryMarshal.Cast(S); + ReadOnlySpan uCtrBlock = MemoryMarshal.Cast(ctrBlock); + Span uOutput = MemoryMarshal.Cast(outputSample); - cipher.ProcessBlock(counter, 0, ctrBlock, 0); - #endregion + uS[0] ^= uInput[0]; + uOutput[0] = uInput[0] ^ uCtrBlock[0]; - ulong* pulongS = (ulong*)pS; + uS[1] ^= uInput[1]; + uOutput[1] = uInput[1] ^ uCtrBlock[1]; - pulongS[0] ^= pulongbufBlock[0]; - pulongS[1] ^= pulongbufBlock[1]; + uS[2] ^= uInput[2]; + uOutput[2] = uInput[2] ^ uCtrBlock[2]; - Tables8kGcmMultiplier_MultiplyH(S); + uS[3] ^= uInput[3]; + uOutput[3] = uInput[3] ^ uCtrBlock[3]; - ulong* pulongOutput = (ulong*)&poutput[outOff + resultLen]; - ulong* pulongctrBlock = (ulong*)pctrBlock; + multiplier.MultiplyH(S); - pulongOutput[0] = pulongctrBlock[0] ^ pulongbufBlock[0]; - pulongOutput[1] = pulongctrBlock[1] ^ pulongbufBlock[1]; + input = input[BlockSize..]; + outputSample = outputSample[BlockSize..]; - totalLength += BlockSize; + //GetNextCtrBlock(ctrBlock); + if (blocksRemaining == 0) + throw new InvalidOperationException("Attempt to process too many blocks"); - #endregion + blocksRemaining--; - pulongbufBlock[0] = pulongbufBlock[2]; - pulongbufBlock[1] = pulongbufBlock[3]; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BinaryPrimitives.WriteUInt32BigEndian(counter.AsSpan(12), ++counter32); +#else + Pack.UInt32_To_BE(++counter32, counter, 12); +#endif - bufOff = macSize; - resultLen += BlockSize; + cipher.ProcessBlock(counter, ctrBlock); - bufLongOff = bufOff / 8; - } - } - } + uInput = MemoryMarshal.Cast(input); + uS = MemoryMarshal.Cast(S); + uCtrBlock = MemoryMarshal.Cast(ctrBlock); + uOutput = MemoryMarshal.Cast(outputSample); - for (int i = longLen * 8; i < len; i++) - { - pbufBlock[bufOff++] = pinput[inOff + i]; + uS[0] ^= uInput[0]; + uOutput[0] = uInput[0] ^ uCtrBlock[0]; - if (bufOff == bufLength) - { - ProcessBlock(bufBlock, 0, output, outOff + resultLen); + uS[1] ^= uInput[1]; + uOutput[1] = uInput[1] ^ uCtrBlock[1]; - pulongbufBlock[0] = pulongbufBlock[2]; - pulongbufBlock[1] = pulongbufBlock[3]; + uS[2] ^= uInput[2]; + uOutput[2] = uInput[2] ^ uCtrBlock[2]; - bufOff = macSize; - resultLen += BlockSize; - } - } + uS[3] ^= uInput[3]; + uOutput[3] = uInput[3] ^ uCtrBlock[3]; + + multiplier.MultiplyH(S); + + totalLength += BlockSize * 2; + + //input = input[(BlockSize * 2)..]; + input = input[BlockSize..]; + resultLen += BlockSize * 2; } + + if (input.Length >= inLimit1) + { + DecryptBlock(input, output[resultLen..]); + input = input[BlockSize..]; + resultLen += BlockSize; + } + + bufOff = input.Length; + input.CopyTo(bufBlock); } return resultLen; } +#endif - private unsafe void ProcessBlock(byte[] buf, int bufOff, byte[] output, int outOff) + public int DoFinal(byte[] output, int outOff) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(output.AsSpan(outOff)); +#else + CheckStatus(); + if (totalLength == 0) + { InitCipher(); + } - GetNextCtrBlock(ctrBlock); + int extra = bufOff; if (forEncryption) { - fixed (byte* pctrBlock = ctrBlock, pbuf = buf, pS = S) - { - - ulong* pulongBuf = (ulong*)&pbuf[bufOff]; - ulong* pulongctrBlock = (ulong*)pctrBlock; - pulongctrBlock[0] ^= pulongBuf[0]; - pulongctrBlock[1] ^= pulongBuf[1]; + Check.OutputLength(output, outOff, extra + macSize, "output buffer too short"); + } + else + { + if (extra < macSize) + throw new InvalidCipherTextException("data too short"); - ulong* pulongS = (ulong*)pS; - pulongS[0] ^= pulongctrBlock[0]; - pulongS[1] ^= pulongctrBlock[1]; + extra -= macSize; - Tables8kGcmMultiplier_MultiplyH(S); + Check.OutputLength(output, outOff, extra, "output buffer too short"); + } - fixed (byte* poutput = output) - { - ulong* pulongoutput = (ulong*)&poutput[outOff]; - pulongoutput[0] = pulongctrBlock[0]; - pulongoutput[1] = pulongctrBlock[1]; - } - } + if (extra > 0) + { + ProcessPartial(bufBlock, 0, extra, output, outOff); } - else + + atLength += (uint)atBlockPos; + + if (atLength > atLengthPre) { - // moved this part to ProcessBytes's main part - fixed (byte* pctrBlock = ctrBlock, pbuf = buf, pS = S, poutput = output) - { - ulong* pulongS = (ulong*)pS; - ulong* pulongBuf = (ulong*)&pbuf[bufOff]; + /* + * 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. + */ - pulongS[0] ^= pulongBuf[0]; - pulongS[1] ^= pulongBuf[1]; + // Finish hash for partial AAD block + if (atBlockPos > 0) + { + gHASHPartial(S_at, atBlock, 0, atBlockPos); + } - Tables8kGcmMultiplier_MultiplyH(S); + // Find the difference between the AAD hashes + if (atLengthPre > 0) + { + GcmUtilities.Xor(S_at, S_atPre); + } - ulong* pulongOutput = (ulong*)&poutput[outOff]; - ulong* pulongctrBlock = (ulong*)pctrBlock; + // Number of cipher-text blocks produced + long c = (long)(((totalLength * 8) + 127) >> 7); - pulongOutput[0] = pulongctrBlock[0] ^ pulongBuf[0]; - pulongOutput[1] = pulongctrBlock[1] ^ pulongBuf[1]; + // Calculate the adjustment factor + byte[] H_c = new byte[16]; + if (exp == null) + { + exp = new BasicGcmExponentiator(); + 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); } - totalLength += BlockSize; + // 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; +#endif } - public int DoFinal(byte[] output, int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) { CheckStatus(); @@ -622,7 +855,7 @@ public int DoFinal(byte[] output, int outOff) if (forEncryption) { - Check.OutputLength(output, outOff, extra + macSize, "Output buffer too short"); + Check.OutputLength(output, extra + macSize, "output buffer too short"); } else { @@ -631,12 +864,12 @@ public int DoFinal(byte[] output, int outOff) extra -= macSize; - Check.OutputLength(output, outOff, extra, "Output buffer too short"); + Check.OutputLength(output, extra, "output buffer too short"); } if (extra > 0) { - ProcessPartial(bufBlock, 0, extra, output, outOff); + ProcessPartial(bufBlock.AsSpan(0, extra), output); } atLength += (uint)atBlockPos; @@ -666,10 +899,10 @@ public int DoFinal(byte[] output, int outOff) long c = (long)(((totalLength * 8) + 127) >> 7); // Calculate the adjustment factor - byte[] H_c = BufferPool.Get(16, true); + byte[] H_c = new byte[16]; if (exp == null) { - exp = new Tables1kGcmExponentiator(); + exp = new BasicGcmExponentiator(); exp.Init(H); } exp.ExponentiateX(c, H_c); @@ -679,100 +912,77 @@ public int DoFinal(byte[] output, int outOff) // Adjust the current hash GcmUtilities.Xor(S, S_at); - - BufferPool.Release(H_c); } // Final gHASH - byte[] X = BufferPool.Get(BlockSize, false); - Pack.UInt64_To_BE(atLength * 8UL, X, 0); - Pack.UInt64_To_BE(totalLength * 8UL, X, 8); + Span X = stackalloc byte[BlockSize]; + Pack.UInt64_To_BE(atLength * 8UL, X); + Pack.UInt64_To_BE(totalLength * 8UL, X[8..]); gHASHBlock(S, X); - BufferPool.Release(X); - // T = MSBt(GCTRk(J0,S)) - byte[] tag = BufferPool.Get(BlockSize, false); - cipher.ProcessBlock(J0, 0, tag, 0); + Span tag = stackalloc byte[BlockSize]; + cipher.ProcessBlock(J0, tag); GcmUtilities.Xor(tag, S); int resultLen = extra; // We place into macBlock our calculated value for T - - if (this.macBlock == null || this.macBlock.Length < macSize) - this.macBlock = BufferPool.Resize(ref this.macBlock, macSize, false, false); - - Array.Copy(tag, 0, macBlock, 0, macSize); - - BufferPool.Release(tag); + this.macBlock = new byte[macSize]; + tag[..macSize].CopyTo(macBlock); if (forEncryption) { // Append T to the message - Array.Copy(macBlock, 0, output, outOff + bufOff, macSize); + macBlock.CopyTo(output[bufOff..]); resultLen += macSize; } else { // Retrieve the T value from the message and compare to calculated one - byte[] msgMac = BufferPool.Get(macSize, false); - Array.Copy(bufBlock, extra, msgMac, 0, macSize); + Span msgMac = stackalloc byte[macSize]; + bufBlock.AsSpan(extra, macSize).CopyTo(msgMac); if (!Arrays.ConstantTimeAreEqual(this.macBlock, msgMac)) throw new InvalidCipherTextException("mac check in GCM failed"); - BufferPool.Release(msgMac); } Reset(false); return resultLen; } +#endif public void Reset() { Reset(true); } - private unsafe void Reset( - bool clearMac) + private void Reset(bool clearMac) { - cipher.Reset(); - // note: we do not reset the nonce. - //BufferPool.Resize(ref this.S, BlockSize, false, true); - //BufferPool.Resize(ref this.S_at, BlockSize, false, true); - //BufferPool.Resize(ref this.S_atPre, BlockSize, false, true); - //BufferPool.Resize(ref this.atBlock, BlockSize, false, true); - fixed (byte* pS = S, pS_at = S_at, pS_atPre = S_atPre, patBlock = atBlock) - { - for (int i = 0; i < BlockSize; ++i) - { - pS[i] = pS_at[i] = pS_atPre[i] = patBlock[i] = 0; - } - } - + S = new byte[BlockSize]; + S_at = new byte[BlockSize]; + S_atPre = new byte[BlockSize]; + atBlock = new byte[BlockSize]; atBlockPos = 0; atLength = 0; atLengthPre = 0; - - //BufferPool.Resize(ref this.counter, BlockSize, false, false); - Array.Copy(this.J0, 0, this.counter, 0, BlockSize); - + counter = Arrays.Clone(J0); + counter32 = Pack.BE_To_UInt32(counter, 12); blocksRemaining = uint.MaxValue - 1; bufOff = 0; totalLength = 0; if (bufBlock != null) { - //Arrays.Fill(bufBlock, 0); + Arrays.Fill(bufBlock, 0); } if (clearMac) { - //macBlock = null; - Array.Clear(this.macBlock, 0, this.macSize); + macBlock = null; } if (forEncryption) @@ -788,207 +998,579 @@ private unsafe void Reset( } } - private void ProcessPartial(byte[] buf, int off, int len, byte[] output, int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void DecryptBlock(ReadOnlySpan input, Span output) { - //byte[] ctrBlock = new byte[BlockSize]; - GetNextCtrBlock(ctrBlock); + Check.OutputLength(output, BlockSize, "output buffer too short"); - if (forEncryption) + if (totalLength == 0) { - GcmUtilities.Xor(buf, off, ctrBlock, 0, len); - gHASHPartial(S, buf, off, len); + InitCipher(); + } + + Span ctrBlock = stackalloc byte[BlockSize]; + + GetNextCtrBlock(ctrBlock); +#if BESTHTTP_WITH_BURST + FastGcmBlockCipherHelper.DecryptBlock(input, output, ctrBlock, S.AsSpan(), BlockSize); +#elif NETCOREAPP3_0_OR_GREATER + if (Sse2.IsSupported && Unsafe.SizeOf>() == BlockSize) + { + var t0 = MemoryMarshal.Read>(input); + var t1 = MemoryMarshal.Read>(ctrBlock); + var t2 = MemoryMarshal.Read>(S.AsSpan()); + + t1 = Sse2.Xor(t1, t0); + t2 = Sse2.Xor(t2, t0); + + MemoryMarshal.Write(output, ref t1); + MemoryMarshal.Write(S.AsSpan(), ref t2); } else +#else { - gHASHPartial(S, buf, off, len); - GcmUtilities.Xor(buf, off, ctrBlock, 0, len); + for (int i = 0; i < BlockSize; i += 4) + { + byte c0 = input[i + 0]; + byte c1 = input[i + 1]; + byte c2 = input[i + 2]; + byte c3 = input[i + 3]; + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + output[i + 0] = (byte)(c0 ^ ctrBlock[i + 0]); + output[i + 1] = (byte)(c1 ^ ctrBlock[i + 1]); + output[i + 2] = (byte)(c2 ^ ctrBlock[i + 2]); + output[i + 3] = (byte)(c3 ^ ctrBlock[i + 3]); + } } +#endif + multiplier.MultiplyH(S); - Array.Copy(buf, off, output, outOff, len); - totalLength += (uint)len; + totalLength += BlockSize; } - private void gHASH(byte[] Y, byte[] b, int len) + private void DecryptBlocks2(ReadOnlySpan input, Span outputSample) { - for (int pos = 0; pos < len; pos += BlockSize) + Check.OutputLength(outputSample, BlockSize * 2, "output buffer too short"); + + if (totalLength == 0) { - int num = System.Math.Min(len - pos, BlockSize); - gHASHPartial(Y, b, pos, num); + InitCipher(); } - } - private void gHASHBlock(byte[] Y, byte[] b) - { - GcmUtilities.Xor(Y, b); - Tables8kGcmMultiplier_MultiplyH(Y); + Span ctrBlock = stackalloc byte[BlockSize]; + + GetNextCtrBlock(ctrBlock); + + for (int i = 0; i < BlockSize; i += 4) + { + byte c0 = input[i + 0]; + byte c1 = input[i + 1]; + byte c2 = input[i + 2]; + byte c3 = input[i + 3]; + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + outputSample[i + 0] = (byte)(c0 ^ ctrBlock[i + 0]); + outputSample[i + 1] = (byte)(c1 ^ ctrBlock[i + 1]); + outputSample[i + 2] = (byte)(c2 ^ ctrBlock[i + 2]); + outputSample[i + 3] = (byte)(c3 ^ ctrBlock[i + 3]); + } + + multiplier.MultiplyH(S); + + input = input[BlockSize..]; + outputSample = outputSample[BlockSize..]; + + GetNextCtrBlock(ctrBlock); + + for (int i = 0; i < BlockSize; i += 4) + { + byte c0 = input[i + 0]; + byte c1 = input[i + 1]; + byte c2 = input[i + 2]; + byte c3 = input[i + 3]; + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + outputSample[i + 0] = (byte)(c0 ^ ctrBlock[i + 0]); + outputSample[i + 1] = (byte)(c1 ^ ctrBlock[i + 1]); + outputSample[i + 2] = (byte)(c2 ^ ctrBlock[i + 2]); + outputSample[i + 3] = (byte)(c3 ^ ctrBlock[i + 3]); + } + + multiplier.MultiplyH(S); + + totalLength += BlockSize * 2; } - private void gHASHBlock(byte[] Y, byte[] b, int off) + private void EncryptBlock(ReadOnlySpan input, Span output) { - GcmUtilities.Xor(Y, b, off); - Tables8kGcmMultiplier_MultiplyH(Y); + Check.OutputLength(output, BlockSize, "output buffer too short"); + + if (totalLength == 0) + { + InitCipher(); + } + + Span ctrBlock = stackalloc byte[BlockSize]; + + GetNextCtrBlock(ctrBlock); +#if NETCOREAPP3_0_OR_GREATER + if (Sse2.IsSupported && Unsafe.SizeOf>() == BlockSize) + { + var t0 = MemoryMarshal.Read>(input); + var t1 = MemoryMarshal.Read>(ctrBlock); + var t2 = MemoryMarshal.Read>(S.AsSpan()); + + t1 = Sse2.Xor(t1, t0); + t2 = Sse2.Xor(t2, t1); + + MemoryMarshal.Write(output, ref t1); + MemoryMarshal.Write(S.AsSpan(), ref t2); + } + else +#endif + { + for (int i = 0; i < BlockSize; i += 4) + { + byte c0 = (byte)(ctrBlock[i + 0] ^ input[i + 0]); + byte c1 = (byte)(ctrBlock[i + 1] ^ input[i + 1]); + byte c2 = (byte)(ctrBlock[i + 2] ^ input[i + 2]); + byte c3 = (byte)(ctrBlock[i + 3] ^ input[i + 3]); + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + output[i + 0] = c0; + output[i + 1] = c1; + output[i + 2] = c2; + output[i + 3] = c3; + } + } + multiplier.MultiplyH(S); + + totalLength += BlockSize; } - private void gHASHPartial(byte[] Y, byte[] b, int off, int len) + private void EncryptBlocks2(ReadOnlySpan input, Span output) { - GcmUtilities.Xor(Y, b, off, len); - Tables8kGcmMultiplier_MultiplyH(Y); + Check.OutputLength(output, BlockSize * 2, "Output buffer too short"); + + if (totalLength == 0) + { + InitCipher(); + } + + Span ctrBlock = stackalloc byte[BlockSize]; + + GetNextCtrBlock(ctrBlock); +#if NETCOREAPP3_0_OR_GREATER + if (Sse2.IsSupported && Unsafe.SizeOf>() == BlockSize) + { + var t0 = MemoryMarshal.Read>(input); + var t1 = MemoryMarshal.Read>(ctrBlock); + var t2 = MemoryMarshal.Read>(S.AsSpan()); + + t1 = Sse2.Xor(t1, t0); + t2 = Sse2.Xor(t2, t1); + + MemoryMarshal.Write(output, ref t1); + MemoryMarshal.Write(S.AsSpan(), ref t2); + } + else +#endif + { + for (int i = 0; i < BlockSize; i += 4) + { + byte c0 = (byte)(ctrBlock[i + 0] ^ input[i + 0]); + byte c1 = (byte)(ctrBlock[i + 1] ^ input[i + 1]); + byte c2 = (byte)(ctrBlock[i + 2] ^ input[i + 2]); + byte c3 = (byte)(ctrBlock[i + 3] ^ input[i + 3]); + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + output[i + 0] = c0; + output[i + 1] = c1; + output[i + 2] = c2; + output[i + 3] = c3; + } + } + multiplier.MultiplyH(S); + + input = input[BlockSize..]; + output = output[BlockSize..]; + + GetNextCtrBlock(ctrBlock); +#if NETCOREAPP3_0_OR_GREATER + if (Sse2.IsSupported && Unsafe.SizeOf>() == BlockSize) + { + var t0 = MemoryMarshal.Read>(input); + var t1 = MemoryMarshal.Read>(ctrBlock); + var t2 = MemoryMarshal.Read>(S.AsSpan()); + + t1 = Sse2.Xor(t1, t0); + t2 = Sse2.Xor(t2, t1); + + MemoryMarshal.Write(output, ref t1); + MemoryMarshal.Write(S.AsSpan(), ref t2); + } + else +#endif + { + for (int i = 0; i < BlockSize; i += 4) + { + byte c0 = (byte)(ctrBlock[i + 0] ^ input[i + 0]); + byte c1 = (byte)(ctrBlock[i + 1] ^ input[i + 1]); + byte c2 = (byte)(ctrBlock[i + 2] ^ input[i + 2]); + byte c3 = (byte)(ctrBlock[i + 3] ^ input[i + 3]); + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + output[i + 0] = c0; + output[i + 1] = c1; + output[i + 2] = c2; + output[i + 3] = c3; + } + } + multiplier.MultiplyH(S); + + totalLength += BlockSize * 2; } - private void GetNextCtrBlock(byte[] block) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void GetNextCtrBlock(Span 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; + Pack.UInt32_To_BE(++counter32, counter, 12); - cipher.ProcessBlock(counter, 0, block, 0); + cipher.ProcessBlock(counter, block); } - private void CheckStatus() + private void ProcessPartial(Span partialBlock, Span output) { - if (!initialised) + Span ctrBlock = stackalloc byte[BlockSize]; + GetNextCtrBlock(ctrBlock); + + if (forEncryption) { - if (forEncryption) + GcmUtilities.Xor(partialBlock, ctrBlock, partialBlock.Length); + gHASHPartial(S, partialBlock); + } + else + { + gHASHPartial(S, partialBlock); + GcmUtilities.Xor(partialBlock, ctrBlock, partialBlock.Length); + } + + partialBlock.CopyTo(output); + totalLength += (uint)partialBlock.Length; + } +#else + private void DecryptBlock(byte[] inBuf, int inOff, byte[] outBuf, int outOff) + { + Check.OutputLength(outBuf, outOff, BlockSize, "Output buffer too short"); + + if (totalLength == 0) + { + InitCipher(); + } + + //byte[] ctrBlock = new byte[BlockSize]; + + GetNextCtrBlock(ctrBlock); + { + for (int i = 0; i < BlockSize; i += 4) { - throw new InvalidOperationException("GCM cipher cannot be reused for encryption"); + byte c0 = inBuf[inOff + i + 0]; + byte c1 = inBuf[inOff + i + 1]; + byte c2 = inBuf[inOff + i + 2]; + byte c3 = inBuf[inOff + i + 3]; + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + outBuf[outOff + i + 0] = (byte)(c0 ^ ctrBlock[i + 0]); + outBuf[outOff + i + 1] = (byte)(c1 ^ ctrBlock[i + 1]); + outBuf[outOff + i + 2] = (byte)(c2 ^ ctrBlock[i + 2]); + outBuf[outOff + i + 3] = (byte)(c3 ^ ctrBlock[i + 3]); } - throw new InvalidOperationException("GCM cipher needs to be initialised"); } + multiplier.MultiplyH(S); + + totalLength += BlockSize; } - #region Tables8kGcmMultiplier + private void DecryptBlocks2(byte[] inBuf, int inOff, byte[] outBuf, int outOff) + { + Check.OutputLength(outBuf, outOff, BlockSize * 2, "Output buffer too short"); + + if (totalLength == 0) + { + InitCipher(); + } - private byte[] Tables8kGcmMultiplier_H; - private uint[][][] Tables8kGcmMultiplier_M; + //byte[] ctrBlock = new byte[BlockSize]; - public void Tables8kGcmMultiplier_Init(byte[] H) - { - if (Tables8kGcmMultiplier_M == null) + GetNextCtrBlock(ctrBlock); { - Tables8kGcmMultiplier_M = new uint[32][][]; + for (int i = 0; i < BlockSize; i += 4) + { + byte c0 = inBuf[inOff + i + 0]; + byte c1 = inBuf[inOff + i + 1]; + byte c2 = inBuf[inOff + i + 2]; + byte c3 = inBuf[inOff + i + 3]; + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + outBuf[outOff + i + 0] = (byte)(c0 ^ ctrBlock[i + 0]); + outBuf[outOff + i + 1] = (byte)(c1 ^ ctrBlock[i + 1]); + outBuf[outOff + i + 2] = (byte)(c2 ^ ctrBlock[i + 2]); + outBuf[outOff + i + 3] = (byte)(c3 ^ ctrBlock[i + 3]); + } } - else if (Arrays.AreEqual(this.Tables8kGcmMultiplier_H, H)) + multiplier.MultiplyH(S); + + inOff += BlockSize; + outOff += BlockSize; + + GetNextCtrBlock(ctrBlock); { - return; + for (int i = 0; i < BlockSize; i += 4) + { + byte c0 = inBuf[inOff + i + 0]; + byte c1 = inBuf[inOff + i + 1]; + byte c2 = inBuf[inOff + i + 2]; + byte c3 = inBuf[inOff + i + 3]; + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + outBuf[outOff + i + 0] = (byte)(c0 ^ ctrBlock[i + 0]); + outBuf[outOff + i + 1] = (byte)(c1 ^ ctrBlock[i + 1]); + outBuf[outOff + i + 2] = (byte)(c2 ^ ctrBlock[i + 2]); + outBuf[outOff + i + 3] = (byte)(c3 ^ ctrBlock[i + 3]); + } } + multiplier.MultiplyH(S); - this.Tables8kGcmMultiplier_H = Arrays.Clone(H); + totalLength += BlockSize * 2; + } - Tables8kGcmMultiplier_M[0] = new uint[16][]; - Tables8kGcmMultiplier_M[1] = new uint[16][]; - Tables8kGcmMultiplier_M[0][0] = new uint[4]; - Tables8kGcmMultiplier_M[1][0] = new uint[4]; - Tables8kGcmMultiplier_M[1][8] = GcmUtilities.AsUints(H); + private void EncryptBlock(byte[] inBuf, int inOff, byte[] outBuf, int outOff) + { + Check.OutputLength(outBuf, outOff, BlockSize, "Output buffer too short"); - for (int j = 4; j >= 1; j >>= 1) + if (totalLength == 0) { - uint[] tmp = (uint[])Tables8kGcmMultiplier_M[1][j + j].Clone(); - GcmUtilities.MultiplyP(tmp); - Tables8kGcmMultiplier_M[1][j] = tmp; + InitCipher(); } + //byte[] ctrBlock = new byte[BlockSize]; + + GetNextCtrBlock(ctrBlock); { - uint[] tmp = (uint[])Tables8kGcmMultiplier_M[1][1].Clone(); - GcmUtilities.MultiplyP(tmp); - Tables8kGcmMultiplier_M[0][8] = tmp; + for (int i = 0; i < BlockSize; i += 4) + { + byte c0 = (byte)(ctrBlock[i + 0] ^ inBuf[inOff + i + 0]); + byte c1 = (byte)(ctrBlock[i + 1] ^ inBuf[inOff + i + 1]); + byte c2 = (byte)(ctrBlock[i + 2] ^ inBuf[inOff + i + 2]); + byte c3 = (byte)(ctrBlock[i + 3] ^ inBuf[inOff + i + 3]); + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + outBuf[outOff + i + 0] = c0; + outBuf[outOff + i + 1] = c1; + outBuf[outOff + i + 2] = c2; + outBuf[outOff + i + 3] = c3; + } } + multiplier.MultiplyH(S); + + totalLength += BlockSize; + } + + private void EncryptBlocks2(byte[] inBuf, int inOff, byte[] outBuf, int outOff) + { + Check.OutputLength(outBuf, outOff, BlockSize * 2, "Output buffer too short"); - for (int j = 4; j >= 1; j >>= 1) + if (totalLength == 0) { - uint[] tmp = (uint[])Tables8kGcmMultiplier_M[0][j + j].Clone(); - GcmUtilities.MultiplyP(tmp); - Tables8kGcmMultiplier_M[0][j] = tmp; + InitCipher(); } - for (int i = 0; ;) + //byte[] ctrBlock = new byte[BlockSize]; + + GetNextCtrBlock(ctrBlock); { - for (int j = 2; j < 16; j += j) + for (int i = 0; i < BlockSize; i += 4) { - for (int k = 1; k < j; ++k) - { - uint[] tmp = (uint[])Tables8kGcmMultiplier_M[i][j].Clone(); - GcmUtilities.Xor(tmp, Tables8kGcmMultiplier_M[i][k]); - Tables8kGcmMultiplier_M[i][j + k] = tmp; - } + byte c0 = (byte)(ctrBlock[i + 0] ^ inBuf[inOff + i + 0]); + byte c1 = (byte)(ctrBlock[i + 1] ^ inBuf[inOff + i + 1]); + byte c2 = (byte)(ctrBlock[i + 2] ^ inBuf[inOff + i + 2]); + byte c3 = (byte)(ctrBlock[i + 3] ^ inBuf[inOff + i + 3]); + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + outBuf[outOff + i + 0] = c0; + outBuf[outOff + i + 1] = c1; + outBuf[outOff + i + 2] = c2; + outBuf[outOff + i + 3] = c3; } + } + multiplier.MultiplyH(S); - if (++i == 32) return; + inOff += BlockSize; + outOff += BlockSize; - if (i > 1) + GetNextCtrBlock(ctrBlock); + { + for (int i = 0; i < BlockSize; i += 4) { - Tables8kGcmMultiplier_M[i] = new uint[16][]; - Tables8kGcmMultiplier_M[i][0] = new uint[4]; - for (int j = 8; j > 0; j >>= 1) - { - uint[] tmp = (uint[])Tables8kGcmMultiplier_M[i - 2][j].Clone(); - GcmUtilities.MultiplyP8(tmp); - Tables8kGcmMultiplier_M[i][j] = tmp; - } + byte c0 = (byte)(ctrBlock[i + 0] ^ inBuf[inOff + i + 0]); + byte c1 = (byte)(ctrBlock[i + 1] ^ inBuf[inOff + i + 1]); + byte c2 = (byte)(ctrBlock[i + 2] ^ inBuf[inOff + i + 2]); + byte c3 = (byte)(ctrBlock[i + 3] ^ inBuf[inOff + i + 3]); + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + outBuf[outOff + i + 0] = c0; + outBuf[outOff + i + 1] = c1; + outBuf[outOff + i + 2] = c2; + outBuf[outOff + i + 3] = c3; } } + multiplier.MultiplyH(S); + + totalLength += BlockSize * 2; } - uint[] Tables8kGcmMultiplier_z = new uint[4]; - public unsafe void Tables8kGcmMultiplier_MultiplyH(byte[] x) + private void GetNextCtrBlock(byte[] block) { - fixed (byte* px = x) - fixed (uint* pz = Tables8kGcmMultiplier_z) - { - ulong* pulongZ = (ulong*)pz; - pulongZ[0] = 0; - pulongZ[1] = 0; + if (blocksRemaining == 0) + throw new InvalidOperationException("Attempt to process too many blocks"); - for (int i = 15; i >= 0; --i) - { - uint[] m = Tables8kGcmMultiplier_M[i + i][px[i] & 0x0f]; - fixed (uint* pm = m) - { - ulong* pulongm = (ulong*)pm; + blocksRemaining--; - pulongZ[0] ^= pulongm[0]; - pulongZ[1] ^= pulongm[1]; - } + Pack.UInt32_To_BE(++counter32, counter, 12); - m = Tables8kGcmMultiplier_M[i + i + 1][(px[i] & 0xf0) >> 4]; - fixed (uint* pm = m) - { - ulong* pulongm = (ulong*)pm; + cipher.ProcessBlock(counter, 0, block, 0); + } - pulongZ[0] ^= pulongm[0]; - pulongZ[1] ^= pulongm[1]; - } - } + private void ProcessPartial(byte[] buf, int off, int len, byte[] output, int outOff) + { + //byte[] ctrBlock = new byte[BlockSize]; + GetNextCtrBlock(ctrBlock); - byte* pbyteZ = (byte*)pz; - px[0] = pbyteZ[3]; - px[1] = pbyteZ[2]; - px[2] = pbyteZ[1]; - px[3] = pbyteZ[0]; + 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); + } - px[4] = pbyteZ[7]; - px[5] = pbyteZ[6]; - px[6] = pbyteZ[5]; - px[7] = pbyteZ[4]; + Array.Copy(buf, off, output, outOff, len); + totalLength += (uint)len; + } +#endif - px[8] = pbyteZ[11]; - px[9] = pbyteZ[10]; - px[10] = pbyteZ[9]; - px[11] = pbyteZ[8]; + 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); + } + } - px[12] = pbyteZ[15]; - px[13] = pbyteZ[14]; - px[14] = pbyteZ[13]; - px[15] = pbyteZ[12]; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void gHASHBlock(byte[] Y, ReadOnlySpan b) + { + GcmUtilities.Xor(Y, b); + multiplier.MultiplyH(Y); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void gHASHPartial(byte[] Y, ReadOnlySpan b) + { + GcmUtilities.Xor(Y, b, b.Length); + multiplier.MultiplyH(Y); + } +#else + 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); + } +#endif + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void gHASHPartial(byte[] Y, byte[] b, int off, int len) + { + GcmUtilities.Xor(Y, b, off, len); + multiplier.MultiplyH(Y); + } + + 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"); } } - #endregion } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastGcmBlockCipherHelper.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastGcmBlockCipherHelper.cs new file mode 100644 index 0000000..3889414 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastGcmBlockCipherHelper.cs @@ -0,0 +1,78 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) && BESTHTTP_WITH_BURST +using System; +using static Unity.Burst.Intrinsics.X86.Sse2; +using static Unity.Burst.Intrinsics.Arm.Neon; +using System.Runtime.CompilerServices; +using Unity.Burst; + +// https://github.com/sschoener/burst-simd-exercises/blob/main/Assets/Examples/2-sum-small-numbers-sse3/SumSmallNumbers_SSE3.cs + +namespace BestHTTP.Connections.TLS.Crypto.Impl +{ + [BurstCompile] + internal sealed unsafe class FastGcmBlockCipherHelper + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void DecryptBlock(ReadOnlySpan input, Span output, Span ctrBlock, Span S, int BlockSize) + { + fixed (byte* pInput = input) + fixed (byte* pOutput = output) + fixed (byte* pctrBlock = ctrBlock) + fixed (byte* pS = S) { + DecryptBlock_Impl(pInput, input.Length, pOutput, output.Length, pctrBlock, pS, BlockSize); + } + } + + [BurstCompile(CompileSynchronously = true)] + private unsafe static void DecryptBlock_Impl([NoAlias] byte* pinput, int inLen, [NoAlias] byte* poutput, int outLen, [NoAlias] byte* pctrBlock, [NoAlias] byte* pS, int BlockSize) + { + if (IsSse2Supported) + { + var vInput = loadu_si128(pinput); + var vCtrBlock = loadu_si128(pctrBlock); + var vS = loadu_si128(pS); + + vS = xor_si128(vS, vInput); + vCtrBlock = xor_si128(vInput, vCtrBlock); + + storeu_si128(pS, vS); + storeu_si128(poutput, vCtrBlock); + } + else if (IsNeonSupported) + { + var vInput = vld1q_u8(pinput); + var vCtrBlock = vld1q_u8(pctrBlock); + var vS = vld1q_u8(pS); + + vS = veorq_u8(vS, vInput); + vCtrBlock = veorq_u8(vInput, vCtrBlock); + + vst1q_u8(pS, vS); + vst1q_u8(poutput, vCtrBlock); + } + else + { + Unity.Burst.CompilerServices.Hint.Assume(BlockSize == 16); + + for (int i = 0; i < BlockSize; i += 4) + { + byte c0 = pinput[i + 0]; + byte c1 = pinput[i + 1]; + byte c2 = pinput[i + 2]; + byte c3 = pinput[i + 3]; + + pS[i + 0] ^= c0; + pS[i + 1] ^= c1; + pS[i + 2] ^= c2; + pS[i + 3] ^= c3; + + poutput[i + 0] = (byte)(c0 ^ pctrBlock[i + 0]); + poutput[i + 1] = (byte)(c1 ^ pctrBlock[i + 1]); + poutput[i + 2] = (byte)(c2 ^ pctrBlock[i + 2]); + poutput[i + 3] = (byte)(c3 ^ pctrBlock[i + 3]); + } + } + } + } +} +#endif diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastGcmBlockCipherHelper.cs.meta b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastGcmBlockCipherHelper.cs.meta new file mode 100644 index 0000000..7501934 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastGcmBlockCipherHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0bc09b804bfd7824c90f995674bdad11 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastPoly1305.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastPoly1305.cs index 01d7b21..334d998 100644 --- a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastPoly1305.cs +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastPoly1305.cs @@ -1,6 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.CompilerServices; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators; @@ -23,9 +24,9 @@ namespace BestHTTP.Connections.TLS.Crypto.Impl /// by Andrew M (@floodyberry). /// /// - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] + + + [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] public sealed class FastPoly1305 : IMac { @@ -33,8 +34,6 @@ public sealed class FastPoly1305 : IMac private readonly IBlockCipher cipher; - private readonly byte[] singleByte = new byte[1]; - // Initialised state /** Polynomial key */ @@ -88,18 +87,18 @@ public void Init(ICipherParameters parameters) if (cipher != null) { - if (!(parameters is FastParametersWithIV)) + if (!(parameters is ParametersWithIV)) throw new ArgumentException("Poly1305 requires an IV when used with a block cipher.", "parameters"); - FastParametersWithIV ivParams = (FastParametersWithIV)parameters; + ParametersWithIV ivParams = (ParametersWithIV)parameters; nonce = ivParams.GetIV(); parameters = ivParams.Parameters; } - if (!(parameters is NoCopyKeyParameter)) + if (!(parameters is KeyParameter)) throw new ArgumentException("Poly1305 requires a key."); - NoCopyKeyParameter keyParams = (NoCopyKeyParameter)parameters; + KeyParameter keyParams = (KeyParameter)parameters; SetKey(keyParams.GetKey(), nonce); @@ -169,60 +168,159 @@ public int GetMacSize() public void Update(byte input) { - singleByte[0] = input; - BlockUpdate(singleByte, 0, 1); + currentBlock[currentBlockOffset++] = input; + if (currentBlockOffset == BlockSize) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ProcessBlock(currentBlock); +#else + ProcessBlock(currentBlock, 0); +#endif + currentBlockOffset = 0; + } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif public void BlockUpdate(byte[] input, int inOff, int len) { - int copied = 0; - while (len > copied) + Check.DataLength(input, inOff, len, "input buffer too short"); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BlockUpdate(input.AsSpan(inOff, len)); +#else + int available = BlockSize - currentBlockOffset; + if (len < available) { - if (currentBlockOffset == BlockSize) - { - ProcessBlock(); - currentBlockOffset = 0; - } + Array.Copy(input, inOff, currentBlock, currentBlockOffset, len); + currentBlockOffset += len; + return; + } + + int pos = 0; + if (currentBlockOffset > 0) + { + Array.Copy(input, inOff, currentBlock, currentBlockOffset, available); + pos = available; + ProcessBlock(currentBlock, 0); + } - int toCopy = System.Math.Min((len - copied), BlockSize - currentBlockOffset); - Array.Copy(input, copied + inOff, currentBlock, currentBlockOffset, toCopy); - copied += toCopy; - currentBlockOffset += toCopy; + int remaining; + while ((remaining = len - pos) >= BlockSize) + { + ProcessBlock(input, inOff + pos); + pos += BlockSize; } + + Array.Copy(input, inOff + pos, currentBlock, 0, remaining); + currentBlockOffset = remaining; +#endif } - private void ProcessBlock() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#if !UNITY_ANDROID || UNITY_EDITOR + unsafe +#endif + public void BlockUpdate(ReadOnlySpan input) { - if (currentBlockOffset < BlockSize) + int available = BlockSize - currentBlockOffset; + if (input.Length < available) + { + input.CopyTo(currentBlock.AsSpan(currentBlockOffset)); + currentBlockOffset += input.Length; + return; + } + + int pos = 0; + if (currentBlockOffset > 0) + { + input[..available].CopyTo(currentBlock.AsSpan(currentBlockOffset)); + pos = available; + ProcessBlock(currentBlock); + } + + int remaining; + while ((remaining = input.Length - pos) >= BlockSize) { - currentBlock[currentBlockOffset] = 1; - for (int i = currentBlockOffset + 1; i < BlockSize; i++) +#if UNITY_ANDROID && !UNITY_EDITOR + uint t0 = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(input[pos..]); + uint t1 = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(input[(pos + 4)..]); + uint t2 = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(input[(pos + 8)..]); + uint t3 = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(input[(pos + 12)..]); +#else + uint t0 = 0; + uint t1 = 0; + uint t2 = 0; + uint t3 = 0; + + fixed (byte* pblock = &input[pos]) { - currentBlock[i] = 0; + uint* publock = (uint*)pblock; + t0 = publock[0]; + t1 = publock[1]; + t2 = publock[2]; + t3 = publock[3]; } +#endif + + h0 += t0 & 0x3ffffffU; + h1 += ((t1 << 6) | (t0 >> 26)) & 0x3ffffffU; + h2 += ((t2 << 12) | (t1 >> 20)) & 0x3ffffffU; + h3 += ((t3 << 18) | (t2 >> 14)) & 0x3ffffffU; + h4 += (1 << 24) | (t3 >> 8); + + ulong tp0 = (ulong)h0 * r0 + (ulong)h1 * s4 + (ulong)h2 * s3 + (ulong)h3 * s2 + (ulong)h4 * s1; + ulong tp1 = (ulong)h0 * r1 + (ulong)h1 * r0 + (ulong)h2 * s4 + (ulong)h3 * s3 + (ulong)h4 * s2; + ulong tp2 = (ulong)h0 * r2 + (ulong)h1 * r1 + (ulong)h2 * r0 + (ulong)h3 * s4 + (ulong)h4 * s3; + ulong tp3 = (ulong)h0 * r3 + (ulong)h1 * r2 + (ulong)h2 * r1 + (ulong)h3 * r0 + (ulong)h4 * s4; + ulong tp4 = (ulong)h0 * r4 + (ulong)h1 * r3 + (ulong)h2 * r2 + (ulong)h3 * r1 + (ulong)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; + + pos += BlockSize; } - 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); + input[pos..].CopyTo(currentBlock); + currentBlockOffset = remaining; + } +#endif - 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 NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ProcessBlock(ReadOnlySpan block) + { + uint t0 = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(block); + uint t1 = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(block[4..]); + uint t2 = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(block[8..]); + uint t3 = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(block[12..]); +#else + private void ProcessBlock(byte[] buf, int off) + { + uint t0 = Pack.LE_To_UInt32(buf, off + 0); + uint t1 = Pack.LE_To_UInt32(buf, off + 4); + uint t2 = Pack.LE_To_UInt32(buf, off + 8); + uint t3 = Pack.LE_To_UInt32(buf, off + 12); +#endif - if (currentBlockOffset == BlockSize) - { - h4 += (1 << 24); - } + h0 += t0 & 0x3ffffffU; + h1 += ((t1 << 6) | (t0 >> 26)) & 0x3ffffffU; + h2 += ((t2 << 12) | (t1 >> 20)) & 0x3ffffffU; + h3 += ((t3 << 18) | (t2 >> 14)) & 0x3ffffffU; + h4 += (1 << 24) | (t3 >> 8); - 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); + ulong tp0 = (ulong)h0 * r0 + (ulong)h1 * s4 + (ulong)h2 * s3 + (ulong)h3 * s2 + (ulong)h4 * s1; + ulong tp1 = (ulong)h0 * r1 + (ulong)h1 * r0 + (ulong)h2 * s4 + (ulong)h3 * s3 + (ulong)h4 * s2; + ulong tp2 = (ulong)h0 * r2 + (ulong)h1 * r1 + (ulong)h2 * r0 + (ulong)h3 * s4 + (ulong)h4 * s3; + ulong tp3 = (ulong)h0 * r3 + (ulong)h1 * r2 + (ulong)h2 * r1 + (ulong)h3 * r0 + (ulong)h4 * s4; + ulong tp4 = (ulong)h0 * r4 + (ulong)h1 * r3 + (ulong)h2 * r2 + (ulong)h3 * r1 + (ulong)h4 * r0; h0 = (uint)tp0 & 0x3ffffff; tp1 += (tp0 >> 26); h1 = (uint)tp1 & 0x3ffffff; tp2 += (tp1 >> 26); @@ -230,69 +328,109 @@ private void ProcessBlock() h3 = (uint)tp3 & 0x3ffffff; tp4 += (tp3 >> 26); h4 = (uint)tp4 & 0x3ffffff; h0 += (uint)(tp4 >> 26) * 5; - h1 += (h0 >> 26); h0 &= 0x3ffffff; + h1 += h0 >> 26; h0 &= 0x3ffffff; } public int DoFinal(byte[] output, int outOff) { - Check.DataLength(output, outOff, BlockSize, "Output buffer is too short."); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(output.AsSpan(outOff)); +#else + Check.OutputLength(output, outOff, BlockSize, "output buffer is too short."); if (currentBlockOffset > 0) { // Process padded block - ProcessBlock(); + if (currentBlockOffset < BlockSize) + { + currentBlock[currentBlockOffset++] = 1; + while (currentBlockOffset < BlockSize) + { + currentBlock[currentBlockOffset++] = 0; + } + + h4 -= (1 << 24); + } + + ProcessBlock(currentBlock, 0); } - 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); + UnityEngine.Debug.Assert(h4 >> 26 == 0); + + //h0 += (h4 >> 26) * 5U + 5U; h4 &= 0x3ffffff; + h0 += 5U; + h1 += h0 >> 26; h0 &= 0x3ffffff; + h2 += h1 >> 26; h1 &= 0x3ffffff; + h3 += h2 >> 26; h2 &= 0x3ffffff; + h4 += h3 >> 26; h3 &= 0x3ffffff; + + long c = ((int)(h4 >> 26) - 1) * 5; + c += (long)k0 + ((h0) | (h1 << 26)); + Pack.UInt32_To_LE((uint)c, output, outOff); c >>= 32; + c += (long)k1 + ((h1 >> 6) | (h2 << 20)); + Pack.UInt32_To_LE((uint)c, output, outOff + 4); c >>= 32; + c += (long)k2 + ((h2 >> 12) | (h3 << 14)); + Pack.UInt32_To_LE((uint)c, output, outOff + 8); c >>= 32; + c += (long)k3 + ((h3 >> 18) | (h4 << 8)); + Pack.UInt32_To_LE((uint)c, output, outOff + 12); Reset(); return BlockSize; +#endif } - public void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) { - currentBlockOffset = 0; + Check.OutputLength(output, BlockSize, "output buffer is too short."); - h0 = h1 = h2 = h3 = h4 = 0; + if (currentBlockOffset > 0) + { + // Process padded block + if (currentBlockOffset < BlockSize) + { + currentBlock[currentBlockOffset++] = 1; + while (currentBlockOffset < BlockSize) + { + currentBlock[currentBlockOffset++] = 0; + } + + h4 -= (1 << 24); + } + + ProcessBlock(currentBlock); + } + + UnityEngine.Debug.Assert(h4 >> 26 == 0); + + //h0 += (h4 >> 26) * 5U + 5U; h4 &= 0x3ffffff; + h0 += 5U; + h1 += h0 >> 26; h0 &= 0x3ffffff; + h2 += h1 >> 26; h1 &= 0x3ffffff; + h3 += h2 >> 26; h2 &= 0x3ffffff; + h4 += h3 >> 26; h3 &= 0x3ffffff; + + long c = ((int)(h4 >> 26) - 1) * 5; + c += (long)k0 + ((h0) | (h1 << 26)); + Pack.UInt32_To_LE((uint)c, output); c >>= 32; + c += (long)k1 + ((h1 >> 6) | (h2 << 20)); + Pack.UInt32_To_LE((uint)c, output[4..]); c >>= 32; + c += (long)k2 + ((h2 >> 12) | (h3 << 14)); + Pack.UInt32_To_LE((uint)c, output[8..]); c >>= 32; + c += (long)k3 + ((h3 >> 18) | (h4 << 8)); + Pack.UInt32_To_LE((uint)c, output[12..]); + + Reset(); + return BlockSize; } +#endif - private static ulong mul32x32_64(uint i1, uint i2) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Reset() { - return ((ulong)i1) * i2; + currentBlockOffset = 0; + + h0 = h1 = h2 = h3 = h4 = 0; } } } diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastSalsa20Engine.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastSalsa20Engine.cs index b13b459..09f1c52 100644 --- a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastSalsa20Engine.cs +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastSalsa20Engine.cs @@ -1,7 +1,15 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Text; +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +#endif +#if NETCOREAPP3_0_OR_GREATER +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; @@ -13,9 +21,9 @@ namespace BestHTTP.Connections.TLS.Crypto.Impl /// /// Implementation of Daniel J. Bernstein's Salsa20 stream cipher, Snuffle 2005 /// - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] + + + [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] public class FastSalsa20Engine : IStreamCipher @@ -36,22 +44,17 @@ internal void PackTauOrSigma(int keyLength, uint[] state, int stateOffset) state[stateOffset + 3] = TAU_SIGMA[tsOff + 3]; } - [Obsolete] - protected readonly static byte[] - sigma = Strings.ToAsciiByteArray("expand 32-byte k"), - tau = Strings.ToAsciiByteArray("expand 16-byte k"); - protected int rounds; /* * variables to hold the state of the engine * during encryption and decryption */ - private int index = 0; + internal int index = 0; internal uint[] engineState = new uint[StateSize]; // state internal uint[] x = new uint[StateSize]; // internal buffer - private byte[] keyStream = new byte[StateSize * 4]; // expanded state, 64 bytes - private bool initialised = false; + internal byte[] keyStream = new byte[StateSize * 4]; // expanded state, 64 bytes + internal bool initialised = false; /* * internal counter @@ -90,7 +93,7 @@ public virtual void Init( * irrelevant. (Like 90% of stream ciphers) */ - FastParametersWithIV ivParams = parameters as FastParametersWithIV; + ParametersWithIV ivParams = parameters as ParametersWithIV; if (ivParams == null) throw new ArgumentException(AlgorithmName + " Init requires an IV", "parameters"); @@ -106,9 +109,9 @@ public virtual void Init( SetKey(null, iv); } - else if (keyParam is NoCopyKeyParameter) + else if (keyParam is KeyParameter) { - SetKey(((NoCopyKeyParameter)keyParam).GetKey(), iv); + SetKey(((KeyParameter)keyParam).GetKey(), iv); } else { @@ -165,7 +168,7 @@ protected virtual void AdvanceCounter() } } - public virtual void ProcessBytes( + public unsafe virtual void ProcessBytes( byte[] inBytes, int inOff, int len, @@ -187,12 +190,78 @@ public virtual void ProcessBytes( { GenerateKeyStream(keyStream); AdvanceCounter(); + + if (len - i >= 64) + { + fixed (byte* pbout = outBytes) + fixed (byte* pbin = inBytes) + fixed (byte* pbkey = keyStream) + { +#if BESTHTTP_WITH_BURST + FastSalsa20EngineHelper.ProcessBytes(pbout, outOff, pbin, inOff, pbkey); +#else + ulong* pulOut = (ulong*)&pbout[outOff]; + ulong* pulIn = (ulong*)&pbin[inOff]; + ulong* pulKeyStream = (ulong*)pbkey; + + pulOut[0] = pulKeyStream[0] ^ pulIn[0]; + pulOut[1] = pulKeyStream[1] ^ pulIn[1]; + pulOut[2] = pulKeyStream[2] ^ pulIn[2]; + pulOut[3] = pulKeyStream[3] ^ pulIn[3]; +#endif + } + + i += 63; + index = 0; + continue; + } } outBytes[i + outOff] = (byte)(keyStream[index] ^ inBytes[i + inOff]); index = (index + 1) & 63; } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void ProcessBytes(ReadOnlySpan input, Span output) + { + if (!initialised) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + + Check.OutputLength(output, input.Length, "output buffer too short"); + + if (LimitExceeded((uint)input.Length)) + throw new MaxBytesExceededException("2^70 byte limit per IV would be exceeded; Change IV"); + + for (int i = 0; i < input.Length; i++) + { + if (index == 0) + { + GenerateKeyStream(keyStream); + AdvanceCounter(); + + if (input.Length - i >= 64) + { + Span lOutput = MemoryMarshal.Cast(output.Slice(i)); + ReadOnlySpan lKeyStream = MemoryMarshal.Cast(keyStream); + ReadOnlySpan lInput = MemoryMarshal.Cast(input.Slice(i)); + + lOutput[0] = lKeyStream[0] ^ lInput[0]; + lOutput[1] = lKeyStream[1] ^ lInput[1]; + lOutput[2] = lKeyStream[2] ^ lInput[2]; + lOutput[3] = lKeyStream[3] ^ lInput[3]; + + i += 63; + index = 0; + continue; + } + } + + output[i] = (byte)(keyStream[index++] ^ input[i]); + index &= 63; + } + } +#endif + public virtual void Reset() { index = 0; @@ -233,11 +302,133 @@ protected virtual void GenerateKeyStream(byte[] output) Pack.UInt32_To_LE(x, output, 0); } - internal static void SalsaCore(int rounds, uint[] input, uint[] x) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal static void SalsaCore(int rounds, ReadOnlySpan input, Span output) + { + if (input.Length < 16) + throw new ArgumentException(); + if (output.Length < 16) + throw new ArgumentException(); + if (rounds % 2 != 0) + throw new ArgumentException("Number of rounds must be even"); + +#if NETCOREAPP3_0_OR_GREATER + if (Sse41.IsSupported && BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 16) + { + Vector128 b0, b1, b2, b3; + { + var I = MemoryMarshal.AsBytes(input[..16]); + var t0 = MemoryMarshal.Read>(I[0x00..0x10]); + var t1 = MemoryMarshal.Read>(I[0x10..0x20]); + var t2 = MemoryMarshal.Read>(I[0x20..0x30]); + var t3 = MemoryMarshal.Read>(I[0x30..0x40]); + + var u0 = Sse41.Blend(t0, t2, 0xF0); + var u1 = Sse41.Blend(t1, t3, 0xC3); + var u2 = Sse41.Blend(t0, t2, 0x0F); + var u3 = Sse41.Blend(t1, t3, 0x3C); + + b0 = Sse41.Blend(u0, u1, 0xCC).AsUInt32(); + b1 = Sse41.Blend(u0, u1, 0x33).AsUInt32(); + b2 = Sse41.Blend(u2, u3, 0xCC).AsUInt32(); + b3 = Sse41.Blend(u2, u3, 0x33).AsUInt32(); + } + + var c0 = b0; + var c1 = b1; + var c2 = b2; + var c3 = b3; + + for (int i = rounds; i > 0; i -= 2) + { + QuarterRound_Sse2(ref c0, ref c3, ref c2, ref c1); + QuarterRound_Sse2(ref c0, ref c1, ref c2, ref c3); + } + + b0 = Sse2.Add(b0, c0); + b1 = Sse2.Add(b1, c1); + b2 = Sse2.Add(b2, c2); + b3 = Sse2.Add(b3, c3); + + { + var t0 = b0.AsUInt16(); + var t1 = b1.AsUInt16(); + var t2 = b2.AsUInt16(); + var t3 = b3.AsUInt16(); + + var u0 = Sse41.Blend(t0, t1, 0xCC); + var u1 = Sse41.Blend(t0, t1, 0x33); + var u2 = Sse41.Blend(t2, t3, 0xCC); + var u3 = Sse41.Blend(t2, t3, 0x33); + + var v0 = Sse41.Blend(u0, u2, 0xF0); + var v1 = Sse41.Blend(u1, u3, 0xC3); + var v2 = Sse41.Blend(u0, u2, 0x0F); + var v3 = Sse41.Blend(u1, u3, 0x3C); + + var X = MemoryMarshal.AsBytes(output[..16]); + MemoryMarshal.Write(X[0x00..0x10], ref v0); + MemoryMarshal.Write(X[0x10..0x20], ref v1); + MemoryMarshal.Write(X[0x20..0x30], ref v2); + MemoryMarshal.Write(X[0x30..0x40], ref v3); + } + return; + } +#endif + + uint x00 = input[ 0]; + uint x01 = input[ 1]; + uint x02 = input[ 2]; + uint x03 = input[ 3]; + uint x04 = input[ 4]; + uint x05 = input[ 5]; + uint x06 = input[ 6]; + uint x07 = input[ 7]; + uint x08 = input[ 8]; + uint x09 = input[ 9]; + uint x10 = input[10]; + uint x11 = input[11]; + uint x12 = input[12]; + uint x13 = input[13]; + uint x14 = input[14]; + uint x15 = input[15]; + + for (int i = rounds; i > 0; i -= 2) { - if (input.Length != 16) + QuarterRound(ref x00, ref x04, ref x08, ref x12); + QuarterRound(ref x05, ref x09, ref x13, ref x01); + QuarterRound(ref x10, ref x14, ref x02, ref x06); + QuarterRound(ref x15, ref x03, ref x07, ref x11); + + QuarterRound(ref x00, ref x01, ref x02, ref x03); + QuarterRound(ref x05, ref x06, ref x07, ref x04); + QuarterRound(ref x10, ref x11, ref x08, ref x09); + QuarterRound(ref x15, ref x12, ref x13, ref x14); + } + + output[ 0] = x00 + input[ 0]; + output[ 1] = x01 + input[ 1]; + output[ 2] = x02 + input[ 2]; + output[ 3] = x03 + input[ 3]; + output[ 4] = x04 + input[ 4]; + output[ 5] = x05 + input[ 5]; + output[ 6] = x06 + input[ 6]; + output[ 7] = x07 + input[ 7]; + output[ 8] = x08 + input[ 8]; + output[ 9] = x09 + input[ 9]; + output[10] = x10 + input[10]; + output[11] = x11 + input[11]; + output[12] = x12 + input[12]; + output[13] = x13 + input[13]; + output[14] = x14 + input[14]; + output[15] = x15 + input[15]; + } +#else + internal static void SalsaCore(int rounds, uint[] input, uint[] output) + { + if (input.Length < 16) throw new ArgumentException(); - if (x.Length != 16) + if (output.Length < 16) throw new ArgumentException(); if (rounds % 2 != 0) throw new ArgumentException("Number of rounds must be even"); @@ -261,67 +452,44 @@ internal static void SalsaCore(int rounds, uint[] input, uint[] x) for (int i = rounds; i > 0; i -= 2) { - x04 ^= Integers.RotateLeft((x00 + x12), 7); - x08 ^= Integers.RotateLeft((x04 + x00), 9); - x12 ^= Integers.RotateLeft((x08 + x04), 13); - x00 ^= Integers.RotateLeft((x12 + x08), 18); - x09 ^= Integers.RotateLeft((x05 + x01), 7); - x13 ^= Integers.RotateLeft((x09 + x05), 9); - x01 ^= Integers.RotateLeft((x13 + x09), 13); - x05 ^= Integers.RotateLeft((x01 + x13), 18); - x14 ^= Integers.RotateLeft((x10 + x06), 7); - x02 ^= Integers.RotateLeft((x14 + x10), 9); - x06 ^= Integers.RotateLeft((x02 + x14), 13); - x10 ^= Integers.RotateLeft((x06 + x02), 18); - x03 ^= Integers.RotateLeft((x15 + x11), 7); - x07 ^= Integers.RotateLeft((x03 + x15), 9); - x11 ^= Integers.RotateLeft((x07 + x03), 13); - x15 ^= Integers.RotateLeft((x11 + x07), 18); - - x01 ^= Integers.RotateLeft((x00 + x03), 7); - x02 ^= Integers.RotateLeft((x01 + x00), 9); - x03 ^= Integers.RotateLeft((x02 + x01), 13); - x00 ^= Integers.RotateLeft((x03 + x02), 18); - x06 ^= Integers.RotateLeft((x05 + x04), 7); - x07 ^= Integers.RotateLeft((x06 + x05), 9); - x04 ^= Integers.RotateLeft((x07 + x06), 13); - x05 ^= Integers.RotateLeft((x04 + x07), 18); - x11 ^= Integers.RotateLeft((x10 + x09), 7); - x08 ^= Integers.RotateLeft((x11 + x10), 9); - x09 ^= Integers.RotateLeft((x08 + x11), 13); - x10 ^= Integers.RotateLeft((x09 + x08), 18); - x12 ^= Integers.RotateLeft((x15 + x14), 7); - x13 ^= Integers.RotateLeft((x12 + x15), 9); - x14 ^= Integers.RotateLeft((x13 + x12), 13); - x15 ^= Integers.RotateLeft((x14 + x13), 18); - } - - x[0] = x00 + input[0]; - x[1] = x01 + input[1]; - x[2] = x02 + input[2]; - x[3] = x03 + input[3]; - x[4] = x04 + input[4]; - x[5] = x05 + input[5]; - x[6] = x06 + input[6]; - x[7] = x07 + input[7]; - x[8] = x08 + input[8]; - x[9] = x09 + input[9]; - x[10] = x10 + input[10]; - x[11] = x11 + input[11]; - x[12] = x12 + input[12]; - x[13] = x13 + input[13]; - x[14] = x14 + input[14]; - x[15] = x15 + input[15]; + QuarterRound(ref x00, ref x04, ref x08, ref x12); + QuarterRound(ref x05, ref x09, ref x13, ref x01); + QuarterRound(ref x10, ref x14, ref x02, ref x06); + QuarterRound(ref x15, ref x03, ref x07, ref x11); + + QuarterRound(ref x00, ref x01, ref x02, ref x03); + QuarterRound(ref x05, ref x06, ref x07, ref x04); + QuarterRound(ref x10, ref x11, ref x08, ref x09); + QuarterRound(ref x15, ref x12, ref x13, ref x14); + } + + output[ 0] = x00 + input[ 0]; + output[ 1] = x01 + input[ 1]; + output[ 2] = x02 + input[ 2]; + output[ 3] = x03 + input[ 3]; + output[ 4] = x04 + input[ 4]; + output[ 5] = x05 + input[ 5]; + output[ 6] = x06 + input[ 6]; + output[ 7] = x07 + input[ 7]; + output[ 8] = x08 + input[ 8]; + output[ 9] = x09 + input[ 9]; + output[10] = x10 + input[10]; + output[11] = x11 + input[11]; + output[12] = x12 + input[12]; + output[13] = x13 + input[13]; + output[14] = x14 + input[14]; + output[15] = x15 + input[15]; } +#endif - private void ResetLimitCounter() + internal void ResetLimitCounter() { cW0 = 0; cW1 = 0; cW2 = 0; } - private bool LimitExceeded() + internal bool LimitExceeded() { if (++cW0 == 0) { @@ -337,7 +505,7 @@ private bool LimitExceeded() /* * this relies on the fact len will always be positive. */ - private bool LimitExceeded( + internal bool LimitExceeded( uint len) { uint old = cW0; @@ -352,6 +520,40 @@ private bool LimitExceeded( return false; } + +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif + private static void QuarterRound(ref uint a, ref uint b, ref uint c, ref uint d) + { + b ^= Integers.RotateLeft(a + d, 7); + c ^= Integers.RotateLeft(b + a, 9); + d ^= Integers.RotateLeft(c + b, 13); + a ^= Integers.RotateLeft(d + c, 18); + } + +#if NETCOREAPP3_0_OR_GREATER + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void QuarterRound_Sse2(ref Vector128 a, ref Vector128 b, ref Vector128 c, + ref Vector128 d) + { + b = Sse2.Xor(b, Rotate_Sse2(Sse2.Add(a, d), 7)); + c = Sse2.Xor(c, Rotate_Sse2(Sse2.Add(b, a), 9)); + d = Sse2.Xor(d, Rotate_Sse2(Sse2.Add(c, b), 13)); + a = Sse2.Xor(a, Rotate_Sse2(Sse2.Add(d, c), 18)); + + b = Sse2.Shuffle(b, 0x93); + c = Sse2.Shuffle(c, 0x4E); + d = Sse2.Shuffle(d, 0x39); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector128 Rotate_Sse2(Vector128 x, byte sl) + { + byte sr = (byte)(32 - sl); + return Sse2.Xor(Sse2.ShiftLeftLogical(x, sl), Sse2.ShiftRightLogical(x, sr)); + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastSalsa20EngineHelper.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastSalsa20EngineHelper.cs new file mode 100644 index 0000000..8747efe --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastSalsa20EngineHelper.cs @@ -0,0 +1,31 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +using System; + +namespace BestHTTP.Connections.TLS.Crypto.Impl +{ +#if BESTHTTP_WITH_BURST + [Unity.Burst.BurstCompile] +#endif + internal static class FastSalsa20EngineHelper + { +#if BESTHTTP_WITH_BURST + [Unity.Burst.BurstCompile] + public unsafe static void ProcessBytes([Unity.Burst.NoAlias] byte* outBytes, int outOff, [Unity.Burst.NoAlias] byte* inBytes, int inOff, [Unity.Burst.NoAlias] byte* keyStream) + { + //for (int i = 0; i < 64; ++i) + // outBytes[idx + i + outOff] = (byte)(keyStream[i] ^ inBytes[idx + i + inOff]); + + ulong* pulOut = (ulong*)&outBytes[outOff]; + ulong* pulIn = (ulong*)&inBytes[inOff]; + ulong* pulKeyStream = (ulong*)keyStream; + + pulOut[0] = pulKeyStream[0] ^ pulIn[0]; + pulOut[1] = pulKeyStream[1] ^ pulIn[1]; + pulOut[2] = pulKeyStream[2] ^ pulIn[2]; + pulOut[3] = pulKeyStream[3] ^ pulIn[3]; + } +#endif + + } +} +#endif diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastSalsa20EngineHelper.cs.meta b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastSalsa20EngineHelper.cs.meta new file mode 100644 index 0000000..48a1586 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastSalsa20EngineHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 07c49c8cf55d75e4fa1d12af126757d3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastSicBlockCipher.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastSicBlockCipher.cs new file mode 100644 index 0000000..9392693 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastSicBlockCipher.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; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; + +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; + +namespace BestHTTP.Connections.TLS.Crypto.Impl +{ + /** + * Implements the Segmented Integer Counter (SIC) mode on top of a simple + * block cipher. + */ + public class FastSicBlockCipher + : IBlockCipherMode + { + 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 FastSicBlockCipher(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 IBlockCipher UnderlyingCipher => 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; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) + { + 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[i] = (byte)(counterOut[i] ^ input[i]); + } + + // Increment the counter + int j = counter.Length; + while (--j >= 0 && ++counter[j] == 0) + { + } + + return counter.Length; + } +#endif + + public virtual void Reset() + { + Arrays.Fill(counter, (byte)0); + Array.Copy(IV, 0, counter, 0, IV.Length); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastSicBlockCipher.cs.meta b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastSicBlockCipher.cs.meta new file mode 100644 index 0000000..938eb60 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastSicBlockCipher.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f774e66db9dd3d54ba629d80531016f2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastTlsAeadCipher.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastTlsAeadCipher.cs index 676e57e..bef2c3a 100644 --- a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastTlsAeadCipher.cs +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastTlsAeadCipher.cs @@ -1,17 +1,19 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable using System; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto.Impl; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls; +using BestHTTP.PlatformSupport.Memory; namespace BestHTTP.Connections.TLS.Crypto.Impl { /// A generic TLS 1.2 AEAD cipher. - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] + + + [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] public sealed class FastTlsAeadCipher : TlsCipher @@ -81,6 +83,33 @@ public FastTlsAeadCipher(TlsCryptoParameters cryptoParams, TlsAeadCipherImpl enc } int keyBlockSize = (2 * keySize) + (2 * m_fixed_iv_length); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span keyBlock = keyBlockSize <= 512 + ? stackalloc byte[keyBlockSize] + : new byte[keyBlockSize]; + TlsImplUtilities.CalculateKeyBlock(cryptoParams, keyBlock); + + if (isServer) + { + decryptCipher.SetKey(keyBlock[..keySize]); keyBlock = keyBlock[keySize..]; + encryptCipher.SetKey(keyBlock[..keySize]); keyBlock = keyBlock[keySize..]; + + keyBlock[..m_fixed_iv_length].CopyTo(m_decryptNonce); keyBlock = keyBlock[m_fixed_iv_length..]; + keyBlock[..m_fixed_iv_length].CopyTo(m_encryptNonce); keyBlock = keyBlock[m_fixed_iv_length..]; + } + else + { + encryptCipher.SetKey(keyBlock[..keySize]); keyBlock = keyBlock[keySize..]; + decryptCipher.SetKey(keyBlock[..keySize]); keyBlock = keyBlock[keySize..]; + + keyBlock[..m_fixed_iv_length].CopyTo(m_encryptNonce); keyBlock = keyBlock[m_fixed_iv_length..]; + keyBlock[..m_fixed_iv_length].CopyTo(m_decryptNonce); keyBlock = keyBlock[m_fixed_iv_length..]; + } + + if (!keyBlock.IsEmpty) + throw new TlsFatalAlert(AlertDescription.internal_error); +#else byte[] keyBlock = TlsImplUtilities.CalculateKeyBlock(cryptoParams, keyBlockSize); int pos = 0; @@ -101,8 +130,9 @@ public FastTlsAeadCipher(TlsCryptoParameters cryptoParams, TlsAeadCipherImpl enc Array.Copy(keyBlock, pos, m_decryptNonce, 0, m_fixed_iv_length); pos += m_fixed_iv_length; } - if (keyBlockSize != pos) + if (pos != keyBlockSize) throw new TlsFatalAlert(AlertDescription.internal_error); +#endif int nonceLength = m_fixed_iv_length + m_record_iv_length; @@ -142,6 +172,10 @@ public int GetPlaintextLimit(int ciphertextLimit) public TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVersion recordVersion, int headerAllocation, byte[] plaintext, int plaintextOffset, int plaintextLength) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return EncodePlaintext(seqNo, contentType, recordVersion, headerAllocation, + plaintext.AsSpan(plaintextOffset, plaintextLength)); +#else byte[] nonce = new byte[m_encryptNonce.Length + m_record_iv_length]; switch (m_nonceMode) @@ -168,7 +202,7 @@ public TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVe int encryptionLength = m_encryptCipher.GetOutputSize(plaintextLength + extraLength); int ciphertextLength = m_record_iv_length + encryptionLength; - byte[] output = new byte[headerAllocation + ciphertextLength]; + byte[] output = BufferPool.Get(headerAllocation + ciphertextLength, true); //new byte[headerAllocation + ciphertextLength]; int outputPos = headerAllocation; if (m_record_iv_length != 0) @@ -184,14 +218,13 @@ public TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVe try { - m_encryptCipher.Init(nonce, m_macSize, additionalData); - Array.Copy(plaintext, plaintextOffset, output, outputPos, plaintextLength); if (m_isTlsV13) { output[outputPos + plaintextLength] = (byte)contentType; } + m_encryptCipher.Init(nonce, m_macSize, additionalData); outputPos += m_encryptCipher.DoFinal(output, outputPos, plaintextLength + extraLength, output, outputPos); } @@ -204,6 +237,81 @@ public TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVe throw new TlsFatalAlert(AlertDescription.internal_error, e); } + if (outputPos != headerAllocation + ciphertextLength) + { + // NOTE: The additional data mechanism for AEAD ciphers requires exact output size prediction. + throw new TlsFatalAlert(AlertDescription.internal_error); + } + + return new TlsEncodeResult(output, 0, outputPos, recordType, true); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVersion recordVersion, + int headerAllocation, ReadOnlySpan plaintext) + { + byte[] nonce = new byte[m_encryptNonce.Length + m_record_iv_length]; + + switch (m_nonceMode) + { + case NONCE_RFC5288: + Array.Copy(m_encryptNonce, 0, nonce, 0, m_encryptNonce.Length); + // RFC 5288/6655: The nonce_explicit MAY be the 64-bit sequence number. + TlsUtilities.WriteUint64(seqNo, nonce, m_encryptNonce.Length); + break; + case NONCE_RFC7905: + TlsUtilities.WriteUint64(seqNo, nonce, nonce.Length - 8); + for (int i = 0; i < m_encryptNonce.Length; ++i) + { + nonce[i] ^= m_encryptNonce[i]; + } + break; + default: + throw new TlsFatalAlert(AlertDescription.internal_error); + } + + int extraLength = m_isTlsV13 ? 1 : 0; + + // TODO[tls13] If we support adding padding to TLSInnerPlaintext, this will need review + int encryptionLength = m_encryptCipher.GetOutputSize(plaintext.Length + extraLength); + int ciphertextLength = m_record_iv_length + encryptionLength; + + byte[] output = new byte[headerAllocation + ciphertextLength]; + int outputPos = headerAllocation; + + if (m_record_iv_length != 0) + { + Array.Copy(nonce, nonce.Length - m_record_iv_length, output, outputPos, m_record_iv_length); + outputPos += m_record_iv_length; + } + + short recordType = m_isTlsV13 ? ContentType.application_data : contentType; + + byte[] additionalData = GetAdditionalData(seqNo, recordType, recordVersion, ciphertextLength, + plaintext.Length); + + try + { + plaintext.CopyTo(output.AsSpan(outputPos)); + if (m_isTlsV13) + { + output[outputPos + plaintext.Length] = (byte)contentType; + } + + m_encryptCipher.Init(nonce, m_macSize, additionalData); + outputPos += m_encryptCipher.DoFinal(output, outputPos, plaintext.Length + extraLength, output, + outputPos); + } + catch (IOException e) + { + throw e; + } + catch (Exception e) + { + throw new TlsFatalAlert(AlertDescription.internal_error, e); + } + if (outputPos != output.Length) { // NOTE: The additional data mechanism for AEAD ciphers requires exact output size prediction. @@ -212,31 +320,28 @@ public TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVe return new TlsEncodeResult(output, 0, output.Length, recordType); } +#endif - byte[] decode_nonce = null; public TlsDecodeResult DecodeCiphertext(long seqNo, short recordType, ProtocolVersion recordVersion, byte[] ciphertext, int ciphertextOffset, int ciphertextLength) { if (GetPlaintextLimit(ciphertextLength) < 0) throw new TlsFatalAlert(AlertDescription.decode_error); - if (decode_nonce == null || decode_nonce.Length != m_decryptNonce.Length + m_record_iv_length) - decode_nonce = new byte[m_decryptNonce.Length + m_record_iv_length]; - else - Array.Clear(decode_nonce, 0, decode_nonce.Length); + byte[] nonce = new byte[m_decryptNonce.Length + m_record_iv_length]; switch (m_nonceMode) { case NONCE_RFC5288: - Array.Copy(m_decryptNonce, 0, decode_nonce, 0, m_decryptNonce.Length); - Array.Copy(ciphertext, ciphertextOffset, decode_nonce, decode_nonce.Length - m_record_iv_length, + Array.Copy(m_decryptNonce, 0, nonce, 0, m_decryptNonce.Length); + Array.Copy(ciphertext, ciphertextOffset, nonce, nonce.Length - m_record_iv_length, m_record_iv_length); break; case NONCE_RFC7905: - TlsUtilities.WriteUint64(seqNo, decode_nonce, decode_nonce.Length - 8); + TlsUtilities.WriteUint64(seqNo, nonce, nonce.Length - 8); for (int i = 0; i < m_decryptNonce.Length; ++i) { - decode_nonce[i] ^= m_decryptNonce[i]; + nonce[i] ^= m_decryptNonce[i]; } break; default: @@ -253,7 +358,7 @@ public TlsDecodeResult DecodeCiphertext(long seqNo, short recordType, ProtocolVe int outputPos; try { - m_decryptCipher.Init(decode_nonce, m_macSize, additionalData); + m_decryptCipher.Init(nonce, m_macSize, additionalData); outputPos = m_decryptCipher.DoFinal(ciphertext, encryptionOffset, encryptionLength, ciphertext, encryptionOffset); } @@ -310,7 +415,6 @@ public bool UsesOpaqueRecordType get { return m_isTlsV13; } } - byte[] additional_data = null; private byte[] GetAdditionalData(long seqNo, short recordType, ProtocolVersion recordVersion, int ciphertextLength, int plaintextLength) { @@ -319,10 +423,7 @@ private byte[] GetAdditionalData(long seqNo, short recordType, ProtocolVersion r /* * TLSCiphertext.opaque_type || TLSCiphertext.legacy_record_version || TLSCiphertext.length */ - if (additional_data == null || additional_data.Length != 5) - additional_data = new byte[5]; - else - Array.Clear(additional_data, 0, additional_data.Length); + byte[] additional_data = new byte[5]; TlsUtilities.WriteUint8(recordType, additional_data, 0); TlsUtilities.WriteVersion(recordVersion, additional_data, 1); @@ -334,10 +435,7 @@ private byte[] GetAdditionalData(long seqNo, short recordType, ProtocolVersion r /* * seq_num + TLSCompressed.type + TLSCompressed.version + TLSCompressed.length */ - if (additional_data == null || additional_data.Length != 13) - additional_data = new byte[13]; - else - Array.Clear(additional_data, 0, additional_data.Length); + byte[] additional_data = new byte[13]; TlsUtilities.WriteUint64(seqNo, additional_data, 0); TlsUtilities.WriteUint8(recordType, additional_data, 8); @@ -397,4 +495,5 @@ private static int GetNonceMode(bool isTLSv13, int aeadType) } } } +#pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastTlsAeadCipherImpl.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastTlsAeadCipherImpl.cs index 96d7c3d..54c965f 100644 --- a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastTlsAeadCipherImpl.cs +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastTlsAeadCipherImpl.cs @@ -12,142 +12,142 @@ namespace BestHTTP.Connections.TLS.Crypto.Impl { - public sealed class NoCopyKeyParameter - : ICipherParameters - { - private readonly byte[] key; - - public NoCopyKeyParameter(byte[] key) - :this(key, 0, key.Length) - { - } - - public NoCopyKeyParameter( - 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 key;// (byte[])key.Clone(); - } - } - - public sealed class FastAeadParameters - : ICipherParameters - { - private readonly byte[] associatedText; - private readonly byte[] nonce; - private readonly NoCopyKeyParameter 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 FastAeadParameters(NoCopyKeyParameter 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 FastAeadParameters( - NoCopyKeyParameter key, - int macSize, - byte[] nonce, - byte[] associatedText) - { - this.key = key; - this.nonce = nonce; - this.macSize = macSize; - this.associatedText = associatedText; - } - - public NoCopyKeyParameter Key - { - get { return key; } - } - - public int MacSize - { - get { return macSize; } - } - - public byte[] GetAssociatedText() - { - return associatedText; - } - - public byte[] GetNonce() - { - return nonce; - } - } - - public sealed class FastParametersWithIV - : ICipherParameters - { - private readonly ICipherParameters parameters; - private readonly byte[] iv; - - public FastParametersWithIV(ICipherParameters parameters, - byte[] iv) - : this(parameters, iv, 0, iv.Length) - { - } - - public FastParametersWithIV(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 iv; // (byte[])iv.Clone(); - } - - public ICipherParameters Parameters - { - get { return parameters; } - } - } + //public sealed class NoCopyKeyParameter + // : ICipherParameters + //{ + // private readonly byte[] key; + // + // public NoCopyKeyParameter(byte[] key) + // :this(key, 0, key.Length) + // { + // } + // + // public NoCopyKeyParameter( + // 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 key;// (byte[])key.Clone(); + // } + //} + // + //public sealed class FastAeadParameters + // : ICipherParameters + //{ + // private readonly byte[] associatedText; + // private readonly byte[] nonce; + // private readonly NoCopyKeyParameter 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 FastAeadParameters(NoCopyKeyParameter 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 FastAeadParameters( + // NoCopyKeyParameter key, + // int macSize, + // byte[] nonce, + // byte[] associatedText) + // { + // this.key = key; + // this.nonce = nonce; + // this.macSize = macSize; + // this.associatedText = associatedText; + // } + // + // public NoCopyKeyParameter Key + // { + // get { return key; } + // } + // + // public int MacSize + // { + // get { return macSize; } + // } + // + // public byte[] GetAssociatedText() + // { + // return associatedText; + // } + // + // public byte[] GetNonce() + // { + // return nonce; + // } + //} + // + //public sealed class FastParametersWithIV + // : ICipherParameters + //{ + // private readonly ICipherParameters parameters; + // private readonly byte[] iv; + // + // public FastParametersWithIV(ICipherParameters parameters, + // byte[] iv) + // : this(parameters, iv, 0, iv.Length) + // { + // } + // + // public FastParametersWithIV(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 iv; // (byte[])iv.Clone(); + // } + // + // public ICipherParameters Parameters + // { + // get { return parameters; } + // } + //} internal sealed class FastTlsAeadCipherImpl : TlsAeadCipherImpl { private readonly bool m_isEncrypting; - private readonly IAeadBlockCipher m_cipher; + private readonly IAeadCipher m_cipher; - private NoCopyKeyParameter key; + private KeyParameter key; - internal FastTlsAeadCipherImpl(IAeadBlockCipher cipher, bool isEncrypting) + internal FastTlsAeadCipherImpl(IAeadCipher cipher, bool isEncrypting) { this.m_cipher = cipher; this.m_isEncrypting = isEncrypting; @@ -155,12 +155,19 @@ internal FastTlsAeadCipherImpl(IAeadBlockCipher cipher, bool isEncrypting) public void SetKey(byte[] key, int keyOff, int keyLen) { - this.key = new NoCopyKeyParameter(key, keyOff, keyLen); + this.key = new KeyParameter(key, keyOff, keyLen); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void SetKey(ReadOnlySpan key) + { + this.key = new KeyParameter(key); } +#endif public void Init(byte[] nonce, int macSize, byte[] additionalData) { - m_cipher.Init(m_isEncrypting, new FastAeadParameters(key, macSize * 8, nonce, additionalData)); + m_cipher.Init(m_isEncrypting, new AeadParameters(key, macSize * 8, nonce, additionalData)); } public int GetOutputSize(int inputLength) @@ -170,7 +177,11 @@ public int GetOutputSize(int inputLength) public int DoFinal(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int len = m_cipher.ProcessBytes(input.AsSpan(inputOffset, inputLength), Spans.FromNullable(output, outputOffset)); +#else int len = m_cipher.ProcessBytes(input, inputOffset, inputLength, output, outputOffset); +#endif try { @@ -183,6 +194,11 @@ public int DoFinal(byte[] input, int inputOffset, int inputLength, byte[] output return len; } + + public void Reset() + { + m_cipher.Reset(); + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastTlsBlockCipher.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastTlsBlockCipher.cs index b22aa9b..f86c281 100644 --- a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastTlsBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastTlsBlockCipher.cs @@ -70,27 +70,55 @@ public FastTlsBlockCipher(TlsCryptoParameters cryptoParams, TlsBlockCipherImpl e serverCipher = decryptCipher; } - int key_block_size = (2 * cipherKeySize) + clientMac.MacLength + serverMac.MacLength; + int keyBlockSize = (2 * cipherKeySize) + clientMac.MacLength + serverMac.MacLength; // From TLS 1.1 onwards, block ciphers don't need IVs from the key_block if (!m_useExplicitIV) { - key_block_size += clientCipher.GetBlockSize() + serverCipher.GetBlockSize(); + keyBlockSize += clientCipher.GetBlockSize() + serverCipher.GetBlockSize(); } - byte[] key_block = TlsImplUtilities.CalculateKeyBlock(cryptoParams, key_block_size); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span keyBlock = keyBlockSize <= 512 + ? stackalloc byte[keyBlockSize] + : new byte[keyBlockSize]; + TlsImplUtilities.CalculateKeyBlock(cryptoParams, keyBlock); - int offset = 0; + clientMac.SetKey(keyBlock[..clientMac.MacLength]); keyBlock = keyBlock[clientMac.MacLength..]; + serverMac.SetKey(keyBlock[..serverMac.MacLength]); keyBlock = keyBlock[serverMac.MacLength..]; - clientMac.SetKey(key_block, offset, clientMac.MacLength); - offset += clientMac.MacLength; - serverMac.SetKey(key_block, offset, serverMac.MacLength); - offset += serverMac.MacLength; + clientCipher.SetKey(keyBlock[..cipherKeySize]); keyBlock = keyBlock[cipherKeySize..]; + serverCipher.SetKey(keyBlock[..cipherKeySize]); keyBlock = keyBlock[cipherKeySize..]; - clientCipher.SetKey(key_block, offset, cipherKeySize); - offset += cipherKeySize; - serverCipher.SetKey(key_block, offset, cipherKeySize); - offset += cipherKeySize; + int clientIVLength = clientCipher.GetBlockSize(); + int serverIVLength = serverCipher.GetBlockSize(); + + if (m_useExplicitIV) + { + clientCipher.Init(clientIVLength <= 64 ? stackalloc byte[clientIVLength] : new byte[clientIVLength]); + serverCipher.Init(serverIVLength <= 64 ? stackalloc byte[serverIVLength] : new byte[serverIVLength]); + } + else + { + clientCipher.Init(keyBlock[..clientIVLength]); keyBlock = keyBlock[clientIVLength..]; + serverCipher.Init(keyBlock[..serverIVLength]); keyBlock = keyBlock[serverIVLength..]; + } + + if (!keyBlock.IsEmpty) + throw new TlsFatalAlert(AlertDescription.internal_error); +#else + byte[] keyBlock = TlsImplUtilities.CalculateKeyBlock(cryptoParams, keyBlockSize); + int pos = 0; + + clientMac.SetKey(keyBlock, pos, clientMac.MacLength); + pos += clientMac.MacLength; + serverMac.SetKey(keyBlock, pos, serverMac.MacLength); + pos += serverMac.MacLength; + + clientCipher.SetKey(keyBlock, pos, cipherKeySize); + pos += cipherKeySize; + serverCipher.SetKey(keyBlock, pos, cipherKeySize); + pos += cipherKeySize; int clientIVLength = clientCipher.GetBlockSize(); int serverIVLength = serverCipher.GetBlockSize(); @@ -102,14 +130,15 @@ public FastTlsBlockCipher(TlsCryptoParameters cryptoParams, TlsBlockCipherImpl e } else { - clientCipher.Init(key_block, offset, clientIVLength); - offset += clientIVLength; - serverCipher.Init(key_block, offset, serverIVLength); - offset += serverIVLength; + clientCipher.Init(keyBlock, pos, clientIVLength); + pos += clientIVLength; + serverCipher.Init(keyBlock, pos, serverIVLength); + pos += serverIVLength; } - if (offset != key_block_size) + if (pos != keyBlockSize) throw new TlsFatalAlert(AlertDescription.internal_error); +#endif if (cryptoParams.IsServer) { @@ -175,6 +204,9 @@ public virtual int GetPlaintextLimit(int ciphertextLimit) public virtual TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVersion recordVersion, int headerAllocation, byte[] plaintext, int offset, int len) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return EncodePlaintext(seqNo, contentType, recordVersion, headerAllocation, plaintext.AsSpan(offset, len)); +#else int blockSize = m_encryptCipher.GetBlockSize(); int macSize = m_writeMac.Size; @@ -240,8 +272,81 @@ public virtual TlsEncodeResult EncodePlaintext(long seqNo, short contentType, Pr throw new TlsFatalAlert(AlertDescription.internal_error); return new TlsEncodeResult(outBuf, 0, outBuf.Length, contentType); +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVersion recordVersion, + int headerAllocation, ReadOnlySpan plaintext) + { + int blockSize = m_encryptCipher.GetBlockSize(); + int macSize = m_writeMac.Size; + + int enc_input_length = plaintext.Length; + if (!m_encryptThenMac) + { + enc_input_length += macSize; + } + + int padding_length = blockSize - (enc_input_length % blockSize); + if (m_useExtraPadding) + { + // Add a random number of extra blocks worth of padding + int maxExtraPadBlocks = (256 - padding_length) / blockSize; + int actualExtraPadBlocks = ChooseExtraPadBlocks(maxExtraPadBlocks); + padding_length += actualExtraPadBlocks * blockSize; + } + + int totalSize = plaintext.Length + macSize + padding_length; + if (m_useExplicitIV) + { + totalSize += blockSize; + } + + byte[] outBuf = new byte[headerAllocation + totalSize]; + int outOff = headerAllocation; + + if (m_useExplicitIV) + { + // Technically the explicit IV will be the encryption of this nonce + byte[] explicitIV = m_cryptoParams.NonceGenerator.GenerateNonce(blockSize); + Array.Copy(explicitIV, 0, outBuf, outOff, blockSize); + outOff += blockSize; + } + + plaintext.CopyTo(outBuf.AsSpan(outOff)); + outOff += plaintext.Length; + + if (!m_encryptThenMac) + { + byte[] mac = m_writeMac.CalculateMac(seqNo, contentType, plaintext); + mac.CopyTo(outBuf.AsSpan(outOff)); + outOff += mac.Length; + } + + byte padByte = (byte)(padding_length - 1); + for (int i = 0; i < padding_length; ++i) + { + outBuf[outOff++] = padByte; + } + + m_encryptCipher.DoFinal(outBuf, headerAllocation, outOff - headerAllocation, outBuf, headerAllocation); + + if (m_encryptThenMac) + { + byte[] mac = m_writeMac.CalculateMac(seqNo, contentType, outBuf, headerAllocation, + outOff - headerAllocation); + Array.Copy(mac, 0, outBuf, outOff, mac.Length); + outOff += mac.Length; + } + + if (outOff != outBuf.Length) + throw new TlsFatalAlert(AlertDescription.internal_error); + + return new TlsEncodeResult(outBuf, 0, outBuf.Length, contentType); + } +#endif + public virtual TlsDecodeResult DecodeCiphertext(long seqNo, short recordType, ProtocolVersion recordVersion, byte[] ciphertext, int offset, int len) { diff --git a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastTlsBlockCipherImpl.cs b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastTlsBlockCipherImpl.cs index aea9053..baef363 100644 --- a/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastTlsBlockCipherImpl.cs +++ b/Assets/URS/Best HTTP/Source/Connections/TLS/Crypto/Impl/FastTlsBlockCipherImpl.cs @@ -14,7 +14,7 @@ internal sealed class FastTlsBlockCipherImpl private readonly bool m_isEncrypting; private readonly IBlockCipher m_cipher; - private NoCopyKeyParameter key; + private KeyParameter key; internal FastTlsBlockCipherImpl(IBlockCipher cipher, bool isEncrypting) { @@ -24,14 +24,28 @@ internal FastTlsBlockCipherImpl(IBlockCipher cipher, bool isEncrypting) public void SetKey(byte[] key, int keyOff, int keyLen) { - this.key = new NoCopyKeyParameter(key, keyOff, keyLen); + this.key = new KeyParameter(key, keyOff, keyLen); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void SetKey(ReadOnlySpan key) + { + this.key = new KeyParameter(key); + } +#endif + public void Init(byte[] iv, int ivOff, int ivLen) { - m_cipher.Init(m_isEncrypting, new FastParametersWithIV(key, iv, ivOff, ivLen)); + m_cipher.Init(m_isEncrypting, new ParametersWithIV(key, iv, ivOff, ivLen)); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Init(ReadOnlySpan iv) + { + m_cipher.Init(m_isEncrypting, new ParametersWithIV(key, iv)); + } +#endif + public int DoFinal(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) { int blockSize = m_cipher.GetBlockSize(); diff --git a/Assets/URS/Best HTTP/Source/Core/ConnectionEvents.cs b/Assets/URS/Best HTTP/Source/Core/ConnectionEvents.cs index d5e0a72..01da92c 100644 --- a/Assets/URS/Best HTTP/Source/Core/ConnectionEvents.cs +++ b/Assets/URS/Best HTTP/Source/Core/ConnectionEvents.cs @@ -131,7 +131,7 @@ internal static void ProcessQueue() if (connectionEvent.Source.LastProcessedUri == null) { - HTTPManager.Logger.Warning("ConnectionEventHelper", String.Format("Ignoring ConnectionEventInfo({0}) because its LastProcessedUri is null!", connectionEvent.ToString())); + HTTPManager.Logger.Information("ConnectionEventHelper", String.Format("Ignoring ConnectionEventInfo({0}) because its LastProcessedUri is null!", connectionEvent.ToString()), connectionEvent.Source.Context); return; } @@ -152,35 +152,43 @@ internal static void ProcessQueue() private static void HandleConnectionStateChange(ConnectionEventInfo @event) { - var connection = @event.Source; + try + { + var connection = @event.Source; + + switch (@event.State) + { + case HTTPConnectionStates.Recycle: + HostManager.GetHost(connection.LastProcessedUri.Host) + .GetHostDefinition(connection.ServerAddress) + .RecycleConnection(connection) + .TryToSendQueuedRequests(); - switch (@event.State) + break; + + case HTTPConnectionStates.WaitForProtocolShutdown: + HostManager.GetHost(connection.LastProcessedUri.Host) + .GetHostDefinition(connection.ServerAddress) + .RemoveConnection(connection, @event.State); + break; + + case HTTPConnectionStates.Closed: + case HTTPConnectionStates.ClosedResendRequest: + // in case of ClosedResendRequest + if (@event.Request != null) + RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(@event.Request, RequestEvents.Resend)); + + HostManager.GetHost(connection.LastProcessedUri.Host) + .GetHostDefinition(connection.ServerAddress) + .RemoveConnection(connection, @event.State) + .TryToSendQueuedRequests(); + break; + } + } + catch (Exception ex) { - case HTTPConnectionStates.Recycle: - HostManager.GetHost(connection.LastProcessedUri.Host) - .GetHostDefinition(connection.ServerAddress) - .RecycleConnection(connection) - .TryToSendQueuedRequests(); - - break; - - case HTTPConnectionStates.WaitForProtocolShutdown: - HostManager.GetHost(connection.LastProcessedUri.Host) - .GetHostDefinition(connection.ServerAddress) - .RemoveConnection(connection, @event.State); - break; - - case HTTPConnectionStates.Closed: - case HTTPConnectionStates.ClosedResendRequest: - // in case of ClosedResendRequest - if (@event.Request != null) - RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(@event.Request, RequestEvents.Resend)); - - HostManager.GetHost(connection.LastProcessedUri.Host) - .GetHostDefinition(connection.ServerAddress) - .RemoveConnection(connection, @event.State) - .TryToSendQueuedRequests(); - break; + HTTPManager.Logger.Exception("ConnectionEvents", $"HandleConnectionStateChange ({@event.State})", ex, @event.Source.Context); + UnityEngine.Debug.LogException(ex); } } } diff --git a/Assets/URS/Best HTTP/Source/Core/HostConnection.cs b/Assets/URS/Best HTTP/Source/Core/HostConnection.cs index 56769d0..31ca081 100644 --- a/Assets/URS/Best HTTP/Source/Core/HostConnection.cs +++ b/Assets/URS/Best HTTP/Source/Core/HostConnection.cs @@ -56,9 +56,10 @@ internal void AddProtocol(HostProtocolSupport protocolSupport) HTTPManager.Logger.Information(typeof(HostConnection).Name, string.Format("AddProtocol({0}) - changing from {1} to {2}", this.VariantId, oldProtocol, protocolSupport), this.Context); HostManager.Save(); + } + if (protocolSupport == HostProtocolSupport.HTTP2) TryToSendQueuedRequests(); - } } internal HostConnection Send(HTTPRequest request) diff --git a/Assets/URS/Best HTTP/Source/Core/HostDefinition.cs b/Assets/URS/Best HTTP/Source/Core/HostDefinition.cs index b90a86c..835f49f 100644 --- a/Assets/URS/Best HTTP/Source/Core/HostDefinition.cs +++ b/Assets/URS/Best HTTP/Source/Core/HostDefinition.cs @@ -1,6 +1,9 @@ using System; using System.Collections.Generic; +using BestHTTP.Connections; +using BestHTTP.PlatformSupport.Text; + namespace BestHTTP.Core { public sealed class HostDefinition @@ -100,22 +103,17 @@ internal void LoadFrom(int version, System.IO.BinaryReader br) } } - private static System.Text.StringBuilder keyBuilder = new System.Text.StringBuilder(11); - - // While a ReaderWriterLockSlim would be best with read and write locking and we use only WriteLock, it's still a lightweight locking mechanism instead of the lock statement. - private static System.Threading.ReaderWriterLockSlim keyBuilderLock = new System.Threading.ReaderWriterLockSlim(System.Threading.LockRecursionPolicy.NoRecursion); - public static string GetKeyForRequest(HTTPRequest request) { return GetKeyFor(request.CurrentUri -#if !BESTHTTP_DISABLE_PROXY +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) , request.Proxy #endif ); } public static string GetKeyFor(Uri uri -#if !BESTHTTP_DISABLE_PROXY +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) , Proxy proxy #endif ) @@ -123,36 +121,27 @@ public static string GetKeyFor(Uri uri if (uri.IsFile) return uri.ToString(); - keyBuilderLock.EnterWriteLock(); + var keyBuilder = StringBuilderPool.Get(11); - try +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) + if (proxy != null && proxy.UseProxyForAddress(uri)) { - keyBuilder.Length = 0; - -#if !BESTHTTP_DISABLE_PROXY - if (proxy != null && proxy.UseProxyForAddress(uri)) - { - keyBuilder.Append(proxy.Address.Scheme); - keyBuilder.Append("://"); - keyBuilder.Append(proxy.Address.Host); - keyBuilder.Append(":"); - keyBuilder.Append(proxy.Address.Port); - keyBuilder.Append(" @ "); - } -#endif - - keyBuilder.Append(uri.Scheme); + keyBuilder.Append(proxy.Address.Scheme); keyBuilder.Append("://"); - keyBuilder.Append(uri.Host); + keyBuilder.Append(proxy.Address.Host); keyBuilder.Append(":"); - keyBuilder.Append(uri.Port); - - return keyBuilder.ToString(); - } - finally - { - keyBuilderLock.ExitWriteLock(); + keyBuilder.Append(proxy.Address.Port); + keyBuilder.Append(" @ "); } +#endif + + keyBuilder.Append(uri.Scheme); + keyBuilder.Append("://"); + keyBuilder.Append(uri.Host); + keyBuilder.Append(":"); + keyBuilder.Append(uri.Port); + + return StringBuilderPool.ReleaseAndGrab(keyBuilder); } } } diff --git a/Assets/URS/Best HTTP/Source/Core/ProtocolEvents.cs b/Assets/URS/Best HTTP/Source/Core/ProtocolEvents.cs index c5a1706..7c2aac9 100644 --- a/Assets/URS/Best HTTP/Source/Core/ProtocolEvents.cs +++ b/Assets/URS/Best HTTP/Source/Core/ProtocolEvents.cs @@ -65,7 +65,7 @@ internal static void ProcessQueue() OnEvent(protocolEvent); } catch (Exception ex) -{ + { HTTPManager.Logger.Exception("ProtocolEventHelper", "ProcessQueue", ex, protocolEvent.Source.LoggingContext); } } diff --git a/Assets/URS/Best HTTP/Source/Core/RequestEvents.cs b/Assets/URS/Best HTTP/Source/Core/RequestEvents.cs index 879e0c0..e10319f 100644 --- a/Assets/URS/Best HTTP/Source/Core/RequestEvents.cs +++ b/Assets/URS/Best HTTP/Source/Core/RequestEvents.cs @@ -211,6 +211,78 @@ public override string ToString() } } + class ProgressFlattener + { + struct FlattenedProgress + { + public HTTPRequest request; + public OnProgressDelegate onProgress; + public long progress; + public long length; + } + + private FlattenedProgress[] progresses; + private bool hasProgress; + + public void InsertOrUpdate(RequestEventInfo info, OnProgressDelegate onProgress) + { + if (progresses == null) + progresses = new FlattenedProgress[1]; + + hasProgress = true; + + var newProgresss = new FlattenedProgress { request = info.SourceRequest, progress = info.Progress, length = info.ProgressLength, onProgress = onProgress }; + + int firstEmptyIdx = -1; + for (int i = 0; i < progresses.Length; i++) + { + var progress = progresses[i]; + if (object.ReferenceEquals(progress.request, info.SourceRequest)) + { + progresses[i] = newProgresss; + return; + } + + if (firstEmptyIdx == -1 && progress.request == null) + firstEmptyIdx = i; + } + + if (firstEmptyIdx == -1) + { + Array.Resize(ref progresses, progresses.Length + 1); + progresses[progresses.Length - 1] = newProgresss; + } + else + progresses[firstEmptyIdx] = newProgresss; + } + + public void DispatchProgressCallbacks() + { + if (progresses == null || !hasProgress) + return; + + for (int i = 0; i < progresses.Length; ++i) + { + var @event = progresses[i]; + var source = @event.request; + if (source != null && @event.onProgress != null) + { + try + { + @event.onProgress(source, @event.progress, @event.length); + } + catch (Exception ex) + { + HTTPManager.Logger.Exception("ProgressFlattener", "DispatchProgressCallbacks", ex, source.Context); + } + } + } + + Array.Clear(progresses, 0, progresses.Length); + hasProgress = false; + } + } + public static class RequestEventHelper { private static ConcurrentQueue requestEventQueue = new ConcurrentQueue(); @@ -219,6 +291,13 @@ public static class RequestEventHelper public static Action OnEvent; #pragma warning restore + // Low frame rate and hight download/upload speed can add more download/upload progress events to dispatch in one frame. + // This can add higher CPU usage as it might cause updating the UI/do other things unnecessary in the same frame. + // To avoid this, instead of calling the events directly, we store the last event's data and call download/upload callbacks only once per frame. + + private static ProgressFlattener downloadProgress; + private static ProgressFlattener uploadProgress; + public static void EnqueueRequestEvent(RequestEventInfo @event) { if (HTTPManager.Logger.Level == Loglevels.All) @@ -282,7 +361,11 @@ internal static void ProcessQueue() try { if (source.OnDownloadProgress != null) - source.OnDownloadProgress(source, requestEvent.Progress, requestEvent.ProgressLength); + { + if (downloadProgress == null) + downloadProgress = new ProgressFlattener(); + downloadProgress.InsertOrUpdate(requestEvent, source.OnDownloadProgress); + } } catch (Exception ex) { @@ -294,7 +377,11 @@ internal static void ProcessQueue() try { if (source.OnUploadProgress != null) - source.OnUploadProgress(source, requestEvent.Progress, requestEvent.ProgressLength); + { + if (uploadProgress == null) + uploadProgress = new ProgressFlattener(); + uploadProgress.InsertOrUpdate(requestEvent, source.OnUploadProgress); + } } catch (Exception ex) { @@ -360,6 +447,9 @@ internal static void ProcessQueue() break; } } + + uploadProgress?.DispatchProgressCallbacks(); + downloadProgress?.DispatchProgressCallbacks(); } private static bool AbortRequestWhenTimedOut(DateTime now, object context) @@ -465,6 +555,10 @@ internal static void HandleRequestStateChange(RequestEventInfo @event) } #endif + // Dispatch any collected download/upload progress, otherwise they would _after_ the callback! + uploadProgress?.DispatchProgressCallbacks(); + downloadProgress?.DispatchProgressCallbacks(); + source.Timing.AddEvent(TimingEventNames.Queued_For_Disptach, DateTime.Now, TimeSpan.Zero); source.Timing.AddEvent(TimingEventNames.Finished, DateTime.Now, DateTime.Now - source.Timing.Start); diff --git a/Assets/URS/Best HTTP/Source/Decompression/BrotliDecompressor.cs b/Assets/URS/Best HTTP/Source/Decompression/BrotliDecompressor.cs new file mode 100644 index 0000000..c339546 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Decompression/BrotliDecompressor.cs @@ -0,0 +1,90 @@ +using System; + +using BestHTTP.Extensions; +using BestHTTP.PlatformSupport.Memory; + +namespace BestHTTP.Decompression +{ + public sealed class BrotliDecompressor : IDecompressor + { +#if (NET_STANDARD_2_1 || UNITY_2021_2_OR_NEWER) && (!(ENABLE_MONO && UNITY_ANDROID) || (!UNITY_WEBGL || UNITY_EDITOR)) + private BufferPoolMemoryStream decompressorInputStream; + private BufferPoolMemoryStream decompressorOutputStream; + private System.IO.Compression.BrotliStream decompressorStream; +#endif + + private int MinLengthToDecompress = 256; + + public static bool IsSupported() + { + // Not enabled under android with the mono runtime +#if (NET_STANDARD_2_1 || UNITY_2021_2_OR_NEWER) && (!(ENABLE_MONO && UNITY_ANDROID) || (!UNITY_WEBGL || UNITY_EDITOR)) + return true; +#else + return false; +#endif + } + + public BrotliDecompressor(int minLengthToDecompress) + { + this.MinLengthToDecompress = minLengthToDecompress; + } + + public DecompressedData Decompress(byte[] data, int offset, int count, bool forceDecompress = false, bool dataCanBeLarger = false) + { +#if (NET_STANDARD_2_1 || UNITY_2021_2_OR_NEWER) && (!(ENABLE_MONO && UNITY_ANDROID) || (!UNITY_WEBGL || UNITY_EDITOR)) + if (decompressorInputStream == null) + decompressorInputStream = new BufferPoolMemoryStream(count); + + if (data != null) + decompressorInputStream.Write(data, offset, count); + + if (!forceDecompress && decompressorInputStream.Length < MinLengthToDecompress) + return new DecompressedData(null, 0); + + decompressorInputStream.Position = 0; + + if (decompressorStream == null) + { + decompressorStream = new System.IO.Compression.BrotliStream(decompressorInputStream, + System.IO.Compression.CompressionMode.Decompress, + true); + } + + if (decompressorOutputStream == null) + decompressorOutputStream = new BufferPoolMemoryStream(); + decompressorOutputStream.SetLength(0); + + byte[] copyBuffer = BufferPool.Get(1024, true); + + int readCount; + int sumReadCount = 0; + while ((readCount = decompressorStream.Read(copyBuffer, 0, copyBuffer.Length)) != 0) + { + decompressorOutputStream.Write(copyBuffer, 0, readCount); + sumReadCount += readCount; + } + + BufferPool.Release(copyBuffer); + + // If no read is done (returned with any data) don't zero out the input stream, as it would delete any not yet used data. + if (sumReadCount > 0) + decompressorStream.SetLength(0); + + byte[] result = decompressorOutputStream.ToArray(dataCanBeLarger); + + return new DecompressedData(result, dataCanBeLarger ? (int)decompressorOutputStream.Length : result.Length); +#else + return default(DecompressedData); +#endif + } + + public void Dispose() + { +#if (NET_STANDARD_2_1 || UNITY_2021_2_OR_NEWER) && (!(ENABLE_MONO && UNITY_ANDROID) || (!UNITY_WEBGL || UNITY_EDITOR)) + this.decompressorStream?.Dispose(); + this.decompressorStream = null; +#endif + } + } +} diff --git a/Assets/URS/Best HTTP/Source/Decompression/BrotliDecompressor.cs.meta b/Assets/URS/Best HTTP/Source/Decompression/BrotliDecompressor.cs.meta new file mode 100644 index 0000000..73cb5c4 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Decompression/BrotliDecompressor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 55a5678ddf697524c8b337e0d3b5cc02 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/Decompression/Deflate.cs b/Assets/URS/Best HTTP/Source/Decompression/Deflate.cs index a196dc8..6260b2e 100644 --- a/Assets/URS/Best HTTP/Source/Decompression/Deflate.cs +++ b/Assets/URS/Best HTTP/Source/Decompression/Deflate.cs @@ -1558,7 +1558,7 @@ internal int Initialize(ZlibCodec codec, CompressionLevel level, int windowBits, hash_mask = hash_size - 1; hash_shift = ((hash_bits + MIN_MATCH - 1) / MIN_MATCH); - window = BufferPool.Get(w_size * 2, false); + window = new byte[w_size * 2];// BufferPool.Get(w_size * 2, false); prev = new short[w_size]; head = new short[hash_size]; @@ -1569,7 +1569,7 @@ internal int Initialize(ZlibCodec codec, CompressionLevel level, int windowBits, // the output distance codes, and the output length codes (aka tree). // orig comment: This works just fine since the average // output size for (length,distance) codes is <= 24 bits. - pending = BufferPool.Get(lit_bufsize * 4, false); + pending = new byte[lit_bufsize * 4];// BufferPool.Get(lit_bufsize * 4, false); _distanceOffset = lit_bufsize; _lengthOffset = (1 + 2) * lit_bufsize; @@ -1614,11 +1614,11 @@ internal int End() return ZlibConstants.Z_STREAM_ERROR; } // Deallocate in reverse order of allocations: - BufferPool.Release(pending); + //BufferPool.Release(pending); pending = null; head = null; prev = null; - BufferPool.Release(window); + //BufferPool.Release(window); window = null; // free // dstate=null; @@ -1881,4 +1881,4 @@ internal int Deflate(FlushType flush) } } -} \ No newline at end of file +} diff --git a/Assets/URS/Best HTTP/Source/Decompression/GZipDecompressor.cs b/Assets/URS/Best HTTP/Source/Decompression/GZipDecompressor.cs index e113ae0..f931882 100644 --- a/Assets/URS/Best HTTP/Source/Decompression/GZipDecompressor.cs +++ b/Assets/URS/Best HTTP/Source/Decompression/GZipDecompressor.cs @@ -1,26 +1,15 @@ +using System; + using BestHTTP.Extensions; using BestHTTP.PlatformSupport.Memory; -using System; namespace BestHTTP.Decompression { - public struct DecompressedData - { - public readonly byte[] Data; - public readonly int Length; - - internal DecompressedData(byte[] data, int length) - { - this.Data = data; - this.Length = length; - } - } - - public sealed class GZipDecompressor : IDisposable + public sealed class GZipDecompressor : IDecompressor { private BufferPoolMemoryStream decompressorInputStream; private BufferPoolMemoryStream decompressorOutputStream; - private Zlib.GZipStream decompressorGZipStream; + private Zlib.GZipStream decompressorStream; private int MinLengthToDecompress = 256; @@ -31,9 +20,9 @@ public GZipDecompressor(int minLengthToDecompress) private void CloseDecompressors() { - if (decompressorGZipStream != null) - decompressorGZipStream.Dispose(); - decompressorGZipStream = null; + if (decompressorStream != null) + decompressorStream.Dispose(); + decompressorStream = null; if (decompressorInputStream != null) decompressorInputStream.Dispose(); @@ -57,13 +46,13 @@ public DecompressedData Decompress(byte[] data, int offset, int count, bool forc decompressorInputStream.Position = 0; - if (decompressorGZipStream == null) + if (decompressorStream == null) { - decompressorGZipStream = new Zlib.GZipStream(decompressorInputStream, + decompressorStream = new Zlib.GZipStream(decompressorInputStream, Zlib.CompressionMode.Decompress, Zlib.CompressionLevel.Default, true); - decompressorGZipStream.FlushMode = Zlib.FlushType.Sync; + decompressorStream.FlushMode = Zlib.FlushType.Sync; } if (decompressorOutputStream == null) @@ -74,7 +63,7 @@ public DecompressedData Decompress(byte[] data, int offset, int count, bool forc int readCount; int sumReadCount = 0; - while ((readCount = decompressorGZipStream.Read(copyBuffer, 0, copyBuffer.Length)) != 0) + while ((readCount = decompressorStream.Read(copyBuffer, 0, copyBuffer.Length)) != 0) { decompressorOutputStream.Write(copyBuffer, 0, readCount); sumReadCount += readCount; @@ -84,7 +73,7 @@ public DecompressedData Decompress(byte[] data, int offset, int count, bool forc // If no read is done (returned with any data) don't zero out the input stream, as it would delete any not yet used data. if (sumReadCount > 0) - decompressorGZipStream.SetLength(0); + decompressorStream.SetLength(0); byte[] result = decompressorOutputStream.ToArray(dataCanBeLarger); diff --git a/Assets/URS/Best HTTP/Source/Decompression/GZipStream.cs b/Assets/URS/Best HTTP/Source/Decompression/GZipStream.cs index c7d9007..1d79823 100644 --- a/Assets/URS/Best HTTP/Source/Decompression/GZipStream.cs +++ b/Assets/URS/Best HTTP/Source/Decompression/GZipStream.cs @@ -860,7 +860,7 @@ private int EmitHeader() int fnLength = (FileName == null) ? 0 : filenameBytes.Length + 1; int bufferLength = 10 + cbLength + fnLength; - byte[] header = BufferPool.Get(bufferLength, false); + byte[] header = BufferPool.Get(bufferLength, true); int i = 0; // ID header[i++] = 0x1F; @@ -909,7 +909,7 @@ private int EmitHeader() header[i++] = 0; // terminate } - _baseStream._stream.Write(header, 0, header.Length); + _baseStream._stream.Write(header, 0, i); int headerLength = header.Length; BufferPool.Release(header); diff --git a/Assets/URS/Best HTTP/Source/Decompression/IDecompressor.cs b/Assets/URS/Best HTTP/Source/Decompression/IDecompressor.cs new file mode 100644 index 0000000..d81ea55 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Decompression/IDecompressor.cs @@ -0,0 +1,102 @@ +using System; +using System.IO; + +using BestHTTP.Logger; + +namespace BestHTTP.Decompression +{ + public struct DecompressedData + { + public readonly byte[] Data; + public readonly int Length; + + internal DecompressedData(byte[] data, int length) + { + this.Data = data; + this.Length = length; + } + } + + public interface IDecompressor : IDisposable + { + DecompressedData Decompress(byte[] data, int offset, int count, bool forceDecompress = false, bool dataCanBeLarger = false); + } + + public static class DecompressorFactory + { + public const int MinLengthToDecompress = 256; + + public static void SetupHeaders(HTTPRequest request) + { + if (!request.HasHeader("Accept-Encoding")) + { +#if BESTHTTP_DISABLE_GZIP + request.AddHeader("Accept-Encoding", "identity"); +#elif NET_STANDARD_2_1 || UNITY_2021_2_OR_NEWER + if (BrotliDecompressor.IsSupported()) + request.AddHeader("Accept-Encoding", "br, gzip, identity"); + else + request.AddHeader("Accept-Encoding", "gzip, identity"); +#else + request.AddHeader("Accept-Encoding", "gzip, identity"); +#endif + } + } + + public static IDecompressor GetDecompressor(string encoding, LoggingContext context) + { + if (encoding == null) + return null; + + switch (encoding.ToLowerInvariant()) + { + case "identity": + case "utf-8": + break; + + case "gzip": return new Decompression.GZipDecompressor(MinLengthToDecompress); + +#if NET_STANDARD_2_1 || UNITY_2021_2_OR_NEWER + case "br": + if (Decompression.BrotliDecompressor.IsSupported()) + return new Decompression.BrotliDecompressor(MinLengthToDecompress); + else + goto default; +#endif + default: + HTTPManager.Logger.Warning("DecompressorFactory", "GetDecompressor - unsupported encoding: " + encoding, context); + break; + } + + return null; + } + + /// + /// Returns with a properly set up GZip/Deflate/Brotli stream, or null if the encoding is null or compiled for WebGl. + /// + public static Stream GetDecoderStream(Stream streamToDecode, string encoding) + { + if (streamToDecode == null) + throw new ArgumentNullException(nameof(streamToDecode)); + + if (string.IsNullOrEmpty(encoding)) + return null; + + switch (encoding) + { +#if !UNITY_WEBGL || UNITY_EDITOR + case "gzip": return new Decompression.Zlib.GZipStream(streamToDecode, Decompression.Zlib.CompressionMode.Decompress); + case "deflate": return new Decompression.Zlib.DeflateStream(streamToDecode, Decompression.Zlib.CompressionMode.Decompress); +#if NET_STANDARD_2_1 || UNITY_2021_2_OR_NEWER + case "br": return new System.IO.Compression.BrotliStream(streamToDecode, System.IO.Compression.CompressionMode.Decompress, true); +#endif +#endif + //identity, utf-8, etc. Or compiled for WebGl. + default: + // Do not copy from one stream to an other, just return with the raw bytes + return null; + } + } + } + +} diff --git a/Assets/URS/Best HTTP/Source/Decompression/IDecompressor.cs.meta b/Assets/URS/Best HTTP/Source/Decompression/IDecompressor.cs.meta new file mode 100644 index 0000000..920090d --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Decompression/IDecompressor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2551f53f7db6a5a4994fea7e611323d1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/Extensions/BufferPoolMemoryStream.cs b/Assets/URS/Best HTTP/Source/Extensions/BufferPoolMemoryStream.cs index 1d3f363..cbf5023 100644 --- a/Assets/URS/Best HTTP/Source/Extensions/BufferPoolMemoryStream.cs +++ b/Assets/URS/Best HTTP/Source/Extensions/BufferPoolMemoryStream.cs @@ -402,7 +402,19 @@ public byte[] ToArray() public byte[] ToArray(bool canBeLarger) { int l = length - initialIndex; - byte[] outBuffer = l > 0 ? BufferPool.Get(l, canBeLarger) : BufferPool.NoData; + byte[] outBuffer = null; + + if (l > 0) + { + if (canBeLarger) + outBuffer = BufferPool.Get(l, true); + else + outBuffer = new byte[l]; + } + else + { + outBuffer = BufferPool.NoData; + } if (internalBuffer != null) Buffer.BlockCopy(internalBuffer, initialIndex, outBuffer, 0, l); diff --git a/Assets/URS/Best HTTP/Source/Extensions/BufferSegmentStream.cs b/Assets/URS/Best HTTP/Source/Extensions/BufferSegmentStream.cs index a9f4e2c..e726488 100644 --- a/Assets/URS/Best HTTP/Source/Extensions/BufferSegmentStream.cs +++ b/Assets/URS/Best HTTP/Source/Extensions/BufferSegmentStream.cs @@ -47,13 +47,13 @@ public override int Read(byte[] buffer, int offset, int count) offset += readCount; count -= readCount; - if (readCount >= buff.Count) + this.bufferList[0] = buff = buff.Slice(buff.Offset + readCount); + + if (buff.Count == 0) { this.bufferList.RemoveAt(0); BufferPool.Release(buff.Data); } - else - this.bufferList[0] = new BufferSegment(buff.Data, buff.Offset + readCount, buff.Count - readCount); } this._length -= sumReadCount; @@ -84,7 +84,7 @@ protected override void Dispose(bool disposing) { base.Dispose(disposing); - this._length = 0; + Reset(); } public override void Flush() { } diff --git a/Assets/URS/Best HTTP/Source/Extensions/CircularBuffer.cs b/Assets/URS/Best HTTP/Source/Extensions/CircularBuffer.cs index 5059f5b..1b29125 100644 --- a/Assets/URS/Best HTTP/Source/Extensions/CircularBuffer.cs +++ b/Assets/URS/Best HTTP/Source/Extensions/CircularBuffer.cs @@ -56,7 +56,8 @@ public void Clear() public override string ToString() { - var sb = new System.Text.StringBuilder("["); + var sb = PlatformSupport.Text.StringBuilderPool.Get(2); + sb.Append("["); int idx = this.startIdx; while (idx != this.endIdx) diff --git a/Assets/URS/Best HTTP/Source/Extensions/Extensions.cs b/Assets/URS/Best HTTP/Source/Extensions/Extensions.cs index f5719b6..1d2d68b 100644 --- a/Assets/URS/Best HTTP/Source/Extensions/Extensions.cs +++ b/Assets/URS/Best HTTP/Source/Extensions/Extensions.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Text; +using BestHTTP.PlatformSupport.Text; #if NETFX_CORE using Windows.Security.Cryptography; @@ -26,25 +26,25 @@ public static class Extensions ///
public static string AsciiToString(this byte[] bytes) { - StringBuilder sb = new StringBuilder(bytes.Length); + StringBuilder sb = StringBuilderPool.Get(bytes.Length); //new StringBuilder(bytes.Length); foreach (byte b in bytes) sb.Append(b <= 0x7f ? (char)b : '?'); - return sb.ToString(); + return StringBuilderPool.ReleaseAndGrab(sb); } /// /// On WP8 platform there are no ASCII encoding. /// - public static byte[] GetASCIIBytes(this string str) + public static BufferSegment GetASCIIBytes(this string str) { - byte[] result = BufferPool.Get(str.Length, false); + byte[] result = BufferPool.Get(str.Length, true); for (int i = 0; i < str.Length; ++i) { char ch = str[i]; result[i] = (byte)((ch < (char)0x80) ? ch : '?'); } - return result; + return new BufferSegment(result, 0, str.Length); } public static void SendAsASCII(this BinaryWriter stream, string str) @@ -69,7 +69,7 @@ public static void WriteLine(this Stream fs) public static void WriteLine(this Stream fs, string line) { var buff = line.GetASCIIBytes(); - fs.Write(buff, 0, buff.Length); + fs.Write(buff.Data, buff.Offset, buff.Count); fs.WriteLine(); BufferPool.Release(buff); } @@ -77,7 +77,7 @@ public static void WriteLine(this Stream fs, string line) public static void WriteLine(this Stream fs, string format, params object[] values) { var buff = string.Format(format, values).GetASCIIBytes(); - fs.Write(buff, 0, buff.Length); + fs.Write(buff.Data, buff.Offset, buff.Count); fs.WriteLine(); BufferPool.Release(buff); } @@ -86,6 +86,21 @@ public static void WriteLine(this Stream fs, string format, params object[] valu #region Other Extensions + public static BufferSegment AsBuffer(this byte[] bytes) + { + return new BufferSegment(bytes, 0, bytes.Length); + } + + public static BufferSegment AsBuffer(this byte[] bytes, int length) + { + return new BufferSegment(bytes, 0, length); + } + + public static BufferSegment AsBuffer(this byte[] bytes, int offset, int length) + { + return new BufferSegment(bytes, offset, length); + } + public static string GetRequestPathAndQueryURL(this Uri uri) { string requestPathAndQuery = uri.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped); @@ -124,6 +139,11 @@ public static void WriteArray(this Stream stream, byte[] array) stream.Write(array, 0, array.Length); } + public static void WriteBufferSegment(this Stream stream, BufferSegment buffer) + { + stream.Write(buffer.Data, buffer.Offset, buffer.Count); + } + /// /// Returns true if the Uri's host is a valid IPv4 or IPv6 address. /// @@ -243,28 +263,29 @@ public static string ToBinaryStr(this byte value) public static string CalculateMD5Hash(this string input) { - byte[] ascii = input.GetASCIIBytes(); - var hash = ascii.CalculateMD5Hash(); - BufferPool.Release(ascii); + var asciiBuff = input.GetASCIIBytes(); + var hash = asciiBuff.CalculateMD5Hash(); + BufferPool.Release(asciiBuff); return hash; } - public static string CalculateMD5Hash(this byte[] input) + public static string CalculateMD5Hash(this BufferSegment input) { #if NETFX_CORE var alg = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5); - IBuffer buff = CryptographicBuffer.CreateFromByteArray(input); + //IBuffer buff = CryptographicBuffer.CreateFromByteArray(input); + IBuffer buff = System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.AsBuffer(input.Data, input.Offset, input.Count); var hashed = alg.HashData(buff); var res = CryptographicBuffer.EncodeToHexString(hashed); return res; #else using (var md5 = Cryptography.MD5.Create()) { - var hash = md5.ComputeHash(input); - var sb = new StringBuilder(hash.Length); + var hash = md5.ComputeHash(input.Data, input.Offset, input.Count); + var sb = StringBuilderPool.Get(hash.Length); //new StringBuilder(hash.Length); for (int i = 0; i < hash.Length; ++i) sb.Append(hash[i].ToString("x2")); BufferPool.Release(hash); - return sb.ToString(); + return StringBuilderPool.ReleaseAndGrab(sb); } #endif } diff --git a/Assets/URS/Best HTTP/Source/Extensions/HeaderValue.cs b/Assets/URS/Best HTTP/Source/Extensions/HeaderValue.cs index d04a642..51ff90b 100644 --- a/Assets/URS/Best HTTP/Source/Extensions/HeaderValue.cs +++ b/Assets/URS/Best HTTP/Source/Extensions/HeaderValue.cs @@ -3,6 +3,8 @@ using System.Linq; using System.Text; +using BestHTTP.PlatformSupport.Text; + namespace BestHTTP.Extensions { /// @@ -107,7 +109,7 @@ public override string ToString() { if (this.Options != null && this.Options.Count > 0) { - StringBuilder sb = new StringBuilder(4); + StringBuilder sb = StringBuilderPool.Get(4); //new StringBuilder(4); sb.Append(Key); sb.Append("="); sb.Append(Value); @@ -118,7 +120,7 @@ public override string ToString() sb.Append(option.ToString()); } - return sb.ToString(); + return StringBuilderPool.ReleaseAndGrab(sb); } else if (!string.IsNullOrEmpty(Value)) return Key + '=' + Value; diff --git a/Assets/URS/Best HTTP/Source/Extensions/ReadOnlyBufferedStream.cs b/Assets/URS/Best HTTP/Source/Extensions/ReadOnlyBufferedStream.cs index 47c88e6..c6e83d2 100644 --- a/Assets/URS/Best HTTP/Source/Extensions/ReadOnlyBufferedStream.cs +++ b/Assets/URS/Best HTTP/Source/Extensions/ReadOnlyBufferedStream.cs @@ -11,7 +11,7 @@ public sealed class ReadOnlyBufferedStream : Stream byte[] buf; int available = 0; int pos = 0; - + public ReadOnlyBufferedStream(Stream nstream) :this(nstream, READBUFFER) { @@ -25,72 +25,33 @@ public ReadOnlyBufferedStream(Stream nstream, int bufferSize) public override int Read(byte[] buffer, int offset, int size) { - if (size <= available) + if (available > 0) { - Array.Copy(buf, pos, buffer, offset, size); - available -= size; - pos += size; - return size; + // copy & return + int copyCount = Math.Min(available, size); + Array.Copy(buf, pos, buffer, offset, copyCount); + pos += copyCount; + available -= copyCount; + return copyCount; } else { - int readcount = 0; - - if (available > 0) + if (size >= buf.Length) { - Array.Copy(buf, pos, buffer, offset, available); - offset += available; - readcount += available; - available = 0; - pos = 0; + // read directly to buffer + return stream.Read(buffer, offset, size); } - - try + else { - available = stream.Read(buf, 0, buf.Length); + // read to buf and copy pos = 0; - } - catch (Exception ex) - { - if (readcount > 0) - { - return readcount; - } - - throw (ex); - } - - if (available < 1) - { - if (readcount > 0) - { - return readcount; - } + available = stream.Read(buf, 0, buf.Length); - return available; - } - else - { - int toread = size - readcount; - if (toread <= available) - { - Array.Copy(buf, pos, buffer, offset, toread); - available -= toread; - pos += toread; - readcount += toread; - return readcount; - } + if (available > 0) + return Read(buffer, offset, size); else - { - Array.Copy(buf, pos, buffer, offset, available); - offset += available; - readcount += available; - pos = 0; - available = 0; - } + return 0; } - - return readcount; } } diff --git a/Assets/URS/Best HTTP/Source/Extensions/StreamList.cs b/Assets/URS/Best HTTP/Source/Extensions/StreamList.cs index e445d41..8d027da 100644 --- a/Assets/URS/Best HTTP/Source/Extensions/StreamList.cs +++ b/Assets/URS/Best HTTP/Source/Extensions/StreamList.cs @@ -100,10 +100,9 @@ public override void Write(byte[] buffer, int offset, int count) public void Write(string str) { - byte[] bytes = str.GetASCIIBytes(); - - this.Write(bytes, 0, bytes.Length); - BufferPool.Release(bytes); + var buffer = str.GetASCIIBytes(); + this.Write(buffer.Data, buffer.Offset, buffer.Count); + BufferPool.Release(buffer); } protected override void Dispose(bool disposing) diff --git a/Assets/URS/Best HTTP/Source/Forms/Implementations/HTTPUrlEncodedForm.cs b/Assets/URS/Best HTTP/Source/Forms/Implementations/HTTPUrlEncodedForm.cs index 82595b1..123ef3a 100644 --- a/Assets/URS/Best HTTP/Source/Forms/Implementations/HTTPUrlEncodedForm.cs +++ b/Assets/URS/Best HTTP/Source/Forms/Implementations/HTTPUrlEncodedForm.cs @@ -1,8 +1,10 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; +using BestHTTP.PlatformSupport.Text; + namespace BestHTTP.Forms { /// @@ -24,7 +26,7 @@ public override byte[] GetData() if (CachedData != null && !IsChanged) return CachedData; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = PlatformSupport.Text.StringBuilderPool.Get(Fields.Count * 4); // Create a "field1=value1&field2=value2" formatted string for (int i = 0; i < Fields.Count; ++i) @@ -45,7 +47,7 @@ public override byte[] GetData() } IsChanged = false; - return CachedData = Encoding.UTF8.GetBytes(sb.ToString()); + return CachedData = Encoding.UTF8.GetBytes(PlatformSupport.Text.StringBuilderPool.ReleaseAndGrab(sb)); } public static string EscapeString(string originalString) @@ -55,15 +57,15 @@ public static string EscapeString(string originalString) else { int loops = originalString.Length / EscapeTreshold; - StringBuilder sb = new StringBuilder(loops); + StringBuilder sb = StringBuilderPool.Get(loops); //new StringBuilder(loops); for (int i = 0; i <= loops; i++) sb.Append(i < loops ? Uri.EscapeDataString(originalString.Substring(EscapeTreshold * i, EscapeTreshold)) : Uri.EscapeDataString(originalString.Substring(EscapeTreshold * i))); - return sb.ToString(); + return StringBuilderPool.ReleaseAndGrab(sb); } } } -} \ No newline at end of file +} diff --git a/Assets/URS/Best HTTP/Source/HTTPManager.cs b/Assets/URS/Best HTTP/Source/HTTPManager.cs index 2d6ff75..0f2b798 100644 --- a/Assets/URS/Best HTTP/Source/HTTPManager.cs +++ b/Assets/URS/Best HTTP/Source/HTTPManager.cs @@ -9,6 +9,8 @@ using BestHTTP.Extensions; using BestHTTP.Logger; using BestHTTP.PlatformSupport.Memory; +using BestHTTP.PlatformSupport.Text; +using Unity.Profiling; #if !BESTHTTP_DISABLE_COOKIES using BestHTTP.Cookies; @@ -70,11 +72,13 @@ static HTTPManager() #if NETFX_CORE IOService = new PlatformSupport.FileSystem.NETFXCOREIOService(); -//#elif UNITY_WEBGL && !UNITY_EDITOR -// IOService = new PlatformSupport.FileSystem.WebGLIOService(); #else IOService = new PlatformSupport.FileSystem.DefaultIOService(); #endif + +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) + ProxyDetector = new Proxies.Autodetect.ProxyDetector(); +#endif } #if (!UNITY_WEBGL || UNITY_EDITOR) && !BESTHTTP_DISABLE_ALTERNATE_SSL && !BESTHTTP_DISABLE_HTTP2 @@ -158,7 +162,17 @@ public static byte MaxConnectionPerServer /// public static System.Func RootCacheFolderProvider { get; set; } -#if !BESTHTTP_DISABLE_PROXY +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) + + public static Proxies.Autodetect.ProxyDetector ProxyDetector { + get => _proxyDetector; + set { + _proxyDetector?.Detach(); + _proxyDetector = value; + } + } + private static Proxies.Autodetect.ProxyDetector _proxyDetector; + /// /// The global, default proxy for all HTTPRequests. The HTTPRequest's Proxy still can be changed per-request. Default value is null. /// @@ -258,7 +272,7 @@ public static Connections.TLS.AbstractTls13Client DefaultTlsClientFactory(HTTPRe /// /// User-agent string that will be sent with each requests. /// - public static string UserAgent = "BestHTTP/2 v2.6.2"; + public static string UserAgent = "BestHTTP/2 v2.8.3"; /// /// It's true if the application is quitting and the plugin is shutting down itself. @@ -404,17 +418,32 @@ public static void ResetSetup() /// public static void OnUpdate() { - RequestEventHelper.ProcessQueue(); - ConnectionEventHelper.ProcessQueue(); - ProtocolEventHelper.ProcessQueue(); - PluginEventHelper.ProcessQueue(); + using (var _ = new ProfilerMarker(nameof(RequestEventHelper)).Auto()) + RequestEventHelper.ProcessQueue(); - BestHTTP.Extensions.Timer.Process(); + using (var _ = new ProfilerMarker(nameof(ConnectionEventHelper)).Auto()) + ConnectionEventHelper.ProcessQueue(); + + using (var _ = new ProfilerMarker(nameof(ProtocolEventHelper)).Auto()) + ProtocolEventHelper.ProcessQueue(); + + using (var _ = new ProfilerMarker(nameof(PluginEventHelper)).Auto()) + PluginEventHelper.ProcessQueue(); + + using (var _ = new ProfilerMarker(nameof(Timer)).Auto()) + BestHTTP.Extensions.Timer.Process(); if (heartbeats != null) - heartbeats.Update(); + { + using (var _ = new ProfilerMarker(nameof(HeartbeatManager)).Auto()) + heartbeats.Update(); + } + + using (var _ = new ProfilerMarker(nameof(BufferPool)).Auto()) + BufferPool.Maintain(); - BufferPool.Maintain(); + using (var _ = new ProfilerMarker(nameof(StringBuilderPool)).Auto()) + StringBuilderPool.Maintain(); } public static void OnQuit() diff --git a/Assets/URS/Best HTTP/Source/HTTPMethods.cs b/Assets/URS/Best HTTP/Source/HTTPMethods.cs index 466c61f..11f80e3 100644 --- a/Assets/URS/Best HTTP/Source/HTTPMethods.cs +++ b/Assets/URS/Best HTTP/Source/HTTPMethods.cs @@ -76,6 +76,12 @@ public enum HTTPMethods : byte /// /// https://tools.ietf.org/html/rfc8441 /// - Connect + Connect, + + /// + /// https://horovits.medium.com/http-s-new-method-for-data-apis-http-query-1ff71e6f73f3 + /// https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/ + /// + Query } } diff --git a/Assets/URS/Best HTTP/Source/HTTPRequest.cs b/Assets/URS/Best HTTP/Source/HTTPRequest.cs index 338940e..6892104 100644 --- a/Assets/URS/Best HTTP/Source/HTTPRequest.cs +++ b/Assets/URS/Best HTTP/Source/HTTPRequest.cs @@ -67,8 +67,7 @@ public enum HTTPRequestStates } public delegate void OnRequestFinishedDelegate(HTTPRequest originalRequest, HTTPResponse response); - public delegate void OnDownloadProgressDelegate(HTTPRequest originalRequest, long downloaded, long downloadLength); - public delegate void OnUploadProgressDelegate(HTTPRequest originalRequest, long uploaded, long uploadLength); + public delegate void OnProgressDelegate(HTTPRequest originalRequest, long progress, long length); public delegate bool OnBeforeRedirectionDelegate(HTTPRequest originalRequest, HTTPResponse response, Uri redirectUri); public delegate void OnHeaderEnumerationDelegate(string header, List values); public delegate void OnBeforeHeaderSendDelegate(HTTPRequest req); @@ -102,6 +101,7 @@ public sealed class HTTPRequest : IEnumerator, IEnumerator HTTPMethods.Merge.ToString().ToUpper(), HTTPMethods.Options.ToString().ToUpper(), HTTPMethods.Connect.ToString().ToUpper(), + HTTPMethods.Query.ToString().ToUpper() }; /// @@ -146,7 +146,7 @@ public sealed class HTTPRequest : IEnumerator, IEnumerator /// /// Called after data sent out to the wire. /// - public OnUploadProgressDelegate OnUploadProgress; + public OnProgressDelegate OnUploadProgress; /// /// Indicates that the connection should be open after the response received. If its true, then the internal TCP connections will be reused if it's possible. Default value is true. @@ -288,7 +288,7 @@ public bool IsTimedOut /// The first parameter is the original HTTTPRequest object itself, the second parameter is the downloaded bytes while the third parameter is the content length. /// There are download modes where we can't figure out the exact length of the final content. In these cases we just guarantee that the third parameter will be at least the size of the second one. /// - public OnDownloadProgressDelegate OnDownloadProgress; + public OnProgressDelegate OnDownloadProgress; /// /// Indicates that the request is redirected. If a request is redirected, the connection that served it will be closed regardless of the value of IsKeepAlive. @@ -311,7 +311,7 @@ public bool IsTimedOut /// public HTTPResponse Response { get; internal set; } -#if !BESTHTTP_DISABLE_PROXY +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) /// /// Response from the Proxy server. It's null with transparent proxies. /// @@ -333,7 +333,7 @@ public bool IsTimedOut /// public Credentials Credentials { get; set; } -#if !BESTHTTP_DISABLE_PROXY +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) /// /// True, if there is a Proxy object. /// @@ -641,7 +641,7 @@ public HTTPRequest(Uri uri, HTTPMethods methodType, bool isKeepAlive, bool disab this.EnableSafeReadOnUnknownContentLength = true; -#if !BESTHTTP_DISABLE_PROXY +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) this.Proxy = HTTPManager.Proxy; #endif @@ -911,14 +911,9 @@ public void EnumerateHeaders(OnHeaderEnumerationDelegate callback, bool callBefo if (IsRedirected && !HasHeader("Referer")) AddHeader("Referer", Uri.ToString()); - if (!HasHeader("Accept-Encoding")) -#if BESTHTTP_DISABLE_GZIP - AddHeader("Accept-Encoding", "identity"); -#else - AddHeader("Accept-Encoding", "gzip, identity"); -#endif + Decompression.DecompressorFactory.SetupHeaders(this); - #if !BESTHTTP_DISABLE_PROXY +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) if (!HTTPProtocolFactory.IsSecureProtocol(this.CurrentUri) && HasProxy && !HasHeader("Proxy-Connection")) AddHeader("Proxy-Connection", IsKeepAlive ? "Keep-Alive" : "Close"); #endif @@ -968,17 +963,19 @@ public void EnumerateHeaders(OnHeaderEnumerationDelegate callback, bool callBefo // Always set the Content-Length header if possible // http://tools.ietf.org/html/rfc2616#section-4.4 : For compatibility with HTTP/1.0 applications, HTTP/1.1 requests containing a message-body MUST include a valid Content-Length header field unless the server is known to be HTTP/1.1 compliant. // 2018.06.03: Changed the condition so that content-length header will be included for zero length too. + // 2022.05.25: Don't send a Content-Length (: 0) header if there's an Upgrade header. Upgrade is set for websocket, and it might be not true that the client doesn't send any bytes. if ( #if !UNITY_WEBGL || UNITY_EDITOR contentLength >= 0 #else contentLength != -1 #endif - && !HasHeader("Content-Length")) + && !HasHeader("Content-Length") + && !HasHeader("Upgrade")) SetHeader("Content-Length", contentLength.ToString()); #if !UNITY_WEBGL || UNITY_EDITOR - #if !BESTHTTP_DISABLE_PROXY + #if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) // Proxy Authentication if (!HTTPProtocolFactory.IsSecureProtocol(this.CurrentUri) && HasProxy && Proxy.Credentials != null) { @@ -1117,7 +1114,7 @@ private void SendHeaders(Stream stream) if (string.IsNullOrEmpty(header) || values == null) return; - byte[] headerName = string.Concat(header, ": ").GetASCIIBytes(); + var headerName = string.Concat(header, ": ").GetASCIIBytes(); for (int i = 0; i < values.Count; ++i) { @@ -1130,10 +1127,10 @@ private void SendHeaders(Stream stream) if (HTTPManager.Logger.Level <= Logger.Loglevels.Information) VerboseLogging("Header - '" + header + "': '" + values[i] + "'"); - byte[] valueBytes = values[i].GetASCIIBytes(); + var valueBytes = values[i].GetASCIIBytes(); - stream.WriteArray(headerName); - stream.WriteArray(valueBytes); + stream.WriteBufferSegment(headerName); + stream.WriteBufferSegment(valueBytes); stream.WriteArray(EOL); BufferPool.Release(valueBytes); @@ -1174,7 +1171,7 @@ public byte[] GetEntityBody() return null; } - internal struct UploadStreamInfo + public struct UploadStreamInfo { public readonly Stream Stream; public readonly long Length; @@ -1229,7 +1226,7 @@ internal void SendOutTo(Stream stream) // Under WEBGL EnumerateHeaders and GetEntityBody are used instead of this function. #if !UNITY_WEBGL || UNITY_EDITOR string requestPathAndQuery = -#if !BESTHTTP_DISABLE_PROXY +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) HasProxy ? this.Proxy.GetRequestPath(CurrentUri) : #endif CurrentUri.GetRequestPathAndQueryURL(); @@ -1244,8 +1241,8 @@ internal void SendOutTo(Stream stream) // it should have enough room for UploadChunkSize data and additional chunk information. using (WriteOnlyBufferedStream bufferStream = new WriteOnlyBufferedStream(stream, (int)(UploadChunkSize * 1.5f))) { - byte[] requestLineBytes = requestLine.GetASCIIBytes(); - bufferStream.WriteArray(requestLineBytes); + var requestLineBytes = requestLine.GetASCIIBytes(); + bufferStream.WriteBufferSegment(requestLineBytes); bufferStream.WriteArray(EOL); BufferPool.Release(requestLineBytes); @@ -1296,8 +1293,8 @@ internal void SendOutTo(Stream stream) // If we don't know the size, send as chunked if (!UseUploadStreamLength) { - byte[] countBytes = count.ToString("X").GetASCIIBytes(); - bufferStream.WriteArray(countBytes); + var countBytes = count.ToString("X").GetASCIIBytes(); + bufferStream.WriteBufferSegment(countBytes); bufferStream.WriteArray(EOL); BufferPool.Release(countBytes); @@ -1394,6 +1391,7 @@ internal void Prepare() public HTTPRequest Send() { this.IsCancellationRequested = false; + this.Exception = null; return HTTPManager.SendRequest(this); } @@ -1452,6 +1450,7 @@ public void Clear() this.IsRedirected = false; this.RedirectCount = 0; + this.Exception = null; } private void VerboseLogging(string str) diff --git a/Assets/URS/Best HTTP/Source/HTTPResponse.cs b/Assets/URS/Best HTTP/Source/HTTPResponse.cs index debd0b9..3d37b27 100644 --- a/Assets/URS/Best HTTP/Source/HTTPResponse.cs +++ b/Assets/URS/Best HTTP/Source/HTTPResponse.cs @@ -226,7 +226,7 @@ public HTTPResponse(HTTPRequest request, Stream stream, bool isStreamed, bool is this.Context.Add("IsFromCache", isFromCache); } - public virtual bool Receive(long forceReadRawContentLength = -1, bool readPayloadData = true, bool sendUpgradedEvent = true) + public bool Receive(long forceReadRawContentLength = -1, bool readPayloadData = true, bool sendUpgradedEvent = true) { if (this.baseRequest.IsCancellationRequested) return false; @@ -384,7 +384,7 @@ protected bool ReadPayload(long forceReadRawContentLength) protected void ReadHeaders(Stream stream) { - var newHeaders = this.baseRequest.OnHeadersReceived != null ? new Dictionary>() : null; + var newHeaders = this.baseRequest.OnHeadersReceived != null ? new Dictionary>(StringComparer.OrdinalIgnoreCase) : null; string headerName = ReadTo(stream, (byte)':', LF)/*.Trim()*/; while (headerName != string.Empty) @@ -414,10 +414,8 @@ protected void ReadHeaders(Stream stream) public void AddHeader(string name, string value) { - name = name.ToLower(); - if (Headers == null) - Headers = new Dictionary>(); + Headers = new Dictionary>(StringComparer.OrdinalIgnoreCase); List values; if (!Headers.TryGetValue(name, out values)) @@ -435,7 +433,6 @@ public void AddHeader(string name, string value) /// /// Returns the list of values that received from the server for the given header name. - /// Remarks: All headers converted to lowercase while reading the response. /// /// Name of the header /// If no header found with the given name or there are no values in the list (eg. Count == 0) returns null. @@ -444,8 +441,6 @@ public List GetHeaderValues(string name) if (Headers == null) return null; - name = name.ToLower(); - List values; if (!Headers.TryGetValue(name, out values) || values.Count == 0) return null; @@ -463,8 +458,6 @@ public string GetFirstHeaderValue(string name) if (Headers == null) return null; - name = name.ToLower(); - List values; if (!Headers.TryGetValue(name, out values) || values.Count == 0) return null; @@ -573,7 +566,8 @@ internal static string ReadTo(Stream stream, byte blocker) internal static string ReadTo(Stream stream, byte blocker1, byte blocker2) { byte[] readBuf = BufferPool.Get(1024, true); - try { + try + { int bufpos = 0; int ch = stream.ReadByte(); @@ -605,7 +599,8 @@ internal static string ReadTo(Stream stream, byte blocker1, byte blocker2) internal static string NoTrimReadTo(Stream stream, byte blocker1, byte blocker2) { byte[] readBuf = BufferPool.Get(1024, true); - try { + try + { int bufpos = 0; int ch = stream.ReadByte(); @@ -671,108 +666,111 @@ protected void ReadChunked(Stream stream) VerboseLogging(string.Format("chunkLength: {0:N0}", chunkLength)); byte[] buffer = baseRequest.ReadBufferSizeOverride > 0 ? BufferPool.Get(baseRequest.ReadBufferSizeOverride, false) : BufferPool.Get(MinReadBufferSize, true); - - // Progress report: - long Downloaded = 0; - long DownloadLength = hasContentLengthHeader ? realLength : chunkLength; - bool sendProgressChanged = this.baseRequest.OnDownloadProgress != null && (this.IsSuccess + + // wrap buffer in a PooledBuffer to release it back to the pool when leaving the current block. + using (var _ = new PooledBuffer(buffer)) + { + // Progress report: + long Downloaded = 0; + long DownloadLength = hasContentLengthHeader ? realLength : chunkLength; + bool sendProgressChanged = this.baseRequest.OnDownloadProgress != null && (this.IsSuccess #if !BESTHTTP_DISABLE_CACHING - || this.IsFromCache + || this.IsFromCache #endif - ); + ); - if (sendProgressChanged) - RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(this.baseRequest, RequestEvents.DownloadProgress, Downloaded, DownloadLength)); + if (sendProgressChanged) + RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(this.baseRequest, RequestEvents.DownloadProgress, Downloaded, DownloadLength)); - string encoding = + string encoding = #if !BESTHTTP_DISABLE_CACHING - IsFromCache ? null : + IsFromCache ? null : #endif - GetFirstHeaderValue("content-encoding"); - bool gzipped = !string.IsNullOrEmpty(encoding) && encoding == "gzip"; + GetFirstHeaderValue("content-encoding"); + bool compressed = !string.IsNullOrEmpty(encoding); + Decompression.IDecompressor decompressor = baseRequest.UseStreaming ? Decompression.DecompressorFactory.GetDecompressor(encoding, this.Context) : null; - Decompression.GZipDecompressor decompressor = gzipped ? new Decompression.GZipDecompressor(256) : null; + while (chunkLength != 0) + { + if (this.baseRequest.IsCancellationRequested) + return; - while (chunkLength != 0) - { - if (this.baseRequest.IsCancellationRequested) - return; + int totalBytes = 0; + // Fill up the buffer + do + { + int tryToReadCount = (int)Math.Min(chunkLength - totalBytes, buffer.Length); - int totalBytes = 0; - // Fill up the buffer - do - { - int tryToReadCount = (int)Math.Min(chunkLength - totalBytes, buffer.Length); + int bytes = stream.Read(buffer, 0, tryToReadCount); + if (bytes <= 0) + throw ExceptionHelper.ServerClosedTCPStream(); - int bytes = stream.Read(buffer, 0, tryToReadCount); - if (bytes <= 0) - throw ExceptionHelper.ServerClosedTCPStream(); - - // Progress report: - // Placing reporting inside this cycle will report progress much more frequent - Downloaded += bytes; + // Progress report: + // Placing reporting inside this cycle will report progress much more frequent + Downloaded += bytes; - if (sendProgressChanged) - RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(this.baseRequest, RequestEvents.DownloadProgress, Downloaded, DownloadLength)); + if (sendProgressChanged) + RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(this.baseRequest, RequestEvents.DownloadProgress, Downloaded, DownloadLength)); - if (baseRequest.UseStreaming) - { - if (gzipped) + if (baseRequest.UseStreaming) { - var decompressed = decompressor.Decompress(buffer, 0, bytes, false, true); - if (decompressed.Data != null) - FeedStreamFragment(decompressed.Data, 0, decompressed.Length); + if (compressed) + { + var decompressed = decompressor.Decompress(buffer, 0, bytes, false, true); + if (decompressed.Data != null) + FeedStreamFragment(decompressed.Data, 0, decompressed.Length); + } + else + FeedStreamFragment(buffer, 0, bytes); } else - FeedStreamFragment(buffer, 0, bytes); - } - else - output.Write(buffer, 0, bytes); + output.Write(buffer, 0, bytes); - totalBytes += bytes; - } while (totalBytes < chunkLength); + totalBytes += bytes; + } while (totalBytes < chunkLength); - // Every chunk data has a trailing CRLF - ReadTo(stream, LF); + // Every chunk data has a trailing CRLF + ReadTo(stream, LF); - // read the next chunk's length - chunkLength = ReadChunkLength(stream); + // read the next chunk's length + chunkLength = ReadChunkLength(stream); - if (!hasContentLengthHeader) - DownloadLength += chunkLength; + if (!hasContentLengthHeader) + DownloadLength += chunkLength; - if (HTTPManager.Logger.Level == Logger.Loglevels.All) - VerboseLogging(string.Format("chunkLength: {0:N0}", chunkLength)); - } + if (HTTPManager.Logger.Level == Logger.Loglevels.All) + VerboseLogging(string.Format("chunkLength: {0:N0}", chunkLength)); + } - BufferPool.Release(buffer); + //BufferPool.Release(buffer); - if (baseRequest.UseStreaming) - { - if (gzipped) + if (baseRequest.UseStreaming) { - var decompressed = decompressor.Decompress(null, 0, 0, true, true); - if (decompressed.Data != null) - FeedStreamFragment(decompressed.Data, 0, decompressed.Length); - } + if (compressed) + { + var decompressed = decompressor.Decompress(null, 0, 0, true, true); + if (decompressed.Data != null) + FeedStreamFragment(decompressed.Data, 0, decompressed.Length); + } - FlushRemainingFragmentBuffer(); - } + FlushRemainingFragmentBuffer(); + } - // Read the trailing headers or the CRLF - ReadHeaders(stream); + // Read the trailing headers or the CRLF + ReadHeaders(stream); - // HTTP servers sometimes use compression (gzip) or deflate methods to optimize transmission. - // How both chunked and gzip encoding interact is dictated by the two-staged encoding of HTTP: - // first the content stream is encoded as (Content-Encoding: gzip), after which the resulting byte stream is encoded for transfer using another encoder (Transfer-Encoding: chunked). - // This means that in case both compression and chunked encoding are enabled, the chunk encoding itself is not compressed, and the data in each chunk should not be compressed individually. - // The remote endpoint can decode the incoming stream by first decoding it with the Transfer-Encoding, followed by the specified Content-Encoding. - // It would be a better implementation when the chunk would be decododed on-the-fly. Becouse now the whole stream must be downloaded, and then decoded. It needs more memory. - if (!baseRequest.UseStreaming) - this.Data = DecodeStream(output); + // HTTP servers sometimes use compression (gzip) or deflate methods to optimize transmission. + // How both chunked and gzip encoding interact is dictated by the two-staged encoding of HTTP: + // first the content stream is encoded as (Content-Encoding: gzip), after which the resulting byte stream is encoded for transfer using another encoder (Transfer-Encoding: chunked). + // This means that in case both compression and chunked encoding are enabled, the chunk encoding itself is not compressed, and the data in each chunk should not be compressed individually. + // The remote endpoint can decode the incoming stream by first decoding it with the Transfer-Encoding, followed by the specified Content-Encoding. + // It would be a better implementation when the chunk would be decododed on-the-fly. Becouse now the whole stream must be downloaded, and then decoded. It needs more memory. + if (!baseRequest.UseStreaming) + this.Data = DecodeStream(output); - if (decompressor != null) - decompressor.Dispose(); + if (decompressor != null) + decompressor.Dispose(); + } } } @@ -805,8 +803,8 @@ internal void ReadRaw(Stream stream, long contentLength) IsFromCache ? null : #endif GetFirstHeaderValue("content-encoding"); - bool gzipped = !string.IsNullOrEmpty(encoding) && encoding == "gzip"; - Decompression.GZipDecompressor decompressor = gzipped ? new Decompression.GZipDecompressor(256) : null; + bool compressed = !string.IsNullOrEmpty(encoding); + Decompression.IDecompressor decompressor = baseRequest.UseStreaming ? Decompression.DecompressorFactory.GetDecompressor(encoding, this.Context) : null; if (!baseRequest.UseStreaming && contentLength > 2147483646) { @@ -818,69 +816,74 @@ internal void ReadRaw(Stream stream, long contentLength) // Because of the last parameter, buffer's size can be larger than the requested but there's no reason to use // an exact sized one if there's an larger one available in the pool. Later we will use the whole buffer. byte[] buffer = baseRequest.ReadBufferSizeOverride > 0 ? BufferPool.Get(baseRequest.ReadBufferSizeOverride, false) : BufferPool.Get(MinReadBufferSize, true); - int readBytes = 0; - while (contentLength > 0) + // wrap buffer in a PooledBuffer to release it back to the pool when leaving the current block. + using (var _ = new PooledBuffer(buffer)) { - if (this.baseRequest.IsCancellationRequested) - return; - - readBytes = 0; + int readBytes = 0; - do + while (contentLength > 0) { - // tryToReadCount contain how much bytes we want to read in once. We try to read the buffer fully in once, - // but with a limit of the remaining contentLength. - int tryToReadCount = (int)Math.Min(Math.Min(int.MaxValue, contentLength), buffer.Length - readBytes); + if (this.baseRequest.IsCancellationRequested) + return; - int bytes = stream.Read(buffer, readBytes, tryToReadCount); + readBytes = 0; - if (bytes <= 0) - throw ExceptionHelper.ServerClosedTCPStream(); + do + { + // tryToReadCount contain how much bytes we want to read in once. We try to read the buffer fully in once, + // but with a limit of the remaining contentLength. + int tryToReadCount = (int)Math.Min(Math.Min(int.MaxValue, contentLength), buffer.Length - readBytes); - readBytes += bytes; - contentLength -= bytes; + int bytes = stream.Read(buffer, readBytes, tryToReadCount); - // Progress report: - if (sendProgressChanged) + if (bytes <= 0) + throw ExceptionHelper.ServerClosedTCPStream(); + + readBytes += bytes; + contentLength -= bytes; + + // Progress report: + if (sendProgressChanged) + { + downloaded += bytes; + RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(this.baseRequest, RequestEvents.DownloadProgress, downloaded, downloadLength)); + } + + } while (readBytes < buffer.Length && contentLength > 0); + + if (baseRequest.UseStreaming) { - downloaded += bytes; - RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(this.baseRequest, RequestEvents.DownloadProgress, downloaded, downloadLength)); + if (compressed) + { + var decompressed = decompressor.Decompress(buffer, 0, readBytes, false, true); + if (decompressed.Data != null) + FeedStreamFragment(decompressed.Data, 0, decompressed.Length); + } + else + FeedStreamFragment(buffer, 0, readBytes); } + else + output.Write(buffer, 0, readBytes); + }; - } while (readBytes < buffer.Length && contentLength > 0); + //BufferPool.Release(buffer); if (baseRequest.UseStreaming) { - if (gzipped) + if (compressed) { - var decompressed = decompressor.Decompress(buffer, 0, readBytes, false, true); + var decompressed = decompressor.Decompress(null, 0, 0, true, true); if (decompressed.Data != null) FeedStreamFragment(decompressed.Data, 0, decompressed.Length); } - else - FeedStreamFragment(buffer, 0, readBytes); - } - else - output.Write(buffer, 0, readBytes); - }; - BufferPool.Release(buffer); - - if (baseRequest.UseStreaming) - { - if (gzipped) - { - var decompressed = decompressor.Decompress(null, 0, 0, true, true); - if (decompressed.Data != null) - FeedStreamFragment(decompressed.Data, 0, decompressed.Length); + FlushRemainingFragmentBuffer(); } - FlushRemainingFragmentBuffer(); + if (!baseRequest.UseStreaming) + this.Data = DecodeStream(output); } - - if (!baseRequest.UseStreaming) - this.Data = DecodeStream(output); } if (decompressor != null) @@ -910,95 +913,100 @@ protected void ReadUnknownSize(Stream stream) IsFromCache ? null : #endif GetFirstHeaderValue("content-encoding"); - bool gzipped = !string.IsNullOrEmpty(encoding) && encoding == "gzip"; - Decompression.GZipDecompressor decompressor = gzipped ? new Decompression.GZipDecompressor(256) : null; + bool compressed = !string.IsNullOrEmpty(encoding); + Decompression.IDecompressor decompressor = baseRequest.UseStreaming ? Decompression.DecompressorFactory.GetDecompressor(encoding, this.Context) : null; using (var output = new BufferPoolMemoryStream()) { byte[] buffer = baseRequest.ReadBufferSizeOverride > 0 ? BufferPool.Get(baseRequest.ReadBufferSizeOverride, false) : BufferPool.Get(MinReadBufferSize, true); - if (HTTPManager.Logger.Level == Logger.Loglevels.All) - VerboseLogging(string.Format("ReadUnknownSize - buffer size: {0:N0}", buffer.Length)); - - int readBytes = 0; - int bytes = 0; - do + // wrap buffer in a PooledBuffer to release it back to the pool when leaving the current block. + using (var _ = new PooledBuffer(buffer)) { - readBytes = 0; + if (HTTPManager.Logger.Level == Logger.Loglevels.All) + VerboseLogging(string.Format("ReadUnknownSize - buffer size: {0:N0}", buffer.Length)); + + int readBytes = 0; + int bytes = 0; do { - if (this.baseRequest.IsCancellationRequested) - return; + readBytes = 0; - bytes = 0; + do + { + if (this.baseRequest.IsCancellationRequested) + return; + + bytes = 0; #if !NETFX_CORE || UNITY_EDITOR - NetworkStream networkStream = stream as NetworkStream; - // If we have the good-old NetworkStream, than we can use the DataAvailable property. On WP8 platforms, these are omitted... :/ - if (networkStream != null && baseRequest.EnableSafeReadOnUnknownContentLength) - { - for (int i = readBytes; i < buffer.Length && networkStream.DataAvailable; ++i) + NetworkStream networkStream = stream as NetworkStream; + // If we have the good-old NetworkStream, than we can use the DataAvailable property. On WP8 platforms, these are omitted... :/ + if (networkStream != null && baseRequest.EnableSafeReadOnUnknownContentLength) { - int read = stream.ReadByte(); - if (read >= 0) + for (int i = readBytes; i < buffer.Length && networkStream.DataAvailable; ++i) { - buffer[i] = (byte)read; - bytes++; + int read = stream.ReadByte(); + if (read >= 0) + { + buffer[i] = (byte)read; + bytes++; + } + else + break; } - else - break; } - } - else // This will be good anyway, but a little slower. + else // This will be good anyway, but a little slower. #endif - { - bytes = stream.Read(buffer, readBytes, buffer.Length - readBytes); - } + { + bytes = stream.Read(buffer, readBytes, buffer.Length - readBytes); + } + + readBytes += bytes; - readBytes += bytes; + // Progress report: + Downloaded += bytes; + DownloadLength = Downloaded; - // Progress report: - Downloaded += bytes; - DownloadLength = Downloaded; + if (sendProgressChanged) + RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(this.baseRequest, RequestEvents.DownloadProgress, Downloaded, DownloadLength)); - if (sendProgressChanged) - RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(this.baseRequest, RequestEvents.DownloadProgress, Downloaded, DownloadLength)); + } while (readBytes < buffer.Length && bytes > 0); - } while (readBytes < buffer.Length && bytes > 0); + if (baseRequest.UseStreaming) + { + if (compressed) + { + var decompressed = decompressor.Decompress(buffer, 0, readBytes, false, true); + if (decompressed.Data != null) + FeedStreamFragment(decompressed.Data, 0, decompressed.Length); + } + else + FeedStreamFragment(buffer, 0, readBytes); + } + else if (readBytes > 0) + output.Write(buffer, 0, readBytes); + + } while (bytes > 0); + + //BufferPool.Release(buffer); if (baseRequest.UseStreaming) { - if (gzipped) + if (compressed) { - var decompressed = decompressor.Decompress(buffer, 0, readBytes, false, true); + var decompressed = decompressor.Decompress(null, 0, 0, true, true); if (decompressed.Data != null) FeedStreamFragment(decompressed.Data, 0, decompressed.Length); } - else - FeedStreamFragment(buffer, 0, readBytes); - } - else if (readBytes > 0) - output.Write(buffer, 0, readBytes); - - } while (bytes > 0); - - BufferPool.Release(buffer); - if (baseRequest.UseStreaming) - { - if (gzipped) - { - var decompressed = decompressor.Decompress(null, 0, 0, true, true); - if (decompressed.Data != null) - FeedStreamFragment(decompressed.Data, 0, decompressed.Length); + FlushRemainingFragmentBuffer(); } - FlushRemainingFragmentBuffer(); + if (!baseRequest.UseStreaming) + this.Data = DecodeStream(output); } - - if (!baseRequest.UseStreaming) - this.Data = DecodeStream(output); } if (decompressor != null) @@ -1020,32 +1028,16 @@ protected byte[] DecodeStream(BufferPoolMemoryStream streamToDecode) #endif GetHeaderValues("content-encoding"); -#if !UNITY_WEBGL || UNITY_EDITOR - Stream decoderStream = null; -#endif + Stream decoderStream = Decompression.DecompressorFactory.GetDecoderStream(streamToDecode, encoding?[0]); - // Return early if there are no encoding used. - if (encoding == null) - return streamToDecode.ToArray(); - else - { - switch (encoding[0]) - { -#if !UNITY_WEBGL || UNITY_EDITOR - case "gzip": decoderStream = new Decompression.Zlib.GZipStream(streamToDecode, Decompression.Zlib.CompressionMode.Decompress); break; - case "deflate": decoderStream = new Decompression.Zlib.DeflateStream(streamToDecode, Decompression.Zlib.CompressionMode.Decompress); break; -#endif - //identity, utf-8, etc. - default: - // Do not copy from one stream to an other, just return with the raw bytes - return streamToDecode.ToArray(); - } - } + // Under WebGL decoderStream is always null. + if (decoderStream == null) + return streamToDecode.ToArray(canBeLarger: false); #if !UNITY_WEBGL || UNITY_EDITOR using (var ms = new BufferPoolMemoryStream((int)streamToDecode.Length)) { - var buf = BufferPool.Get(1024, true); + var buf = BufferPool.Get(HTTPResponse.MinReadBufferSize, true); int byteCount = 0; while ((byteCount = decoderStream.Read(buf, 0, buf.Length)) > 0) @@ -1056,6 +1048,8 @@ protected byte[] DecodeStream(BufferPoolMemoryStream streamToDecode) decoderStream.Dispose(); return ms.ToArray(); } +#else + return streamToDecode.ToArray(canBeLarger: false); #endif } diff --git a/Assets/URS/Best HTTP/Source/HTTPUpdateDelegator.cs b/Assets/URS/Best HTTP/Source/HTTPUpdateDelegator.cs index 05e12b5..8285fc3 100644 --- a/Assets/URS/Best HTTP/Source/HTTPUpdateDelegator.cs +++ b/Assets/URS/Best HTTP/Source/HTTPUpdateDelegator.cs @@ -1,3 +1,8 @@ +using System; +using System.Threading; + +using BestHTTP.PlatformSupport.Threading; + using UnityEngine; #if NETFX_CORE @@ -6,6 +11,27 @@ namespace BestHTTP { + /// + /// Threading mode the plugin will use to call HTTPManager.OnUpdate(). + /// + public enum ThreadingMode : int + { + /// + /// HTTPManager.OnUpdate() is called from the HTTPUpdateDelegator's Update functions (Unity's main thread). + /// + UnityUpdate, + + /// + /// The plugin starts a dedicated thread to call HTTPManager.OnUpdate() periodically. + /// + Threaded, + + /// + /// HTTPManager.OnUpdate() will not be called automatically. + /// + None + } + /// /// Will route some U3D calls to the HTTPManager. /// @@ -18,7 +44,8 @@ public sealed class HTTPUpdateDelegator : MonoBehaviour /// /// The singleton instance of the HTTPUpdateDelegator /// - public static HTTPUpdateDelegator Instance { get; private set; } + public static HTTPUpdateDelegator Instance { get { return CheckInstance(); } } + private volatile static HTTPUpdateDelegator instance; /// /// True, if the Instance property should hold a valid value. @@ -26,14 +53,15 @@ public sealed class HTTPUpdateDelegator : MonoBehaviour public static bool IsCreated { get; private set; } /// - /// Set it true before any CheckInstance() call, or before any request sent to dispatch callbacks on another thread. + /// It's true if the dispatch thread running. /// - public static bool IsThreaded { get; set; } + public static bool IsThreadRunning { get; private set; } /// - /// It's true if the dispatch thread running. + /// The current threading mode the plugin is in. /// - public static bool IsThreadRunning { get; private set; } + public ThreadingMode CurrentThreadingMode { get { return _currentThreadingMode; } set { SetThreadingMode(value); } } + private ThreadingMode _currentThreadingMode = ThreadingMode.UnityUpdate; /// /// How much time the plugin should wait between two update call. Its default value 100 ms. @@ -46,11 +74,17 @@ public sealed class HTTPUpdateDelegator : MonoBehaviour /// public static System.Func OnBeforeApplicationQuit; + /// + /// Called when the Unity application's foreground state changed. + /// public static System.Action OnApplicationForegroundStateChanged; #endregion - private static bool IsSetupCalled; + private static bool isSetupCalled; + private int isHTTPManagerOnUpdateRunning; + private AutoResetEvent pingEvent = new AutoResetEvent(false); + private int updateThreadCount = 0; #if UNITY_EDITOR /// @@ -61,7 +95,9 @@ public sealed class HTTPUpdateDelegator : MonoBehaviour #endif static void ResetSetup() { - IsSetupCalled = false; + isSetupCalled = false; + instance?.SetThreadingMode(ThreadingMode.UnityUpdate); + HTTPManager.Logger.Information("HTTPUpdateDelegator", "Reset called!"); } #endif @@ -74,7 +110,7 @@ static HTTPUpdateDelegator() /// /// Will create the HTTPUpdateDelegator instance and set it up. /// - public static void CheckInstance() + public static HTTPUpdateDelegator CheckInstance() { try { @@ -83,32 +119,37 @@ public static void CheckInstance() GameObject go = GameObject.Find("HTTP Update Delegator"); if (go != null) - Instance = go.GetComponent(); + instance = go.GetComponent(); - if (Instance == null) + if (instance == null) { go = new GameObject("HTTP Update Delegator"); go.hideFlags = HideFlags.HideAndDontSave; - Instance = go.AddComponent(); + instance = go.AddComponent(); } IsCreated = true; #if UNITY_EDITOR if (!UnityEditor.EditorApplication.isPlaying) { - UnityEditor.EditorApplication.update -= Instance.Update; - UnityEditor.EditorApplication.update += Instance.Update; + UnityEditor.EditorApplication.update -= instance.Update; + UnityEditor.EditorApplication.update += instance.Update; } #if UNITY_2017_2_OR_NEWER - UnityEditor.EditorApplication.playModeStateChanged -= Instance.OnPlayModeStateChanged; - UnityEditor.EditorApplication.playModeStateChanged += Instance.OnPlayModeStateChanged; + UnityEditor.EditorApplication.playModeStateChanged -= instance.OnPlayModeStateChanged; + UnityEditor.EditorApplication.playModeStateChanged += instance.OnPlayModeStateChanged; #else - UnityEditor.EditorApplication.playmodeStateChanged -= Instance.OnPlayModeStateChanged; - UnityEditor.EditorApplication.playmodeStateChanged += Instance.OnPlayModeStateChanged; + UnityEditor.EditorApplication.playmodeStateChanged -= instance.OnPlayModeStateChanged; + UnityEditor.EditorApplication.playmodeStateChanged += instance.OnPlayModeStateChanged; #endif #endif + + // https://docs.unity3d.com/ScriptReference/Application-wantsToQuit.html + Application.wantsToQuit -= UnityApplication_WantsToQuit; + Application.wantsToQuit += UnityApplication_WantsToQuit; + HTTPManager.Logger.Information("HTTPUpdateDelegator", "Instance Created!"); } } @@ -116,62 +157,131 @@ public static void CheckInstance() { HTTPManager.Logger.Error("HTTPUpdateDelegator", "Please call the BestHTTP.HTTPManager.Setup() from one of Unity's event(eg. awake, start) before you send any request!"); } + + return instance; } private void Setup() { - if (IsSetupCalled) + if (isSetupCalled) return; - IsSetupCalled = true; - HTTPManager.Setup(); + using (var _ = new Unity.Profiling.ProfilerMarker(nameof(HTTPUpdateDelegator.Setup)).Auto()) + { + isSetupCalled = true; + + HTTPManager.Logger.Information("HTTPUpdateDelegator", $"Setup called Threading Mode: {this._currentThreadingMode}"); -#if UNITY_WEBGL && !UNITY_EDITOR - // Threads are not implemented in WEBGL builds, disable it for now. - IsThreaded = false; -#endif - if (IsThreaded) - PlatformSupport.Threading.ThreadedRunner.RunLongLiving(ThreadFunc); + HTTPManager.Setup(); + + SetThreadingMode(this._currentThreadingMode); + + // Unity doesn't tolerate well if the DontDestroyOnLoad called when purely in editor mode. So, we will set the flag + // only when we are playing, or not in the editor. + if (!Application.isEditor || Application.isPlaying) + GameObject.DontDestroyOnLoad(this.gameObject); + + HTTPManager.Logger.Information("HTTPUpdateDelegator", "Setup done!"); + } + } + + /// + /// Set directly the threading mode to use. + /// + public void SetThreadingMode(ThreadingMode mode) + { + if (_currentThreadingMode == mode) + return; + + HTTPManager.Logger.Information("HTTPUpdateDelegator", $"SetThreadingMode({mode}, {isSetupCalled})"); - // Unity doesn't tolerate well if the DontDestroyOnLoad called when purely in editor mode. So, we will set the flag - // only when we are playing, or not in the editor. - if (!Application.isEditor || Application.isPlaying) - GameObject.DontDestroyOnLoad(this.gameObject); + _currentThreadingMode = mode; - HTTPManager.Logger.Information("HTTPUpdateDelegator", "Setup done!"); + if (!isSetupCalled) + Setup(); + + switch (_currentThreadingMode) + { + case ThreadingMode.UnityUpdate: + case ThreadingMode.None: + IsThreadRunning = false; + PingUpdateThread(); + break; + + case ThreadingMode.Threaded: +#if !UNITY_WEBGL || UNITY_EDITOR + ThreadedRunner.RunLongLiving(ThreadFunc); +#else + HTTPManager.Logger.Warning(nameof(HTTPUpdateDelegator), "Threading mode set to ThreadingMode.Threaded, but threads aren't supported under WebGL!"); +#endif + break; + } } + /// + /// Swaps threading mode between Unity's Update function or a distinct thread. + /// + public void SwapThreadingMode() => SetThreadingMode(_currentThreadingMode == ThreadingMode.Threaded ? ThreadingMode.UnityUpdate : ThreadingMode.Threaded); + + /// + /// Pings the update thread to call HTTPManager.OnUpdate immediately. + /// + /// Works only when the current threading mode is Threaded! + public void PingUpdateThread() => pingEvent.Set(); + void ThreadFunc() { - HTTPManager.Logger.Information ("HTTPUpdateDelegator", "Update Thread Started"); + HTTPManager.Logger.Information("HTTPUpdateDelegator", "Update Thread Started"); + + ThreadedRunner.SetThreadName("BestHTTP.Update Thread"); try { - IsThreadRunning = true; + if (Interlocked.Increment(ref updateThreadCount) > 1) + { + HTTPManager.Logger.Information("HTTPUpdateDelegator", "An update thread already started."); + return; + } + + // Threading mode might be already changed, so set IsThreadRunning to IsThreaded's value. + IsThreadRunning = CurrentThreadingMode == ThreadingMode.Threaded; while (IsThreadRunning) { - HTTPManager.OnUpdate(); + CallOnUpdate(); -#if NETFX_CORE - await Task.Delay(ThreadFrequencyInMS); -#else - System.Threading.Thread.Sleep(ThreadFrequencyInMS); -#endif + pingEvent.WaitOne(ThreadFrequencyInMS); } } finally { + Interlocked.Decrement(ref updateThreadCount); HTTPManager.Logger.Information("HTTPUpdateDelegator", "Update Thread Ended"); } } void Update() { - if (!IsSetupCalled) + if (!isSetupCalled) Setup(); - if (!IsThreaded) - HTTPManager.OnUpdate(); + if (CurrentThreadingMode == ThreadingMode.UnityUpdate) + CallOnUpdate(); + } + + private void CallOnUpdate() + { + // Prevent overlapping call of OnUpdate from unity's main thread and a separate thread + if (Interlocked.CompareExchange(ref isHTTPManagerOnUpdateRunning, 1, 0) == 0) + { + try + { + HTTPManager.OnUpdate(); + } + finally + { + Interlocked.Exchange(ref isHTTPManagerOnUpdateRunning, 0); + } + } } #if UNITY_EDITOR @@ -179,7 +289,9 @@ void Update() void OnPlayModeStateChanged(UnityEditor.PlayModeStateChange playMode) { if (playMode == UnityEditor.PlayModeStateChange.EnteredPlayMode) + { UnityEditor.EditorApplication.update -= Update; + } else if (playMode == UnityEditor.PlayModeStateChange.EnteredEditMode) { UnityEditor.EditorApplication.update -= Update; @@ -208,7 +320,7 @@ void OnDisable() #if UNITY_EDITOR if (UnityEditor.EditorApplication.isPlaying) #endif - OnApplicationQuit(); + UnityApplication_WantsToQuit(); } void OnApplicationPause(bool isPaused) @@ -219,9 +331,9 @@ void OnApplicationPause(bool isPaused) HTTPUpdateDelegator.OnApplicationForegroundStateChanged(isPaused); } - void OnApplicationQuit() + private static bool UnityApplication_WantsToQuit() { - HTTPManager.Logger.Information("HTTPUpdateDelegator", "OnApplicationQuit Called!"); + HTTPManager.Logger.Information("HTTPUpdateDelegator", "UnityApplication_WantsToQuit Called!"); if (OnBeforeApplicationQuit != null) { @@ -229,24 +341,27 @@ void OnApplicationQuit() { if (!OnBeforeApplicationQuit()) { - HTTPManager.Logger.Information("HTTPUpdateDelegator", "OnBeforeApplicationQuit call returned false, postponing plugin shutdown."); - return; + HTTPManager.Logger.Information("HTTPUpdateDelegator", "OnBeforeApplicationQuit call returned false, postponing plugin and application shutdown."); + return false; } } - catch(System.Exception ex) + catch (System.Exception ex) { HTTPManager.Logger.Exception("HTTPUpdateDelegator", string.Empty, ex); } } IsThreadRunning = false; + Instance.PingUpdateThread(); if (!IsCreated) - return; + return true; IsCreated = false; HTTPManager.OnQuit(); + + return true; } } } diff --git a/Assets/URS/Best HTTP/Source/JSON/JSON.cs b/Assets/URS/Best HTTP/Source/JSON/JSON.cs index ccfef9e..e0898cb 100644 --- a/Assets/URS/Best HTTP/Source/JSON/JSON.cs +++ b/Assets/URS/Best HTTP/Source/JSON/JSON.cs @@ -4,6 +4,8 @@ using System.Globalization; using System.Text; +using BestHTTP.PlatformSupport.Text; + namespace BestHTTP.JSON { /// @@ -69,9 +71,11 @@ public static object Decode(string json, ref bool success) /// A JSON encoded string, or null if object 'json' is not serializable public static string Encode(object json) { - StringBuilder builder = new StringBuilder(BUILDER_CAPACITY); - bool success = SerializeValue(json, builder); - return (success ? builder.ToString() : null); + StringBuilder builder = StringBuilderPool.Get(BUILDER_CAPACITY); //new StringBuilder(BUILDER_CAPACITY); + + bool success = SerializeValue(json, builder); + + return (success ? StringBuilderPool.ReleaseAndGrab(builder) : null); } protected static Dictionary ParseObject(char[] json, ref int index, ref bool success) @@ -184,8 +188,9 @@ protected static object ParseValue(char[] json, ref int index, ref bool success) protected static string ParseString(char[] json, ref int index, ref bool success) { - StringBuilder s = new StringBuilder(BUILDER_CAPACITY); - char c; + StringBuilder s = StringBuilderPool.Get(BUILDER_CAPACITY); //new StringBuilder(BUILDER_CAPACITY); + + char c; EatWhitespace(json, ref index); @@ -253,7 +258,7 @@ protected static string ParseString(char[] json, ref int index, ref bool success return null; } - return s.ToString(); + return StringBuilderPool.ReleaseAndGrab(s); } protected static double ParseNumber(char[] json, ref int index, ref bool success) @@ -484,4 +489,4 @@ protected static bool SerializeNumber(double number, StringBuilder builder) return true; } } -} \ No newline at end of file +} diff --git a/Assets/URS/Best HTTP/Source/JSON/LitJson/JsonReader.cs b/Assets/URS/Best HTTP/Source/JSON/LitJson/JsonReader.cs index cd1b5b6..60cb905 100644 --- a/Assets/URS/Best HTTP/Source/JSON/LitJson/JsonReader.cs +++ b/Assets/URS/Best HTTP/Source/JSON/LitJson/JsonReader.cs @@ -398,6 +398,7 @@ public void Close () { using(reader){} } + lexer.Clear(); reader = null; } diff --git a/Assets/URS/Best HTTP/Source/JSON/LitJson/Lexer.cs b/Assets/URS/Best HTTP/Source/JSON/LitJson/Lexer.cs index 89232e5..39f2736 100644 --- a/Assets/URS/Best HTTP/Source/JSON/LitJson/Lexer.cs +++ b/Assets/URS/Best HTTP/Source/JSON/LitJson/Lexer.cs @@ -14,6 +14,7 @@ using System.IO; using System.Text; +using BestHTTP.PlatformSupport.Text; namespace BestHTTP.JSON.LitJson { @@ -86,7 +87,7 @@ public Lexer (TextReader reader) allow_single_quoted_strings = true; input_buffer = 0; - string_buffer = new StringBuilder (128); + string_buffer = StringBuilderPool.Get(128); // new StringBuilder (128); state = 1; end_of_input = false; this.reader = reader; @@ -908,5 +909,10 @@ private void UngetChar () { input_buffer = input_char; } + + public void Clear() + { + StringBuilderPool.Release(this.string_buffer); + } } } diff --git a/Assets/URS/Best HTTP/Source/Logger/LoggingContext.cs b/Assets/URS/Best HTTP/Source/Logger/LoggingContext.cs index 2778cc6..87d99b7 100644 --- a/Assets/URS/Best HTTP/Source/Logger/LoggingContext.cs +++ b/Assets/URS/Best HTTP/Source/Logger/LoggingContext.cs @@ -25,13 +25,19 @@ private struct LoggingContextField } private List fields = null; + private static System.Random random = new System.Random(); private LoggingContext() { } public LoggingContext(object boundto) { - Add("TypeName", boundto.GetType().Name); - Add("Hash", boundto.GetHashCode()); + var name = boundto.GetType().Name; + Add("TypeName", name); + + long hash = 0; + lock (random) + hash = ((long)boundto.GetHashCode() << 32 | (long)name.GetHashCode()) ^ ((long)this.GetHashCode() << 16) | (long)(random.Next(int.MaxValue) << 32) | (long)random.Next(int.MaxValue); + Add("Hash", hash); } public void Add(string key, long value) @@ -152,7 +158,8 @@ public void ToJson(System.Text.StringBuilder sb) public static string Escape(string original) { - return new StringBuilder(original) + return PlatformSupport.Text.StringBuilderPool.ReleaseAndGrab(PlatformSupport.Text.StringBuilderPool.Get(1) + .Append(original) .Replace("\\", "\\\\") .Replace("\"", "\\\"") .Replace("/", "\\/") @@ -160,8 +167,7 @@ public static string Escape(string original) .Replace("\f", "\\f") .Replace("\n", "\\n") .Replace("\r", "\\r") - .Replace("\t", "\\t") - .ToString(); + .Replace("\t", "\\t")); } } } diff --git a/Assets/URS/Best HTTP/Source/Logger/ThreadedLogger.cs b/Assets/URS/Best HTTP/Source/Logger/ThreadedLogger.cs index e2f5dec..b42eed0 100644 --- a/Assets/URS/Best HTTP/Source/Logger/ThreadedLogger.cs +++ b/Assets/URS/Best HTTP/Source/Logger/ThreadedLogger.cs @@ -2,11 +2,13 @@ using System.Collections.Concurrent; using System.Text; +using BestHTTP.PlatformSupport.Threading; + namespace BestHTTP.Logger { - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] + + + public sealed class ThreadedLogger : BestHTTP.Logger.ILogger, IDisposable { public Loglevels Level { get; set; } @@ -123,7 +125,7 @@ private void AddJob(Loglevels level, string div, string msg, Exception ex, Loggi #if !UNITY_WEBGL || UNITY_EDITOR private void ThreadFunc() { - System.Threading.Thread.CurrentThread.Name = "BestHTTP.Logger"; + ThreadedRunner.SetThreadName("BestHTTP.Logger"); try { do diff --git a/Assets/URS/Best HTTP/Source/PlatformSupport/Memory/BufferPool.cs b/Assets/URS/Best HTTP/Source/PlatformSupport/Memory/BufferPool.cs index 31e4fe7..7adc0db 100644 --- a/Assets/URS/Best HTTP/Source/PlatformSupport/Memory/BufferPool.cs +++ b/Assets/URS/Best HTTP/Source/PlatformSupport/Memory/BufferPool.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; -using System.Text; using System.Threading; using BestHTTP.PlatformSupport.Threading; +using System.Linq; #if NET_STANDARD_2_0 || NETFX_CORE using System.Runtime.CompilerServices; @@ -11,211 +11,6 @@ namespace BestHTTP.PlatformSupport.Memory { - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] - public struct BufferSegment - { - private const int ToStringMaxDumpLength = 128; - - public static readonly BufferSegment Empty = new BufferSegment(null, 0, 0); - - public readonly byte[] Data; - public readonly int Offset; - public readonly int Count; - - public BufferSegment(byte[] data, int offset, int count) - { - this.Data = data; - this.Offset = offset; - this.Count = count; - } - - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - public override bool Equals(object obj) - { - if (obj == null || !(obj is BufferSegment)) - return false; - - return Equals((BufferSegment)obj); - } - - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - public bool Equals(BufferSegment other) - { - return this.Data == other.Data && - this.Offset == other.Offset && - this.Count == other.Count; - } - - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - public override int GetHashCode() - { - return (this.Data != null ? this.Data.GetHashCode() : 0) * 21 + this.Offset + this.Count; - } - - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - public static bool operator ==(BufferSegment left, BufferSegment right) - { - return left.Equals(right); - } - - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - public static bool operator !=(BufferSegment left, BufferSegment right) - { - return !left.Equals(right); - } - - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - public override string ToString() - { - var sb = new System.Text.StringBuilder("[BufferSegment "); - sb.AppendFormat("Offset: {0} ", this.Offset); - sb.AppendFormat("Count: {0} ", this.Count); - sb.Append("Data: ["); - - if (this.Count > 0) - { - if (this.Count <= ToStringMaxDumpLength) - { - sb.AppendFormat("{0:X2}", this.Data[this.Offset]); - for (int i = 1; i < this.Count; ++i) - sb.AppendFormat(", {0:X2}", this.Data[this.Offset + i]); - } - else - sb.Append("..."); - } - - sb.Append("]]"); - return sb.ToString(); - } - } - - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] - public struct PooledBuffer : IDisposable - { - public byte[] Data; - public int Length; - - public void Dispose() - { - if (this.Data != null) - BufferPool.Release(this.Data); - this.Data = null; - } - } - - /// - /// Private data struct that contains the size <-> byte arrays mapping. - /// - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] - struct BufferStore - { - /// - /// Size/length of the arrays stored in the buffers. - /// - public readonly long Size; - - /// - /// - /// - public List buffers; - - public BufferStore(long size) - { - this.Size = size; - this.buffers = new List(); - } - - /// - /// Create a new store with its first byte[] to store. - /// - public BufferStore(long size, byte[] buffer) - : this(size) - { - this.buffers.Add(new BufferDesc(buffer)); - } - - public override string ToString() - { - return string.Format("[BufferStore Size: {0:N0}, Buffers: {1}]", this.Size, this.buffers.Count); - } - } - - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] - struct BufferDesc - { - public static readonly BufferDesc Empty = new BufferDesc(null); - - /// - /// The actual reference to the stored byte array. - /// - public byte[] buffer; - - /// - /// When the buffer is put back to the pool. Based on this value the pool will calculate the age of the buffer. - /// - public DateTime released; - -#if UNITY_EDITOR - public string stackTrace; -#endif - - public BufferDesc(byte[] buff) - { - this.buffer = buff; - this.released = DateTime.UtcNow; -#if UNITY_EDITOR - if (BufferPool.EnableDebugStackTraceCollection) - this.stackTrace = ProcessStackTrace(System.Environment.StackTrace); - else - this.stackTrace = string.Empty; -#endif - } - -#if UNITY_EDITOR - private static string ProcessStackTrace(string stackTrace) - { - if (string.IsNullOrEmpty(stackTrace)) - return null; - - var lines = stackTrace.Split('\n'); - - StringBuilder sb = new StringBuilder(lines.Length - 3); - // skip top 4 lines that would show the logger. - for (int i = 3; i < lines.Length; ++i) - sb.Append(lines[i].Replace("BestHTTP.", "")); - - return sb.ToString(); - } -#endif - - public override string ToString() - { -#if UNITY_EDITOR - if (BufferPool.EnableDebugStackTraceCollection) - return string.Format("[BufferDesc Size: {0}, Released: {1}, Released StackTrace: {2}]", this.buffer.Length, DateTime.UtcNow - this.released, this.stackTrace); - else - return string.Format("[BufferDesc Size: {0}, Released: {1}]", this.buffer.Length, DateTime.UtcNow - this.released); -#else - return string.Format("[BufferDesc Size: {0}, Released: {1}]", this.buffer.Length, DateTime.UtcNow - this.released); -#endif - } - } - - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] public static class BufferPool { @@ -260,7 +55,7 @@ public static bool IsEnabled { /// /// Maximum accumulated size of the stored buffers. /// - public static long MaxPoolSize = 10 * 1024 * 1024; + public static long MaxPoolSize = 30 * 1024 * 1024; /// /// Whether to remove empty buffer stores from the free list. @@ -272,13 +67,6 @@ public static bool IsEnabled { /// public static bool IsDoubleReleaseCheckEnabled = false; -#if UNITY_EDITOR - /// - /// When set to true, the plugin collects Get and Release stack trace informations. - /// - public static bool EnableDebugStackTraceCollection = false; -#endif - // It must be sorted by buffer size! private readonly static List FreeBuffers = new List(); private static DateTime lastMaintenance = DateTime.MinValue; @@ -287,15 +75,15 @@ public static bool IsEnabled { private static long PoolSize = 0; private static long GetBuffers = 0; private static long ReleaseBuffers = 0; - private readonly static System.Text.StringBuilder statiscticsBuilder = new System.Text.StringBuilder(); - - private readonly static ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); + private static long Borrowed = 0; + private static long ArrayAllocations = 0; -#if UNITY_EDITOR - private readonly static Dictionary getStackStats = new Dictionary(); - private readonly static Dictionary releaseStackStats = new Dictionary(); +#if BESTHTTP_ENABLE_BUFFERPOOL_BORROWED_BUFFERS_COLLECTION + private static Dictionary BorrowedBuffers = new Dictionary(); #endif + private readonly static ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); + static BufferPool() { #if UNITY_EDITOR @@ -318,21 +106,6 @@ public static byte[] Get(long size, bool canBeLarger) if (size == 0) return BufferPool.NoData; -#if UNITY_EDITOR - if (EnableDebugStackTraceCollection) - { - lock (getStackStats) - { - string stack = ProcessStackTrace(System.Environment.StackTrace); - int value; - if (!getStackStats.TryGetValue(stack, out value)) - getStackStats.Add(stack, 1); - else - getStackStats[stack] = ++value; - } - } -#endif - if (canBeLarger) { if (size < MinBufferSize) @@ -340,17 +113,54 @@ public static byte[] Get(long size, bool canBeLarger) else if (!IsPowerOfTwo(size)) size = NextPowerOf2(size); } + else + { + if (size < MinBufferSize) + return new byte[size]; + } if (FreeBuffers.Count == 0) - return new byte[size]; + { + Interlocked.Add(ref Borrowed, size); + Interlocked.Increment(ref ArrayAllocations); + + var result = new byte[size]; + +#if BESTHTTP_ENABLE_BUFFERPOOL_BORROWED_BUFFERS_COLLECTION + lock (FreeBuffers) + BorrowedBuffers.Add(result, ProcessStackTrace(Environment.StackTrace)); +#endif + + return result; + } BufferDesc bufferDesc = FindFreeBuffer(size, canBeLarger); if (bufferDesc.buffer == null) - return new byte[size]; + { + Interlocked.Add(ref Borrowed, size); + Interlocked.Increment(ref ArrayAllocations); + + var result = new byte[size]; + +#if BESTHTTP_ENABLE_BUFFERPOOL_BORROWED_BUFFERS_COLLECTION + lock (FreeBuffers) + BorrowedBuffers.Add(result, ProcessStackTrace(Environment.StackTrace)); +#endif + + return result; + } else + { +#if BESTHTTP_ENABLE_BUFFERPOOL_BORROWED_BUFFERS_COLLECTION + lock (FreeBuffers) + BorrowedBuffers.Add(bufferDesc.buffer, ProcessStackTrace(Environment.StackTrace)); +#endif + Interlocked.Increment(ref GetBuffers); + } + Interlocked.Add(ref Borrowed, bufferDesc.buffer.Length); Interlocked.Add(ref PoolSize, -bufferDesc.buffer.Length); return bufferDesc.buffer; @@ -360,6 +170,9 @@ public static byte[] Get(long size, bool canBeLarger) /// Release back a BufferSegment's data to the pool. /// /// +#if NET_STANDARD_2_0 || NETFX_CORE + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif public static void Release(BufferSegment segment) { Release(segment.Data); @@ -373,31 +186,25 @@ public static void Release(byte[] buffer) if (!_isEnabled || buffer == null) return; -#if UNITY_EDITOR - if (EnableDebugStackTraceCollection) - { - lock (releaseStackStats) - { - string stack = ProcessStackTrace(System.Environment.StackTrace); - int value; - if (!releaseStackStats.TryGetValue(stack, out value)) - releaseStackStats.Add(stack, 1); - else - releaseStackStats[stack] = ++value; - } - } + int size = buffer.Length; + +#if BESTHTTP_ENABLE_BUFFERPOOL_BORROWED_BUFFERS_COLLECTION + lock (FreeBuffers) + BorrowedBuffers.Remove(buffer); #endif - int size = buffer.Length; + Interlocked.Add(ref Borrowed, -size); - if (size == 0 || size > MaxBufferSize) + if (size == 0 || size < MinBufferSize || size > MaxBufferSize) return; using (new WriteLock(rwLock)) { - if (PoolSize + size > MaxPoolSize) + var ps = Interlocked.Read(ref PoolSize); + if (ps + size > MaxPoolSize) return; - PoolSize += size; + + Interlocked.Add(ref PoolSize, size); ReleaseBuffers++; @@ -430,64 +237,78 @@ public static byte[] Resize(ref byte[] buffer, int newSize, bool canBeLarger, bo return buffer = newBuf; } - /// - /// Get textual statistics about the buffer pool. - /// - public static string GetStatistics(bool showEmptyBuffers = true) + + public static KeyValuePair[] GetBorrowedBuffers() + { +#if BESTHTTP_ENABLE_BUFFERPOOL_BORROWED_BUFFERS_COLLECTION + lock (FreeBuffers) + return BorrowedBuffers.ToArray(); +#else + return new KeyValuePair[0]; +#endif + } + +#if true //UNITY_EDITOR + public struct BufferStats + { + public long Size; + public int Count; + } + + public struct BufferPoolStats + { + public long GetBuffers; + public long ReleaseBuffers; + public long PoolSize; + public long MaxPoolSize; + public long MinBufferSize; + public long MaxBufferSize; + + public long Borrowed; + public long ArrayAllocations; + + public int FreeBufferCount; + public List FreeBufferStats; + + public TimeSpan NextMaintenance; + } + + public static void GetStatistics(ref BufferPoolStats stats) { using (new ReadLock(rwLock)) { - statiscticsBuilder.Length = 0; - statiscticsBuilder.AppendFormat("Pooled array reused count: {0:N0}\n", GetBuffers); - statiscticsBuilder.AppendFormat("Release call count: {0:N0}\n", ReleaseBuffers); - statiscticsBuilder.AppendFormat("PoolSize: {0:N0}\n", PoolSize); - statiscticsBuilder.AppendFormat("Buffers: {0}\n", FreeBuffers.Count); + stats.GetBuffers = GetBuffers; + stats.ReleaseBuffers = ReleaseBuffers; + stats.PoolSize = PoolSize; + stats.MinBufferSize = MinBufferSize; + stats.MaxBufferSize = MaxBufferSize; + stats.MaxPoolSize = MaxPoolSize; + + stats.Borrowed = Borrowed; + stats.ArrayAllocations = ArrayAllocations; + + stats.FreeBufferCount = FreeBuffers.Count; + if (stats.FreeBufferStats == null) + stats.FreeBufferStats = new List(FreeBuffers.Count); + else + stats.FreeBufferStats.Clear(); for (int i = 0; i < FreeBuffers.Count; ++i) { BufferStore store = FreeBuffers[i]; List buffers = store.buffers; - if (showEmptyBuffers || buffers.Count > 0) - statiscticsBuilder.AppendFormat("- Size: {0:N0} Count: {1:N0}\n", store.Size, buffers.Count); - } - -#if UNITY_EDITOR - if (EnableDebugStackTraceCollection) - { - lock (getStackStats) - { - int sum = 0; - foreach (var kvp in getStackStats) - sum += kvp.Value; - - statiscticsBuilder.AppendFormat("Get stacks: {0:N0}\n", sum); - - foreach (var kvp in getStackStats) - { - statiscticsBuilder.AppendFormat("- {0:N0}: {1}\n", kvp.Value, kvp.Key); - } - } - - lock (releaseStackStats) - { - int sum = 0; - foreach (var kvp in releaseStackStats) - sum += kvp.Value; + BufferStats bufferStats = new BufferStats(); + bufferStats.Size = store.Size; + bufferStats.Count = buffers.Count; - statiscticsBuilder.AppendFormat("Release stacks: {0:N0}\n", sum); - - foreach (var kvp in releaseStackStats) - { - statiscticsBuilder.AppendFormat("- {0:N0}: {1}\n", kvp.Value, kvp.Key); - } - } + stats.FreeBufferStats.Add(bufferStats); } -#endif - return statiscticsBuilder.ToString(); + stats.NextMaintenance = (lastMaintenance + RunMaintenanceEvery) - DateTime.UtcNow; } } +#endif /// /// Remove all stored entries instantly. @@ -497,7 +318,7 @@ public static void Clear() using (new WriteLock(rwLock)) { FreeBuffers.Clear(); - PoolSize = 0; + Interlocked.Exchange(ref PoolSize, 0); } } @@ -511,9 +332,6 @@ internal static void Maintain() return; lastMaintenance = now; - //if (HTTPManager.Logger.Level == Logger.Loglevels.All) - // HTTPManager.Logger.Information("BufferPool", "Before Maintain: " + GetStatistics()); - DateTime olderThan = now - RemoveOlderThan; using (new WriteLock(rwLock)) { @@ -542,9 +360,6 @@ internal static void Maintain() FreeBuffers.RemoveAt(i--); } } - - //if (HTTPManager.Logger.Level == Logger.Loglevels.All) - // HTTPManager.Logger.Information("BufferPool", "After Maintain: " + GetStatistics()); } #region Private helper functions @@ -552,7 +367,7 @@ internal static void Maintain() #if NET_STANDARD_2_0 || NETFX_CORE [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif - private static bool IsPowerOfTwo(long x) + public static bool IsPowerOfTwo(long x) { return (x & (x - 1)) == 0; } @@ -560,7 +375,7 @@ private static bool IsPowerOfTwo(long x) #if NET_STANDARD_2_0 || NETFX_CORE [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif - private static long NextPowerOf2(long x) + public static long NextPowerOf2(long x) { long pow = 1; while (pow <= x) @@ -652,7 +467,8 @@ private static void AddFreeBuffer(byte[] buffer) FreeBuffers.Add(new BufferStore(bufferLength, buffer)); } -#if UNITY_EDITOR +#if BESTHTTP_ENABLE_BUFFERPOOL_BORROWED_BUFFERS_COLLECTION + private static System.Text.StringBuilder stacktraceBuilder; private static string ProcessStackTrace(string stackTrace) { if (string.IsNullOrEmpty(stackTrace)) @@ -660,12 +476,20 @@ private static string ProcessStackTrace(string stackTrace) var lines = stackTrace.Split('\n'); - StringBuilder sb = new StringBuilder(lines.Length); + if (stacktraceBuilder == null) + stacktraceBuilder = new System.Text.StringBuilder(lines.Length); + else + stacktraceBuilder.Length = 0; + // skip top 4 lines that would show the logger. - for (int i = 2; i < Math.Min(5, lines.Length); ++i) - sb.Append(lines[i].Replace("BestHTTP.", "")); - return sb.ToString(); + for (int i = 0; i < lines.Length; ++i) + if (!lines[i].Contains(".Memory.BufferPool") && + !lines[i].Contains("Environment") && + !lines[i].Contains("System.Threading")) + stacktraceBuilder.Append(lines[i].Replace("BestHTTP.", "")); + + return stacktraceBuilder.ToString(); } #endif diff --git a/Assets/URS/Best HTTP/Source/PlatformSupport/Memory/BufferSegment.cs b/Assets/URS/Best HTTP/Source/PlatformSupport/Memory/BufferSegment.cs new file mode 100644 index 0000000..0140a52 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/PlatformSupport/Memory/BufferSegment.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; + +using BestHTTP.PlatformSupport.Threading; +using System.Collections.Concurrent; +using BestHTTP.PlatformSupport.Text; + +#if NET_STANDARD_2_0 || NETFX_CORE +using System.Runtime.CompilerServices; +#endif + +namespace BestHTTP.PlatformSupport.Memory +{ + [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] + public struct BufferSegment + { + private const int ToStringMaxDumpLength = 128; + + public static readonly BufferSegment Empty = new BufferSegment(null, 0, 0); + + public readonly byte[] Data; + public readonly int Offset; + public readonly int Count; + + public BufferSegment(byte[] data, int offset, int count) + { + this.Data = data; + this.Offset = offset; + this.Count = count; + } + + public BufferSegment Slice(int newOffset) + { + int diff = newOffset - this.Offset; + return new BufferSegment(this.Data, newOffset, this.Count - diff); + } + + public BufferSegment Slice(int offset, int count) + { + return new BufferSegment(this.Data, offset, count); + } + + public override bool Equals(object obj) + { + if (obj == null || !(obj is BufferSegment)) + return false; + + return Equals((BufferSegment)obj); + } + + public bool Equals(BufferSegment other) + { + return this.Data == other.Data && + this.Offset == other.Offset && + this.Count == other.Count; + } + + public override int GetHashCode() + { + return (this.Data != null ? this.Data.GetHashCode() : 0) * 21 + this.Offset + this.Count; + } + + public static bool operator ==(BufferSegment left, BufferSegment right) + { + return left.Equals(right); + } + + public static bool operator !=(BufferSegment left, BufferSegment right) + { + return !left.Equals(right); + } + + public override string ToString() + { + var sb = StringBuilderPool.Get(this.Count + 5); + sb.Append("[BufferSegment "); + sb.AppendFormat("Offset: {0:N0} ", this.Offset); + sb.AppendFormat("Count: {0:N0} ", this.Count); + sb.Append("Data: ["); + + if (this.Count > 0) + { + if (this.Count <= ToStringMaxDumpLength) + { + sb.AppendFormat("{0:X2}", this.Data[this.Offset]); + for (int i = 1; i < this.Count; ++i) + sb.AppendFormat(", {0:X2}", this.Data[this.Offset + i]); + } + else + sb.Append("..."); + } + + sb.Append("]]"); + return StringBuilderPool.ReleaseAndGrab(sb); + } + } +} diff --git a/Assets/URS/Best HTTP/Source/PlatformSupport/Memory/BufferSegment.cs.meta b/Assets/URS/Best HTTP/Source/PlatformSupport/Memory/BufferSegment.cs.meta new file mode 100644 index 0000000..568bdca --- /dev/null +++ b/Assets/URS/Best HTTP/Source/PlatformSupport/Memory/BufferSegment.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 113ff5eff505e8f41bd264ab17bf78b1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/PlatformSupport/Memory/BufferStore.cs b/Assets/URS/Best HTTP/Source/PlatformSupport/Memory/BufferStore.cs new file mode 100644 index 0000000..f6c0af3 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/PlatformSupport/Memory/BufferStore.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; + +using BestHTTP.PlatformSupport.Threading; +using System.Collections.Concurrent; + +#if NET_STANDARD_2_0 || NETFX_CORE +using System.Runtime.CompilerServices; +#endif + +namespace BestHTTP.PlatformSupport.Memory +{ + [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] + public struct PooledBuffer : IDisposable + { + public byte[] Data; + public int Length; + + public PooledBuffer(byte[] data) + { + this.Data = data; + this.Length = data != null ? data.Length : 0; + } + + public PooledBuffer(BufferSegment segment) + { + this.Data = segment.Data; + this.Length = segment.Count; + } + + public PooledBuffer(byte[] data, int length) + { + this.Data = data; + this.Length = length; + } + + public void Dispose() + { + if (this.Data != null) + BufferPool.Release(this.Data); + this.Data = null; + } + } + + /// + /// Private data struct that contains the size <-> byte arrays mapping. + /// + [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] + struct BufferStore + { + /// + /// Size/length of the arrays stored in the buffers. + /// + public readonly long Size; + + /// + /// + /// + public List buffers; + + public BufferStore(long size) + { + this.Size = size; + this.buffers = new List(); + } + + /// + /// Create a new store with its first byte[] to store. + /// + public BufferStore(long size, byte[] buffer) + : this(size) + { + this.buffers.Add(new BufferDesc(buffer)); + } + + public override string ToString() + { + return string.Format("[BufferStore Size: {0:N0}, Buffers: {1}]", this.Size, this.buffers.Count); + } + } + + [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] + struct BufferDesc + { + public static readonly BufferDesc Empty = new BufferDesc(null); + + /// + /// The actual reference to the stored byte array. + /// + public byte[] buffer; + + /// + /// When the buffer is put back to the pool. Based on this value the pool will calculate the age of the buffer. + /// + public DateTime released; + + public BufferDesc(byte[] buff) + { + this.buffer = buff; + this.released = DateTime.UtcNow; + } + public override string ToString() + { + return string.Format("[BufferDesc Size: {0}, Released: {1}]", this.buffer.Length, DateTime.UtcNow - this.released); + } + } +} diff --git a/Assets/URS/Best HTTP/Source/PlatformSupport/Memory/BufferStore.cs.meta b/Assets/URS/Best HTTP/Source/PlatformSupport/Memory/BufferStore.cs.meta new file mode 100644 index 0000000..87fab53 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/PlatformSupport/Memory/BufferStore.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d6021d9bfd261f642a7da50ccb964482 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/PlatformSupport/TcpClient/TcpClient.cs b/Assets/URS/Best HTTP/Source/PlatformSupport/TcpClient/TcpClient.cs index 04e98c6..2c5c55d 100644 --- a/Assets/URS/Best HTTP/Source/PlatformSupport/TcpClient/TcpClient.cs +++ b/Assets/URS/Best HTTP/Source/PlatformSupport/TcpClient/TcpClient.cs @@ -34,6 +34,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; +using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; @@ -438,11 +439,14 @@ public void Connect(IPAddress[] ipAddresses, int port, HTTPRequest request) throw new ArgumentNullException("ipAddresses"); } - for (int i = 0; i < ipAddresses.Length; i++) + List addresses = new List(ipAddresses); + addresses.Sort((a, b) => a.AddressFamily - b.AddressFamily); + + for (int i = 0; i < addresses.Count; i++) { try { - IPAddress address = ipAddresses[i]; + IPAddress address = addresses[i]; if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) @@ -522,7 +526,7 @@ TCP_KEEPCNT 6 // Number of keepalives before death * address, so re-throw the * exception */ - if (i == ipAddresses.Length - 1) + if (i == addresses.Count - 1) { throw e; } diff --git a/Assets/URS/Setting/Editor.meta b/Assets/URS/Best HTTP/Source/PlatformSupport/Text.meta similarity index 77% rename from Assets/URS/Setting/Editor.meta rename to Assets/URS/Best HTTP/Source/PlatformSupport/Text.meta index 52e43e7..4173860 100644 --- a/Assets/URS/Setting/Editor.meta +++ b/Assets/URS/Best HTTP/Source/PlatformSupport/Text.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: f302e55fba97a884caf6b9a3ffc0fd07 +guid: dc866afc8c452ac4bab7c1f770dc92e4 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Assets/URS/Best HTTP/Source/PlatformSupport/Text/StringBuilderPool.cs b/Assets/URS/Best HTTP/Source/PlatformSupport/Text/StringBuilderPool.cs new file mode 100644 index 0000000..ef01b6d --- /dev/null +++ b/Assets/URS/Best HTTP/Source/PlatformSupport/Text/StringBuilderPool.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; + +using BestHTTP.PlatformSupport.Threading; + +namespace BestHTTP.PlatformSupport.Text +{ + [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] + public static class StringBuilderPool + { + /// + /// Setting this property to false the pooling mechanism can be disabled. + /// + public static bool IsEnabled + { + get { return _isEnabled; } + set + { + _isEnabled = value; + + // When set to non-enabled remove all stored entries + if (!_isEnabled) + Clear(); + } + } + private static volatile bool _isEnabled = true; + + /// + /// Buffer entries that released back to the pool and older than this value are moved when next maintenance is triggered. + /// + public static TimeSpan RemoveOlderThan = TimeSpan.FromSeconds(10); + + /// + /// How often pool maintenance must run. + /// + public static TimeSpan RunMaintenanceEvery = TimeSpan.FromSeconds(5); + + private static DateTime lastMaintenance = DateTime.MinValue; + + private readonly static ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); + + struct BuilderShelf + { + public StringBuilder builder; + public DateTime released; + + public BuilderShelf(StringBuilder sb) + { + this.builder = sb; + this.released = DateTime.UtcNow; + } + } + + private static List pooledBuilders = new List(); + + public static StringBuilder Get(int lengthHint) + { + if (!_isEnabled) + return new StringBuilder(lengthHint); + + using (new WriteLock(rwLock)) + { + for (int i = pooledBuilders.Count - 1; i >= 0; i--) + { + BuilderShelf shelf = pooledBuilders[i]; + if (shelf.builder.Capacity >= lengthHint) + { + pooledBuilders.RemoveAt(i); + return shelf.builder; + } + } + + // no builder found with lengthHint, take the first available + if (pooledBuilders.Count > 0) + { + BuilderShelf shelf = pooledBuilders[pooledBuilders.Count - 1]; + pooledBuilders.RemoveAt(pooledBuilders.Count - 1); + return shelf.builder; + } + } + + return new StringBuilder(lengthHint); + } + + public static void Release(StringBuilder builder) + { + if (builder == null) + return; + + if (!_isEnabled) + return; + + builder.Clear(); + + using (new WriteLock(rwLock)) + pooledBuilders.Add(new BuilderShelf(builder)); + } + + public static string ReleaseAndGrab(StringBuilder builder) + { + if (builder == null) + return null; + + var result = builder.ToString(); + if (!_isEnabled) + return result; + + builder.Clear(); + + using (new WriteLock(rwLock)) + pooledBuilders.Add(new BuilderShelf(builder)); + + return result; + } + + internal static void Maintain() + { + DateTime now = DateTime.UtcNow; + if (!_isEnabled || lastMaintenance + RunMaintenanceEvery > now) + return; + lastMaintenance = now; + + DateTime olderThan = now - RemoveOlderThan; + using (new WriteLock(rwLock)) + { + for (int i = 0; i < pooledBuilders.Count; i++) + { + BuilderShelf shelf = pooledBuilders[i]; + + if (shelf.released < olderThan) + pooledBuilders.RemoveAt(i--); + } + } + } + + public static void Clear() + { + using (new WriteLock(rwLock)) + pooledBuilders.Clear(); + } + } +} diff --git a/Assets/URS/Best HTTP/Source/PlatformSupport/Text/StringBuilderPool.cs.meta b/Assets/URS/Best HTTP/Source/PlatformSupport/Text/StringBuilderPool.cs.meta new file mode 100644 index 0000000..ec6a1df --- /dev/null +++ b/Assets/URS/Best HTTP/Source/PlatformSupport/Text/StringBuilderPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: be78127ff31739148be6638f5e141470 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/PlatformSupport/Threading/ThreadedRunner.cs b/Assets/URS/Best HTTP/Source/PlatformSupport/Threading/ThreadedRunner.cs index 7c74ef2..d76002e 100644 --- a/Assets/URS/Best HTTP/Source/PlatformSupport/Threading/ThreadedRunner.cs +++ b/Assets/URS/Best HTTP/Source/PlatformSupport/Threading/ThreadedRunner.cs @@ -9,6 +9,19 @@ namespace BestHTTP.PlatformSupport.Threading { public static class ThreadedRunner { + public static void SetThreadName(string name) + { + try + { + System.Threading.Thread.CurrentThread.Name = name; + } + catch(Exception ex) + { + if (HTTPManager.Logger.Level == Logger.Loglevels.All) + HTTPManager.Logger.Exception("ThreadedRunner", "SetThreadName", ex); + } + } + public static void RunShortLiving(Action job, T param) { #if NETFX_CORE diff --git a/Assets/URS/Setting/Editor/Settings.meta b/Assets/URS/Best HTTP/Source/Proxies/Autodetect.meta similarity index 77% rename from Assets/URS/Setting/Editor/Settings.meta rename to Assets/URS/Best HTTP/Source/Proxies/Autodetect.meta index 274b10d..237c7a2 100644 --- a/Assets/URS/Setting/Editor/Settings.meta +++ b/Assets/URS/Best HTTP/Source/Proxies/Autodetect.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: cce5c77bcd5840d4fb8c9be8c016686a +guid: 855ac4bfd19c3a4409869bf1ac3f6b55 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Assets/URS/Best HTTP/Source/Proxies/Autodetect/AndroidProxyDetector.cs b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/AndroidProxyDetector.cs new file mode 100644 index 0000000..d4006e2 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/AndroidProxyDetector.cs @@ -0,0 +1,59 @@ +#if !BESTHTTP_DISABLE_PROXY && UNITY_ANDROID && !UNITY_EDITOR +using System; + +using UnityEngine; + +namespace BestHTTP.Proxies.Autodetect +{ + public sealed class AndroidProxyDetector : IProxyDetector + { + private const string ClassPath = "com.besthttp.proxy.ProxyFinder"; + + Proxy IProxyDetector.GetProxy(HTTPRequest request) + { + try + { + var proxyUrl = FindFor(request.CurrentUri.ToString()); + + HTTPManager.Logger.Information(nameof(AndroidProxyDetector), $"{nameof(IProxyDetector.GetProxy)} - FindFor returned with proxyUrl: '{proxyUrl}'", request.Context); + + if (proxyUrl == null) + return null; + + if (proxyUrl.StartsWith("socks://", StringComparison.OrdinalIgnoreCase)) + { + return new SOCKSProxy(new Uri(proxyUrl), null); + } + else if (proxyUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) + { + return new HTTPProxy(new Uri(proxyUrl)); + } + else + { + HTTPManager.Logger.Warning(nameof(AndroidProxyDetector), $"{nameof(IProxyDetector.GetProxy)} - FindFor returned with unknown format. proxyUrl: '{proxyUrl}'", request.Context); + } + } + catch (Exception ex) + { + HTTPManager.Logger.Exception(nameof(AndroidProxyDetector), nameof(IProxyDetector.GetProxy), ex, request.Context); + } + + return null; + } + + private string FindFor(string uriStr) => Call("FindFor", uriStr); + + private static void Call(string methodName, params object[] args) + { + using (var javaClass = new AndroidJavaClass(ClassPath)) + javaClass.CallStatic(methodName, args); + } + + private static T Call(string methodName, params object[] args) + { + using (var javaClass = new AndroidJavaClass(ClassPath)) + return javaClass.CallStatic(methodName, args); + } + } +} +#endif diff --git a/Assets/URS/Best HTTP/Source/Proxies/Autodetect/AndroidProxyDetector.cs.meta b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/AndroidProxyDetector.cs.meta new file mode 100644 index 0000000..d98ef43 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/AndroidProxyDetector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ac7faed5a1e9336479173f34a38a8965 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/Proxies/Autodetect/EnvironmentProxyDetector.cs b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/EnvironmentProxyDetector.cs new file mode 100644 index 0000000..19a378e --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/EnvironmentProxyDetector.cs @@ -0,0 +1,80 @@ +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) +using System; +using System.Linq; + +using BestHTTP.Connections; + +// Examples on proxy strings: +// https://gist.github.com/yougg/5d2b3353fc5e197a0917aae0b3287d64 + +namespace BestHTTP.Proxies.Autodetect +{ + /// + /// Based on https://curl.se/docs/manual.html "Environment Variables" section. + /// + public sealed class EnvironmentProxyDetector : IProxyDetector + { + private Proxy _cachedProxy; + + Proxy IProxyDetector.GetProxy(HTTPRequest request) + { + if (this._cachedProxy != null) + return this._cachedProxy; + + string proxyUrl = null; + + if (HTTPProtocolFactory.IsSecureProtocol(request.CurrentUri)) + { + proxyUrl = GetEnv("HTTPS_PROXY"); + HTTPManager.Logger.Information(nameof(EnvironmentProxyDetector), $"{nameof(IProxyDetector.GetProxy)} - HTTPS_PROXY: '{proxyUrl}'", request.Context); + } + else + { + proxyUrl = GetEnv("HTTP_PROXY"); + HTTPManager.Logger.Information(nameof(EnvironmentProxyDetector), $"{nameof(IProxyDetector.GetProxy)} - HTTP_PROXY: '{proxyUrl}'", request.Context); + } + + if (proxyUrl == null) + { + proxyUrl = GetEnv("ALL_PROXY"); + } + else + HTTPManager.Logger.Information(nameof(EnvironmentProxyDetector), $"{nameof(IProxyDetector.GetProxy)} - ALL_PROXY: '{proxyUrl}'", request.Context); + + if (string.IsNullOrEmpty(proxyUrl)) + return null; + + // if the url is just a host[:port], add the http:// part too. Checking for :// should keep and treat the socks:// scheme too. + if (proxyUrl.IndexOf("://") == -1 && !proxyUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + proxyUrl = "http://" + proxyUrl; + + string exceptionList = null; + try + { + var proxyUri = new Uri(proxyUrl); + + Proxy proxy = null; + if (proxyUri.Scheme.StartsWith("socks", StringComparison.OrdinalIgnoreCase)) + proxy = new SOCKSProxy(proxyUri, null); + else + proxy = new HTTPProxy(proxyUri); + + // A comma-separated list of host names that should not go through any proxy is set in (only an asterisk, * matches all hosts) + exceptionList = GetEnv("NO_PROXY"); + if (!string.IsNullOrEmpty(exceptionList)) + proxy.Exceptions = exceptionList.Split(';').ToList(); + + return this._cachedProxy = proxy; + } + catch (Exception ex) + { + HTTPManager.Logger.Exception(nameof(EnvironmentProxyDetector), $"GetProxy - proxyUrl: '{proxyUrl}', exceptionList: '{exceptionList}'", ex, request.Context); + } + + return null; + } + + string GetEnv(string key) => System.Environment.GetEnvironmentVariable(key) ?? System.Environment.GetEnvironmentVariable(key.ToLowerInvariant()); + } +} +#endif diff --git a/Assets/URS/Best HTTP/Source/Proxies/Autodetect/EnvironmentProxyDetector.cs.meta b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/EnvironmentProxyDetector.cs.meta new file mode 100644 index 0000000..0107498 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/EnvironmentProxyDetector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 152166acb3a569d45a58d0fa2b33eec3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/Proxies/Autodetect/FrameworkProxyDetector.cs b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/FrameworkProxyDetector.cs new file mode 100644 index 0000000..11e431a --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/FrameworkProxyDetector.cs @@ -0,0 +1,62 @@ +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) + +using System; + +namespace BestHTTP.Proxies.Autodetect +{ + /// + /// This is a detector using the .net framework's implementation. It might work not just under Windows but MacOS and Linux too. + /// + /// + public sealed class FrameworkProxyDetector : IProxyDetector + { + Proxy IProxyDetector.GetProxy(HTTPRequest request) + { + var detectedProxy = System.Net.WebRequest.GetSystemWebProxy() as System.Net.WebProxy; + if (detectedProxy != null && detectedProxy.Address != null) + { + var proxyUri = detectedProxy.GetProxy(request.CurrentUri); + if (proxyUri != null && !proxyUri.Equals(request.CurrentUri)) + { + if (proxyUri.Scheme.StartsWith("socks", StringComparison.OrdinalIgnoreCase)) + { + return SetExceptionList(new SOCKSProxy(proxyUri, null), detectedProxy); + } + else if (proxyUri.Scheme.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + { + return SetExceptionList(new HTTPProxy(proxyUri), detectedProxy); + } + else + { + HTTPManager.Logger.Warning(nameof(FrameworkProxyDetector), $"{nameof(IProxyDetector.GetProxy)} - FindFor returned with unknown format. proxyUri: '{proxyUri}'", request.Context); + } + } + } + + return null; + } + + private Proxy SetExceptionList(Proxy proxy, System.Net.WebProxy detectedProxy) + { + if (detectedProxy.BypassProxyOnLocal) + { + proxy.Exceptions = proxy.Exceptions ?? new System.Collections.Generic.List(); + + proxy.Exceptions.Add("localhost"); + proxy.Exceptions.Add("127.0.0.1"); + } + + // TODO: use BypassList to put more entries to the Exceptions list. + // But because BypassList contains regex strings, we either + // 1.) store and use regex strings in the Exception list (not backward compatible) + // 2.) store non-regex strings but create a new list for regex + // 3.) detect if the stored entry in the Exceptions list is regex or not and use it accordingly + // "^.*\\.httpbin\\.org$" + // https://github.com/Benedicht/BestHTTP-Issues/issues/141 + + return proxy; + } + } +} + +#endif diff --git a/Assets/URS/Best HTTP/Source/Proxies/Autodetect/FrameworkProxyDetector.cs.meta b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/FrameworkProxyDetector.cs.meta new file mode 100644 index 0000000..3d2a505 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/FrameworkProxyDetector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 58ef74f62e307544fa7e434332a6d3ac +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/Proxies/Autodetect/ProgrammaticallyAddedProxyDetector.cs b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/ProgrammaticallyAddedProxyDetector.cs new file mode 100644 index 0000000..b75376a --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/ProgrammaticallyAddedProxyDetector.cs @@ -0,0 +1,14 @@ +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) +namespace BestHTTP.Proxies.Autodetect +{ + /// + /// This one just returns with HTTPManager.Proxy, + /// so when ProgrammaticallyAddedProxyDetector is used in the first place for the ProxyDetector, + /// HTTPManager.Proxy gets the highest priority. + /// + public sealed class ProgrammaticallyAddedProxyDetector : IProxyDetector + { + Proxy IProxyDetector.GetProxy(HTTPRequest request) => HTTPManager.Proxy; + } +} +#endif diff --git a/Assets/URS/Best HTTP/Source/Proxies/Autodetect/ProgrammaticallyAddedProxyDetector.cs.meta b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/ProgrammaticallyAddedProxyDetector.cs.meta new file mode 100644 index 0000000..e253cbd --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/ProgrammaticallyAddedProxyDetector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ad0e404074491274e83de0ce83db8a97 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/Proxies/Autodetect/ProxyDetector.cs b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/ProxyDetector.cs new file mode 100644 index 0000000..9fc35cf --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/ProxyDetector.cs @@ -0,0 +1,145 @@ +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) +using System; + +using BestHTTP.Core; + +namespace BestHTTP.Proxies.Autodetect +{ + public interface IProxyDetector + { + Proxy GetProxy(HTTPRequest request); + } + + public enum ProxyDetectionMode + { + /// + /// In Continouos mode the ProxyDetector will check for a proxy for every request. + /// + Continouos, + + /// + /// This mode will cache the first Proxy found and use it for consecutive requests. + /// + CacheFirstFound + } + + public sealed class ProxyDetector + { + public static IProxyDetector[] GetDefaultDetectors() => new IProxyDetector[] { + // HTTPManager.Proxy has the highest priority + new ProgrammaticallyAddedProxyDetector(), + + // then comes the environment set + new EnvironmentProxyDetector(), + + // .net framework's detector + new FrameworkProxyDetector(), + +#if UNITY_ANDROID && !UNITY_EDITOR + new AndroidProxyDetector(), +#endif + }; + + private IProxyDetector[] _proxyDetectors; + private ProxyDetectionMode _detectionMode; + private bool _attached; + + public ProxyDetector() + : this(ProxyDetectionMode.CacheFirstFound, GetDefaultDetectors()) + { } + + public ProxyDetector(ProxyDetectionMode detectionMode) + :this(detectionMode, GetDefaultDetectors()) + { } + + public ProxyDetector(ProxyDetectionMode detectionMode, IProxyDetector[] proxyDetectors) + { + this._detectionMode = detectionMode; + this._proxyDetectors = proxyDetectors; + + if (this._proxyDetectors != null) + Reattach(); + } + + public void Reattach() + { + HTTPManager.Logger.Information(nameof(ProxyDetector), $"{nameof(Reattach)}({this._attached})"); + + if (!this._attached) + { + RequestEventHelper.OnEvent += OnRequestEvent; + this._attached = true; + } + } + + /// + /// Call Detach() to disable ProxyDetector's logic to find and set a proxy. + /// + public void Detach() + { + HTTPManager.Logger.Information(nameof(ProxyDetector), $"{nameof(Detach)}({this._attached})"); + + if (this._attached) + { + RequestEventHelper.OnEvent -= OnRequestEvent; + this._attached = false; + } + } + + private void OnRequestEvent(RequestEventInfo @event) + { + // The Resend event is raised for every request when it's queued up (sent or redirected). + if (@event.Event == RequestEvents.Resend && @event.SourceRequest.Proxy == null) + { + Uri uri = @event.SourceRequest.CurrentUri; + + HTTPManager.Logger.Information(nameof(ProxyDetector), $"OnRequestEvent(RequestEvents.Resend) uri: '{uri}'", @event.SourceRequest.Context); + + try + { + foreach (var detector in this._proxyDetectors) + { + if (detector == null) + continue; + + if (HTTPManager.Logger.Level == Logger.Loglevels.All) + HTTPManager.Logger.Verbose(nameof(ProxyDetector), $"Calling {detector.GetType().Name}'s GetProxy", @event.SourceRequest.Context); + + var proxy = detector.GetProxy(@event.SourceRequest); + if (proxy != null && proxy.UseProxyForAddress(uri)) + { + if (HTTPManager.Logger.Level == Logger.Loglevels.All) + HTTPManager.Logger.Verbose(nameof(ProxyDetector), $"[{detector.GetType().Name}] Proxy found: {proxy.Address} ", @event.SourceRequest.Context); + + switch (this._detectionMode) + { + case ProxyDetectionMode.Continouos: + @event.SourceRequest.Proxy = proxy; + break; + + case ProxyDetectionMode.CacheFirstFound: + HTTPManager.Proxy = @event.SourceRequest.Proxy = proxy; + + HTTPManager.Logger.Verbose(nameof(ProxyDetector), $"Proxy cached in HTTPManager.Proxy!", @event.SourceRequest.Context); + + Detach(); + break; + } + + return; + } + } + + HTTPManager.Logger.Information(nameof(ProxyDetector), $"No Proxy for '{uri}'.", @event.SourceRequest.Context); + } + catch (Exception ex) + { + if (HTTPManager.Logger.Level == BestHTTP.Logger.Loglevels.All) + HTTPManager.Logger.Exception(nameof(ProxyDetector), $"GetProxyFor({@event.SourceRequest.CurrentUri})", ex, @event.SourceRequest.Context); + } + } + } + } +} + +#endif diff --git a/Assets/URS/Best HTTP/Source/Proxies/Autodetect/ProxyDetector.cs.meta b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/ProxyDetector.cs.meta new file mode 100644 index 0000000..3a9f80a --- /dev/null +++ b/Assets/URS/Best HTTP/Source/Proxies/Autodetect/ProxyDetector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f11e35f15ae944141a7fe661e2783ae4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/Proxies/HTTPProxy.cs b/Assets/URS/Best HTTP/Source/Proxies/HTTPProxy.cs index 9c1dc87..1181d3a 100644 --- a/Assets/URS/Best HTTP/Source/Proxies/HTTPProxy.cs +++ b/Assets/URS/Best HTTP/Source/Proxies/HTTPProxy.cs @@ -1,4 +1,4 @@ -#if !BESTHTTP_DISABLE_PROXY +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) using System; using System.Collections.Generic; @@ -44,10 +44,37 @@ internal bool UseProxyForAddress(Uri address) if (this.Exceptions == null) return true; + string host = address.Host; + + // https://github.com/httplib2/httplib2/issues/94 + // If domain starts with a dot (example: .example.com): + // 1. Use endswith to match any subdomain (foo.example.com should match) + // 2. Remove the dot and do an exact match (example.com should also match) + // + // If domain does not start with a dot (example: example.com): + // 1. It should be an exact match. for (int i = 0; i < this.Exceptions.Count; ++i) - if (address.Host.StartsWith(this.Exceptions[i])) + { + var exception = this.Exceptions[i]; + + if (exception == "*") return false; + if (exception.StartsWith(".")) + { + // Use EndsWith to match any subdomain + if (host.EndsWith(exception)) + return false; + + // Remove the dot and + exception = exception.Substring(1); + } + + // do an exact match + if (host.Equals(exception)) + return false; + } + return true; } } @@ -176,31 +203,39 @@ internal override void Connect(Stream stream, HTTPRequest request) switch (this.Credentials.Type) { case AuthenticationTypes.Basic: - // With Basic authentication we don't want to wait for a challenge, we will send the hash with the first request - outStream.Write(string.Format("Proxy-Authorization: {0}", string.Concat("Basic ", Convert.ToBase64String(Encoding.UTF8.GetBytes(this.Credentials.UserName + ":" + this.Credentials.Password)))).GetASCIIBytes()); - outStream.Write(HTTPRequest.EOL); - break; + { + // With Basic authentication we don't want to wait for a challenge, we will send the hash with the first request + var buff = string.Format("Proxy-Authorization: {0}", string.Concat("Basic ", Convert.ToBase64String(Encoding.UTF8.GetBytes(this.Credentials.UserName + ":" + this.Credentials.Password)))).GetASCIIBytes(); + outStream.Write(buff.Data, buff.Offset, buff.Count); + BufferPool.Release(buff); + + outStream.Write(HTTPRequest.EOL); + break; + } case AuthenticationTypes.Unknown: case AuthenticationTypes.Digest: - var digest = DigestStore.Get(this.Address); - if (digest != null) { - string authentication = digest.GenerateResponseHeader(request, this.Credentials, true); - if (!string.IsNullOrEmpty(authentication)) + var digest = DigestStore.Get(this.Address); + if (digest != null) { - string auth = string.Format("Proxy-Authorization: {0}", authentication); - if (HTTPManager.Logger.Level <= Logger.Loglevels.Information) - HTTPManager.Logger.Information("HTTPProxy", "Sending proxy authorization header: " + auth, request.Context); - - var bytes = auth.GetASCIIBytes(); - outStream.Write(bytes); - outStream.Write(HTTPRequest.EOL); - BufferPool.Release(bytes); + string authentication = digest.GenerateResponseHeader(request, this.Credentials, true); + if (!string.IsNullOrEmpty(authentication)) + { + string auth = string.Format("Proxy-Authorization: {0}", authentication); + if (HTTPManager.Logger.Level <= Logger.Loglevels.Information) + HTTPManager.Logger.Information("HTTPProxy", "Sending proxy authorization header: " + auth, request.Context); + + var buff = auth.GetASCIIBytes(); + outStream.Write(buff.Data, buff.Offset, buff.Count); + BufferPool.Release(buff); + + outStream.Write(HTTPRequest.EOL); + } } - } - break; + break; + } } } diff --git a/Assets/URS/Best HTTP/Source/Proxies/SOCKSProxy.cs b/Assets/URS/Best HTTP/Source/Proxies/SOCKSProxy.cs index fa71fc0..86707e9 100644 --- a/Assets/URS/Best HTTP/Source/Proxies/SOCKSProxy.cs +++ b/Assets/URS/Best HTTP/Source/Proxies/SOCKSProxy.cs @@ -1,10 +1,11 @@ -#if !BESTHTTP_DISABLE_PROXY +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) using System; using System.IO; using System.Text; using BestHTTP.Authentication; using BestHTTP.Extensions; using BestHTTP.PlatformSupport.Memory; +using BestHTTP.PlatformSupport.Text; namespace BestHTTP { @@ -360,10 +361,10 @@ private void WriteBytes(byte[] buffer, ref int count, byte[] bytes) private string BufferToHexStr(byte[] buffer, int count) { - StringBuilder sb = new StringBuilder(count * 2); + StringBuilder sb = StringBuilderPool.Get(count * 2); //new StringBuilder(count * 2); for (int i = 0; i < count; ++i) sb.AppendFormat("0x{0} ", buffer[i].ToString("X2")); - return sb.ToString(); + return StringBuilderPool.ReleaseAndGrab(sb); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ASN1Generator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ASN1Generator.cs index f6fc110..b61edf4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ASN1Generator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ASN1Generator.cs @@ -1,6 +1,5 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System.Collections; using System.IO; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ASN1OctetStringParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ASN1OctetStringParser.cs index a0390fd..924e7ba 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ASN1OctetStringParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ASN1OctetStringParser.cs @@ -1,5 +1,6 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable +using System; using System.IO; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 @@ -7,7 +8,9 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public interface Asn1OctetStringParser : IAsn1Convertible { - Stream GetOctetStream(); + /// Return the content of the OCTET STRING as a . + /// A represnting the OCTET STRING's content. + Stream GetOctetStream(); } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ASN1StreamParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ASN1StreamParser.cs index e1cbc25..bee937c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ASN1StreamParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ASN1StreamParser.cs @@ -37,206 +37,211 @@ internal Asn1StreamParser(Stream input, int limit, byte[][] tmpBuffers) this.tmpBuffers = tmpBuffers; } - internal IAsn1Convertible ReadIndef(int tagValue) - { - // Note: INDEF => CONSTRUCTED - - // TODO There are other tags that may be constructed (e.g. BIT_STRING) - switch (tagValue) - { - case Asn1Tags.External: - return new DerExternalParser(this); - case Asn1Tags.OctetString: - return new BerOctetStringParser(this); - case Asn1Tags.Sequence: - return new BerSequenceParser(this); - case Asn1Tags.Set: - return new BerSetParser(this); - default: - throw new Asn1Exception("unknown BER object encountered: 0x" + tagValue.ToString("X")); - } - } - - internal IAsn1Convertible ReadImplicit(bool constructed, int tag) - { - if (_in is IndefiniteLengthInputStream) - { - if (!constructed) - throw new IOException("indefinite-length primitive encoding encountered"); - - return ReadIndef(tag); - } - - if (constructed) - { - switch (tag) - { - case Asn1Tags.Set: - return new DerSetParser(this); - case Asn1Tags.Sequence: - return new DerSequenceParser(this); - case Asn1Tags.OctetString: - return new BerOctetStringParser(this); - } - } - else - { - switch (tag) - { - case Asn1Tags.Set: - throw new Asn1Exception("sequences must use constructed encoding (see X.690 8.9.1/8.10.1)"); - case Asn1Tags.Sequence: - throw new Asn1Exception("sets must use constructed encoding (see X.690 8.11.1/8.12.1)"); - case Asn1Tags.OctetString: - return new DerOctetStringParser((DefiniteLengthInputStream)_in); - } - } - - throw new Asn1Exception("implicit tagging not implemented"); - } - - internal Asn1Object ReadTaggedObject(bool constructed, int tag) - { - if (!constructed) - { - // Note: !CONSTRUCTED => IMPLICIT - DefiniteLengthInputStream defIn = (DefiniteLengthInputStream)_in; - return new DerTaggedObject(false, tag, new DerOctetString(defIn.ToArray())); - } - - Asn1EncodableVector v = ReadVector(); - - if (_in is IndefiniteLengthInputStream) - { - return v.Count == 1 - ? new BerTaggedObject(true, tag, v[0]) - : new BerTaggedObject(false, tag, BerSequence.FromVector(v)); - } - - return v.Count == 1 - ? new DerTaggedObject(true, tag, v[0]) - : new DerTaggedObject(false, tag, DerSequence.FromVector(v)); - } - public virtual IAsn1Convertible ReadObject() { - int tag = _in.ReadByte(); - if (tag == -1) + int tagHdr = _in.ReadByte(); + if (tagHdr < 0) return null; - // turn of looking for "00" while we resolve the tag - Set00Check(false); + return ImplParseObject(tagHdr); + } + + internal IAsn1Convertible ImplParseObject(int tagHdr) + { + // turn off looking for "00" while we resolve the tag + Set00Check(false); // // calculate tag number // - int tagNo = Asn1InputStream.ReadTagNumber(_in, tag); - - bool isConstructed = (tag & Asn1Tags.Constructed) != 0; + int tagNo = Asn1InputStream.ReadTagNumber(_in, tagHdr); // // calculate length // int length = Asn1InputStream.ReadLength(_in, _limit, - tagNo == Asn1Tags.OctetString || tagNo == Asn1Tags.Sequence || tagNo == Asn1Tags.Set || tagNo == Asn1Tags.External); + tagNo == Asn1Tags.BitString || tagNo == Asn1Tags.OctetString || tagNo == Asn1Tags.Sequence || + tagNo == Asn1Tags.Set || tagNo == Asn1Tags.External); if (length < 0) // indefinite-length method { - if (!isConstructed) - throw new IOException("indefinite-length primitive encoding encountered"); + if (0 == (tagHdr & Asn1Tags.Constructed)) + throw new IOException("indefinite-length primitive encoding encountered"); IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream(_in, _limit); Asn1StreamParser sp = new Asn1StreamParser(indIn, _limit, tmpBuffers); - int tagClass = tag & Asn1Tags.Private; + int tagClass = tagHdr & Asn1Tags.Private; if (0 != tagClass) - { - if ((tag & Asn1Tags.Application) != 0) - return new BerApplicationSpecificParser(tagNo, sp); + return new BerTaggedObjectParser(tagClass, tagNo, sp); - return new BerTaggedObjectParser(true, tagNo, sp); - } - - return sp.ReadIndef(tagNo); + return sp.ParseImplicitConstructedIL(tagNo); } else { DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(_in, length, _limit); - int tagClass = tag & Asn1Tags.Private; - if (0 != tagClass) - { - if ((tag & Asn1Tags.Application) != 0) - return new DerApplicationSpecific(isConstructed, tagNo, defIn.ToArray()); + if (0 == (tagHdr & Asn1Tags.Flags)) + return ParseImplicitPrimitive(tagNo, defIn); - return new BerTaggedObjectParser(isConstructed, tagNo, - new Asn1StreamParser(defIn, defIn.Remaining, tmpBuffers)); - } + Asn1StreamParser sp = new Asn1StreamParser(defIn, defIn.Remaining, tmpBuffers); - if (!isConstructed) + int tagClass = tagHdr & Asn1Tags.Private; + if (0 != tagClass) { - // Some primitive encodings can be handled by parsers too... - switch (tagNo) - { - case Asn1Tags.OctetString: - return new DerOctetStringParser(defIn); - } - - try - { - return Asn1InputStream.CreatePrimitiveDerObject(tagNo, defIn, tmpBuffers); - } - catch (ArgumentException e) - { - throw new Asn1Exception("corrupted stream detected", e); - } - } - - Asn1StreamParser sp = new Asn1StreamParser(defIn, defIn.Remaining, tmpBuffers); + bool isConstructed = (tagHdr & Asn1Tags.Constructed) != 0; - // TODO There are other tags that may be constructed (e.g. BitString) - switch (tagNo) - { - case Asn1Tags.OctetString: - // - // yes, people actually do this... - // - return new BerOctetStringParser(sp); - case Asn1Tags.Sequence: - return new DerSequenceParser(sp); - case Asn1Tags.Set: - return new DerSetParser(sp); - case Asn1Tags.External: - return new DerExternalParser(sp); - default: - throw new IOException("unknown tag " + tagNo + " encountered"); + return new DLTaggedObjectParser(tagClass, tagNo, isConstructed, sp); } - } - } - private void Set00Check( - bool enabled) - { - if (_in is IndefiniteLengthInputStream) - { - ((IndefiniteLengthInputStream) _in).SetEofOn00(enabled); + return sp.ParseImplicitConstructedDL(tagNo); } } + internal Asn1Object LoadTaggedDL(int tagClass, int tagNo, bool constructed) + { + if (!constructed) + { + byte[] contentsOctets = ((DefiniteLengthInputStream)_in).ToArray(); + return Asn1TaggedObject.CreatePrimitive(tagClass, tagNo, contentsOctets); + } + + Asn1EncodableVector contentsElements = ReadVector(); + return Asn1TaggedObject.CreateConstructedDL(tagClass, tagNo, contentsElements); + } + + internal Asn1Object LoadTaggedIL(int tagClass, int tagNo) + { + Asn1EncodableVector contentsElements = ReadVector(); + return Asn1TaggedObject.CreateConstructedIL(tagClass, tagNo, contentsElements); + } + + internal IAsn1Convertible ParseImplicitConstructedDL(int univTagNo) + { + switch (univTagNo) + { + case Asn1Tags.BitString: + // TODO[asn1] DLConstructedBitStringParser + return new BerBitStringParser(this); + case Asn1Tags.External: + return new DerExternalParser(this); + case Asn1Tags.OctetString: + // TODO[asn1] DLConstructedOctetStringParser + return new BerOctetStringParser(this); + case Asn1Tags.Set: + return new DerSetParser(this); + case Asn1Tags.Sequence: + return new DerSequenceParser(this); + default: + throw new Asn1Exception("unknown DL object encountered: 0x" + univTagNo.ToString("X")); + } + } + + internal IAsn1Convertible ParseImplicitConstructedIL(int univTagNo) + { + switch (univTagNo) + { + case Asn1Tags.BitString: + return new BerBitStringParser(this); + case Asn1Tags.External: + // TODO[asn1] BERExternalParser + return new DerExternalParser(this); + case Asn1Tags.OctetString: + return new BerOctetStringParser(this); + case Asn1Tags.Sequence: + return new BerSequenceParser(this); + case Asn1Tags.Set: + return new BerSetParser(this); + default: + throw new Asn1Exception("unknown BER object encountered: 0x" + univTagNo.ToString("X")); + } + } + + internal IAsn1Convertible ParseImplicitPrimitive(int univTagNo) + { + return ParseImplicitPrimitive(univTagNo, (DefiniteLengthInputStream)_in); + } + + internal IAsn1Convertible ParseImplicitPrimitive(int univTagNo, DefiniteLengthInputStream defIn) + { + // Some primitive encodings can be handled by parsers too... + switch (univTagNo) + { + case Asn1Tags.BitString: + return new DLBitStringParser(defIn); + case Asn1Tags.External: + throw new Asn1Exception("externals must use constructed encoding (see X.690 8.18)"); + case Asn1Tags.OctetString: + return new DerOctetStringParser(defIn); + case Asn1Tags.Set: + throw new Asn1Exception("sequences must use constructed encoding (see X.690 8.9.1/8.10.1)"); + case Asn1Tags.Sequence: + throw new Asn1Exception("sets must use constructed encoding (see X.690 8.11.1/8.12.1)"); + } + + try + { + return Asn1InputStream.CreatePrimitiveDerObject(univTagNo, defIn, tmpBuffers); + } + catch (ArgumentException e) + { + throw new Asn1Exception("corrupted stream detected", e); + } + } + + internal IAsn1Convertible ParseObject(int univTagNo) + { + if (univTagNo < 0 || univTagNo > 30) + throw new ArgumentException("invalid universal tag number: " + univTagNo, "univTagNo"); + + int tagHdr = _in.ReadByte(); + if (tagHdr < 0) + return null; + + if ((tagHdr & ~Asn1Tags.Constructed) != univTagNo) + throw new IOException("unexpected identifier encountered: " + tagHdr); + + return ImplParseObject(tagHdr); + } + + internal Asn1TaggedObjectParser ParseTaggedObject() + { + int tagHdr = _in.ReadByte(); + if (tagHdr< 0) + return null; + + int tagClass = tagHdr & Asn1Tags.Private; + if (0 == tagClass) + throw new Asn1Exception("no tagged object found"); + + return (Asn1TaggedObjectParser)ImplParseObject(tagHdr); + } + + // TODO[asn1] Prefer 'LoadVector' internal Asn1EncodableVector ReadVector() { - IAsn1Convertible obj = ReadObject(); - if (null == obj) + int tagHdr = _in.ReadByte(); + if (tagHdr < 0) return new Asn1EncodableVector(0); Asn1EncodableVector v = new Asn1EncodableVector(); do { + IAsn1Convertible obj = ImplParseObject(tagHdr); + v.Add(obj.ToAsn1Object()); } - while ((obj = ReadObject()) != null); + while ((tagHdr = _in.ReadByte()) >= 0); return v; } + + private void Set00Check(bool enabled) + { + if (_in is IndefiniteLengthInputStream indef) + { + indef.SetEofOn00(enabled); + } + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ASN1TaggedObjectParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ASN1TaggedObjectParser.cs index 12410c0..07e7a16 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ASN1TaggedObjectParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ASN1TaggedObjectParser.cs @@ -1,14 +1,39 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable +using System; +using System.IO; + namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 { public interface Asn1TaggedObjectParser : IAsn1Convertible { + int TagClass { get; } + int TagNo { get; } - IAsn1Convertible GetObjectParser(int tag, bool isExplicit); - } + bool HasContextTag(int tagNo); + + bool HasTag(int tagClass, int tagNo); + + /// + IAsn1Convertible ParseBaseUniversal(bool declaredExplicit, int baseTagNo); + + /// Needed for open types, until we have better type-guided parsing support. + /// + /// Use sparingly for other purposes, and prefer or + /// where possible. Before using, check for matching tag + /// class and number. + /// + /// + IAsn1Convertible ParseExplicitBaseObject(); + + /// + Asn1TaggedObjectParser ParseExplicitBaseTagged(); + + /// + Asn1TaggedObjectParser ParseImplicitBaseTagged(int baseTagClass, int baseTagNo); + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1BitStringParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1BitStringParser.cs new file mode 100644 index 0000000..776fecc --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1BitStringParser.cs @@ -0,0 +1,36 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.IO; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + public interface Asn1BitStringParser + : IAsn1Convertible + { + /// Return a representing the contents of the BIT STRING. The final byte, if any, + /// may include pad bits. See . + /// A with its source as the BIT STRING content. + /// + Stream GetBitStream(); + + /// Return a representing the contents of the BIT STRING, where the content is + /// expected to be octet-aligned (this will be automatically checked during parsing). + /// A with its source as the BIT STRING content. + /// + Stream GetOctetStream(); + + /// Return the number of pad bits, if any, in the final byte, if any, read from + /// . + /// + /// This number is in the range zero to seven. That number of the least significant bits of the final byte, if + /// any, are not part of the contents and should be ignored. NOTE: Must be called AFTER the stream has been + /// fully processed. (Does not need to be called if was used instead of + /// . + /// + /// The number of pad bits. In the range zero to seven. + int PadBits { get; } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1BitStringParser.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1BitStringParser.cs.meta new file mode 100644 index 0000000..a1c0638 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1BitStringParser.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 24137e6820af97b4bb29831a34398f8f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Encodable.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Encodable.cs index b81b45b..fbe06a8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Encodable.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Encodable.cs @@ -23,14 +23,14 @@ public virtual void EncodeTo(Stream output, string encoding) public byte[] GetEncoded() { MemoryStream bOut = new MemoryStream(); - EncodeTo(bOut); + ToAsn1Object().EncodeTo(bOut); return bOut.ToArray(); } public byte[] GetEncoded(string encoding) { MemoryStream bOut = new MemoryStream(); - EncodeTo(bOut, encoding); + ToAsn1Object().EncodeTo(bOut, encoding); return bOut.ToArray(); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1EncodableVector.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1EncodableVector.cs index 49a453b..5b68177 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1EncodableVector.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1EncodableVector.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 { @@ -9,7 +9,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 * Mutable class for building ASN.1 constructed objects such as SETs or SEQUENCEs. */ public class Asn1EncodableVector - : IEnumerable + : IEnumerable { internal static readonly Asn1Encodable[] EmptyElements = new Asn1Encodable[0]; @@ -19,7 +19,7 @@ public class Asn1EncodableVector private int elementCount; private bool copyOnWrite; - public static Asn1EncodableVector FromEnumerable(IEnumerable e) + public static Asn1EncodableVector FromEnumerable(IEnumerable e) { Asn1EncodableVector v = new Asn1EncodableVector(); foreach (Asn1Encodable obj in e) @@ -44,6 +44,19 @@ public Asn1EncodableVector(int initialCapacity) this.copyOnWrite = false; } + public Asn1EncodableVector(Asn1Encodable element) + : this() + { + Add(element); + } + + public Asn1EncodableVector(Asn1Encodable element1, Asn1Encodable element2) + : this() + { + Add(element1); + Add(element2); + } + public Asn1EncodableVector(params Asn1Encodable[] v) : this() { @@ -66,6 +79,12 @@ public void Add(Asn1Encodable element) this.elementCount = minCapacity; } + public void Add(Asn1Encodable element1, Asn1Encodable element2) + { + Add(element1); + Add(element2); + } + public void Add(params Asn1Encodable[] objs) { foreach (Asn1Encodable obj in objs) @@ -74,15 +93,35 @@ public void Add(params Asn1Encodable[] objs) } } - public void AddOptional(params Asn1Encodable[] objs) + public void AddOptional(Asn1Encodable element) + { + if (element != null) + { + Add(element); + } + } + + public void AddOptional(Asn1Encodable element1, Asn1Encodable element2) { - if (objs != null) + if (element1 != null) { - foreach (Asn1Encodable obj in objs) + Add(element1); + } + if (element2 != null) + { + Add(element2); + } + } + + public void AddOptional(params Asn1Encodable[] elements) + { + if (elements != null) + { + foreach (var element in elements) { - if (obj != null) + if (element != null) { - Add(obj); + Add(element); } } } @@ -96,6 +135,14 @@ public void AddOptionalTagged(bool isExplicit, int tagNo, Asn1Encodable obj) } } + public void AddOptionalTagged(bool isExplicit, int tagClass, int tagNo, Asn1Encodable obj) + { + if (null != obj) + { + Add(new DerTaggedObject(isExplicit, tagClass, tagNo, obj)); + } + } + public void AddAll(Asn1EncodableVector other) { if (null == other) @@ -142,9 +189,15 @@ public int Count get { return elementCount; } } - public IEnumerator GetEnumerator() + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public IEnumerator GetEnumerator() { - return CopyElements().GetEnumerator(); + IEnumerable e = CopyElements(); + return e.GetEnumerator(); } internal Asn1Encodable[] CopyElements() diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Exception.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Exception.cs index 0cb0ac2..5b28c22 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Exception.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Exception.cs @@ -2,12 +2,11 @@ #pragma warning disable using System; using System.IO; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 { -#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE) [Serializable] -#endif public class Asn1Exception : IOException { @@ -16,16 +15,18 @@ public Asn1Exception() { } - public Asn1Exception( - string message) + public Asn1Exception(string message) : base(message) { } - public Asn1Exception( - string message, - Exception exception) - : base(message, exception) + public Asn1Exception(string message, Exception innerException) + : base(message, innerException) + { + } + + protected Asn1Exception(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1GeneralizedTime.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1GeneralizedTime.cs new file mode 100644 index 0000000..303640b --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1GeneralizedTime.cs @@ -0,0 +1,266 @@ +#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; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + /// GeneralizedTime ASN.1 type + public class Asn1GeneralizedTime + : Asn1Object + { + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(Asn1GeneralizedTime), Asn1Tags.GeneralizedTime) { } + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return CreatePrimitive(octetString.GetOctets()); + } + } + + public static Asn1GeneralizedTime GetInstance(object obj) + { + if (obj == null) + return null; + + if (obj is Asn1GeneralizedTime asn1GeneralizedTime) + return asn1GeneralizedTime; + + if (obj is IAsn1Convertible asn1Convertible) + { + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is Asn1GeneralizedTime converted) + return converted; + } + else if (obj is byte[] bytes) + { + try + { + return (Asn1GeneralizedTime)Meta.Instance.FromByteArray(bytes); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct generalized time from byte[]: " + e.Message); + } + } + + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), nameof(obj)); + } + + public static Asn1GeneralizedTime GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) + { + return (Asn1GeneralizedTime)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); + } + + private readonly string m_timeString; + private readonly bool m_timeStringCanonical; + private readonly DateTime m_dateTime; + + public Asn1GeneralizedTime(string timeString) + { + m_timeString = timeString ?? throw new ArgumentNullException(nameof(timeString)); + m_timeStringCanonical = false; // TODO Dynamic check? + + try + { + m_dateTime = FromString(timeString); + } + catch (FormatException e) + { + throw new ArgumentException("invalid date string: " + e.Message); + } + } + + public Asn1GeneralizedTime(DateTime dateTime) + { + dateTime = dateTime.ToUniversalTime(); + + m_dateTime = dateTime; + m_timeString = ToStringCanonical(dateTime); + m_timeStringCanonical = true; + } + + // TODO TimeZoneInfo or other locale-specific constructors? + + internal Asn1GeneralizedTime(byte[] contents) + : this(Encoding.ASCII.GetString(contents)) + { + } + + public string TimeString => m_timeString; + + public DateTime ToDateTime() + { + return m_dateTime; + } + + internal byte[] GetContents(int encoding) + { + if (encoding == Asn1OutputStream.EncodingDer && !m_timeStringCanonical) + return Encoding.ASCII.GetBytes(ToStringCanonical(m_dateTime)); + + return Encoding.ASCII.GetBytes(m_timeString); + } + + internal override IAsn1Encoding GetEncoding(int encoding) + { + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.GeneralizedTime, GetContents(encoding)); + } + + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + return new PrimitiveEncoding(tagClass, tagNo, GetContents(encoding)); + } + + protected override bool Asn1Equals(Asn1Object asn1Object) + { + if (!(asn1Object is Asn1GeneralizedTime that)) + return false; + + // TODO Performance + return Arrays.AreEqual( + this.GetContents(Asn1OutputStream.EncodingDer), + that.GetContents(Asn1OutputStream.EncodingDer)); + } + + protected override int Asn1GetHashCode() + { + // TODO Performance + return Arrays.GetHashCode( + this.GetContents(Asn1OutputStream.EncodingDer)); + } + + internal static Asn1GeneralizedTime CreatePrimitive(byte[] contents) + { + return new Asn1GeneralizedTime(contents); + } + + private static DateTime FromString(string s) + { + if (s.Length < 10) + throw new FormatException(); + + s = s.Replace(',', '.'); + + if (Org.BouncyCastle.Utilities.Platform.EndsWith(s, "Z")) + { + switch (s.Length) + { + case 11: return ParseUtc(s, @"yyyyMMddHH\Z"); + case 13: return ParseUtc(s, @"yyyyMMddHHmm\Z"); + case 15: return ParseUtc(s, @"yyyyMMddHHmmss\Z"); + case 17: return ParseUtc(s, @"yyyyMMddHHmmss.f\Z"); + case 18: return ParseUtc(s, @"yyyyMMddHHmmss.ff\Z"); + case 19: return ParseUtc(s, @"yyyyMMddHHmmss.fff\Z"); + case 20: return ParseUtc(s, @"yyyyMMddHHmmss.ffff\Z"); + case 21: return ParseUtc(s, @"yyyyMMddHHmmss.fffff\Z"); + case 22: return ParseUtc(s, @"yyyyMMddHHmmss.ffffff\Z"); + case 23: return ParseUtc(s, @"yyyyMMddHHmmss.fffffff\Z"); + default: + throw new FormatException(); + } + } + + int signIndex = IndexOfSign(s, System.Math.Max(10, s.Length - 5)); + + if (signIndex < 0) + { + switch (s.Length) + { + case 10: return ParseLocal(s, @"yyyyMMddHH"); + case 12: return ParseLocal(s, @"yyyyMMddHHmm"); + case 14: return ParseLocal(s, @"yyyyMMddHHmmss"); + case 16: return ParseLocal(s, @"yyyyMMddHHmmss.f"); + case 17: return ParseLocal(s, @"yyyyMMddHHmmss.ff"); + case 18: return ParseLocal(s, @"yyyyMMddHHmmss.fff"); + case 19: return ParseLocal(s, @"yyyyMMddHHmmss.ffff"); + case 20: return ParseLocal(s, @"yyyyMMddHHmmss.fffff"); + case 21: return ParseLocal(s, @"yyyyMMddHHmmss.ffffff"); + case 22: return ParseLocal(s, @"yyyyMMddHHmmss.fffffff"); + default: + throw new FormatException(); + } + } + + if (signIndex == s.Length - 5) + { + switch (s.Length) + { + case 15: return ParseTimeZone(s, @"yyyyMMddHHzzz"); + case 17: return ParseTimeZone(s, @"yyyyMMddHHmmzzz"); + case 19: return ParseTimeZone(s, @"yyyyMMddHHmmsszzz"); + case 21: return ParseTimeZone(s, @"yyyyMMddHHmmss.fzzz"); + case 22: return ParseTimeZone(s, @"yyyyMMddHHmmss.ffzzz"); + case 23: return ParseTimeZone(s, @"yyyyMMddHHmmss.fffzzz"); + case 24: return ParseTimeZone(s, @"yyyyMMddHHmmss.ffffzzz"); + case 25: return ParseTimeZone(s, @"yyyyMMddHHmmss.fffffzzz"); + case 26: return ParseTimeZone(s, @"yyyyMMddHHmmss.ffffffzzz"); + case 27: return ParseTimeZone(s, @"yyyyMMddHHmmss.fffffffzzz"); + default: + throw new FormatException(); + } + } + + if (signIndex == s.Length - 3) + { + switch (s.Length) + { + case 13: return ParseTimeZone(s, @"yyyyMMddHHzz"); + case 15: return ParseTimeZone(s, @"yyyyMMddHHmmzz"); + case 17: return ParseTimeZone(s, @"yyyyMMddHHmmsszz"); + case 19: return ParseTimeZone(s, @"yyyyMMddHHmmss.fzz"); + case 20: return ParseTimeZone(s, @"yyyyMMddHHmmss.ffzz"); + case 21: return ParseTimeZone(s, @"yyyyMMddHHmmss.fffzz"); + case 22: return ParseTimeZone(s, @"yyyyMMddHHmmss.ffffzz"); + case 23: return ParseTimeZone(s, @"yyyyMMddHHmmss.fffffzz"); + case 24: return ParseTimeZone(s, @"yyyyMMddHHmmss.ffffffzz"); + case 25: return ParseTimeZone(s, @"yyyyMMddHHmmss.fffffffzz"); + default: + throw new FormatException(); + } + } + + throw new FormatException(); + } + + private static int IndexOfSign(string s, int startIndex) + { + int index = Org.BouncyCastle.Utilities.Platform.IndexOf(s, '+', startIndex); + if (index < 0) + { + index = Org.BouncyCastle.Utilities.Platform.IndexOf(s, '-', startIndex); + } + return index; + } + + private static DateTime ParseLocal(string s, string format) + { + return DateTime.ParseExact(s, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeLocal); + } + + private static DateTime ParseTimeZone(string s, string format) + { + return DateTime.ParseExact(s, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal); + } + + private static DateTime ParseUtc(string s, string format) + { + return DateTime.ParseExact(s, format, DateTimeFormatInfo.InvariantInfo, + DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal); + } + + private static string ToStringCanonical(DateTime dateTime) + { + return dateTime.ToUniversalTime().ToString(@"yyyyMMddHHmmss.FFFFFFFK", DateTimeFormatInfo.InvariantInfo); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1GeneralizedTime.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1GeneralizedTime.cs.meta new file mode 100644 index 0000000..bdf4573 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1GeneralizedTime.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d717ef26a13ca4645a37a12bf5d48229 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1InputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1InputStream.cs index db5410f..823d9c3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1InputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1InputStream.cs @@ -1,7 +1,6 @@ #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; @@ -20,21 +19,18 @@ public class Asn1InputStream { private readonly int limit; - internal readonly byte[][] tmpBuffers; + internal byte[][] tmpBuffers; internal static int FindLimit(Stream input) { - if (input is LimitedInputStream) - return ((LimitedInputStream)input).Limit; + if (input is LimitedInputStream limited) + return limited.Limit; - if (input is Asn1InputStream) - return ((Asn1InputStream)input).Limit; + if (input is Asn1InputStream asn1) + return asn1.Limit; - if (input is MemoryStream) - { - MemoryStream mem = (MemoryStream)input; - return (int)(mem.Length - mem.Position); - } + if (input is MemoryStream memory) + return Convert.ToInt32(memory.Length - memory.Position); return int.MaxValue; } @@ -73,54 +69,61 @@ internal Asn1InputStream(Stream input, int limit, byte[][] tmpBuffers) this.tmpBuffers = tmpBuffers; } + protected override void Dispose(bool disposing) + { + tmpBuffers = null; + + base.Dispose(disposing); + } + /** * build an object given its tag and the number of bytes to construct it from. */ - private Asn1Object BuildObject( - int tag, - int tagNo, - int length) + private Asn1Object BuildObject(int tagHdr, int tagNo, int length) { - bool isConstructed = (tag & Asn1Tags.Constructed) != 0; + // TODO[asn1] Special-case zero length first? + + DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(s, length, limit); - DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(this, length, limit); + if (0 == (tagHdr & Asn1Tags.Flags)) + return CreatePrimitiveDerObject(tagNo, defIn, tmpBuffers); - int tagClass = tag & Asn1Tags.Private; + int tagClass = tagHdr & Asn1Tags.Private; if (0 != tagClass) { - if ((tag & Asn1Tags.Application) != 0) - return new DerApplicationSpecific(isConstructed, tagNo, defIn.ToArray()); - - return new Asn1StreamParser(defIn, defIn.Remaining, tmpBuffers).ReadTaggedObject(isConstructed, tagNo); + bool isConstructed = (tagHdr & Asn1Tags.Constructed) != 0; + return ReadTaggedObjectDL(tagClass, tagNo, isConstructed, defIn); } - if (!isConstructed) - return CreatePrimitiveDerObject(tagNo, defIn, tmpBuffers); - switch (tagNo) { case Asn1Tags.BitString: - { return BuildConstructedBitString(ReadVector(defIn)); - } case Asn1Tags.OctetString: - { - // - // yes, people actually do this... - // return BuildConstructedOctetString(ReadVector(defIn)); - } case Asn1Tags.Sequence: - return CreateDerSequence(defIn); + return CreateDLSequence(defIn); case Asn1Tags.Set: - return CreateDerSet(defIn); + return CreateDLSet(defIn); case Asn1Tags.External: - return new DerExternal(ReadVector(defIn)); + return DLSequence.FromVector(ReadVector(defIn)).ToAsn1External(); default: throw new IOException("unknown tag " + tagNo + " encountered"); } } + internal Asn1Object ReadTaggedObjectDL(int tagClass, int tagNo, bool constructed, DefiniteLengthInputStream defIn) + { + if (!constructed) + { + byte[] contentsOctets = defIn.ToArray(); + return Asn1TaggedObject.CreatePrimitive(tagClass, tagNo, contentsOctets); + } + + Asn1EncodableVector contentsElements = ReadVector(defIn); + return Asn1TaggedObject.CreateConstructedDL(tagClass, tagNo, contentsElements); + } + internal virtual Asn1EncodableVector ReadVector() { Asn1Object o = ReadObject(); @@ -145,38 +148,36 @@ internal virtual Asn1EncodableVector ReadVector(DefiniteLengthInputStream defIn) return new Asn1InputStream(defIn, remaining, tmpBuffers).ReadVector(); } - internal virtual DerSequence CreateDerSequence( - DefiniteLengthInputStream dIn) + internal virtual Asn1Sequence CreateDLSequence(DefiniteLengthInputStream defIn) { - return DerSequence.FromVector(ReadVector(dIn)); + return DLSequence.FromVector(ReadVector(defIn)); } - internal virtual DerSet CreateDerSet( - DefiniteLengthInputStream dIn) + internal virtual Asn1Set CreateDLSet(DefiniteLengthInputStream defIn) { - return DerSet.FromVector(ReadVector(dIn), false); + return DLSet.FromVector(ReadVector(defIn)); } public Asn1Object ReadObject() { - int tag = ReadByte(); - if (tag <= 0) + int tagHdr = s.ReadByte(); + if (tagHdr <= 0) { - if (tag == 0) + if (tagHdr == 0) throw new IOException("unexpected end-of-contents marker"); return null; } - int tagNo = ReadTagNumber(this, tag); - int length = ReadLength(this, limit, false); + int tagNo = ReadTagNumber(s, tagHdr); + int length = ReadLength(s, limit, false); if (length >= 0) { // definite-length try { - return BuildObject(tag, tagNo, length); + return BuildObject(tagHdr, tagNo, length); } catch (ArgumentException e) { @@ -186,24 +187,20 @@ public Asn1Object ReadObject() // indefinite-length - if (0 == (tag & Asn1Tags.Constructed)) + if (0 == (tagHdr & Asn1Tags.Constructed)) throw new IOException("indefinite-length primitive encoding encountered"); - IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream(this, limit); + IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream(s, limit); Asn1StreamParser sp = new Asn1StreamParser(indIn, limit, tmpBuffers); - int tagClass = tag & Asn1Tags.Private; + int tagClass = tagHdr & Asn1Tags.Private; if (0 != tagClass) - { - if ((tag & Asn1Tags.Application) != 0) - return new BerApplicationSpecificParser(tagNo, sp).ToAsn1Object(); + return sp.LoadTaggedIL(tagClass, tagNo); - return new BerTaggedObjectParser(true, tagNo, sp).ToAsn1Object(); - } - - // TODO There are other tags that may be constructed (e.g. BitString) switch (tagNo) { + case Asn1Tags.BitString: + return BerBitStringParser.Parse(sp); case Asn1Tags.OctetString: return BerOctetStringParser.Parse(sp); case Asn1Tags.Sequence: @@ -211,6 +208,7 @@ public Asn1Object ReadObject() case Asn1Tags.Set: return BerSetParser.Parse(sp); case Asn1Tags.External: + // TODO[asn1] BerExternalParser return DerExternalParser.Parse(sp); default: throw new IOException("unknown BER object encountered"); @@ -226,13 +224,12 @@ internal virtual DerBitString BuildConstructedBitString(Asn1EncodableVector cont DerBitString bitString = contentsElements[i] as DerBitString; if (null == bitString) throw new Asn1Exception("unknown object encountered in constructed BIT STRING: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(contentsElements[i])); + + Org.BouncyCastle.Utilities.Platform.GetTypeName(contentsElements[i])); bitStrings[i] = bitString; } - // TODO Probably ought to be DLBitString - return new BerBitString(bitStrings); + return new DLBitString(BerBitString.FlattenBitStrings(bitStrings), false); } internal virtual Asn1OctetString BuildConstructedOctetString(Asn1EncodableVector contentsElements) @@ -244,13 +241,13 @@ internal virtual Asn1OctetString BuildConstructedOctetString(Asn1EncodableVector Asn1OctetString octetString = contentsElements[i] as Asn1OctetString; if (null == octetString) throw new Asn1Exception("unknown object encountered in constructed OCTET STRING: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(contentsElements[i])); + + Org.BouncyCastle.Utilities.Platform.GetTypeName(contentsElements[i])); octetStrings[i] = octetString; } - // TODO Probably ought to be DerOctetString (no DLOctetString available) - return new BerOctetString(octetStrings); + // Note: No DLOctetString available + return new DerOctetString(BerOctetString.FlattenOctetStrings(octetStrings)); } internal virtual int Limit @@ -258,17 +255,15 @@ internal virtual int Limit get { return limit; } } - internal static int ReadTagNumber(Stream s, int tag) + internal static int ReadTagNumber(Stream s, int tagHdr) { - int tagNo = tag & 0x1f; + int tagNo = tagHdr & 0x1f; // // with tagged object tag number is bottom 5 bits, or stored at the start of the content // if (tagNo == 0x1f) { - tagNo = 0; - int b = s.ReadByte(); if (b < 31) { @@ -278,9 +273,11 @@ internal static int ReadTagNumber(Stream s, int tag) throw new IOException("corrupted stream - high tag number < 31 found"); } + tagNo = b & 0x7f; + // X.690-0207 8.1.2.4.2 // "c) bits 7 to 1 of the first subsequent octet shall not all be zero." - if ((b & 0x7f) == 0) + if (0 == tagNo) throw new IOException("corrupted stream - invalid high tag number found"); while ((b & 0x80) != 0) @@ -288,14 +285,14 @@ internal static int ReadTagNumber(Stream s, int tag) if (((uint)tagNo >> 24) != 0U) throw new IOException("Tag number more than 31 bits"); - tagNo |= b & 0x7f; tagNo <<= 7; + b = s.ReadByte(); if (b < 0) throw new EndOfStreamException("EOF found inside tag value."); - } - tagNo |= b & 0x7f; + tagNo |= b & 0x7f; + } } return tagNo; @@ -407,67 +404,65 @@ private static char[] GetBmpCharBuffer(DefiniteLengthInputStream defIn) return str; } - internal static Asn1Object CreatePrimitiveDerObject( - int tagNo, - DefiniteLengthInputStream defIn, - byte[][] tmpBuffers) + internal static Asn1Object CreatePrimitiveDerObject(int tagNo, DefiniteLengthInputStream defIn, + byte[][] tmpBuffers) { switch (tagNo) { - case Asn1Tags.BmpString: - return new DerBmpString(GetBmpCharBuffer(defIn)); - case Asn1Tags.Boolean: - return DerBoolean.FromOctetString(GetBuffer(defIn, tmpBuffers)); - case Asn1Tags.Enumerated: - return DerEnumerated.FromOctetString(GetBuffer(defIn, tmpBuffers)); - case Asn1Tags.ObjectIdentifier: - // TODO Ideally only clone if we used a buffer - return DerObjectIdentifier.CreatePrimitive(GetBuffer(defIn, tmpBuffers), true); + case Asn1Tags.BmpString: + return DerBmpString.CreatePrimitive(GetBmpCharBuffer(defIn)); + case Asn1Tags.Boolean: + return DerBoolean.CreatePrimitive(GetBuffer(defIn, tmpBuffers)); + case Asn1Tags.Enumerated: + // TODO Ideally only clone if we used a buffer + return DerEnumerated.CreatePrimitive(GetBuffer(defIn, tmpBuffers), true); + case Asn1Tags.ObjectIdentifier: + // TODO Ideally only clone if we used a buffer + return DerObjectIdentifier.CreatePrimitive(GetBuffer(defIn, tmpBuffers), true); } byte[] bytes = defIn.ToArray(); switch (tagNo) { - case Asn1Tags.BitString: - return DerBitString.CreatePrimitive(bytes); - case Asn1Tags.GeneralizedTime: - return new DerGeneralizedTime(bytes); - case Asn1Tags.GeneralString: - return new DerGeneralString(bytes); - case Asn1Tags.GraphicString: - return new DerGraphicString(bytes); - case Asn1Tags.IA5String: - return new DerIA5String(bytes); - case Asn1Tags.Integer: - return new DerInteger(bytes, false); - case Asn1Tags.Null: - { - if (0 != bytes.Length) - throw new InvalidOperationException("malformed NULL encoding encountered"); - - return DerNull.Instance; - } - case Asn1Tags.NumericString: - return new DerNumericString(bytes); - case Asn1Tags.OctetString: - return new DerOctetString(bytes); - case Asn1Tags.PrintableString: - return new DerPrintableString(bytes); - case Asn1Tags.T61String: - return new DerT61String(bytes); - case Asn1Tags.UniversalString: - return new DerUniversalString(bytes); - case Asn1Tags.UtcTime: - return new DerUtcTime(bytes); - case Asn1Tags.Utf8String: - return new DerUtf8String(bytes); - case Asn1Tags.VideotexString: - return new DerVideotexString(bytes); - case Asn1Tags.VisibleString: - return new DerVisibleString(bytes); - default: - throw new IOException("unknown tag " + tagNo + " encountered"); + case Asn1Tags.BitString: + return DerBitString.CreatePrimitive(bytes); + case Asn1Tags.GeneralizedTime: + return Asn1GeneralizedTime.CreatePrimitive(bytes); + case Asn1Tags.GeneralString: + return DerGeneralString.CreatePrimitive(bytes); + case Asn1Tags.GraphicString: + return DerGraphicString.CreatePrimitive(bytes); + case Asn1Tags.IA5String: + return DerIA5String.CreatePrimitive(bytes); + case Asn1Tags.Integer: + return DerInteger.CreatePrimitive(bytes); + case Asn1Tags.Null: + return Asn1Null.CreatePrimitive(bytes); + case Asn1Tags.NumericString: + return DerNumericString.CreatePrimitive(bytes); + case Asn1Tags.ObjectDescriptor: + return Asn1ObjectDescriptor.CreatePrimitive(bytes); + case Asn1Tags.OctetString: + return Asn1OctetString.CreatePrimitive(bytes); + case Asn1Tags.PrintableString: + return DerPrintableString.CreatePrimitive(bytes); + case Asn1Tags.RelativeOid: + return Asn1RelativeOid.CreatePrimitive(bytes, false); + case Asn1Tags.T61String: + return DerT61String.CreatePrimitive(bytes); + case Asn1Tags.UniversalString: + return DerUniversalString.CreatePrimitive(bytes); + case Asn1Tags.UtcTime: + return Asn1UtcTime.CreatePrimitive(bytes); + case Asn1Tags.Utf8String: + return DerUtf8String.CreatePrimitive(bytes); + case Asn1Tags.VideotexString: + return DerVideotexString.CreatePrimitive(bytes); + case Asn1Tags.VisibleString: + return DerVisibleString.CreatePrimitive(bytes); + default: + throw new IOException("unknown tag " + tagNo + " encountered"); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Null.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Null.cs index f1d756b..58003f7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Null.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Null.cs @@ -1,5 +1,10 @@ #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 { /** @@ -8,14 +13,68 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public abstract class Asn1Null : Asn1Object { + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(Asn1Null), Asn1Tags.Null) {} + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return CreatePrimitive(octetString.GetOctets()); + } + } + + public static Asn1Null GetInstance(object obj) + { + if (obj == null) + return null; + + if (obj is Asn1Null asn1Null) + return asn1Null; + + if (obj is IAsn1Convertible asn1Convertible) + { + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is Asn1Null converted) + return converted; + } + else if (obj is byte[] bytes) + { + try + { + return (Asn1Null)Meta.Instance.FromByteArray(bytes); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct NULL from byte[]: " + e.Message); + } + } + + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + } + + public static Asn1Null GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) + { + return (Asn1Null)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); + } + internal Asn1Null() { } - public override string ToString() - { - return "NULL"; - } + public override string ToString() + { + return "NULL"; + } + + internal static Asn1Null CreatePrimitive(byte[] contents) + { + if (0 != contents.Length) + throw new InvalidOperationException("malformed NULL encoding encountered"); + + return DerNull.Instance; + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Object.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Object.cs index efbf5a4..1b9a6de 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Object.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Object.cs @@ -10,12 +10,21 @@ public abstract class Asn1Object { public override void EncodeTo(Stream output) { - Asn1OutputStream.Create(output).WriteObject(this); + Asn1OutputStream asn1Out = Asn1OutputStream.Create(output); + GetEncoding(asn1Out.Encoding).Encode(asn1Out); + asn1Out.FlushInternal(); } public override void EncodeTo(Stream output, string encoding) { - Asn1OutputStream.Create(output, encoding).WriteObject(this); + Asn1OutputStream asn1Out = Asn1OutputStream.Create(output, encoding); + GetEncoding(asn1Out.Encoding).Encode(asn1Out); + asn1Out.FlushInternal(); + } + + public bool Equals(Asn1Object other) + { + return this == other || Asn1Equals(other); } /// Create a base ASN.1 object from a byte array. @@ -64,9 +73,9 @@ public sealed override Asn1Object ToAsn1Object() return this; } - internal abstract int EncodedLength(bool withID); + internal abstract IAsn1Encoding GetEncoding(int encoding); - internal abstract void Encode(Asn1OutputStream asn1Out, bool withID); + internal abstract IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo); protected abstract bool Asn1Equals(Asn1Object asn1Object); protected abstract int Asn1GetHashCode(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1ObjectDescriptor.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1ObjectDescriptor.cs new file mode 100644 index 0000000..318fd71 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1ObjectDescriptor.cs @@ -0,0 +1,125 @@ +#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 +{ + public sealed class Asn1ObjectDescriptor + : Asn1Object + { + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(Asn1ObjectDescriptor), Asn1Tags.ObjectDescriptor) {} + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return new Asn1ObjectDescriptor( + (DerGraphicString)DerGraphicString.Meta.Instance.FromImplicitPrimitive(octetString)); + } + + internal override Asn1Object FromImplicitConstructed(Asn1Sequence sequence) + { + return new Asn1ObjectDescriptor( + (DerGraphicString)DerGraphicString.Meta.Instance.FromImplicitConstructed(sequence)); + } + } + + /** + * Return an ObjectDescriptor from the passed in object. + * + * @param obj an ASN1ObjectDescriptor or an object that can be converted into one. + * @exception IllegalArgumentException if the object cannot be converted. + * @return an ASN1ObjectDescriptor instance, or null. + */ + public static Asn1ObjectDescriptor GetInstance(object obj) + { + if (obj == null) + return null; + + if (obj is Asn1ObjectDescriptor asn1ObjectDescriptor) + return asn1ObjectDescriptor; + + if (obj is IAsn1Convertible asn1Convertible) + { + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is Asn1ObjectDescriptor converted) + return converted; + } + else if (obj is byte[] bytes) + { + try + { + return (Asn1ObjectDescriptor)Meta.Instance.FromByteArray(bytes); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct object descriptor from byte[]: " + e.Message); + } + } + + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + } + + /** + * Return an ObjectDescriptor from a tagged object. + * + * @param taggedObject the tagged object holding the object we want. + * @param declaredExplicit true if the object is meant to be explicitly tagged, false otherwise. + * @exception IllegalArgumentException if the tagged object cannot be converted. + * @return an ASN1ObjectDescriptor instance, or null. + */ + public static Asn1ObjectDescriptor GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) + { + return (Asn1ObjectDescriptor)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); + } + + private readonly DerGraphicString m_baseGraphicString; + + public Asn1ObjectDescriptor(DerGraphicString baseGraphicString) + { + if (null == baseGraphicString) + throw new ArgumentNullException("baseGraphicString"); + + this.m_baseGraphicString = baseGraphicString; + } + + public DerGraphicString BaseGraphicString + { + get { return m_baseGraphicString; } + } + + internal override IAsn1Encoding GetEncoding(int encoding) + { + return m_baseGraphicString.GetEncodingImplicit(encoding, Asn1Tags.Universal, Asn1Tags.ObjectDescriptor); + } + + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + return m_baseGraphicString.GetEncodingImplicit(encoding, tagClass, tagNo); + } + + protected override int Asn1GetHashCode() + { + return ~m_baseGraphicString.CallAsn1GetHashCode(); + } + + protected override bool Asn1Equals(Asn1Object asn1Object) + { + Asn1ObjectDescriptor that = asn1Object as Asn1ObjectDescriptor; + return null != that + && this.m_baseGraphicString.Equals(that.m_baseGraphicString); + } + + internal static Asn1ObjectDescriptor CreatePrimitive(byte[] contents) + { + return new Asn1ObjectDescriptor(DerGraphicString.CreatePrimitive(contents)); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1ObjectDescriptor.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1ObjectDescriptor.cs.meta new file mode 100644 index 0000000..e2d818f --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1ObjectDescriptor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ef670ce0aae993744a256d3bb7362b31 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1OctetString.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1OctetString.cs index 0498a78..ec14b53 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1OctetString.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1OctetString.cs @@ -1,7 +1,6 @@ #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; @@ -12,32 +11,24 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public abstract class Asn1OctetString : Asn1Object, Asn1OctetStringParser { - internal static readonly byte[] EmptyOctets = new byte[0]; + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); - internal byte[] str; + private Meta() : base(typeof(Asn1OctetString), Asn1Tags.OctetString) {} - /** - * return an Octet 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 Asn1OctetString GetInstance( - Asn1TaggedObject obj, - bool isExplicit) - { - Asn1Object o = obj.GetObject(); + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return octetString; + } - if (isExplicit || o is Asn1OctetString) - { - return GetInstance(o); - } + internal override Asn1Object FromImplicitConstructed(Asn1Sequence sequence) + { + return sequence.ToAsn1OctetString(); + } + } - return BerOctetString.FromSequence(Asn1Sequence.GetInstance(o)); - } + internal static readonly byte[] EmptyOctets = new byte[0]; /** * return an Octet string from the given object. @@ -47,54 +38,61 @@ public static Asn1OctetString GetInstance( */ public static Asn1OctetString GetInstance(object obj) { - if (obj == null || obj is Asn1OctetString) + if (obj == null) + return null; + + if (obj is Asn1OctetString asn1OctetString) + return asn1OctetString; + + if (obj is IAsn1Convertible asn1Convertible) { - return (Asn1OctetString)obj; + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is Asn1OctetString converted) + return converted; } - else if (obj is byte[]) + else if (obj is byte[] bytes) { try { - return GetInstance(FromByteArray((byte[])obj)); + return (Asn1OctetString)Meta.Instance.FromByteArray(bytes); } catch (IOException e) { throw new ArgumentException("failed to construct OCTET STRING from byte[]: " + e.Message); } } - // TODO: this needs to be deleted in V2 - else if (obj is Asn1TaggedObject) - { - return GetInstance(((Asn1TaggedObject)obj).GetObject()); - } - else if (obj is Asn1Encodable) - { - Asn1Object primitive = ((Asn1Encodable)obj).ToAsn1Object(); - if (primitive is Asn1OctetString) - { - return (Asn1OctetString)primitive; - } - } + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + } - throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + /** + * return an octet string from a tagged object. + * + * @param taggedObject the tagged object holding the object we want. + * @param declaredExplicit true if the object is meant to be explicitly tagged false otherwise. + * @exception ArgumentException if the tagged object cannot be converted. + */ + public static Asn1OctetString GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) + { + return (Asn1OctetString)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); } + internal readonly byte[] contents; + /** * @param string the octets making up the octet string. */ - internal Asn1OctetString( - byte[] str) + internal Asn1OctetString(byte[] contents) { - if (str == null) - throw new ArgumentNullException("str"); + if (null == contents) + throw new ArgumentNullException("contents"); - this.str = str; + this.contents = contents; } public Stream GetOctetStream() { - return new MemoryStream(str, false); + return new MemoryStream(contents, false); } public Asn1OctetStringParser Parser @@ -104,7 +102,7 @@ public Asn1OctetStringParser Parser public virtual byte[] GetOctets() { - return str; + return contents; } protected override int Asn1GetHashCode() @@ -125,9 +123,14 @@ protected override bool Asn1Equals( public override string ToString() { - return "#" + Hex.ToHexString(str); + return "#" + Hex.ToHexString(contents); } - } + + internal static Asn1OctetString CreatePrimitive(byte[] contents) + { + return new DerOctetString(contents); + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1OutputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1OutputStream.cs index c3b360a..a522ed9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1OutputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1OutputStream.cs @@ -2,12 +2,22 @@ #pragma warning disable using System; using System.IO; +using System.Diagnostics; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ +using System.Buffers.Binary; +using System.Numerics; +#endif + +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 { public class Asn1OutputStream - : DerOutputStream + : FilterStream { + internal const int EncodingBer = 1; + internal const int EncodingDer = 2; + public static Asn1OutputStream Create(Stream output) { return new Asn1OutputStream(output); @@ -17,7 +27,7 @@ public static Asn1OutputStream Create(Stream output, string encoding) { if (Asn1Encodable.Der.Equals(encoding)) { - return new DerOutputStreamNew(output); + return new DerOutputStream(output); } else { @@ -25,175 +35,130 @@ public static Asn1OutputStream Create(Stream output, string encoding) } } - - public Asn1OutputStream(Stream os) + internal Asn1OutputStream(Stream os) : base(os) { } - public override void WriteObject(Asn1Encodable encodable) + public virtual void WriteObject(Asn1Encodable asn1Encodable) { - if (null == encodable) - throw new IOException("null object detected"); + if (null == asn1Encodable) + throw new ArgumentNullException("asn1Encodable"); - WritePrimitive(encodable.ToAsn1Object(), true); + asn1Encodable.ToAsn1Object().GetEncoding(this.Encoding).Encode(this); FlushInternal(); } - public override void WriteObject(Asn1Object primitive) + public virtual void WriteObject(Asn1Object asn1Object) { - if (null == primitive) - throw new IOException("null object detected"); + if (null == asn1Object) + throw new ArgumentNullException("asn1Object"); - WritePrimitive(primitive, true); + asn1Object.GetEncoding(this.Encoding).Encode(this); FlushInternal(); } - internal void FlushInternal() - { - // Placeholder to support future internal buffering - } - - internal virtual bool IsBer - { - get { return true; } - } - - internal void WriteDL(int length) - { - if (length < 128) - { - WriteByte((byte)length); - } - else - { - byte[] stack = new byte[5]; - int pos = stack.Length; - - do - { - stack[--pos] = (byte)length; - length >>= 8; - } - while (length > 0); - - int count = stack.Length - pos; - stack[--pos] = (byte)(0x80 | count); - - Write(stack, pos, count + 1); - } - } - - internal virtual void WriteElements(Asn1Encodable[] elements) + internal void EncodeContents(IAsn1Encoding[] contentsEncodings) { - for (int i = 0, count = elements.Length; i < count; ++i) + for (int i = 0, count = contentsEncodings.Length; i < count; ++i) { - elements[i].ToAsn1Object().Encode(this, true); + contentsEncodings[i].Encode(this); } } - internal void WriteEncodingDL(bool withID, int identifier, byte contents) + internal virtual int Encoding { - WriteIdentifier(withID, identifier); - WriteDL(1); - WriteByte(contents); + get { return EncodingBer; } } - internal void WriteEncodingDL(bool withID, int identifier, byte[] contents) - { - WriteIdentifier(withID, identifier); - WriteDL(contents.Length); - Write(contents, 0, contents.Length); - } - - internal void WriteEncodingDL(bool withID, int identifier, byte[] contents, int contentsOff, int contentsLen) + internal void FlushInternal() { - WriteIdentifier(withID, identifier); - WriteDL(contentsLen); - Write(contents, contentsOff, contentsLen); + // Placeholder to support future internal buffering } - internal void WriteEncodingDL(bool withID, int identifier, byte contentsPrefix, byte[] contents, - int contentsOff, int contentsLen) + internal void WriteDL(int dl) { - WriteIdentifier(withID, identifier); - WriteDL(1 + contentsLen); - WriteByte(contentsPrefix); - Write(contents, contentsOff, contentsLen); - } + if (dl < 128) + { + Debug.Assert(dl >= 0); + WriteByte((byte)dl); + return; + } - internal void WriteEncodingDL(bool withID, int identifier, byte[] contents, int contentsOff, int contentsLen, - byte contentsSuffix) - { - WriteIdentifier(withID, identifier); - WriteDL(contentsLen + 1); - Write(contents, contentsOff, contentsLen); - WriteByte(contentsSuffix); - } +#if false && (NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_) + Span encoding = stackalloc byte[5]; + BinaryPrimitives.WriteUInt32BigEndian(encoding[1..], (uint)dl); + int leadingZeroBytes = BitOperations.LeadingZeroCount((uint)dl) / 8; + encoding[leadingZeroBytes] = (byte)(0x84 - leadingZeroBytes); + Write(encoding[leadingZeroBytes..]); +#else + byte[] stack = new byte[5]; + int pos = stack.Length; + + do + { + stack[--pos] = (byte)dl; + dl >>= 8; + } + while (dl > 0); - internal void WriteEncodingDL(bool withID, int flags, int tag, byte[] contents) - { - WriteIdentifier(withID, flags, tag); - WriteDL(contents.Length); - Write(contents, 0, contents.Length); - } + int count = stack.Length - pos; + stack[--pos] = (byte)(0x80 | count); - internal void WriteEncodingIL(bool withID, int identifier, Asn1Encodable[] elements) - { - WriteIdentifier(withID, identifier); - WriteByte(0x80); - WriteElements(elements); - WriteByte(0x00); - WriteByte(0x00); + Write(stack, pos, count + 1); +#endif } - internal void WriteIdentifier(bool withID, int identifier) + internal void WriteIdentifier(int tagClass, int tagNo) { - if (withID) + if (tagNo < 31) { - WriteByte((byte)identifier); + WriteByte((byte)(tagClass | tagNo)); + return; } - } - internal void WriteIdentifier(bool withID, int flags, int tag) - { - if (!withID) - { - // Don't write the identifier - } - else if (tag < 31) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span stack = stackalloc byte[6]; +#else + byte[] stack = new byte[6]; +#endif + int pos = stack.Length; + + stack[--pos] = (byte)(tagNo & 0x7F); + while (tagNo > 127) { - WriteByte((byte)(flags | tag)); + tagNo >>= 7; + stack[--pos] = (byte)(tagNo & 0x7F | 0x80); } - else - { - byte[] stack = new byte[6]; - int pos = stack.Length; - - stack[--pos] = (byte)(tag & 0x7F); - while (tag > 127) - { - tag >>= 7; - stack[--pos] = (byte)(tag & 0x7F | 0x80); - } - stack[--pos] = (byte)(flags | 0x1F); + stack[--pos] = (byte)(tagClass | 0x1F); - Write(stack, pos, stack.Length - pos); - } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Write(stack[pos..]); +#else + Write(stack, pos, stack.Length - pos); +#endif } - internal virtual void WritePrimitive(Asn1Object primitive, bool withID) + internal static IAsn1Encoding[] GetContentsEncodings(int encoding, Asn1Encodable[] elements) { - primitive.Encode(this, withID); + int count = elements.Length; + IAsn1Encoding[] contentsEncodings = new IAsn1Encoding[count]; + for (int i = 0; i < count; ++i) + { + contentsEncodings[i] = elements[i].ToAsn1Object().GetEncoding(encoding); + } + return contentsEncodings; } - internal virtual void WritePrimitives(Asn1Object[] primitives) + internal static int GetLengthOfContents(IAsn1Encoding[] contentsEncodings) { - for (int i = 0, count = primitives.Length; i < count; ++i) + int contentsLength = 0; + for (int i = 0, count = contentsEncodings.Length; i < count; ++i) { - WritePrimitive(primitives[i], true); + contentsLength += contentsEncodings[i].GetLength(); } + return contentsLength; } internal static int GetLengthOfDL(int dl) @@ -209,23 +174,13 @@ internal static int GetLengthOfDL(int dl) return length; } - internal static int GetLengthOfEncodingDL(bool withID, int contentsLength) - { - return (withID ? 1 : 0) + GetLengthOfDL(contentsLength) + contentsLength; - } - - internal static int GetLengthOfEncodingDL(bool withID, int tag, int contentsLength) - { - return (withID ? GetLengthOfIdentifier(tag) : 0) + GetLengthOfDL(contentsLength) + contentsLength; - } - - internal static int GetLengthOfIdentifier(int tag) + internal static int GetLengthOfIdentifier(int tagNo) { - if (tag < 31) + if (tagNo < 31) return 1; int length = 2; - while ((tag >>= 7) > 0) + while ((tagNo >>= 7) > 0) { ++length; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1ParsingException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1ParsingException.cs index 48b6a8f..ccae61b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1ParsingException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1ParsingException.cs @@ -1,12 +1,11 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 { -#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE) [Serializable] -#endif public class Asn1ParsingException : InvalidOperationException { @@ -15,16 +14,18 @@ public Asn1ParsingException() { } - public Asn1ParsingException( - string message) + public Asn1ParsingException(string message) : base(message) { } - public Asn1ParsingException( - string message, - Exception exception) - : base(message, exception) + public Asn1ParsingException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected Asn1ParsingException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1RelativeOid.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1RelativeOid.cs new file mode 100644 index 0000000..cd93da5 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1RelativeOid.cs @@ -0,0 +1,320 @@ +#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.Math; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + public class Asn1RelativeOid + : Asn1Object + { + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(Asn1RelativeOid), Asn1Tags.RelativeOid) {} + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return CreatePrimitive(octetString.GetOctets(), false); + } + } + + public static Asn1RelativeOid FromContents(byte[] contents) + { + return CreatePrimitive(contents, true); + } + + public static Asn1RelativeOid GetInstance(object obj) + { + if (obj == null) + return null; + + if (obj is Asn1RelativeOid asn1RelativeOid) + return asn1RelativeOid; + + if (obj is IAsn1Convertible asn1Convertible) + { + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is Asn1RelativeOid converted) + return converted; + } + else if (obj is byte[] bytes) + { + try + { + return (Asn1RelativeOid)FromByteArray(bytes); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct relative OID from byte[]: " + e.Message); + } + } + + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + } + + public static Asn1RelativeOid GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) + { + return (Asn1RelativeOid)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); + } + + private const long LongLimit = (long.MaxValue >> 7) - 0x7F; + + private readonly string identifier; + private byte[] contents; + + public Asn1RelativeOid(string identifier) + { + if (identifier == null) + throw new ArgumentNullException("identifier"); + if (!IsValidIdentifier(identifier, 0)) + throw new FormatException("string " + identifier + " not a relative OID"); + + this.identifier = identifier; + } + + private Asn1RelativeOid(Asn1RelativeOid oid, string branchID) + { + if (!IsValidIdentifier(branchID, 0)) + throw new FormatException("string " + branchID + " not a valid relative OID branch"); + + this.identifier = oid.Id + "." + branchID; + } + + private Asn1RelativeOid(byte[] contents, bool clone) + { + this.identifier = ParseContents(contents); + this.contents = clone ? Arrays.Clone(contents) : contents; + } + + public virtual Asn1RelativeOid Branch(string branchID) + { + return new Asn1RelativeOid(this, branchID); + } + + public string Id + { + get { return identifier; } + } + + public override string ToString() + { + return identifier; + } + + protected override bool Asn1Equals(Asn1Object asn1Object) + { + Asn1RelativeOid that = asn1Object as Asn1RelativeOid; + return null != that + && this.identifier == that.identifier; + } + + protected override int Asn1GetHashCode() + { + return identifier.GetHashCode(); + } + + internal override IAsn1Encoding GetEncoding(int encoding) + { + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.RelativeOid, GetContents()); + } + + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + return new PrimitiveEncoding(tagClass, tagNo, GetContents()); + } + + private void DoOutput(MemoryStream bOut) + { + OidTokenizer tok = new OidTokenizer(identifier); + while (tok.HasMoreTokens) + { + string token = tok.NextToken(); + if (token.Length <= 18) + { + WriteField(bOut, long.Parse(token)); + } + else + { + WriteField(bOut, new BigInteger(token)); + } + } + } + + private byte[] GetContents() + { + lock (this) + { + if (contents == null) + { + MemoryStream bOut = new MemoryStream(); + DoOutput(bOut); + contents = bOut.ToArray(); + } + + return contents; + } + } + + internal static Asn1RelativeOid CreatePrimitive(byte[] contents, bool clone) + { + return new Asn1RelativeOid(contents, clone); + } + + internal static bool IsValidIdentifier(string identifier, int from) + { + int digitCount = 0; + + int pos = identifier.Length; + while (--pos >= from) + { + char ch = identifier[pos]; + + if (ch == '.') + { + if (0 == digitCount || (digitCount > 1 && identifier[pos + 1] == '0')) + return false; + + digitCount = 0; + } + else if ('0' <= ch && ch <= '9') + { + ++digitCount; + } + else + { + return false; + } + } + + if (0 == digitCount || (digitCount > 1 && identifier[pos + 1] == '0')) + return false; + + return true; + } + + internal static void WriteField(Stream outputStream, long fieldValue) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span result = stackalloc byte[9]; +#else + byte[] result = new byte[9]; +#endif + int pos = 8; + result[pos] = (byte)((int)fieldValue & 0x7F); + while (fieldValue >= (1L << 7)) + { + fieldValue >>= 7; + result[--pos] = (byte)((int)fieldValue | 0x80); + } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + outputStream.Write(result[pos..]); +#else + outputStream.Write(result, pos, 9 - pos); +#endif + } + + internal static void WriteField(Stream outputStream, BigInteger fieldValue) + { + int byteCount = (fieldValue.BitLength + 6) / 7; + if (byteCount == 0) + { + outputStream.WriteByte(0); + } + else + { + BigInteger tmpValue = fieldValue; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span tmp = byteCount <= 16 + ? stackalloc byte[byteCount] + : new byte[byteCount]; +#else + byte[] tmp = new byte[byteCount]; +#endif + for (int i = byteCount - 1; i >= 0; i--) + { + tmp[i] = (byte)(tmpValue.IntValue | 0x80); + tmpValue = tmpValue.ShiftRight(7); + } + tmp[byteCount - 1] &= 0x7F; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + outputStream.Write(tmp); +#else + outputStream.Write(tmp, 0, tmp.Length); +#endif + } + } + + private static string ParseContents(byte[] contents) + { + StringBuilder objId = new StringBuilder(); + long value = 0; + BigInteger bigValue = null; + bool first = true; + + for (int i = 0; i != contents.Length; i++) + { + int b = contents[i]; + + if (value <= LongLimit) + { + value += b & 0x7F; + if ((b & 0x80) == 0) + { + if (first) + { + first = false; + } + else + { + 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) + { + first = false; + } + else + { + objId.Append('.'); + } + + objId.Append(bigValue); + bigValue = null; + value = 0; + } + else + { + bigValue = bigValue.ShiftLeft(7); + } + } + } + + return objId.ToString(); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1RelativeOid.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1RelativeOid.cs.meta new file mode 100644 index 0000000..90e06b3 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1RelativeOid.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ae6c5229271568c4f968518558270b85 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Sequence.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Sequence.cs index f2f757a..2e5e0e4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Sequence.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Sequence.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -10,10 +10,19 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 { public abstract class Asn1Sequence - : Asn1Object, IEnumerable + : Asn1Object, IEnumerable { - // NOTE: Only non-readonly to support LazyDerSequence - internal Asn1Encodable[] elements; + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(Asn1Sequence), Asn1Tags.Sequence) {} + + internal override Asn1Object FromImplicitConstructed(Asn1Sequence sequence) + { + return sequence; + } + } /** * return an Asn1Sequence from the given object. @@ -21,39 +30,33 @@ public abstract class Asn1Sequence * @param obj the object we want converted. * @exception ArgumentException if the object cannot be converted. */ - public static Asn1Sequence GetInstance( - object obj) + public static Asn1Sequence GetInstance(object obj) { - if (obj == null || obj is Asn1Sequence) - { - return (Asn1Sequence)obj; - } - else if (obj is Asn1SequenceParser) + if (obj == null) + return null; + + if (obj is Asn1Sequence asn1Sequence) + return asn1Sequence; + + if (obj is IAsn1Convertible asn1Convertible) { - return GetInstance(((Asn1SequenceParser)obj).ToAsn1Object()); + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is Asn1Sequence converted) + return converted; } - else if (obj is byte[]) + else if (obj is byte[] bytes) { try { - return GetInstance(FromByteArray((byte[])obj)); + return (Asn1Sequence)Meta.Instance.FromByteArray(bytes); } catch (IOException e) { throw new ArgumentException("failed to construct sequence from byte[]: " + e.Message); } } - else if (obj is Asn1Encodable) - { - Asn1Object primitive = ((Asn1Encodable)obj).ToAsn1Object(); - - if (primitive is Asn1Sequence) - { - return (Asn1Sequence)primitive; - } - } - throw new ArgumentException("Unknown object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** @@ -66,49 +69,18 @@ public static Asn1Sequence GetInstance( * dealing with implicitly tagged sequences you really should * be using this method. * - * @param obj the tagged object. - * @param explicitly true if the object is meant to be explicitly tagged, - * false otherwise. - * @exception ArgumentException if the tagged object cannot - * be converted. + * @param taggedObject the tagged object. + * @param declaredExplicit true if the object is meant to be explicitly tagged, false otherwise. + * @exception ArgumentException if the tagged object cannot be converted. */ - public static Asn1Sequence GetInstance( - Asn1TaggedObject obj, - bool explicitly) + public static Asn1Sequence GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - Asn1Object inner = obj.GetObject(); - - if (explicitly) - { - if (!obj.IsExplicit()) - throw new ArgumentException("object implicit - explicit expected."); - - return (Asn1Sequence) inner; - } - - // - // constructed object which appears to be explicitly tagged - // when it should be implicit means we have to add the - // surrounding sequence. - // - if (obj.IsExplicit()) - { - if (obj is BerTaggedObject) - { - return new BerSequence(inner); - } - - return new DerSequence(inner); - } - - if (inner is Asn1Sequence) - { - return (Asn1Sequence) inner; - } - - throw new ArgumentException("Unknown object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + return (Asn1Sequence)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); } + // NOTE: Only non-readonly to support LazyDLSequence + internal Asn1Encodable[] elements; + protected internal Asn1Sequence() { this.elements = Asn1EncodableVector.EmptyElements; @@ -117,11 +89,21 @@ protected internal Asn1Sequence() protected internal Asn1Sequence(Asn1Encodable element) { if (null == element) - throw new ArgumentNullException("element"); + throw new ArgumentNullException(nameof(element)); this.elements = new Asn1Encodable[]{ element }; } + protected internal Asn1Sequence(Asn1Encodable element1, Asn1Encodable element2) + { + if (null == element1) + throw new ArgumentNullException(nameof(element1)); + if (null == element2) + throw new ArgumentNullException(nameof(element2)); + + this.elements = new Asn1Encodable[]{ element1, element2 }; + } + protected internal Asn1Sequence(params Asn1Encodable[] elements) { if (Arrays.IsNullOrContainsNull(elements)) @@ -130,6 +112,11 @@ protected internal Asn1Sequence(params Asn1Encodable[] elements) this.elements = Asn1EncodableVector.CloneElements(elements); } + internal Asn1Sequence(Asn1Encodable[] elements, bool clone) + { + this.elements = clone ? Asn1EncodableVector.CloneElements(elements) : elements; + } + protected internal Asn1Sequence(Asn1EncodableVector elementVector) { if (null == elementVector) @@ -138,9 +125,15 @@ protected internal Asn1Sequence(Asn1EncodableVector elementVector) this.elements = elementVector.TakeElements(); } - public virtual IEnumerator GetEnumerator() + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { - return elements.GetEnumerator(); + return GetEnumerator(); + } + + public virtual IEnumerator GetEnumerator() + { + IEnumerable e = elements; + return e.GetEnumerator(); } private class Asn1SequenceParserImpl @@ -154,6 +147,7 @@ public Asn1SequenceParserImpl( Asn1Sequence outer) { this.outer = outer; + // NOTE: Call Count here to 'force' a LazyDerSequence this.max = outer.Count; } @@ -204,6 +198,18 @@ public virtual int Count get { return elements.Length; } } + public virtual T[] MapElements(Func func) + { + // NOTE: Call Count here to 'force' a LazyDerSequence + int count = Count; + T[] result = new T[count]; + for (int i = 0; i < count; ++i) + { + result[i] = func(elements[i]); + } + return result; + } + public virtual Asn1Encodable[] ToArray() { return Asn1EncodableVector.CloneElements(elements); @@ -211,8 +217,8 @@ public virtual Asn1Encodable[] ToArray() protected override int Asn1GetHashCode() { - //return Arrays.GetHashCode(elements); - int i = elements.Length; + // NOTE: Call Count here to 'force' a LazyDerSequence + int i = Count; int hc = i + 1; while (--i >= 0) @@ -230,6 +236,7 @@ protected override bool Asn1Equals(Asn1Object asn1Object) if (null == that) return false; + // NOTE: Call Count here (on both) to 'force' a LazyDerSequence int count = this.Count; if (that.Count != count) return false; @@ -239,7 +246,7 @@ protected override bool Asn1Equals(Asn1Object asn1Object) Asn1Object o1 = this.elements[i].ToAsn1Object(); Asn1Object o2 = that.elements[i].ToAsn1Object(); - if (o1 != o2 && !o1.CallAsn1Equals(o2)) + if (!o1.Equals(o2)) return false; } @@ -250,6 +257,27 @@ public override string ToString() { return CollectionUtilities.ToString(elements); } + + // TODO[asn1] Preferably return an Asn1BitString[] (doesn't exist yet) + internal DerBitString[] GetConstructedBitStrings() + { + return MapElements(DerBitString.GetInstance); + } + + internal Asn1OctetString[] GetConstructedOctetStrings() + { + return MapElements(Asn1OctetString.GetInstance); + } + + // TODO[asn1] Preferably return an Asn1BitString (doesn't exist yet) + internal abstract DerBitString ToAsn1BitString(); + + // TODO[asn1] Preferably return an Asn1External (doesn't exist yet) + internal abstract DerExternal ToAsn1External(); + + internal abstract Asn1OctetString ToAsn1OctetString(); + + internal abstract Asn1Set ToAsn1Set(); } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Set.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Set.cs index a53d112..d1245ab 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Set.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Set.cs @@ -1,25 +1,29 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.Diagnostics; using System.IO; -#if PORTABLE || NETFX_CORE -using System.Collections.Generic; -using System.Linq; -#endif - using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 { - abstract public class Asn1Set - : Asn1Object, IEnumerable + public abstract class Asn1Set + : Asn1Object, IEnumerable { - // NOTE: Only non-readonly to support LazyDerSet - internal Asn1Encodable[] elements; + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(Asn1Set), Asn1Tags.Set) {} + + internal override Asn1Object FromImplicitConstructed(Asn1Sequence sequence) + { + return sequence.ToAsn1Set(); + } + } /** * return an ASN1Set from the given object. @@ -27,39 +31,33 @@ abstract public class Asn1Set * @param obj the object we want converted. * @exception ArgumentException if the object cannot be converted. */ - public static Asn1Set GetInstance( - object obj) + public static Asn1Set GetInstance(object obj) { - if (obj == null || obj is Asn1Set) - { - return (Asn1Set)obj; - } - else if (obj is Asn1SetParser) + if (obj == null) + return null; + + if (obj is Asn1Set asn1Set) + return asn1Set; + + if (obj is IAsn1Convertible asn1Convertible) { - return Asn1Set.GetInstance(((Asn1SetParser)obj).ToAsn1Object()); + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is Asn1Set converted) + return converted; } - else if (obj is byte[]) + else if (obj is byte[] bytes) { try { - return Asn1Set.GetInstance(FromByteArray((byte[])obj)); + return (Asn1Set)Meta.Instance.FromByteArray(bytes); } catch (IOException e) { throw new ArgumentException("failed to construct set from byte[]: " + e.Message); } } - else if (obj is Asn1Encodable) - { - Asn1Object primitive = ((Asn1Encodable)obj).ToAsn1Object(); - - if (primitive is Asn1Set) - { - return (Asn1Set)primitive; - } - } - throw new ArgumentException("Unknown object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** @@ -72,65 +70,23 @@ public static Asn1Set GetInstance( * dealing with implicitly tagged sets you really should * be using this method. * - * @param obj the tagged object. - * @param explicitly true if the object is meant to be explicitly tagged - * false otherwise. - * @exception ArgumentException if the tagged object cannot - * be converted. + * @param taggedObject the tagged object. + * @param declaredExplicit true if the object is meant to be explicitly tagged false otherwise. + * @exception ArgumentException if the tagged object cannot be converted. */ - public static Asn1Set GetInstance( - Asn1TaggedObject obj, - bool explicitly) + public static Asn1Set GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - Asn1Object inner = obj.GetObject(); - - if (explicitly) - { - if (!obj.IsExplicit()) - throw new ArgumentException("object implicit - explicit expected."); - - return (Asn1Set) inner; - } - - // - // constructed object which appears to be explicitly tagged - // and it's really implicit means we have to add the - // surrounding sequence. - // - if (obj.IsExplicit()) - { - return new DerSet(inner); - } - - if (inner is Asn1Set) - { - return (Asn1Set) inner; - } - - // - // in this case the parser returns a sequence, convert it - // into a set. - // - if (inner is Asn1Sequence) - { - Asn1EncodableVector v = new Asn1EncodableVector(); - Asn1Sequence s = (Asn1Sequence) inner; - - foreach (Asn1Encodable ae in s) - { - v.Add(ae); - } - - // TODO Should be able to construct set directly from sequence? - return new DerSet(v, false); - } - - throw new ArgumentException("Unknown object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + return (Asn1Set)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); } + // NOTE: Only non-readonly to support LazyDLSet + internal Asn1Encodable[] elements; + internal bool isSorted; + protected internal Asn1Set() { this.elements = Asn1EncodableVector.EmptyElements; + this.isSorted = true; } protected internal Asn1Set(Asn1Encodable element) @@ -139,27 +95,58 @@ protected internal Asn1Set(Asn1Encodable element) throw new ArgumentNullException("element"); this.elements = new Asn1Encodable[]{ element }; + this.isSorted = true; } - protected internal Asn1Set(params Asn1Encodable[] elements) + protected internal Asn1Set(Asn1Encodable[] elements, bool doSort) { if (Arrays.IsNullOrContainsNull(elements)) throw new NullReferenceException("'elements' cannot be null, or contain null"); - this.elements = Asn1EncodableVector.CloneElements(elements); + Asn1Encodable[] tmp = Asn1EncodableVector.CloneElements(elements); + if (doSort && tmp.Length >= 2) + { + tmp = Sort(tmp); + } + + this.elements = tmp; + this.isSorted = doSort || tmp.Length < 2; } - protected internal Asn1Set(Asn1EncodableVector elementVector) + protected internal Asn1Set(Asn1EncodableVector elementVector, bool doSort) { if (null == elementVector) throw new ArgumentNullException("elementVector"); - this.elements = elementVector.TakeElements(); + Asn1Encodable[] tmp; + if (doSort && elementVector.Count >= 2) + { + tmp = Sort(elementVector.CopyElements()); + } + else + { + tmp = elementVector.TakeElements(); + } + + this.elements = tmp; + this.isSorted = doSort || tmp.Length < 2; + } + + protected internal Asn1Set(bool isSorted, Asn1Encodable[] elements) + { + this.elements = elements; + this.isSorted = isSorted || elements.Length < 2; } - public virtual IEnumerator GetEnumerator() + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { - return elements.GetEnumerator(); + return GetEnumerator(); + } + + public virtual IEnumerator GetEnumerator() + { + IEnumerable e = elements; + return e.GetEnumerator(); } /** @@ -178,6 +165,18 @@ public virtual int Count get { return elements.Length; } } + public virtual T[] MapElements(Func func) + { + // NOTE: Call Count here to 'force' a LazyDerSet + int count = Count; + T[] result = new T[count]; + for (int i = 0; i < count; ++i) + { + result[i] = func(elements[i]); + } + return result; + } + public virtual Asn1Encodable[] ToArray() { return Asn1EncodableVector.CloneElements(elements); @@ -194,6 +193,7 @@ public Asn1SetParserImpl( Asn1Set outer) { this.outer = outer; + // NOTE: Call Count here to 'force' a LazyDerSet this.max = outer.Count; } @@ -229,8 +229,8 @@ public Asn1SetParser Parser protected override int Asn1GetHashCode() { - //return Arrays.GetHashCode(elements); - int i = elements.Length; + // NOTE: Call Count here to 'force' a LazyDerSet + int i = Count; int hc = i + 1; while (--i >= 0) @@ -248,6 +248,7 @@ protected override bool Asn1Equals(Asn1Object asn1Object) if (null == that) return false; + // NOTE: Call Count here (on both) to 'force' a LazyDerSet int count = this.Count; if (that.Count != count) return false; @@ -257,56 +258,38 @@ protected override bool Asn1Equals(Asn1Object asn1Object) Asn1Object o1 = this.elements[i].ToAsn1Object(); Asn1Object o2 = that.elements[i].ToAsn1Object(); - if (o1 != o2 && !o1.CallAsn1Equals(o2)) + if (!o1.Equals(o2)) return false; } return true; } - protected internal void Sort() + public override string ToString() + { + return CollectionUtilities.ToString(elements); + } + + internal static Asn1Encodable[] Sort(Asn1Encodable[] elements) { - if (elements.Length < 2) - return; - -#if PORTABLE || NETFX_CORE - this.elements = elements - .Cast() - .Select(a => new { Item = a, Key = a.GetEncoded(Asn1Encodable.Der) }) - .OrderBy(t => t.Key, new DerComparer()) - .Select(t => t.Item) - .ToArray(); -#else int count = elements.Length; + if (count < 2) + return elements; + byte[][] keys = new byte[count][]; for (int i = 0; i < count; ++i) { keys[i] = elements[i].GetEncoded(Der); } Array.Sort(keys, elements, new DerComparer()); -#endif - } - - public override string ToString() - { - return CollectionUtilities.ToString(elements); + return elements; } -#if PORTABLE || NETFX_CORE private class DerComparer : IComparer { - public int Compare(byte[] x, byte[] y) - { - byte[] a = x, b = y; -#else - private class DerComparer - : IComparer - { - public int Compare(object x, object y) + public int Compare(byte[] a, byte[] b) { - byte[] a = (byte[])x, b = (byte[])y; -#endif Debug.Assert(a.Length >= 2 && b.Length >= 2); /* @@ -326,6 +309,10 @@ public int Compare(object x, object y) if (a0 != b0) return a0 < b0 ? -1 : 1; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int compareLength = System.Math.Min(a.Length, b.Length) - 1; + return a.AsSpan(1, compareLength).SequenceCompareTo(b.AsSpan(1, compareLength)); +#else int len = System.Math.Min(a.Length, b.Length); for (int i = 1; i < len; ++i) { @@ -335,6 +322,7 @@ public int Compare(object x, object y) } Debug.Assert(a.Length == b.Length); return 0; +#endif } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Tag.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Tag.cs new file mode 100644 index 0000000..f491772 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Tag.cs @@ -0,0 +1,35 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + internal sealed class Asn1Tag + { + internal static Asn1Tag Create(int tagClass, int tagNo) + { + return new Asn1Tag(tagClass, tagNo); + } + + private readonly int m_tagClass; + private readonly int m_tagNo; + + private Asn1Tag(int tagClass, int tagNo) + { + m_tagClass = tagClass; + m_tagNo = tagNo; + } + + internal int TagClass + { + get { return m_tagClass; } + } + + internal int TagNo + { + get { return m_tagNo; } + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Tag.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Tag.cs.meta new file mode 100644 index 0000000..5df92a5 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Tag.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 86fc5dd31416c1b4797892dbb3a76111 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1TaggedObject.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1TaggedObject.cs index c178df6..06faecd 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1TaggedObject.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1TaggedObject.cs @@ -1,6 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -14,104 +15,157 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public abstract class Asn1TaggedObject : Asn1Object, Asn1TaggedObjectParser { - internal static bool IsConstructed(bool isExplicit, Asn1Object obj) - { - if (isExplicit || obj is Asn1Sequence || obj is Asn1Set) - return true; - Asn1TaggedObject tagged = obj as Asn1TaggedObject; - if (tagged == null) - return false; - return IsConstructed(tagged.IsExplicit(), tagged.GetObject()); - } + private const int DeclaredExplicit = 1; + private const int DeclaredImplicit = 2; + // TODO It will probably be better to track parsing constructed vs primitive instead + private const int ParsedExplicit = 3; + private const int ParsedImplicit = 4; - internal int tagNo; -// internal bool empty; - internal bool explicitly = true; - internal Asn1Encodable obj; + public static Asn1TaggedObject GetInstance(object obj) + { + if (obj == null) + return null; - static public Asn1TaggedObject GetInstance( - Asn1TaggedObject obj, - bool explicitly) - { - if (explicitly) + if (obj is Asn1TaggedObject asn1TaggedObject) + return asn1TaggedObject; + + if (obj is IAsn1Convertible asn1Convertible) + { + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is Asn1TaggedObject converted) + return converted; + } + else if (obj is byte[] bytes) { - return GetInstance(obj.GetObject()); + try + { + return CheckedCast(FromByteArray(bytes)); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct tagged object from byte[]: " + e.Message); + } } - throw new ArgumentException("implicitly tagged tagged object"); + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + } + + public static Asn1TaggedObject GetInstance(object obj, int tagClass) + { + if (obj == null) + throw new ArgumentNullException(nameof(obj)); + + Asn1TaggedObject taggedObject = GetInstance(obj); + if (tagClass != taggedObject.TagClass) + throw new ArgumentException("unexpected tag in GetInstance: " + Asn1Utilities.GetTagText(taggedObject)); + + return taggedObject; } - static public Asn1TaggedObject GetInstance( - object obj) - { - if (obj == null || obj is Asn1TaggedObject) - { - return (Asn1TaggedObject) obj; - } + public static Asn1TaggedObject GetInstance(object obj, int tagClass, int tagNo) + { + if (obj == null) + throw new ArgumentNullException(nameof(obj)); - throw new ArgumentException("Unknown object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); - } + Asn1TaggedObject taggedObject = GetInstance(obj); + if (!taggedObject.HasTag(tagClass, tagNo)) + throw new ArgumentException("unexpected tag in GetInstance: " + Asn1Utilities.GetTagText(taggedObject)); - /** - * @param tagNo the tag number for this object. - * @param obj the tagged object. - */ - protected Asn1TaggedObject( - int tagNo, - Asn1Encodable obj) + return taggedObject; + } + + public static Asn1TaggedObject GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - this.explicitly = true; - this.tagNo = tagNo; - this.obj = obj; + if (Asn1Tags.ContextSpecific != taggedObject.TagClass) + throw new InvalidOperationException("this method only valid for CONTEXT_SPECIFIC tags"); + + if (declaredExplicit) + return taggedObject.GetExplicitBaseTagged(); + + throw new ArgumentException("this method not valid for implicitly tagged tagged objects"); } + internal readonly int explicitness; + internal readonly int tagClass; + internal readonly int tagNo; + internal readonly Asn1Encodable obj; + /** * @param explicitly true if the object is explicitly tagged. * @param tagNo the tag number for this object. * @param obj the tagged object. */ - protected Asn1TaggedObject( - bool explicitly, - int tagNo, - Asn1Encodable obj) + protected Asn1TaggedObject(bool isExplicit, int tagNo, Asn1Encodable obj) + : this(isExplicit, Asn1Tags.ContextSpecific, tagNo, obj) { - // IAsn1Choice marker interface 'insists' on explicit tagging - this.explicitly = explicitly || (obj is IAsn1Choice); + } + + protected Asn1TaggedObject(bool isExplicit, int tagClass, int tagNo, Asn1Encodable obj) + : this(isExplicit ? DeclaredExplicit : DeclaredImplicit, tagClass, tagNo, obj) + { + } + + internal Asn1TaggedObject(int explicitness, int tagClass, int tagNo, Asn1Encodable obj) + { + if (null == obj) + throw new ArgumentNullException("obj"); + if (Asn1Tags.Universal == tagClass || (tagClass & Asn1Tags.Private) != tagClass) + throw new ArgumentException("invalid tag class: " + tagClass, "tagClass"); + + this.explicitness = (obj is IAsn1Choice) ? DeclaredExplicit : explicitness; + this.tagClass = tagClass; this.tagNo = tagNo; this.obj = obj; } - protected override bool Asn1Equals( - Asn1Object asn1Object) + protected override bool Asn1Equals(Asn1Object asn1Object) { - Asn1TaggedObject other = asn1Object as Asn1TaggedObject; - - if (other == null) - return false; + Asn1TaggedObject that = asn1Object as Asn1TaggedObject; + if (null == that || this.tagNo != that.tagNo || this.tagClass != that.tagClass) + return false; - return this.tagNo == other.tagNo -// && this.empty == other.empty - && this.explicitly == other.explicitly // TODO Should this be part of equality? - && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(GetObject(), other.GetObject()); - } + if (this.explicitness != that.explicitness) + { + /* + * TODO This seems incorrect for some cases of implicit tags e.g. if one is a + * declared-implicit SET and the other a parsed object. + */ + if (this.IsExplicit() != that.IsExplicit()) + return false; + } - protected override int Asn1GetHashCode() - { - int code = tagNo.GetHashCode(); + Asn1Object p1 = this.obj.ToAsn1Object(); + Asn1Object p2 = that.obj.ToAsn1Object(); - // TODO: actually this is wrong - the problem is that a re-encoded - // object may end up with a different hashCode due to implicit - // tagging. As implicit tagging is ambiguous if a sequence is involved - // it seems the only correct method for both equals and hashCode is to - // compare the encodings... -// code ^= explicitly.GetHashCode(); + if (p1 == p2) + return true; - if (obj != null) + if (!this.IsExplicit()) { - code ^= obj.GetHashCode(); + try + { + byte[] d1 = this.GetEncoded(); + byte[] d2 = that.GetEncoded(); + + return Arrays.AreEqual(d1, d2); + } + catch (IOException) + { + return false; + } } - return code; + return p1.CallAsn1Equals(p2); + } + + protected override int Asn1GetHashCode() + { + return (tagClass * 7919) ^ tagNo ^ (IsExplicit() ? 0x0F : 0xF0) ^ obj.ToAsn1Object().CallAsn1GetHashCode(); + } + + public int TagClass + { + get { return tagClass; } } public int TagNo @@ -119,7 +173,17 @@ public int TagNo get { return tagNo; } } - /** + public bool HasContextTag(int tagNo) + { + return this.tagClass == Asn1Tags.ContextSpecific && this.tagNo == tagNo; + } + + public bool HasTag(int tagClass, int tagNo) + { + return this.tagClass == tagClass && this.tagNo == tagNo; + } + + /** * return whether or not the object may be explicitly tagged. *

* Note: if the object has been read from an input stream, the only @@ -130,15 +194,30 @@ public int TagNo */ public bool IsExplicit() { - return explicitly; + // TODO New methods like 'IsKnownExplicit' etc. to distinguish uncertain cases? + switch (explicitness) + { + case DeclaredExplicit: + case ParsedExplicit: + return true; + default: + return false; + } } - public bool IsEmpty() + internal bool IsParsed() { - return false; //empty; + switch (explicitness) + { + case ParsedExplicit: + case ParsedImplicit: + return true; + default: + return false; + } } - /** + /** * return whatever was following the tag. *

* Note: tagged objects are generally context dependent if you're @@ -147,46 +226,184 @@ public bool IsEmpty() */ public Asn1Object GetObject() { - if (obj != null) + if (Asn1Tags.ContextSpecific != TagClass) + throw new InvalidOperationException("this method only valid for CONTEXT_SPECIFIC tags"); + + return obj.ToAsn1Object(); + } + + /** + * Needed for open types, until we have better type-guided parsing support. Use sparingly for other + * purposes, and prefer {@link #getExplicitBaseTagged()}, {@link #getImplicitBaseTagged(int, int)} or + * {@link #getBaseUniversal(boolean, int)} where possible. Before using, check for matching tag + * {@link #getTagClass() class} and {@link #getTagNo() number}. + */ + public Asn1Encodable GetBaseObject() + { + return obj; + } + + /** + * Needed for open types, until we have better type-guided parsing support. Use + * sparingly for other purposes, and prefer {@link #getExplicitBaseTagged()} or + * {@link #getBaseUniversal(boolean, int)} where possible. Before using, check + * for matching tag {@link #getTagClass() class} and {@link #getTagNo() number}. + */ + public Asn1Encodable GetExplicitBaseObject() + { + if (!IsExplicit()) + throw new InvalidOperationException("object implicit - explicit expected."); + + return obj; + } + + public Asn1TaggedObject GetExplicitBaseTagged() + { + if (!IsExplicit()) + throw new InvalidOperationException("object implicit - explicit expected."); + + return CheckedCast(obj.ToAsn1Object()); + } + + public Asn1TaggedObject GetImplicitBaseTagged(int baseTagClass, int baseTagNo) + { + if (Asn1Tags.Universal == baseTagClass || (baseTagClass & Asn1Tags.Private) != baseTagClass) + throw new ArgumentException("invalid base tag class: " + baseTagClass, "baseTagClass"); + + switch (explicitness) { - return obj.ToAsn1Object(); + case DeclaredExplicit: + throw new InvalidOperationException("object explicit - implicit expected."); + + case DeclaredImplicit: + { + Asn1TaggedObject declared = CheckedCast(obj.ToAsn1Object()); + return Asn1Utilities.CheckTag(declared, baseTagClass, baseTagNo); } - return null; + // Parsed; return a virtual tag (i.e. that couldn't have been present in the encoding) + default: + return ReplaceTag(baseTagClass, baseTagNo); + } } - /** - * Return the object held in this tagged object as a parser assuming it has - * the type of the passed in tag. If the object doesn't have a parser - * associated with it, the base object is returned. - */ - public IAsn1Convertible GetObjectParser( - int tag, - bool isExplicit) - { - switch (tag) - { - case Asn1Tags.Set: - return Asn1Set.GetInstance(this, isExplicit).Parser; - case Asn1Tags.Sequence: - return Asn1Sequence.GetInstance(this, isExplicit).Parser; - case Asn1Tags.OctetString: - return Asn1OctetString.GetInstance(this, isExplicit).Parser; - } - - if (isExplicit) - { - return GetObject(); - } - - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("implicit tagging for tag: " + tag); - } + public Asn1Object GetBaseUniversal(bool declaredExplicit, int tagNo) + { + Asn1UniversalType universalType = Asn1UniversalTypes.Get(tagNo); + if (null == universalType) + throw new ArgumentException("unsupported UNIVERSAL tag number: " + tagNo, "tagNo"); + + return GetBaseUniversal(declaredExplicit, universalType); + } + + internal Asn1Object GetBaseUniversal(bool declaredExplicit, Asn1UniversalType universalType) + { + if (declaredExplicit) + { + if (!IsExplicit()) + throw new InvalidOperationException("object explicit - implicit expected."); + + return universalType.CheckedCast(obj.ToAsn1Object()); + } + + if (DeclaredExplicit == explicitness) + throw new InvalidOperationException("object explicit - implicit expected."); + + Asn1Object baseObject = obj.ToAsn1Object(); + switch (explicitness) + { + case ParsedExplicit: + return universalType.FromImplicitConstructed(RebuildConstructed(baseObject)); + case ParsedImplicit: + { + if (baseObject is Asn1Sequence asn1Sequence) + return universalType.FromImplicitConstructed(asn1Sequence); + + return universalType.FromImplicitPrimitive((DerOctetString)baseObject); + } + default: + return universalType.CheckedCast(baseObject); + } + } + + public IAsn1Convertible ParseBaseUniversal(bool declaredExplicit, int baseTagNo) + { + Asn1Object asn1Object = GetBaseUniversal(declaredExplicit, baseTagNo); + + switch (baseTagNo) + { + case Asn1Tags.BitString: + return ((DerBitString)asn1Object).Parser; + case Asn1Tags.OctetString: + return ((Asn1OctetString)asn1Object).Parser; + case Asn1Tags.Sequence: + return ((Asn1Sequence)asn1Object).Parser; + case Asn1Tags.Set: + return ((Asn1Set)asn1Object).Parser; + } + + return asn1Object; + } + + public IAsn1Convertible ParseExplicitBaseObject() + { + return GetExplicitBaseObject(); + } + + public Asn1TaggedObjectParser ParseExplicitBaseTagged() + { + return GetExplicitBaseTagged(); + } + + public Asn1TaggedObjectParser ParseImplicitBaseTagged(int baseTagClass, int baseTagNo) + { + return GetImplicitBaseTagged(baseTagClass, baseTagNo); + } public override string ToString() { - return "[" + tagNo + "]" + obj; + return Asn1Utilities.GetTagText(tagClass, tagNo) + obj; } - } + + internal abstract string Asn1Encoding { get; } + + internal abstract Asn1Sequence RebuildConstructed(Asn1Object asn1Object); + + internal abstract Asn1TaggedObject ReplaceTag(int tagClass, int tagNo); + + internal static Asn1Object CreateConstructedDL(int tagClass, int tagNo, Asn1EncodableVector contentsElements) + { + bool maybeExplicit = (contentsElements.Count == 1); + + return maybeExplicit + ? new DLTaggedObject(ParsedExplicit, tagClass, tagNo, contentsElements[0]) + : new DLTaggedObject(ParsedImplicit, tagClass, tagNo, DLSequence.FromVector(contentsElements)); + } + + internal static Asn1Object CreateConstructedIL(int tagClass, int tagNo, Asn1EncodableVector contentsElements) + { + bool maybeExplicit = (contentsElements.Count == 1); + + return maybeExplicit + ? new BerTaggedObject(ParsedExplicit, tagClass, tagNo, contentsElements[0]) + : new BerTaggedObject(ParsedImplicit, tagClass, tagNo, BerSequence.FromVector(contentsElements)); + } + + internal static Asn1Object CreatePrimitive(int tagClass, int tagNo, byte[] contentsOctets) + { + // Note: !CONSTRUCTED => IMPLICIT + return new DLTaggedObject(ParsedImplicit, tagClass, tagNo, new DerOctetString(contentsOctets)); + } + + private static Asn1TaggedObject CheckedCast(Asn1Object asn1Object) + { + Asn1TaggedObject taggedObject = asn1Object as Asn1TaggedObject; + if (null != taggedObject) + return taggedObject; + + throw new InvalidOperationException("unexpected object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(asn1Object)); + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Tags.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Tags.cs index 1705555..94c9568 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Tags.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Tags.cs @@ -43,10 +43,10 @@ public class Asn1Tags public const int Universal = 0x00; public const int Application = 0x40; - - public const int Tagged = 0x80; public const int ContextSpecific = 0x80; public const int Private = 0xC0; + + public const int Flags = 0xE0; } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Type.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Type.cs new file mode 100644 index 0000000..900044f --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Type.cs @@ -0,0 +1,33 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + internal abstract class Asn1Type + { + internal readonly Type m_platformType; + + internal Asn1Type(Type platformType) + { + m_platformType = platformType; + } + + internal Type PlatformType + { + get { return m_platformType; } + } + + public sealed override bool Equals(object that) + { + return this == that; + } + + public sealed override int GetHashCode() + { + return base.GetHashCode(); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Type.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Type.cs.meta new file mode 100644 index 0000000..ac1b51b --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Type.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ffac7d6916dbabc449fd3c8f9f3b51c5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1UniversalType.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1UniversalType.cs new file mode 100644 index 0000000..db051b8 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1UniversalType.cs @@ -0,0 +1,63 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.IO; +#if UNITY_WSA && !UNITY_EDITOR && !ENABLE_IL2CPP +using System.TypeFix; +#endif + +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + internal abstract class Asn1UniversalType + : Asn1Type + { + internal readonly Asn1Tag m_tag; + + internal Asn1UniversalType(Type platformType, int tagNo) + : base(platformType) + { + m_tag = Asn1Tag.Create(Asn1Tags.Universal, tagNo); + } + + internal Asn1Object CheckedCast(Asn1Object asn1Object) + { + if (PlatformType.IsInstanceOfType(asn1Object)) + return asn1Object; + + throw new InvalidOperationException("unexpected object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(asn1Object)); + } + + internal virtual Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + throw new InvalidOperationException("unexpected implicit primitive encoding"); + } + + internal virtual Asn1Object FromImplicitConstructed(Asn1Sequence sequence) + { + throw new InvalidOperationException("unexpected implicit constructed encoding"); + } + + /// + internal Asn1Object FromByteArray(byte[] bytes) + { + return CheckedCast(Asn1Object.FromByteArray(bytes)); + } + + internal Asn1Object GetContextInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) + { + if (Asn1Tags.ContextSpecific != taggedObject.TagClass) + throw new InvalidOperationException("this method only valid for CONTEXT_SPECIFIC tags"); + + return CheckedCast(taggedObject.GetBaseUniversal(declaredExplicit, this)); + } + + internal Asn1Tag Tag + { + get { return m_tag; } + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1UniversalType.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1UniversalType.cs.meta new file mode 100644 index 0000000..40e9a05 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1UniversalType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1449dc3fb760c69478b79ac2d2d26975 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1UniversalTypes.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1UniversalTypes.cs new file mode 100644 index 0000000..67d9649 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1UniversalTypes.cs @@ -0,0 +1,78 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + internal sealed class Asn1UniversalTypes + { + private Asn1UniversalTypes() + { + } + + internal static Asn1UniversalType Get(int tagNo) + { + switch (tagNo) + { + case Asn1Tags.Boolean: + return DerBoolean.Meta.Instance; + case Asn1Tags.Integer: + return DerInteger.Meta.Instance; + case Asn1Tags.BitString: + return DerBitString.Meta.Instance; + case Asn1Tags.OctetString: + return Asn1OctetString.Meta.Instance; + case Asn1Tags.Null: + return Asn1Null.Meta.Instance; + case Asn1Tags.ObjectIdentifier: + return DerObjectIdentifier.Meta.Instance; + case Asn1Tags.ObjectDescriptor: // [UNIVERSAL 7] IMPLICIT GraphicString + return Asn1ObjectDescriptor.Meta.Instance; + case Asn1Tags.External: + return DerExternal.Meta.Instance; + case Asn1Tags.Enumerated: + return DerEnumerated.Meta.Instance; + case Asn1Tags.Utf8String: // [UNIVERSAL 12] IMPLICIT OCTET STRING (encode as if) + return DerUtf8String.Meta.Instance; + case Asn1Tags.RelativeOid: + return Asn1RelativeOid.Meta.Instance; + case Asn1Tags.Sequence: + return Asn1Sequence.Meta.Instance; + case Asn1Tags.Set: + return Asn1Set.Meta.Instance; + case Asn1Tags.NumericString: // [UNIVERSAL 18] IMPLICIT OCTET STRING (encode as if) + return DerNumericString.Meta.Instance; + case Asn1Tags.PrintableString: // [UNIVERSAL 19] IMPLICIT OCTET STRING (encode as if) + return DerPrintableString.Meta.Instance; + case Asn1Tags.T61String: // [UNIVERSAL 20] IMPLICIT OCTET STRING (encode as if) + return DerT61String.Meta.Instance; + case Asn1Tags.VideotexString: // [UNIVERSAL 21] IMPLICIT OCTET STRING (encode as if) + return DerVideotexString.Meta.Instance; + case Asn1Tags.IA5String: // [UNIVERSAL 22] IMPLICIT OCTET STRING (encode as if) + return DerIA5String.Meta.Instance; + case Asn1Tags.UtcTime: // [UNIVERSAL 23] IMPLICIT VisibleString (restricted values) + return Asn1UtcTime.Meta.Instance; + case Asn1Tags.GeneralizedTime: // [UNIVERSAL 24] IMPLICIT VisibleString (restricted values) + return Asn1GeneralizedTime.Meta.Instance; + case Asn1Tags.GraphicString: // [UNIVERSAL 25] IMPLICIT OCTET STRING (encode as if) + return DerGraphicString.Meta.Instance; + case Asn1Tags.VisibleString: // [UNIVERSAL 26] IMPLICIT OCTET STRING (encode as if) + return DerVisibleString.Meta.Instance; + case Asn1Tags.GeneralString: // [UNIVERSAL 27] IMPLICIT OCTET STRING (encode as if) + return DerGeneralString.Meta.Instance; + case Asn1Tags.UniversalString: // [UNIVERSAL 28] IMPLICIT OCTET STRING (encode as if) + return DerUniversalString.Meta.Instance; + case Asn1Tags.BmpString: // [UNIVERSAL 30] IMPLICIT OCTET STRING (encode as if) + return DerBmpString.Meta.Instance; + + case Asn1Tags.Real: + case Asn1Tags.EmbeddedPdv: + case Asn1Tags.UnrestrictedString: + default: + return null; + } + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1UniversalTypes.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1UniversalTypes.cs.meta new file mode 100644 index 0000000..534e2bf --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1UniversalTypes.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 839094e1a57356a4eaefab55a4481ef9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1UtcTime.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1UtcTime.cs new file mode 100644 index 0000000..e24dcd2 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1UtcTime.cs @@ -0,0 +1,257 @@ +#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; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + ///

UTCTime ASN.1 type + public class Asn1UtcTime + : Asn1Object + { + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(Asn1UtcTime), Asn1Tags.UtcTime) {} + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return CreatePrimitive(octetString.GetOctets()); + } + } + + /** + * return a UTC Time from the passed in object. + * + * @exception ArgumentException if the object cannot be converted. + */ + public static Asn1UtcTime GetInstance(object obj) + { + if (obj == null) + return null; + + if (obj is Asn1UtcTime asn1UtcTime) + return asn1UtcTime; + + if (obj is IAsn1Convertible asn1Convertible) + { + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is Asn1UtcTime converted) + return converted; + } + else if (obj is byte[] bytes) + { + try + { + return (Asn1UtcTime)Meta.Instance.FromByteArray(bytes); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct UTC time from byte[]: " + e.Message); + } + } + + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), nameof(obj)); + } + + public static Asn1UtcTime GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) + { + return (Asn1UtcTime)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); + } + + private readonly string m_timeString; + private readonly DateTime m_dateTime; + private readonly bool m_dateTimeLocked; + private readonly int m_twoDigitYearMax; + + public Asn1UtcTime(string timeString) + { + m_timeString = timeString ?? throw new ArgumentNullException(nameof(timeString)); + + try + { + m_dateTime = FromString(timeString, out m_twoDigitYearMax); + m_dateTimeLocked = false; + } + catch (FormatException e) + { + throw new ArgumentException("invalid date string: " + e.Message); + } + } + + + public Asn1UtcTime(DateTime dateTime) + { + dateTime = DateTimeUtilities.WithPrecisionSecond(dateTime.ToUniversalTime()); + + m_dateTime = dateTime; + m_dateTimeLocked = true; + m_timeString = ToStringCanonical(dateTime, out m_twoDigitYearMax); + } + + public Asn1UtcTime(DateTime dateTime, int twoDigitYearMax) + { + dateTime = DateTimeUtilities.WithPrecisionSecond(dateTime.ToUniversalTime()); + + Validate(dateTime, twoDigitYearMax); + + m_dateTime = dateTime; + m_dateTimeLocked = true; + m_timeString = ToStringCanonical(dateTime); + m_twoDigitYearMax = twoDigitYearMax; + } + + internal Asn1UtcTime(byte[] contents) + // NOTE: Non-ASCII characters will produce '?' characters, which will fail DateTime parsing + : this(Encoding.ASCII.GetString(contents)) + { + } + + public string TimeString => m_timeString; + + public DateTime ToDateTime() + { + return m_dateTime; + } + + public DateTime ToDateTime(int twoDigitYearMax) + { + if (InRange(m_dateTime, twoDigitYearMax)) + return m_dateTime; + + if (m_dateTimeLocked) + throw new InvalidOperationException(); + + int twoDigitYear = m_dateTime.Year % 100; + int twoDigitYearCutoff = twoDigitYearMax % 100; + + int diff = twoDigitYear - twoDigitYearCutoff; + int newYear = twoDigitYearMax + diff; + if (diff > 0) + { + newYear -= 100; + } + + return m_dateTime.AddYears(newYear - m_dateTime.Year); + } + + public DateTime ToDateTime(Calendar calendar) + { + return ToDateTime(calendar.TwoDigitYearMax); + } + + /// Return an adjusted date in the range of 1950 - 2049. + + public DateTime ToAdjustedDateTime() + { + return ToDateTime(2049); + } + + public int TwoDigitYearMax => m_twoDigitYearMax; + + internal byte[] GetContents(int encoding) + { + if (encoding == Asn1OutputStream.EncodingDer && m_timeString.Length != 13) + { + string canonical = ToStringCanonical(m_dateTime); + return Encoding.ASCII.GetBytes(canonical); + } + + return Encoding.ASCII.GetBytes(m_timeString); + } + + internal override IAsn1Encoding GetEncoding(int encoding) + { + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.UtcTime, GetContents(encoding)); + } + + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + return new PrimitiveEncoding(tagClass, tagNo, GetContents(encoding)); + } + + protected override bool Asn1Equals(Asn1Object asn1Object) + { + if (!(asn1Object is Asn1UtcTime that)) + return false; + + // TODO Performance + return Arrays.AreEqual( + this.GetContents(Asn1OutputStream.EncodingDer), + that.GetContents(Asn1OutputStream.EncodingDer)); + } + + protected override int Asn1GetHashCode() + { + // TODO Performance + return Arrays.GetHashCode( + this.GetContents(Asn1OutputStream.EncodingDer)); + } + + public override string ToString() + { + return m_timeString; + } + + internal static Asn1UtcTime CreatePrimitive(byte[] contents) + { + return new Asn1UtcTime(contents); + } + + private static DateTime FromString(string s, out int twoDigitYearMax) + { + var provider = DateTimeFormatInfo.InvariantInfo; + twoDigitYearMax = provider.Calendar.TwoDigitYearMax; + + switch (s.Length) + { + case 11: + return DateTime.ParseExact(s, @"yyMMddHHmm\Z", provider, + DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal); + case 13: + return DateTime.ParseExact(s, @"yyMMddHHmmss\Z", provider, + DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal); + case 15: + return DateTime.ParseExact(s, @"yyMMddHHmmzzz", provider, DateTimeStyles.AdjustToUniversal); + case 17: + return DateTime.ParseExact(s, @"yyMMddHHmmsszzz", provider, DateTimeStyles.AdjustToUniversal); + default: + throw new FormatException(); + } + } + + private static bool InRange(DateTime dateTime, int twoDigitYearMax) + { + return (uint)(twoDigitYearMax - dateTime.Year) < 100; + } + + private static string ToStringCanonical(DateTime dateTime, out int twoDigitYearMax) + { + var provider = DateTimeFormatInfo.InvariantInfo; + twoDigitYearMax = provider.Calendar.TwoDigitYearMax; + + Validate(dateTime, twoDigitYearMax); + + return dateTime.ToString(@"yyMMddHHmmss\Z", provider); + } + + private static string ToStringCanonical(DateTime dateTime) + { + return dateTime.ToString(@"yyMMddHHmmss\Z", DateTimeFormatInfo.InvariantInfo); + } + + private static void Validate(DateTime dateTime, int twoDigitYearMax) + { + if (!InRange(dateTime, twoDigitYearMax)) + throw new ArgumentOutOfRangeException(nameof(dateTime)); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1UtcTime.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1UtcTime.cs.meta new file mode 100644 index 0000000..499bdd2 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1UtcTime.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: edf61982cdff33c408181b8d191ae7ce +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Utilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Utilities.cs new file mode 100644 index 0000000..e76bffb --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Utilities.cs @@ -0,0 +1,333 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.IO; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + public abstract class Asn1Utilities + { + internal static Asn1TaggedObject CheckTag(Asn1TaggedObject taggedObject, int tagClass, int tagNo) + { + if (!taggedObject.HasTag(tagClass, tagNo)) + { + string expected = GetTagText(tagClass, tagNo); + string found = GetTagText(taggedObject); + throw new InvalidOperationException("Expected " + expected + " tag but found " + found); + } + return taggedObject; + } + + internal static Asn1TaggedObjectParser CheckTag(Asn1TaggedObjectParser taggedObjectParser, int tagClass, + int tagNo) + { + if (!taggedObjectParser.HasTag(tagClass, tagNo)) + { + string expected = GetTagText(tagClass, tagNo); + string found = GetTagText(taggedObjectParser); + throw new InvalidOperationException("Expected " + expected + " tag but found " + found); + } + return taggedObjectParser; + } + + + internal static string GetTagText(Asn1Tag tag) + { + return GetTagText(tag.TagClass, tag.TagNo); + } + + public static string GetTagText(Asn1TaggedObject taggedObject) + { + return GetTagText(taggedObject.TagClass, taggedObject.TagNo); + } + + public static string GetTagText(Asn1TaggedObjectParser taggedObjectParser) + { + return GetTagText(taggedObjectParser.TagClass, taggedObjectParser.TagNo); + } + + public static string GetTagText(int tagClass, int tagNo) + { + switch (tagClass) + { + case Asn1Tags.Application: + return "[APPLICATION " + tagNo + "]"; + case Asn1Tags.ContextSpecific: + return "[CONTEXT " + tagNo + "]"; + case Asn1Tags.Private: + return "[PRIVATE " + tagNo + "]"; + default: + return "[UNIVERSAL " + tagNo + "]"; + } + } + + + /* + * Wrappers for Asn1TaggedObject.GetExplicitBaseObject + */ + + public static Asn1Encodable GetExplicitBaseObject(Asn1TaggedObject taggedObject, int tagClass, int tagNo) + { + return CheckTag(taggedObject, tagClass, tagNo).GetExplicitBaseObject(); + } + + public static Asn1Encodable GetExplicitContextBaseObject(Asn1TaggedObject taggedObject, int tagNo) + { + return GetExplicitBaseObject(taggedObject, Asn1Tags.ContextSpecific, tagNo); + } + + public static Asn1Encodable TryGetExplicitBaseObject(Asn1TaggedObject taggedObject, int tagClass, int tagNo) + { + if (!taggedObject.HasTag(tagClass, tagNo)) + return null; + + return taggedObject.GetExplicitBaseObject(); + } + + public static Asn1Encodable TryGetExplicitContextBaseObject(Asn1TaggedObject taggedObject, int tagNo) + { + return TryGetExplicitBaseObject(taggedObject, Asn1Tags.ContextSpecific, tagNo); + } + + + /* + * Wrappers for Asn1TaggedObject.GetExplicitBaseTagged + */ + + public static Asn1TaggedObject GetExplicitBaseTagged(Asn1TaggedObject taggedObject, int tagClass, int tagNo) + { + return CheckTag(taggedObject, tagClass, tagNo).GetExplicitBaseTagged(); + } + + public static Asn1TaggedObject GetExplicitContextBaseTagged(Asn1TaggedObject taggedObject, int tagNo) + { + return GetExplicitBaseTagged(taggedObject, Asn1Tags.ContextSpecific, tagNo); + } + + public static Asn1TaggedObject TryGetExplicitBaseTagged(Asn1TaggedObject taggedObject, int tagClass, int tagNo) + { + if (!taggedObject.HasTag(tagClass, tagNo)) + return null; + + return taggedObject.GetExplicitBaseTagged(); + } + + public static Asn1TaggedObject TryGetExplicitContextBaseTagged(Asn1TaggedObject taggedObject, int tagNo) + { + return TryGetExplicitBaseTagged(taggedObject, Asn1Tags.ContextSpecific, tagNo); + } + + + /* + * Wrappers for Asn1TaggedObject.GetImplicitBaseTagged + */ + + public static Asn1TaggedObject GetImplicitBaseTagged(Asn1TaggedObject taggedObject, int tagClass, int tagNo, + int baseTagClass, int baseTagNo) + { + return CheckTag(taggedObject, tagClass, tagNo).GetImplicitBaseTagged(baseTagClass, baseTagNo); + } + + public static Asn1TaggedObject GetImplicitContextBaseTagged(Asn1TaggedObject taggedObject, int tagNo, + int baseTagClass, int baseTagNo) + { + return GetImplicitBaseTagged(taggedObject, Asn1Tags.ContextSpecific, tagNo, baseTagClass, baseTagNo); + } + + public static Asn1TaggedObject TryGetImplicitBaseTagged(Asn1TaggedObject taggedObject, int tagClass, int tagNo, + int baseTagClass, int baseTagNo) + { + if (!taggedObject.HasTag(tagClass, tagNo)) + return null; + + return taggedObject.GetImplicitBaseTagged(baseTagClass, baseTagNo); + } + + public static Asn1TaggedObject TryGetImplicitContextBaseTagged(Asn1TaggedObject taggedObject, int tagNo, + int baseTagClass, int baseTagNo) + { + return TryGetImplicitBaseTagged(taggedObject, Asn1Tags.ContextSpecific, tagNo, baseTagClass, baseTagNo); + } + + + /* + * Wrappers for Asn1TaggedObject.GetBaseUniversal + */ + + public static Asn1Object GetBaseUniversal(Asn1TaggedObject taggedObject, int tagClass, int tagNo, + bool declaredExplicit, int baseTagNo) + { + return CheckTag(taggedObject, tagClass, tagNo).GetBaseUniversal(declaredExplicit, baseTagNo); + } + + public static Asn1Object GetContextBaseUniversal(Asn1TaggedObject taggedObject, int tagNo, + bool declaredExplicit, int baseTagNo) + { + return GetBaseUniversal(taggedObject, Asn1Tags.ContextSpecific, tagNo, declaredExplicit, baseTagNo); + } + + public static Asn1Object TryGetBaseUniversal(Asn1TaggedObject taggedObject, int tagClass, int tagNo, + bool declaredExplicit, int baseTagNo) + { + if (!taggedObject.HasTag(tagClass, tagNo)) + return null; + + return taggedObject.GetBaseUniversal(declaredExplicit, baseTagNo); + } + + public static Asn1Object TryGetContextBaseUniversal(Asn1TaggedObject taggedObject, int tagNo, + bool declaredExplicit, int baseTagNo) + { + return TryGetBaseUniversal(taggedObject, Asn1Tags.ContextSpecific, tagNo, declaredExplicit, baseTagNo); + } + + + /* + * Wrappers for Asn1TaggedObjectParser.ParseExplicitBaseTagged + */ + + /// + public static Asn1TaggedObjectParser ParseExplicitBaseTagged(Asn1TaggedObjectParser taggedObjectParser, + int tagClass, int tagNo) + { + return CheckTag(taggedObjectParser, tagClass, tagNo).ParseExplicitBaseTagged(); + } + + /// + public static Asn1TaggedObjectParser ParseExplicitContextBaseTagged(Asn1TaggedObjectParser taggedObjectParser, + int tagNo) + { + return ParseExplicitBaseTagged(taggedObjectParser, Asn1Tags.ContextSpecific, tagNo); + } + + /// + public static Asn1TaggedObjectParser TryParseExplicitBaseTagged(Asn1TaggedObjectParser taggedObjectParser, + int tagClass, int tagNo) + { + if (!taggedObjectParser.HasTag(tagClass, tagNo)) + return null; + + return taggedObjectParser.ParseExplicitBaseTagged(); + } + + /// + public static Asn1TaggedObjectParser TryParseExplicitContextBaseTagged( + Asn1TaggedObjectParser taggedObjectParser, int tagNo) + { + return TryParseExplicitBaseTagged(taggedObjectParser, Asn1Tags.ContextSpecific, tagNo); + } + + + /* + * Wrappers for Asn1TaggedObjectParser.ParseImplicitBaseTagged + */ + + /// + public static Asn1TaggedObjectParser ParseImplicitBaseTagged(Asn1TaggedObjectParser taggedObjectParser, + int tagClass, int tagNo, int baseTagClass, int baseTagNo) + { + return CheckTag(taggedObjectParser, tagClass, tagNo).ParseImplicitBaseTagged(baseTagClass, baseTagNo); + } + + /// + public static Asn1TaggedObjectParser ParseImplicitContextBaseTagged(Asn1TaggedObjectParser taggedObjectParser, + int tagNo, int baseTagClass, int baseTagNo) + { + return ParseImplicitBaseTagged(taggedObjectParser, Asn1Tags.ContextSpecific, tagNo, baseTagClass, + baseTagNo); + } + + /// + public static Asn1TaggedObjectParser TryParseImplicitBaseTagged(Asn1TaggedObjectParser taggedObjectParser, + int tagClass, int tagNo, int baseTagClass, int baseTagNo) + { + if (!taggedObjectParser.HasTag(tagClass, tagNo)) + return null; + + return taggedObjectParser.ParseImplicitBaseTagged(baseTagClass, baseTagNo); + } + + /// + public static Asn1TaggedObjectParser TryParseImplicitContextBaseTagged( + Asn1TaggedObjectParser taggedObjectParser, int tagNo, int baseTagClass, int baseTagNo) + { + return TryParseImplicitBaseTagged(taggedObjectParser, Asn1Tags.ContextSpecific, tagNo, baseTagClass, + baseTagNo); + } + + + /* + * Wrappers for Asn1TaggedObjectParser.ParseBaseUniversal + */ + + /// + public static IAsn1Convertible ParseBaseUniversal(Asn1TaggedObjectParser taggedObjectParser, int tagClass, + int tagNo, bool declaredExplicit, int baseTagNo) + { + return CheckTag(taggedObjectParser, tagClass, tagNo).ParseBaseUniversal(declaredExplicit, baseTagNo); + } + + /// + public static IAsn1Convertible ParseContextBaseUniversal(Asn1TaggedObjectParser taggedObjectParser, int tagNo, + bool declaredExplicit, int baseTagNo) + { + return ParseBaseUniversal(taggedObjectParser, Asn1Tags.ContextSpecific, tagNo, declaredExplicit, baseTagNo); + } + + /// + public static IAsn1Convertible TryParseBaseUniversal(Asn1TaggedObjectParser taggedObjectParser, int tagClass, + int tagNo, bool declaredExplicit, int baseTagNo) + { + if (!taggedObjectParser.HasTag(tagClass, tagNo)) + return null; + + return taggedObjectParser.ParseBaseUniversal(declaredExplicit, baseTagNo); + } + + /// + public static IAsn1Convertible TryParseContextBaseUniversal(Asn1TaggedObjectParser taggedObjectParser, + int tagNo, bool declaredExplicit, int baseTagNo) + { + return TryParseBaseUniversal(taggedObjectParser, Asn1Tags.ContextSpecific, tagNo, declaredExplicit, + baseTagNo); + } + + + /* + * Wrappers for Asn1TaggedObjectParser.ParseExplicitBaseObject + */ + + /// + public static IAsn1Convertible ParseExplicitBaseObject(Asn1TaggedObjectParser taggedObjectParser, int tagClass, + int tagNo) + { + return CheckTag(taggedObjectParser, tagClass, tagNo).ParseExplicitBaseObject(); + } + + /// + public static IAsn1Convertible ParseExplicitContextBaseObject(Asn1TaggedObjectParser taggedObjectParser, + int tagNo) + { + return ParseExplicitBaseObject(taggedObjectParser, Asn1Tags.ContextSpecific, tagNo); + } + + /// + public static IAsn1Convertible TryParseExplicitBaseObject(Asn1TaggedObjectParser taggedObjectParser, + int tagClass, int tagNo) + { + if (!taggedObjectParser.HasTag(tagClass, tagNo)) + return null; + + return taggedObjectParser.ParseExplicitBaseObject(); + } + + /// + public static IAsn1Convertible TryParseExplicitContextBaseObject(Asn1TaggedObjectParser taggedObjectParser, + int tagNo) + { + return TryParseExplicitBaseObject(taggedObjectParser, Asn1Tags.ContextSpecific, tagNo); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Utilities.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Utilities.cs.meta new file mode 100644 index 0000000..192c793 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/Asn1Utilities.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 62e229680bdece24987221dc054bce7d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BERBitString.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BERBitString.cs index d61ca1d..d8ddfcd 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BERBitString.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BERBitString.cs @@ -3,8 +3,6 @@ using System; using System.Diagnostics; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; - namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 { public class BerBitString @@ -115,87 +113,28 @@ internal BerBitString(byte[] contents, bool check) this.segmentLimit = DefaultSegmentLimit; } - private bool IsConstructed + internal override IAsn1Encoding GetEncoding(int encoding) { - get { return null != elements || contents.Length > segmentLimit; } - } + if (Asn1OutputStream.EncodingBer != encoding) + return base.GetEncoding(encoding); - internal override int EncodedLength(bool withID) - { - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("BerBitString.EncodedLength"); - - // TODO This depends on knowing it's not DER - //if (!IsConstructed) - // return EncodedLength(withID, contents.Length); - - //int totalLength = withID ? 4 : 3; - - //if (null != elements) - //{ - // for (int i = 0; i < elements.Length; ++i) - // { - // totalLength += elements[i].EncodedLength(true); - // } - //} - //else if (contents.Length < 2) - //{ - // // No bits - //} - //else - //{ - // int extraSegments = (contents.Length - 2) / (segmentLimit - 1); - // totalLength += extraSegments * EncodedLength(true, segmentLimit); - - // int lastSegmentLength = contents.Length - (extraSegments * (segmentLimit - 1)); - // totalLength += EncodedLength(true, lastSegmentLength); - //} - - //return totalLength; + if (null == elements) + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.BitString, contents); + + return new ConstructedILEncoding(Asn1Tags.Universal, Asn1Tags.BitString, + Asn1OutputStream.GetContentsEncodings(encoding, elements)); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) { - if (!asn1Out.IsBer) - { - base.Encode(asn1Out, withID); - return; - } + if (Asn1OutputStream.EncodingBer != encoding) + return base.GetEncodingImplicit(encoding, tagClass, tagNo); - if (!IsConstructed) - { - Encode(asn1Out, withID, contents, 0, contents.Length); - return; - } - - asn1Out.WriteIdentifier(withID, Asn1Tags.Constructed | Asn1Tags.BitString); - asn1Out.WriteByte(0x80); - - if (null != elements) - { - asn1Out.WritePrimitives(elements); - } - else if (contents.Length < 2) - { - // No bits - } - else - { - byte pad = contents[0]; - int length = contents.Length; - int remaining = length - 1; - int segmentLength = segmentLimit - 1; - - while (remaining > segmentLength) - { - Encode(asn1Out, true, (byte)0, contents, length - remaining, segmentLength); - remaining -= segmentLength; - } - - Encode(asn1Out, true, pad, contents, length - remaining, remaining); - } + if (null == elements) + return new PrimitiveEncoding(tagClass, tagNo, contents); - asn1Out.WriteByte(0x00); - asn1Out.WriteByte(0x00); + return new ConstructedILEncoding(tagClass, tagNo, + Asn1OutputStream.GetContentsEncodings(encoding, elements)); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BEROctetStringGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BEROctetStringGenerator.cs index 1e66765..3006361 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BEROctetStringGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BEROctetStringGenerator.cs @@ -62,80 +62,101 @@ internal BufferedBerOctetStream( _derOut = Asn1OutputStream.Create(_gen.Out, Asn1Encodable.Der); } - public override void WriteByte( - byte b) + public override void Write(byte[] buffer, int offset, int count) { - _buf[_off++] = b; + Streams.ValidateBufferArguments(buffer, offset, count); - if (_off == _buf.Length) - { - DerOctetString.Encode(_derOut, true, _buf, 0, _off); - _off = 0; - } - } - - public override void Write(byte[] b, int off, int len) - { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Write(buffer.AsSpan(offset, count)); +#else int bufLen = _buf.Length; int available = bufLen - _off; - if (len < available) + if (count < available) { - Array.Copy(b, off, _buf, _off, len); - _off += len; + Array.Copy(buffer, offset, _buf, _off, count); + _off += count; return; } - int count = 0; + int pos = 0; if (_off > 0) { - Array.Copy(b, off, _buf, _off, available); - count += available; - DerOctetString.Encode(_derOut, true, _buf, 0, bufLen); + Array.Copy(buffer, offset, _buf, _off, available); + pos = available; + DerOctetString.Encode(_derOut, _buf, 0, bufLen); + //_off = 0; } int remaining; - while ((remaining = len - count) >= bufLen) + while ((remaining = count - pos) >= bufLen) { - DerOctetString.Encode(_derOut, true, b, off + count, bufLen); - count += bufLen; + DerOctetString.Encode(_derOut, buffer, offset + pos, bufLen); + pos += bufLen; } - Array.Copy(b, off + count, _buf, 0, remaining); + Array.Copy(buffer, offset + pos, _buf, 0, remaining); this._off = remaining; +#endif } -#if PORTABLE || NETFX_CORE - protected override void Dispose(bool disposing) - { - if (disposing) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) + { + int bufLen = _buf.Length; + int available = bufLen - _off; + if (buffer.Length < available) { - if (_off != 0) - { - DerOctetString.Encode(_derOut, true, _buf, 0, _off); - } + buffer.CopyTo(_buf.AsSpan(_off)); + _off += buffer.Length; + return; + } - _derOut.FlushInternal(); + if (_off > 0) + { + DerOctetString.Encode(_derOut, _buf.AsSpan(0, _off), buffer[..available]); + buffer = buffer[available..]; + //_off = 0; + } - _gen.WriteBerEnd(); + while (buffer.Length >= bufLen) + { + DerOctetString.Encode(_derOut, buffer[..bufLen]); + buffer = buffer[bufLen..]; } - base.Dispose(disposing); + + buffer.CopyTo(_buf.AsSpan()); + _off = buffer.Length; } -#else - public override void Close() +#endif + + public override void WriteByte(byte value) { - if (_off != 0) + _buf[_off++] = value; + + if (_off == _buf.Length) { - DerOctetString.Encode(_derOut, true, _buf, 0, _off); + DerOctetString.Encode(_derOut, _buf, 0, _off); + _off = 0; } + } - _derOut.FlushInternal(); + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (_off != 0) + { + DerOctetString.Encode(_derOut, _buf, 0, _off); + } - _gen.WriteBerEnd(); - base.Close(); - } -#endif - } - } + _derOut.FlushInternal(); + + _gen.WriteBerEnd(); + } + base.Dispose(disposing); + } + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BERTaggedObjectParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BERTaggedObjectParser.cs index 245cba7..ca88f25 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BERTaggedObjectParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BERTaggedObjectParser.cs @@ -3,67 +3,76 @@ using System; using System.IO; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; - namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 { - public class BerTaggedObjectParser + internal class BerTaggedObjectParser : Asn1TaggedObjectParser { - private bool _constructed; - private int _tagNumber; - private Asn1StreamParser _parser; + internal readonly int m_tagClass; + internal readonly int m_tagNo; + internal readonly Asn1StreamParser m_parser; - [Obsolete] - internal BerTaggedObjectParser( - int baseTag, - int tagNumber, - Stream contentStream) - : this((baseTag & Asn1Tags.Constructed) != 0, tagNumber, new Asn1StreamParser(contentStream)) + internal BerTaggedObjectParser(int tagClass, int tagNo, Asn1StreamParser parser) { + m_tagClass = tagClass; + m_tagNo = tagNo; + m_parser = parser; } - internal BerTaggedObjectParser( - bool constructed, - int tagNumber, - Asn1StreamParser parser) + public virtual bool IsConstructed { - _constructed = constructed; - _tagNumber = tagNumber; - _parser = parser; + get { return true; } } - public bool IsConstructed - { - get { return _constructed; } - } + public int TagClass + { + get { return m_tagClass; } + } public int TagNo { - get { return _tagNumber; } + get { return m_tagNo; } } - public IAsn1Convertible GetObjectParser( - int tag, - bool isExplicit) - { - if (isExplicit) - { - if (!_constructed) - throw new IOException("Explicit tags must be constructed (see X.690 8.14.2)"); + public bool HasContextTag(int tagNo) + { + return m_tagClass == Asn1Tags.ContextSpecific && m_tagNo == tagNo; + } - return _parser.ReadObject(); - } + public bool HasTag(int tagClass, int tagNo) + { + return m_tagClass == tagClass && m_tagNo == tagNo; + } - return _parser.ReadImplicit(_constructed, tag); - } + public virtual IAsn1Convertible ParseBaseUniversal(bool declaredExplicit, int baseTagNo) + { + if (declaredExplicit) + return m_parser.ParseObject(baseTagNo); + + return m_parser.ParseImplicitConstructedIL(baseTagNo); + } + + public virtual IAsn1Convertible ParseExplicitBaseObject() + { + return m_parser.ReadObject(); + } - public Asn1Object ToAsn1Object() + public virtual Asn1TaggedObjectParser ParseExplicitBaseTagged() + { + return m_parser.ParseTaggedObject(); + } + + public virtual Asn1TaggedObjectParser ParseImplicitBaseTagged(int baseTagClass, int baseTagNo) + { + return new BerTaggedObjectParser(baseTagClass, baseTagNo, m_parser); + } + + public virtual Asn1Object ToAsn1Object() { try { - return _parser.ReadTaggedObject(_constructed, _tagNumber); - } + return m_parser.LoadTaggedIL(TagClass, TagNo); + } catch (IOException e) { throw new Asn1ParsingException(e.Message); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerApplicationSpecific.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerApplicationSpecific.cs index 1cf9014..0454b34 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerApplicationSpecific.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerApplicationSpecific.cs @@ -1,19 +1,3 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) -#pragma warning disable -using System; -namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 -{ - public class BerApplicationSpecific - : DerApplicationSpecific - { - public BerApplicationSpecific( - int tagNo, - Asn1EncodableVector vec) - : base(tagNo, vec) - { - } - } -} -#pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerApplicationSpecific.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerApplicationSpecific.cs.meta index f96ac9a..7be134d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerApplicationSpecific.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerApplicationSpecific.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: e34e4ccb03d83c34393d6d2588965d04 +guid: 2d565bd50647e32459915b52caf8d736 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerApplicationSpecificParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerApplicationSpecificParser.cs index 6bf80e8..3b1d777 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerApplicationSpecificParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerApplicationSpecificParser.cs @@ -1,33 +1,2 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) -#pragma warning disable -using System; - -namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 -{ - public class BerApplicationSpecificParser - : IAsn1ApplicationSpecificParser - { - private readonly int tag; - private readonly Asn1StreamParser parser; - - internal BerApplicationSpecificParser( - int tag, - Asn1StreamParser parser) - { - this.tag = tag; - this.parser = parser; - } - - public IAsn1Convertible ReadObject() - { - return parser.ReadObject(); - } - - public Asn1Object ToAsn1Object() - { - return new BerApplicationSpecific(tag, parser.ReadVector()); - } - } -} -#pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerApplicationSpecificParser.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerApplicationSpecificParser.cs.meta index 1e4e53b..190e820 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerApplicationSpecificParser.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerApplicationSpecificParser.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 584fba93d29d0d84da6c0b7606076a8a +guid: f60af26f2a3ecad4ab67ab32b5796bbe MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerBitStringParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerBitStringParser.cs new file mode 100644 index 0000000..47013e3 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerBitStringParser.cs @@ -0,0 +1,60 @@ +#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 +{ + /// A parser for indefinite-length BIT STRINGs. + internal class BerBitStringParser + : Asn1BitStringParser + { + private readonly Asn1StreamParser m_parser; + + private ConstructedBitStream m_bitStream; + + internal BerBitStringParser(Asn1StreamParser parser) + { + m_parser = parser; + } + + public Stream GetOctetStream() + { + return m_bitStream = new ConstructedBitStream(m_parser, true); + } + + public Stream GetBitStream() + { + return m_bitStream = new ConstructedBitStream(m_parser, false); + } + + public int PadBits + { + get { return m_bitStream.PadBits; } + } + + public Asn1Object ToAsn1Object() + { + try + { + return Parse(m_parser); + } + catch (IOException e) + { + throw new Asn1ParsingException("IOException converting stream to byte array: " + e.Message, e); + } + } + + internal static BerBitString Parse(Asn1StreamParser sp) + { + ConstructedBitStream bitStream = new ConstructedBitStream(sp, false); + byte[] data = Streams.ReadAll(bitStream); + int padBits = bitStream.PadBits; + return new BerBitString(data, padBits); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerBitStringParser.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerBitStringParser.cs.meta new file mode 100644 index 0000000..8e378fd --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerBitStringParser.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0935e7c4731287a488fd95f8f9670666 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerOctetString.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerOctetString.cs index 0e8eb83..d867b00 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerOctetString.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerOctetString.cs @@ -1,15 +1,12 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; using System.Diagnostics; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; - namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 { public class BerOctetString - : DerOctetString, IEnumerable + : DerOctetString { private const int DefaultSegmentLimit = 1000; @@ -32,20 +29,20 @@ internal static byte[] FlattenOctetStrings(Asn1OctetString[] octetStrings) case 0: return EmptyOctets; case 1: - return octetStrings[0].str; + return octetStrings[0].contents; default: { int totalOctets = 0; for (int i = 0; i < count; ++i) { - totalOctets += octetStrings[i].str.Length; + totalOctets += octetStrings[i].contents.Length; } byte[] str = new byte[totalOctets]; int pos = 0; for (int i = 0; i < count; ++i) { - byte[] octets = octetStrings[i].str; + byte[] octets = octetStrings[i].contents; Array.Copy(octets, 0, str, pos, octets.Length); pos += octets.Length; } @@ -56,30 +53,11 @@ internal static byte[] FlattenOctetStrings(Asn1OctetString[] octetStrings) } } - private static Asn1OctetString[] ToOctetStringArray(IEnumerable e) - { - IList list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(e); - - int count = list.Count; - Asn1OctetString[] v = new Asn1OctetString[count]; - for (int i = 0; i < count; ++i) - { - v[i] = GetInstance(list[i]); - } - return v; - } - private readonly int segmentLimit; private readonly Asn1OctetString[] elements; - - public BerOctetString(IEnumerable e) - : this(ToOctetStringArray(e)) - { - } - - public BerOctetString(byte[] str) - : this(str, DefaultSegmentLimit) + public BerOctetString(byte[] contents) + : this(contents, DefaultSegmentLimit) { } @@ -88,8 +66,8 @@ public BerOctetString(Asn1OctetString[] elements) { } - public BerOctetString(byte[] str, int segmentLimit) - : this(str, null, segmentLimit) + public BerOctetString(byte[] contents, int segmentLimit) + : this(contents, null, segmentLimit) { } @@ -98,144 +76,35 @@ public BerOctetString(Asn1OctetString[] elements, int segmentLimit) { } - private BerOctetString(byte[] octets, Asn1OctetString[] elements, int segmentLimit) - : base(octets) + private BerOctetString(byte[] contents, Asn1OctetString[] elements, int segmentLimit) + : base(contents) { this.elements = elements; this.segmentLimit = segmentLimit; } - /** - * return the DER octets that make up this string. - */ - public IEnumerator GetEnumerator() - { - if (elements == null) - return new ChunkEnumerator(str, segmentLimit); - - return elements.GetEnumerator(); - } - - - public IEnumerator GetObjects() - { - return GetEnumerator(); - } - - private bool IsConstructed - { - get { return null != elements || str.Length > segmentLimit; } - } - - internal override int EncodedLength(bool withID) - { - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("BerOctetString.EncodedLength"); - - // TODO This depends on knowing it's not DER - //if (!IsConstructed) - // return EncodedLength(withID, str.Length); - - //int totalLength = withID ? 4 : 3; - - //if (null != elements) - //{ - // for (int i = 0; i < elements.Length; ++i) - // { - // totalLength += elements[i].EncodedLength(true); - // } - //} - //else - //{ - // int fullSegments = str.Length / segmentLimit; - // totalLength += fullSegments * EncodedLength(true, segmentLimit); - - // int lastSegmentLength = str.Length - (fullSegments * segmentLimit); - // if (lastSegmentLength > 0) - // { - // totalLength += EncodedLength(true, lastSegmentLength); - // } - //} - - //return totalLength; - } - - internal override void Encode(Asn1OutputStream asn1Out, bool withID) + internal override IAsn1Encoding GetEncoding(int encoding) { - if (!asn1Out.IsBer || !IsConstructed) - { - base.Encode(asn1Out, withID); - return; - } + if (Asn1OutputStream.EncodingBer != encoding) + return base.GetEncoding(encoding); - asn1Out.WriteIdentifier(withID, Asn1Tags.Constructed | Asn1Tags.OctetString); - asn1Out.WriteByte(0x80); - - if (null != elements) - { - asn1Out.WritePrimitives(elements); - } - else - { - int pos = 0; - while (pos < str.Length) - { - int segmentLength = System.Math.Min(str.Length - pos, segmentLimit); - Encode(asn1Out, true, str, pos, segmentLength); - pos += segmentLength; - } - } + if (null == elements) + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.OctetString, contents); - asn1Out.WriteByte(0x00); - asn1Out.WriteByte(0x00); + return new ConstructedILEncoding(Asn1Tags.Universal, Asn1Tags.OctetString, + Asn1OutputStream.GetContentsEncodings(encoding, elements)); } - private class ChunkEnumerator - : IEnumerator + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) { - private readonly byte[] octets; - private readonly int segmentLimit; + if (Asn1OutputStream.EncodingBer != encoding) + return base.GetEncodingImplicit(encoding, tagClass, tagNo); - private DerOctetString currentSegment = null; - private int nextSegmentPos = 0; + if (null == elements) + return new PrimitiveEncoding(tagClass, tagNo, contents); - internal ChunkEnumerator(byte[] octets, int segmentLimit) - { - this.octets = octets; - this.segmentLimit = segmentLimit; - } - - public object Current - { - get - { - if (null == currentSegment) - throw new InvalidOperationException(); - - return currentSegment; - } - } - - public bool MoveNext() - { - if (nextSegmentPos >= octets.Length) - { - this.currentSegment = null; - return false; - } - - int length = System.Math.Min(octets.Length - nextSegmentPos, segmentLimit); - byte[] segment = new byte[length]; - Array.Copy(octets, nextSegmentPos, segment, 0, length); - this.currentSegment = new DerOctetString(segment); - this.nextSegmentPos += length; - return true; - } - - public void Reset() - { - this.currentSegment = null; - this.nextSegmentPos = 0; - } + return new ConstructedILEncoding(tagClass, tagNo, + Asn1OutputStream.GetContentsEncodings(encoding, elements)); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerOutputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerOutputStream.cs index 6ffb31e..0454b34 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerOutputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerOutputStream.cs @@ -1,30 +1,3 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) -#pragma warning disable -using System; -using System.IO; -namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 -{ - - public class BerOutputStream - : DerOutputStream - { - - public BerOutputStream(Stream os) - : base(os) - { - } - - public override void WriteObject(Asn1Encodable encodable) - { - Asn1OutputStream.Create(s).WriteObject(encodable); - } - - public override void WriteObject(Asn1Object primitive) - { - Asn1OutputStream.Create(s).WriteObject(primitive); - } - } -} -#pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerOutputStream.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerOutputStream.cs.meta index 87584cc..6e7d69f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerOutputStream.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerOutputStream.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 2fda066304739a7438fe6eedca01a7a7 +guid: 4acf00c72bf317e489e931a8c0c3c3da MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerSequence.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerSequence.cs index fb9d8cc..a79443a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerSequence.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerSequence.cs @@ -2,8 +2,6 @@ #pragma warning disable using System; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; - namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 { public class BerSequence @@ -32,7 +30,15 @@ public BerSequence(Asn1Encodable element) { } - public BerSequence(params Asn1Encodable[] elements) + /** + * create a sequence containing two objects + */ + public BerSequence(Asn1Encodable element1, Asn1Encodable element2) + : base(element1, element2) + { + } + + public BerSequence(params Asn1Encodable[] elements) : base(elements) { } @@ -45,23 +51,51 @@ public BerSequence(Asn1EncodableVector elementVector) { } - internal override int EncodedLength(bool withID) + internal BerSequence(Asn1Encodable[] elements, bool clone) + : base(elements, clone) { - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("BerSequence.EncodedLength"); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) - { - if (asn1Out.IsBer) - { - asn1Out.WriteEncodingIL(withID, Asn1Tags.Constructed | Asn1Tags.Sequence, elements); - } - else - { - base.Encode(asn1Out, withID); - } - } - } + internal override IAsn1Encoding GetEncoding(int encoding) + { + if (Asn1OutputStream.EncodingBer != encoding) + return base.GetEncoding(encoding); + + return new ConstructedILEncoding(Asn1Tags.Universal, Asn1Tags.Sequence, + Asn1OutputStream.GetContentsEncodings(encoding, elements)); + } + + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + if (Asn1OutputStream.EncodingBer != encoding) + return base.GetEncodingImplicit(encoding, tagClass, tagNo); + + return new ConstructedILEncoding(tagClass, tagNo, + Asn1OutputStream.GetContentsEncodings(encoding, elements)); + } + + internal override DerBitString ToAsn1BitString() + { + return new BerBitString(GetConstructedBitStrings()); + } + + internal override DerExternal ToAsn1External() + { + // TODO There is currently no BerExternal class (or ToDLObject/ToDerObject) + //return ((Asn1Sequence)ToDLObject()).ToAsn1External(); + return new DLSequence(elements).ToAsn1External(); + } + + internal override Asn1OctetString ToAsn1OctetString() + { + return new BerOctetString(GetConstructedOctetStrings()); + } + + internal override Asn1Set ToAsn1Set() + { + return new BerSet(false, elements); + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerSet.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerSet.cs index 481cea0..ffc9605 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerSet.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerSet.cs @@ -16,13 +16,8 @@ public class BerSet return elementVector.Count < 1 ? Empty : new BerSet(elementVector); } - internal static new BerSet FromVector(Asn1EncodableVector elementVector, bool needsSorting) - { - return elementVector.Count < 1 ? Empty : new BerSet(elementVector, needsSorting); - } - /** - * create an empty sequence + * create an empty set */ public BerSet() : base() @@ -37,6 +32,11 @@ public BerSet(Asn1Encodable element) { } + public BerSet(params Asn1Encodable[] elements) + : base(elements, false) + { + } + /** * create a set containing a vector of objects. */ @@ -45,26 +45,27 @@ public BerSet(Asn1EncodableVector elementVector) { } - internal BerSet(Asn1EncodableVector elementVector, bool needsSorting) - : base(elementVector, needsSorting) + internal BerSet(bool isSorted, Asn1Encodable[] elements) + : base(isSorted, elements) { } - internal override int EncodedLength(bool withID) + internal override IAsn1Encoding GetEncoding(int encoding) { - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("BerSet.EncodedLength"); + if (Asn1OutputStream.EncodingBer != encoding) + return base.GetEncoding(encoding); + + return new ConstructedILEncoding(Asn1Tags.Universal, Asn1Tags.Set, + Asn1OutputStream.GetContentsEncodings(encoding, elements)); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) { - if (asn1Out.IsBer) - { - asn1Out.WriteEncodingIL(withID, Asn1Tags.Constructed | Asn1Tags.Set, elements); - } - else - { - base.Encode(asn1Out, withID); - } + if (Asn1OutputStream.EncodingBer != encoding) + return base.GetEncodingImplicit(encoding, tagClass, tagNo); + + return new ConstructedILEncoding(tagClass, tagNo, + Asn1OutputStream.GetContentsEncodings(encoding, elements)); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerTaggedObject.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerTaggedObject.cs index b91587f..09781c7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerTaggedObject.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/BerTaggedObject.cs @@ -1,9 +1,6 @@ #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 { @@ -15,106 +12,81 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public class BerTaggedObject : DerTaggedObject { - /** + /** * @param tagNo the tag number for this object. * @param obj the tagged object. */ - public BerTaggedObject( - int tagNo, - Asn1Encodable obj) - : base(tagNo, obj) + public BerTaggedObject(int tagNo, Asn1Encodable obj) + : base(true, tagNo, obj) { } - /** - * @param explicitly true if an explicitly tagged object. + public BerTaggedObject(int tagClass, int tagNo, Asn1Encodable obj) + : base(true, tagClass, tagNo, obj) + { + } + + /** + * @param isExplicit true if an explicitly tagged object. * @param tagNo the tag number for this object. * @param obj the tagged object. */ - public BerTaggedObject( - bool explicitly, - int tagNo, - Asn1Encodable obj) - : base(explicitly, tagNo, obj) + public BerTaggedObject(bool isExplicit, int tagNo, Asn1Encodable obj) + : base(isExplicit, tagNo, obj) { } - /** - * create an implicitly tagged object that contains a zero - * length sequence. - */ - public BerTaggedObject( - int tagNo) - : base(false, tagNo, BerSequence.Empty) - { - } + public BerTaggedObject(bool isExplicit, int tagClass, int tagNo, Asn1Encodable obj) + : base(isExplicit, tagClass, tagNo, obj) + { + } - internal override int EncodedLength(bool withID) + internal BerTaggedObject(int explicitness, int tagClass, int tagNo, Asn1Encodable obj) + : base(explicitness, tagClass, tagNo, obj) { - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("BerTaggedObject.EncodedLength"); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) - { - if (asn1Out.IsBer) - { - if (withID) - { - asn1Out.WriteIdentifier(true, Asn1Tags.Constructed | Asn1Tags.ContextSpecific, tagNo); - } - - asn1Out.WriteByte(0x80); - - if (!IsEmpty()) - { - if (!explicitly) - { - IEnumerable eObj; - if (obj is Asn1OctetString) - { - if (obj is BerOctetString) - { - eObj = (BerOctetString) obj; - } - else - { - Asn1OctetString octs = (Asn1OctetString)obj; - eObj = new BerOctetString(octs.GetOctets()); - } - } - else if (obj is Asn1Sequence) - { - eObj = (Asn1Sequence) obj; - } - else if (obj is Asn1Set) - { - eObj = (Asn1Set) obj; - } - else - { - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); - } - - foreach (Asn1Encodable o in eObj) - { - asn1Out.WritePrimitive(o.ToAsn1Object(), true); - } - } - else - { - asn1Out.WritePrimitive(obj.ToAsn1Object(), true); - } - } - - asn1Out.WriteByte(0x00); - asn1Out.WriteByte(0x00); - } - else - { - base.Encode(asn1Out, withID); - } - } - } + internal override string Asn1Encoding + { + get { return Ber; } + } + + internal override IAsn1Encoding GetEncoding(int encoding) + { + if (Asn1OutputStream.EncodingBer != encoding) + return base.GetEncoding(encoding); + + Asn1Object baseObject = GetBaseObject().ToAsn1Object(); + + if (!IsExplicit()) + return baseObject.GetEncodingImplicit(encoding, TagClass, TagNo); + + return new ConstructedILEncoding(TagClass, TagNo, new IAsn1Encoding[]{ baseObject.GetEncoding(encoding) }); + } + + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + if (Asn1OutputStream.EncodingBer != encoding) + return base.GetEncodingImplicit(encoding, tagClass, tagNo); + + Asn1Object baseObject = GetBaseObject().ToAsn1Object(); + + if (!IsExplicit()) + return baseObject.GetEncodingImplicit(encoding, tagClass, tagNo); + + return new ConstructedILEncoding(tagClass, tagNo, new IAsn1Encoding[]{ baseObject.GetEncoding(encoding) }); + } + + internal override Asn1Sequence RebuildConstructed(Asn1Object asn1Object) + { + return new BerSequence(asn1Object); + } + + internal override Asn1TaggedObject ReplaceTag(int tagClass, int tagNo) + { + return new BerTaggedObject(explicitness, tagClass, tagNo, obj); + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedBitStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedBitStream.cs new file mode 100644 index 0000000..c4e7623 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedBitStream.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.Utilities; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + internal class ConstructedBitStream + : BaseInputStream + { + private readonly Asn1StreamParser m_parser; + private readonly bool m_octetAligned; + + private bool m_first = true; + private int m_padBits = 0; + + private Asn1BitStringParser m_currentParser; + private Stream m_currentStream; + + internal ConstructedBitStream(Asn1StreamParser parser, bool octetAligned) + { + m_parser = parser; + m_octetAligned = octetAligned; + } + + internal int PadBits + { + get { return m_padBits; } + } + + public override int Read(byte[] buffer, int offset, int count) + { + Streams.ValidateBufferArguments(buffer, offset, count); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return Read(buffer.AsSpan(offset, count)); +#else + if (count < 1) + return 0; + + if (m_currentStream == null) + { + if (!m_first) + return 0; + + m_currentParser = GetNextParser(); + if (m_currentParser == null) + return 0; + + m_first = false; + m_currentStream = m_currentParser.GetBitStream(); + } + + int totalRead = 0; + + for (;;) + { + int numRead = m_currentStream.Read(buffer, offset + totalRead, count - totalRead); + + if (numRead > 0) + { + totalRead += numRead; + + if (totalRead == count) + return totalRead; + } + else + { + m_padBits = m_currentParser.PadBits; + m_currentParser = GetNextParser(); + if (m_currentParser == null) + { + m_currentStream = null; + return totalRead; + } + + m_currentStream = m_currentParser.GetBitStream(); + } + } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int Read(Span buffer) + { + if (buffer.IsEmpty) + return 0; + + if (m_currentStream == null) + { + if (!m_first) + return 0; + + m_currentParser = GetNextParser(); + if (m_currentParser == null) + return 0; + + m_first = false; + m_currentStream = m_currentParser.GetBitStream(); + } + + int totalRead = 0; + + for (;;) + { + int numRead = m_currentStream.Read(buffer[totalRead..]); + + if (numRead > 0) + { + totalRead += numRead; + + if (totalRead == buffer.Length) + return totalRead; + } + else + { + m_padBits = m_currentParser.PadBits; + m_currentParser = GetNextParser(); + if (m_currentParser == null) + { + m_currentStream = null; + return totalRead; + } + + m_currentStream = m_currentParser.GetBitStream(); + } + } + } +#endif + + public override int ReadByte() + { + if (m_currentStream == null) + { + if (!m_first) + return -1; + + m_currentParser = GetNextParser(); + if (m_currentParser == null) + return -1; + + m_first = false; + m_currentStream = m_currentParser.GetBitStream(); + } + + for (;;) + { + int b = m_currentStream.ReadByte(); + + if (b >= 0) + return b; + + m_padBits = m_currentParser.PadBits; + m_currentParser = GetNextParser(); + if (m_currentParser == null) + { + m_currentStream = null; + return -1; + } + + m_currentStream = m_currentParser.GetBitStream(); + } + } + + private Asn1BitStringParser GetNextParser() + { + IAsn1Convertible asn1Obj = m_parser.ReadObject(); + if (asn1Obj == null) + { + if (m_octetAligned && m_padBits != 0) + throw new IOException("expected octet-aligned bitstring, but found padBits: " + m_padBits); + + return null; + } + + if (asn1Obj is Asn1BitStringParser) + { + if (m_padBits != 0) + throw new IOException("only the last nested bitstring can have padding"); + + return (Asn1BitStringParser)asn1Obj; + } + + throw new IOException("unknown object encountered: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(asn1Obj)); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedBitStream.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedBitStream.cs.meta new file mode 100644 index 0000000..365cb96 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedBitStream.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 86bbb9386c084ce47a3672ac12a5afa1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedDLEncoding.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedDLEncoding.cs new file mode 100644 index 0000000..b4d0bc9 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedDLEncoding.cs @@ -0,0 +1,39 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + internal class ConstructedDLEncoding + : IAsn1Encoding + { + private readonly int m_tagClass; + private readonly int m_tagNo; + private readonly IAsn1Encoding[] m_contentsElements; + private readonly int m_contentsLength; + + internal ConstructedDLEncoding(int tagClass, int tagNo, IAsn1Encoding[] contentsElements) + { + m_tagClass = tagClass; + m_tagNo = tagNo; + m_contentsElements = contentsElements; + m_contentsLength = Asn1OutputStream.GetLengthOfContents(contentsElements); + } + + void IAsn1Encoding.Encode(Asn1OutputStream asn1Out) + { + asn1Out.WriteIdentifier(Asn1Tags.Constructed | m_tagClass, m_tagNo); + asn1Out.WriteDL(m_contentsLength); + asn1Out.EncodeContents(m_contentsElements); + } + + int IAsn1Encoding.GetLength() + { + return Asn1OutputStream.GetLengthOfIdentifier(m_tagNo) + + Asn1OutputStream.GetLengthOfDL(m_contentsLength) + + m_contentsLength; + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedDLEncoding.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedDLEncoding.cs.meta new file mode 100644 index 0000000..9b5d231 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedDLEncoding.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 95ca1443910ef7d48b13c585349fd261 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedILEncoding.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedILEncoding.cs new file mode 100644 index 0000000..0317f15 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedILEncoding.cs @@ -0,0 +1,39 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + internal class ConstructedILEncoding + : IAsn1Encoding + { + private readonly int m_tagClass; + private readonly int m_tagNo; + private readonly IAsn1Encoding[] m_contentsElements; + + internal ConstructedILEncoding(int tagClass, int tagNo, IAsn1Encoding[] contentsElements) + { + m_tagClass = tagClass; + m_tagNo = tagNo; + m_contentsElements = contentsElements; + } + + void IAsn1Encoding.Encode(Asn1OutputStream asn1Out) + { + asn1Out.WriteIdentifier(Asn1Tags.Constructed | m_tagClass, m_tagNo); + asn1Out.WriteByte(0x80); + asn1Out.EncodeContents(m_contentsElements); + asn1Out.WriteByte(0x00); + asn1Out.WriteByte(0x00); + } + + int IAsn1Encoding.GetLength() + { + return Asn1OutputStream.GetLengthOfIdentifier(m_tagNo) + + 3 + + Asn1OutputStream.GetLengthOfContents(m_contentsElements); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedILEncoding.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedILEncoding.cs.meta new file mode 100644 index 0000000..6c785c8 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedILEncoding.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8ddca6f0e8886b5409e7379e9d09dc77 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedLazyDLEncoding.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedLazyDLEncoding.cs new file mode 100644 index 0000000..f604680 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedLazyDLEncoding.cs @@ -0,0 +1,37 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + internal class ConstructedLazyDLEncoding + : IAsn1Encoding + { + private readonly int m_tagClass; + private readonly int m_tagNo; + private readonly byte[] m_contentsOctets; + + internal ConstructedLazyDLEncoding(int tagClass, int tagNo, byte[] contentsOctets) + { + m_tagClass = tagClass; + m_tagNo = tagNo; + m_contentsOctets = contentsOctets; + } + + void IAsn1Encoding.Encode(Asn1OutputStream asn1Out) + { + asn1Out.WriteIdentifier(Asn1Tags.Constructed | m_tagClass, m_tagNo); + asn1Out.WriteDL(m_contentsOctets.Length); + asn1Out.Write(m_contentsOctets, 0, m_contentsOctets.Length); + } + + int IAsn1Encoding.GetLength() + { + return Asn1OutputStream.GetLengthOfIdentifier(m_tagNo) + + Asn1OutputStream.GetLengthOfDL(m_contentsOctets.Length) + + m_contentsOctets.Length; + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedLazyDLEncoding.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedLazyDLEncoding.cs.meta new file mode 100644 index 0000000..25d99cc --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedLazyDLEncoding.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c7c2fedd867a2bf41bb4a45ced6041d4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedOctetStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedOctetStream.cs index 9314b77..6e79861 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedOctetStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ConstructedOctetStream.cs @@ -1,5 +1,6 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable +using System; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -10,37 +11,44 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 internal class ConstructedOctetStream : BaseInputStream { - private readonly Asn1StreamParser _parser; + private readonly Asn1StreamParser m_parser; - private bool _first = true; - private Stream _currentStream; + private bool m_first = true; + private Stream m_currentStream; - internal ConstructedOctetStream( - Asn1StreamParser parser) + internal ConstructedOctetStream(Asn1StreamParser parser) { - _parser = parser; + m_parser = parser; } public override int Read(byte[] buffer, int offset, int count) { - if (_currentStream == null) + Streams.ValidateBufferArguments(buffer, offset, count); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return Read(buffer.AsSpan(offset, count)); +#else + if (count < 1) + return 0; + + if (m_currentStream == null) { - if (!_first) + if (!m_first) return 0; Asn1OctetStringParser next = GetNextParser(); if (next == null) return 0; - _first = false; - _currentStream = next.GetOctetStream(); + m_first = false; + m_currentStream = next.GetOctetStream(); } int totalRead = 0; for (;;) { - int numRead = _currentStream.Read(buffer, offset + totalRead, count - totalRead); + int numRead = m_currentStream.Read(buffer, offset + totalRead, count - totalRead); if (numRead > 0) { @@ -54,33 +62,81 @@ public override int Read(byte[] buffer, int offset, int count) Asn1OctetStringParser next = GetNextParser(); if (next == null) { - _currentStream = null; + m_currentStream = null; return totalRead; } - _currentStream = next.GetOctetStream(); + m_currentStream = next.GetOctetStream(); } } +#endif } - public override int ReadByte() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int Read(Span buffer) { - if (_currentStream == null) + if (buffer.IsEmpty) + return 0; + + if (m_currentStream == null) { - if (!_first) + if (!m_first) return 0; Asn1OctetStringParser next = GetNextParser(); if (next == null) - return 0; + return 0; + + m_first = false; + m_currentStream = next.GetOctetStream(); + } + + int totalRead = 0; + + for (;;) + { + int numRead = m_currentStream.Read(buffer[totalRead..]); + + if (numRead > 0) + { + totalRead += numRead; + + if (totalRead == buffer.Length) + return totalRead; + } + else + { + Asn1OctetStringParser next = GetNextParser(); + if (next == null) + { + m_currentStream = null; + return totalRead; + } + + m_currentStream = next.GetOctetStream(); + } + } + } +#endif + + public override int ReadByte() + { + if (m_currentStream == null) + { + if (!m_first) + return -1; + + Asn1OctetStringParser next = GetNextParser(); + if (next == null) + return -1; - _first = false; - _currentStream = next.GetOctetStream(); + m_first = false; + m_currentStream = next.GetOctetStream(); } for (;;) { - int b = _currentStream.ReadByte(); + int b = m_currentStream.ReadByte(); if (b >= 0) return b; @@ -88,24 +144,24 @@ public override int ReadByte() Asn1OctetStringParser next = GetNextParser(); if (next == null) { - _currentStream = null; + m_currentStream = null; return -1; } - _currentStream = next.GetOctetStream(); + m_currentStream = next.GetOctetStream(); } } private Asn1OctetStringParser GetNextParser() { - IAsn1Convertible asn1Obj = _parser.ReadObject(); + IAsn1Convertible asn1Obj = m_parser.ReadObject(); if (asn1Obj == null) return null; if (asn1Obj is Asn1OctetStringParser) return (Asn1OctetStringParser)asn1Obj; - throw new IOException("unknown object encountered: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(asn1Obj)); + throw new IOException("unknown object encountered: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(asn1Obj)); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DERExternal.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DERExternal.cs index 7973588..06bb37f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DERExternal.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DERExternal.cs @@ -13,54 +13,97 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public class DerExternal : Asn1Object { - private DerObjectIdentifier directReference; - private DerInteger indirectReference; - private Asn1Object dataValueDescriptor; - private int encoding; - private Asn1Object externalContent; - - public DerExternal( - Asn1EncodableVector vector) + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(DerExternal), Asn1Tags.External) {} + + internal override Asn1Object FromImplicitConstructed(Asn1Sequence sequence) + { + return sequence.ToAsn1External(); + } + } + + public static DerExternal GetInstance(object obj) + { + if (obj == null) + return null; + + if (obj is DerExternal derExternal) + return derExternal; + + if (obj is IAsn1Convertible asn1Convertible) + { + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is DerExternal converted) + return converted; + } + else if (obj is byte[] bytes) + { + try + { + return (DerExternal)Meta.Instance.FromByteArray(bytes); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct external from byte[]: " + e.Message); + } + } + + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + } + + public static DerExternal GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) + { + return (DerExternal)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); + } + + private readonly DerObjectIdentifier directReference; + private readonly DerInteger indirectReference; + private readonly Asn1ObjectDescriptor dataValueDescriptor; + private readonly int encoding; + private readonly Asn1Object externalContent; + + public DerExternal(Asn1EncodableVector vector) + : this(new DerSequence(vector)) + { + } + + public DerExternal(Asn1Sequence sequence) { int offset = 0; - Asn1Object enc = GetObjFromVector(vector, offset); - if (enc is DerObjectIdentifier) + + Asn1Object asn1 = GetObjFromSequence(sequence, offset); + if (asn1 is DerObjectIdentifier) { - directReference = (DerObjectIdentifier)enc; - offset++; - enc = GetObjFromVector(vector, offset); + directReference = (DerObjectIdentifier)asn1; + asn1 = GetObjFromSequence(sequence, ++offset); } - if (enc is DerInteger) + if (asn1 is DerInteger) { - indirectReference = (DerInteger) enc; - offset++; - enc = GetObjFromVector(vector, offset); + indirectReference = (DerInteger)asn1; + asn1 = GetObjFromSequence(sequence, ++offset); } - if (!(enc is Asn1TaggedObject)) + if (!(asn1 is Asn1TaggedObject)) { - dataValueDescriptor = enc; - offset++; - enc = GetObjFromVector(vector, offset); + dataValueDescriptor = (Asn1ObjectDescriptor)asn1; + asn1 = GetObjFromSequence(sequence, ++offset); } - if (vector.Count != offset + 1) - throw new ArgumentException("input vector too large", "vector"); - - if (!(enc is Asn1TaggedObject)) - throw new ArgumentException("No tagged object found in vector. Structure doesn't seem to be of type External", "vector"); - - Asn1TaggedObject obj = (Asn1TaggedObject)enc; - - // Use property accessor to include check on value - Encoding = obj.TagNo; + if (sequence.Count != offset + 1) + throw new ArgumentException("input sequence too large", "sequence"); - if (encoding < 0 || encoding > 2) - throw new InvalidOperationException("invalid encoding value"); + if (!(asn1 is Asn1TaggedObject)) + throw new ArgumentException( + "No tagged object found in sequence. Structure doesn't seem to be of type External", "sequence"); - externalContent = obj.GetObject(); + Asn1TaggedObject obj = (Asn1TaggedObject)asn1; + this.encoding = CheckEncoding(obj.TagNo); + this.externalContent = GetExternalContent(obj); } - /** + /** * Creates a new instance of DerExternal * See X.690 for more informations about the meaning of these parameters * @param directReference The direct reference or null if not set. @@ -68,12 +111,17 @@ public DerExternal( * @param dataValueDescriptor The data value descriptor or null if not set. * @param externalData The external data in its encoded form. */ - public DerExternal(DerObjectIdentifier directReference, DerInteger indirectReference, Asn1Object dataValueDescriptor, DerTaggedObject externalData) - : this(directReference, indirectReference, dataValueDescriptor, externalData.TagNo, externalData.ToAsn1Object()) - { - } + public DerExternal(DerObjectIdentifier directReference, DerInteger indirectReference, + Asn1ObjectDescriptor dataValueDescriptor, DerTaggedObject externalData) + { + this.directReference = directReference; + this.indirectReference = indirectReference; + this.dataValueDescriptor = dataValueDescriptor; + this.encoding = CheckEncoding(externalData.TagNo); + this.externalContent = GetExternalContent(externalData); + } - /** + /** * Creates a new instance of DerExternal. * See X.690 for more informations about the meaning of these parameters * @param directReference The direct reference or null if not set. @@ -82,96 +130,62 @@ public DerExternal(DerObjectIdentifier directReference, DerInteger indirectRefer * @param encoding The encoding to be used for the external data * @param externalData The external data */ - public DerExternal(DerObjectIdentifier directReference, DerInteger indirectReference, Asn1Object dataValueDescriptor, int encoding, Asn1Object externalData) - { - DirectReference = directReference; - IndirectReference = indirectReference; - DataValueDescriptor = dataValueDescriptor; - Encoding = encoding; - ExternalContent = externalData.ToAsn1Object(); - } - - internal override int EncodedLength(bool withID) + public DerExternal(DerObjectIdentifier directReference, DerInteger indirectReference, + Asn1ObjectDescriptor dataValueDescriptor, int encoding, Asn1Object externalData) { - int contentsLength = 0; - if (directReference != null) - { - contentsLength += directReference.EncodedLength(true); - } - if (indirectReference != null) - { - contentsLength += indirectReference.EncodedLength(true); - } - if (dataValueDescriptor != null) - { - // TODO[asn1] - //contentsLength += dataValueDescriptor.ToDerObject().EncodedLength(true); - contentsLength += dataValueDescriptor.GetDerEncoded().Length; - } - - // TODO[asn1] - //contentsLength += new DerTaggedObject(true, encoding, externalContent).EncodedLength(true); - contentsLength += new DerTaggedObject(Asn1Tags.External, externalContent).EncodedLength(true); + this.directReference = directReference; + this.indirectReference = indirectReference; + this.dataValueDescriptor = dataValueDescriptor; + this.encoding = CheckEncoding(encoding); + this.externalContent = CheckExternalContent(encoding, externalData); + } - return Asn1OutputStream.GetLengthOfEncodingDL(withID, contentsLength); + internal Asn1Sequence BuildSequence() + { + Asn1EncodableVector v = new Asn1EncodableVector(4); + v.AddOptional(directReference, indirectReference, dataValueDescriptor); + v.Add(new DerTaggedObject(0 == encoding, encoding, externalContent)); + return new DerSequence(v); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) - { - MemoryStream ms = new MemoryStream(); - WriteEncodable(ms, directReference); - WriteEncodable(ms, indirectReference); - WriteEncodable(ms, dataValueDescriptor); - WriteEncodable(ms, new DerTaggedObject(Asn1Tags.External, externalContent)); + internal override IAsn1Encoding GetEncoding(int encoding) + { + return BuildSequence().GetEncodingImplicit(encoding, Asn1Tags.Universal, Asn1Tags.External); + } - asn1Out.WriteEncodingDL(withID, Asn1Tags.Constructed | Asn1Tags.External, ms.ToArray()); - } + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + return BuildSequence().GetEncodingImplicit(encoding, tagClass, tagNo); + } - protected override int Asn1GetHashCode() + protected override int Asn1GetHashCode() { - int ret = externalContent.GetHashCode(); - if (directReference != null) - { - ret ^= directReference.GetHashCode(); - } - if (indirectReference != null) - { - ret ^= indirectReference.GetHashCode(); - } - if (dataValueDescriptor != null) - { - ret ^= dataValueDescriptor.GetHashCode(); - } - return ret; + return Objects.GetHashCode(this.directReference) + ^ Objects.GetHashCode(this.indirectReference) + ^ Objects.GetHashCode(this.dataValueDescriptor) + ^ this.encoding + ^ this.externalContent.GetHashCode(); } - protected override bool Asn1Equals( - Asn1Object asn1Object) + protected override bool Asn1Equals(Asn1Object asn1Object) { - if (this == asn1Object) - return true; - - DerExternal other = asn1Object as DerExternal; - - if (other == null) - return false; - - return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(directReference, other.directReference) - && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(indirectReference, other.indirectReference) - && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(dataValueDescriptor, other.dataValueDescriptor) - && externalContent.Equals(other.externalContent); + DerExternal that = asn1Object as DerExternal; + return null != that + && Equals(this.directReference, that.directReference) + && Equals(this.indirectReference, that.indirectReference) + && Equals(this.dataValueDescriptor, that.dataValueDescriptor) + && this.encoding == that.encoding + && this.externalContent.Equals(that.externalContent); } - public Asn1Object DataValueDescriptor + public Asn1ObjectDescriptor DataValueDescriptor { get { return dataValueDescriptor; } - set { this.dataValueDescriptor = value; } } public DerObjectIdentifier DirectReference { get { return directReference; } - set { this.directReference = value; } } /** @@ -184,46 +198,75 @@ public DerObjectIdentifier DirectReference */ public int Encoding { - get - { - return encoding; - } - set - { - if (encoding < 0 || encoding > 2) - throw new InvalidOperationException("invalid encoding value: " + encoding); - - this.encoding = value; - } + get { return encoding; } } public Asn1Object ExternalContent { get { return externalContent; } - set { this.externalContent = value; } } public DerInteger IndirectReference { get { return indirectReference; } - set { this.indirectReference = value; } } - private static Asn1Object GetObjFromVector(Asn1EncodableVector v, int index) - { - if (v.Count <= index) - throw new ArgumentException("too few objects in input vector", "v"); + private static Asn1ObjectDescriptor CheckDataValueDescriptor(Asn1Object dataValueDescriptor) + { + if (dataValueDescriptor is Asn1ObjectDescriptor) + return (Asn1ObjectDescriptor)dataValueDescriptor; + if (dataValueDescriptor is DerGraphicString) + return new Asn1ObjectDescriptor((DerGraphicString)dataValueDescriptor); - return v[index].ToAsn1Object(); - } + throw new ArgumentException("incompatible type for data-value-descriptor", "dataValueDescriptor"); + } + + private static int CheckEncoding(int encoding) + { + if (encoding < 0 || encoding > 2) + throw new InvalidOperationException("invalid encoding value: " + encoding); + + return encoding; + } + + private static Asn1Object CheckExternalContent(int tagNo, Asn1Object externalContent) + { + switch (tagNo) + { + case 1: + return Asn1OctetString.Meta.Instance.CheckedCast(externalContent); + case 2: + return DerBitString.Meta.Instance.CheckedCast(externalContent); + default: + return externalContent; + } + } + + private static Asn1Object GetExternalContent(Asn1TaggedObject encoding) + { + int tagClass = encoding.TagClass, tagNo = encoding.TagNo; + if (Asn1Tags.ContextSpecific != tagClass) + throw new ArgumentException("invalid tag: " + Asn1Utilities.GetTagText(tagClass, tagNo), "encoding"); - private static void WriteEncodable(MemoryStream ms, Asn1Encodable e) + switch (tagNo) + { + case 0: + return encoding.GetExplicitBaseObject().ToAsn1Object(); + case 1: + return Asn1OctetString.GetInstance(encoding, false); + case 2: + return DerBitString.GetInstance(encoding, false); + default: + throw new ArgumentException("invalid tag: " + Asn1Utilities.GetTagText(tagClass, tagNo), "encoding"); + } + } + + private static Asn1Object GetObjFromSequence(Asn1Sequence sequence, int index) { - if (e != null) - { - byte[] bs = e.GetDerEncoded(); - ms.Write(bs, 0, bs.Length); - } + if (sequence.Count <= index) + throw new ArgumentException("too few objects in input sequence", "sequence"); + + return sequence[index].ToAsn1Object(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DERExternalParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DERExternalParser.cs index 5fab03b..415ec89 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DERExternalParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DERExternalParser.cs @@ -7,22 +7,21 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public class DerExternalParser : Asn1Encodable { - private readonly Asn1StreamParser _parser; + private readonly Asn1StreamParser m_parser; - - public DerExternalParser(Asn1StreamParser parser) + internal DerExternalParser(Asn1StreamParser parser) { - this._parser = parser; + m_parser = parser; } public IAsn1Convertible ReadObject() { - return _parser.ReadObject(); + return m_parser.ReadObject(); } public override Asn1Object ToAsn1Object() { - return Parse(_parser); + return Parse(m_parser); } internal static DerExternal Parse(Asn1StreamParser sp) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DERSequenceParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DERSequenceParser.cs index 02aa686..423fa42 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DERSequenceParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DERSequenceParser.cs @@ -1,26 +1,28 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable +using System; + namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 { - public class DerSequenceParser + // TODO[asn1] Should be renamed/replaced with DLSequenceParser + public class DerSequenceParser : Asn1SequenceParser { - private readonly Asn1StreamParser _parser; + private readonly Asn1StreamParser m_parser; - internal DerSequenceParser( - Asn1StreamParser parser) + internal DerSequenceParser(Asn1StreamParser parser) { - this._parser = parser; + this.m_parser = parser; } public IAsn1Convertible ReadObject() { - return _parser.ReadObject(); + return m_parser.ReadObject(); } public Asn1Object ToAsn1Object() { - return new DerSequence(_parser.ReadVector()); + return DLSequence.FromVector(m_parser.ReadVector()); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DERSetParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DERSetParser.cs index 346cec0..43be31b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DERSetParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DERSetParser.cs @@ -1,26 +1,28 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable +using System; + namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 { + // TODO[asn1] Should be renamed/replaced with DLSetParser public class DerSetParser : Asn1SetParser { - private readonly Asn1StreamParser _parser; + private readonly Asn1StreamParser m_parser; - internal DerSetParser( - Asn1StreamParser parser) + internal DerSetParser(Asn1StreamParser parser) { - this._parser = parser; + this.m_parser = parser; } public IAsn1Convertible ReadObject() { - return _parser.ReadObject(); + return m_parser.ReadObject(); } public Asn1Object ToAsn1Object() { - return new DerSet(_parser.ReadVector(), false); + return DLSet.FromVector(m_parser.ReadVector()); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLBitString.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLBitString.cs new file mode 100644 index 0000000..72b9976 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLBitString.cs @@ -0,0 +1,59 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + /// A Definite length BIT STRING + public class DLBitString + : DerBitString + { + public DLBitString(byte data, int padBits) + : base(data, padBits) + { + } + + public DLBitString(byte[] data) + : this(data, 0) + { + } + + public DLBitString(byte[] data, int padBits) + : base(data, padBits) + { + } + + public DLBitString(int namedBits) + : base(namedBits) + { + } + + public DLBitString(Asn1Encodable obj) + : this(obj.GetDerEncoded(), 0) + { + } + + internal DLBitString(byte[] contents, bool check) + : base(contents, check) + { + } + + internal override IAsn1Encoding GetEncoding(int encoding) + { + if (Asn1OutputStream.EncodingDer == encoding) + return base.GetEncoding(encoding); + + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.BitString, contents); + } + + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + if (Asn1OutputStream.EncodingDer == encoding) + return base.GetEncodingImplicit(encoding, tagClass, tagNo); + + return new PrimitiveEncoding(tagClass, tagNo, contents); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLBitString.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLBitString.cs.meta new file mode 100644 index 0000000..7c67064 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLBitString.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 986e474ccac71c949b5a6f940fe786c4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLBitStringParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLBitStringParser.cs new file mode 100644 index 0000000..2837642 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLBitStringParser.cs @@ -0,0 +1,69 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.IO; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + /// Parser for a DL encoded BIT STRING. + internal class DLBitStringParser + : Asn1BitStringParser + { + private readonly DefiniteLengthInputStream m_stream; + private int m_padBits = 0; + + internal DLBitStringParser(DefiniteLengthInputStream stream) + { + m_stream = stream; + } + + public Stream GetBitStream() + { + return GetBitStream(false); + } + + public Stream GetOctetStream() + { + return GetBitStream(true); + } + + public int PadBits + { + get { return m_padBits; } + } + + public Asn1Object ToAsn1Object() + { + try + { + return DerBitString.CreatePrimitive(m_stream.ToArray()); + } + catch (IOException e) + { + throw new Asn1ParsingException("IOException converting stream to byte array: " + e.Message, e); + } + } + + private Stream GetBitStream(bool octetAligned) + { + int length = m_stream.Remaining; + if (length < 1) + throw new InvalidOperationException("content octets cannot be empty"); + + m_padBits = m_stream.ReadByte(); + if (m_padBits > 0) + { + if (length < 2) + throw new InvalidOperationException("zero length data with non-zero pad bits"); + if (m_padBits > 7) + throw new InvalidOperationException("pad bits cannot be greater than 7 or less than 0"); + if (octetAligned) + throw new IOException("expected octet-aligned bitstring, but found padBits: " + m_padBits); + } + + return m_stream; + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLBitStringParser.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLBitStringParser.cs.meta new file mode 100644 index 0000000..2bca098 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLBitStringParser.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 24a951851976cf046ad8b7ea513aaef3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLSequence.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLSequence.cs new file mode 100644 index 0000000..0cce03b --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLSequence.cs @@ -0,0 +1,95 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + internal class DLSequence + : DerSequence + { + internal static new readonly DLSequence Empty = new DLSequence(); + + internal static new DLSequence FromVector(Asn1EncodableVector elementVector) + { + return elementVector.Count < 1 ? Empty : new DLSequence(elementVector); + } + + /** + * create an empty sequence + */ + internal DLSequence() + : base() + { + } + + /** + * create a sequence containing one object + */ + internal DLSequence(Asn1Encodable element) + : base(element) + { + } + + /** + * create a sequence containing two objects + */ + public DLSequence(Asn1Encodable element1, Asn1Encodable element2) + : base(element1, element2) + { + } + + internal DLSequence(params Asn1Encodable[] elements) + : base(elements) + { + } + + /** + * create a sequence containing a vector of objects. + */ + internal DLSequence(Asn1EncodableVector elementVector) + : base(elementVector) + { + } + + internal DLSequence(Asn1Encodable[] elements, bool clone) + : base(elements, clone) + { + } + + internal override IAsn1Encoding GetEncoding(int encoding) + { + if (Asn1OutputStream.EncodingDer == encoding) + return base.GetEncoding(encoding); + + return new ConstructedDLEncoding(Asn1Tags.Universal, Asn1Tags.Sequence, + Asn1OutputStream.GetContentsEncodings(encoding, elements)); + } + + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + if (Asn1OutputStream.EncodingDer == encoding) + return base.GetEncodingImplicit(encoding, tagClass, tagNo); + + return new ConstructedDLEncoding(tagClass, tagNo, + Asn1OutputStream.GetContentsEncodings(encoding, elements)); + } + + internal override DerBitString ToAsn1BitString() + { + return new DLBitString(BerBitString.FlattenBitStrings(GetConstructedBitStrings()), false); + } + + // TODO[asn1] DLExternal + //internal override DerExternal ToAsn1External() + //{ + // return new DLExternal(this); + //} + + internal override Asn1Set ToAsn1Set() + { + return new DLSet(false, elements); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLSequence.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLSequence.cs.meta new file mode 100644 index 0000000..1d263ac --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLSequence.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 821aa4f8eba1f69488486a017ab09680 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLSet.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLSet.cs new file mode 100644 index 0000000..fd1e840 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLSet.cs @@ -0,0 +1,71 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + internal class DLSet + : DerSet + { + internal static new readonly DLSet Empty = new DLSet(); + + internal static new DLSet FromVector(Asn1EncodableVector elementVector) + { + return elementVector.Count < 1 ? Empty : new DLSet(elementVector); + } + + /** + * create an empty set + */ + internal DLSet() + : base() + { + } + + /** + * create a set containing one object + */ + internal DLSet(Asn1Encodable element) + : base(element) + { + } + + internal DLSet(params Asn1Encodable[] elements) + : base(elements, false) + { + } + + /** + * create a set containing a vector of objects. + */ + internal DLSet(Asn1EncodableVector elementVector) + : base(elementVector, false) + { + } + + internal DLSet(bool isSorted, Asn1Encodable[] elements) + : base(isSorted, elements) + { + } + + internal override IAsn1Encoding GetEncoding(int encoding) + { + if (Asn1OutputStream.EncodingDer == encoding) + return base.GetEncoding(encoding); + + return new ConstructedDLEncoding(Asn1Tags.Universal, Asn1Tags.Set, + Asn1OutputStream.GetContentsEncodings(encoding, elements)); + } + + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + if (Asn1OutputStream.EncodingDer == encoding) + return base.GetEncodingImplicit(encoding, tagClass, tagNo); + + return new ConstructedDLEncoding(tagClass, tagNo, + Asn1OutputStream.GetContentsEncodings(encoding, elements)); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLSet.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLSet.cs.meta new file mode 100644 index 0000000..f4755c8 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLSet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6524089898db35644b2343ee5c380e6b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLTaggedObject.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLTaggedObject.cs new file mode 100644 index 0000000..55de758 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLTaggedObject.cs @@ -0,0 +1,79 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + internal class DLTaggedObject + : DerTaggedObject + { + internal DLTaggedObject(int tagNo, Asn1Encodable obj) + : base(tagNo, obj) + { + } + + internal DLTaggedObject(int tagClass, int tagNo, Asn1Encodable obj) + : base(tagClass, tagNo, obj) + { + } + + internal DLTaggedObject(bool isExplicit, int tagNo, Asn1Encodable obj) + : base(isExplicit, tagNo, obj) + { + } + + internal DLTaggedObject(bool isExplicit, int tagClass, int tagNo, Asn1Encodable obj) + : base(isExplicit, tagClass, tagNo, obj) + { + } + + internal DLTaggedObject(int explicitness, int tagClass, int tagNo, Asn1Encodable obj) + : base(explicitness, tagClass, tagNo, obj) + { + } + + internal override string Asn1Encoding + { + // TODO[asn1] Use DL encoding when supported + get { return Ber; } + } + + internal override IAsn1Encoding GetEncoding(int encoding) + { + if (Asn1OutputStream.EncodingDer == encoding) + return base.GetEncoding(encoding); + + Asn1Object baseObject = GetBaseObject().ToAsn1Object(); + + if (!IsExplicit()) + return baseObject.GetEncodingImplicit(encoding, TagClass, TagNo); + + return new ConstructedDLEncoding(TagClass, TagNo, new IAsn1Encoding[]{ baseObject.GetEncoding(encoding) }); + } + + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + if (Asn1OutputStream.EncodingDer == encoding) + return base.GetEncodingImplicit(encoding, tagClass, tagNo); + + Asn1Object baseObject = GetBaseObject().ToAsn1Object(); + + if (!IsExplicit()) + return baseObject.GetEncodingImplicit(encoding, tagClass, tagNo); + + return new ConstructedDLEncoding(tagClass, tagNo, new IAsn1Encoding[]{ baseObject.GetEncoding(encoding) }); + } + + internal override Asn1Sequence RebuildConstructed(Asn1Object asn1Object) + { + return new DLSequence(asn1Object); + } + + internal override Asn1TaggedObject ReplaceTag(int tagClass, int tagNo) + { + return new DLTaggedObject(explicitness, tagClass, tagNo, obj); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLTaggedObject.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLTaggedObject.cs.meta new file mode 100644 index 0000000..51a0f4d --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLTaggedObject.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cd68f6d88a9b2c1418c72e64c599ce93 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLTaggedObjectParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLTaggedObjectParser.cs new file mode 100644 index 0000000..4365e8f --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLTaggedObjectParser.cs @@ -0,0 +1,78 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.IO; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + /** + * Parser for definite-length tagged objects. + */ + internal class DLTaggedObjectParser + : BerTaggedObjectParser + { + private readonly bool m_constructed; + + internal DLTaggedObjectParser(int tagClass, int tagNo, bool constructed, Asn1StreamParser parser) + : base(tagClass, tagNo, parser) + { + m_constructed = constructed; + } + + public override bool IsConstructed + { + get { return m_constructed; } + } + + public override IAsn1Convertible ParseBaseUniversal(bool declaredExplicit, int baseTagNo) + { + if (declaredExplicit) + { + if (!m_constructed) + throw new IOException("Explicit tags must be constructed (see X.690 8.14.2)"); + + return m_parser.ParseObject(baseTagNo); + } + + return m_constructed + ? m_parser.ParseImplicitConstructedDL(baseTagNo) + : m_parser.ParseImplicitPrimitive(baseTagNo); + } + + public override IAsn1Convertible ParseExplicitBaseObject() + { + if (!m_constructed) + throw new IOException("Explicit tags must be constructed (see X.690 8.14.2)"); + + return m_parser.ReadObject(); + } + + public override Asn1TaggedObjectParser ParseExplicitBaseTagged() + { + if (!m_constructed) + throw new IOException("Explicit tags must be constructed (see X.690 8.14.2)"); + + return m_parser.ParseTaggedObject(); + } + + public override Asn1TaggedObjectParser ParseImplicitBaseTagged(int baseTagClass, int baseTagNo) + { + return new DLTaggedObjectParser(baseTagClass, baseTagNo, m_constructed, m_parser); + } + + public override Asn1Object ToAsn1Object() + { + try + { + return m_parser.LoadTaggedDL(TagClass, TagNo, m_constructed); + } + catch (IOException e) + { + throw new Asn1ParsingException(e.Message); + } + } + } +} + +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLTaggedObjectParser.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLTaggedObjectParser.cs.meta new file mode 100644 index 0000000..83d548b --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DLTaggedObjectParser.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5e1d9345964a51d4ca58f102e52dc9b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DefiniteLengthInputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DefiniteLengthInputStream.cs index 9222a19..115da9d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DefiniteLengthInputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DefiniteLengthInputStream.cs @@ -23,7 +23,7 @@ internal DefiniteLengthInputStream(Stream inStream, int length, int limit) if (length < 0) throw new ArgumentException("negative lengths not allowed", "length"); - SetParentEofDetect(true); + SetParentEofDetect(); } this._originalLength = length; @@ -37,43 +37,70 @@ internal int Remaining public override int ReadByte() { - if (_remaining == 0) - return -1; + if (_remaining < 2) + { + if (_remaining == 0) + return -1; - int b = _in.ReadByte(); + int b = _in.ReadByte(); + if (b < 0) + throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining); - if (b < 0) - throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining); + _remaining = 0; + SetParentEofDetect(); - if (--_remaining == 0) - { - SetParentEofDetect(true); - } + return b; + } + else + { + int b = _in.ReadByte(); + if (b < 0) + throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining); - return b; + --_remaining; + return b; + } } - public override int Read( - byte[] buf, - int off, - int len) + public override int Read(byte[] buf, int off, int len) { - if (_remaining == 0) - return 0; + if (_remaining == 0) + return 0; - int toRead = System.Math.Min(len, _remaining); - int numRead = _in.Read(buf, off, toRead); + int toRead = System.Math.Min(len, _remaining); + int numRead = _in.Read(buf, off, toRead); - if (numRead < 1) - throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining); + if (numRead < 1) + throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining); - if ((_remaining -= numRead) == 0) - { - SetParentEofDetect(true); - } + if ((_remaining -= numRead) == 0) + { + SetParentEofDetect(); + } - return numRead; - } + return numRead; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int Read(Span buffer) + { + if (_remaining == 0) + return 0; + + int toRead = System.Math.Min(buffer.Length, _remaining); + int numRead = _in.Read(buffer[..toRead]); + + if (numRead < 1) + throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining); + + if ((_remaining -= numRead) == 0) + { + SetParentEofDetect(); + } + + return numRead; + } +#endif internal void ReadAllIntoByteArray(byte[] buf) { @@ -88,9 +115,9 @@ internal void ReadAllIntoByteArray(byte[] buf) if (_remaining >= limit) throw new IOException("corrupted stream - out of bounds length found: " + _remaining + " >= " + limit); - if ((_remaining -= Streams.ReadFully(_in, buf)) != 0) + if ((_remaining -= Streams.ReadFully(_in, buf, 0, buf.Length)) != 0) throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining); - SetParentEofDetect(true); + SetParentEofDetect(); } internal byte[] ToArray() @@ -104,9 +131,9 @@ internal byte[] ToArray() throw new IOException("corrupted stream - out of bounds length found: " + _remaining + " >= " + limit); byte[] bytes = new byte[_remaining]; - if ((_remaining -= Streams.ReadFully(_in, bytes)) != 0) + if ((_remaining -= Streams.ReadFully(_in, bytes, 0, bytes.Length)) != 0) throw new EndOfStreamException("DEF length " + _originalLength + " object truncated by " + _remaining); - SetParentEofDetect(true); + SetParentEofDetect(); return bytes; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerApplicationSpecific.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerApplicationSpecific.cs index f05ab48..0454b34 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerApplicationSpecific.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerApplicationSpecific.cs @@ -1,234 +1,3 @@ #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 -{ - /** - * Base class for an application specific object - */ - public class DerApplicationSpecific - : Asn1Object - { - private readonly bool isConstructed; - private readonly int tag; - private readonly byte[] octets; - - internal DerApplicationSpecific( - bool isConstructed, - int tag, - byte[] octets) - { - this.isConstructed = isConstructed; - this.tag = tag; - this.octets = octets; - } - - public DerApplicationSpecific( - int tag, - byte[] octets) - : this(false, tag, octets) - { - } - - public DerApplicationSpecific( - int tag, - Asn1Encodable obj) - : this(true, tag, obj) - { - } - - public DerApplicationSpecific( - bool isExplicit, - int tag, - Asn1Encodable obj) - { - Asn1Object asn1Obj = obj.ToAsn1Object(); - - byte[] data = asn1Obj.GetDerEncoded(); - - this.isConstructed = Asn1TaggedObject.IsConstructed(isExplicit, asn1Obj); - this.tag = tag; - - if (isExplicit) - { - this.octets = data; - } - else - { - int lenBytes = GetLengthOfHeader(data); - byte[] tmp = new byte[data.Length - lenBytes]; - Array.Copy(data, lenBytes, tmp, 0, tmp.Length); - this.octets = tmp; - } - } - - public DerApplicationSpecific( - int tagNo, - Asn1EncodableVector vec) - { - this.tag = tagNo; - this.isConstructed = true; - MemoryStream bOut = new MemoryStream(); - - for (int i = 0; i != vec.Count; i++) - { - try - { - byte[] bs = vec[i].GetDerEncoded(); - bOut.Write(bs, 0, bs.Length); - } - catch (IOException e) - { - throw new InvalidOperationException("malformed object", e); - } - } - this.octets = bOut.ToArray(); - } - - private int GetLengthOfHeader( - byte[] data) - { - int length = data[1]; // TODO: assumes 1 byte tag - - if (length == 0x80) - { - return 2; // indefinite-length encoding - } - - if (length > 127) - { - int size = length & 0x7f; - - // Note: The invalid long form "0xff" (see X.690 8.1.3.5c) will be caught here - if (size > 4) - { - throw new InvalidOperationException("DER length more than 4 bytes: " + size); - } - - return size + 2; - } - - return 2; - } - - public bool IsConstructed() - { - return isConstructed; - } - - public byte[] GetContents() - { - return octets; - } - - public int ApplicationTag - { - get { return tag; } - } - - /** - * Return the enclosed object assuming explicit tagging. - * - * @return the resulting object - * @throws IOException if reconstruction fails. - */ - public Asn1Object GetObject() - { - return FromByteArray(GetContents()); - } - - /** - * Return the enclosed object assuming implicit tagging. - * - * @param derTagNo the type tag that should be applied to the object's contents. - * @return the resulting object - * @throws IOException if reconstruction fails. - */ - public Asn1Object GetObject( - int derTagNo) - { - if (derTagNo >= 0x1f) - throw new IOException("unsupported tag number"); - - byte[] orig = this.GetEncoded(); - byte[] tmp = ReplaceTagNumber(derTagNo, orig); - - if ((orig[0] & Asn1Tags.Constructed) != 0) - { - tmp[0] |= Asn1Tags.Constructed; - } - - return FromByteArray(tmp); - } - - internal override int EncodedLength(bool withID) - { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, tag, octets.Length); - } - - internal override void Encode(Asn1OutputStream asn1Out, bool withID) - { - int flags = Asn1Tags.Application; - if (isConstructed) - { - flags |= Asn1Tags.Constructed; - } - - asn1Out.WriteEncodingDL(withID, flags, tag, octets); - } - - protected override bool Asn1Equals( - Asn1Object asn1Object) - { - DerApplicationSpecific other = asn1Object as DerApplicationSpecific; - - if (other == null) - return false; - - return this.isConstructed == other.isConstructed - && this.tag == other.tag - && Arrays.AreEqual(this.octets, other.octets); - } - - protected override int Asn1GetHashCode() - { - return isConstructed.GetHashCode() ^ tag.GetHashCode() ^ Arrays.GetHashCode(octets); - } - - private byte[] ReplaceTagNumber( - int newTag, - byte[] input) - { - int tagNo = input[0] & 0x1f; - int index = 1; - - // with tagged object tag number is bottom 5 bits, or stored at the start of the content - if (tagNo == 0x1f) - { - int b = input[index++]; - - // X.690-0207 8.1.2.4.2 - // "c) bits 7 to 1 of the first subsequent octet shall not all be zero." - if ((b & 0x7f) == 0) // Note: -1 will pass - throw new IOException("corrupted stream - invalid high tag number found"); - - while ((b & 0x80) != 0) - { - b = input[index++]; - } - } - - int remaining = input.Length - index; - byte[] tmp = new byte[1 + remaining]; - tmp[0] = (byte)newTag; - Array.Copy(input, index, tmp, 1, remaining); - return tmp; - } - } -} -#pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerApplicationSpecific.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerApplicationSpecific.cs.meta index 335a204..4ea9e84 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerApplicationSpecific.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerApplicationSpecific.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 788472ee00a6d10478a465572f1ffddb +guid: bce8e7bbc9b4e2248b00e554b19a01c3 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerBMPString.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerBMPString.cs index 8a53321..1924a50 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerBMPString.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerBMPString.cs @@ -1,6 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -12,7 +13,17 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public class DerBmpString : DerStringBase { - private readonly string str; + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(DerBmpString), Asn1Tags.BmpString) {} + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return CreatePrimitive(octetString.GetOctets()); + } + } /** * return a BMP string from the given object. @@ -20,62 +31,67 @@ public class DerBmpString * @param obj the object we want converted. * @exception ArgumentException if the object cannot be converted. */ - public static DerBmpString GetInstance( - object obj) + public static DerBmpString GetInstance(object obj) { - if (obj == null || obj is DerBmpString) + if (obj == null) + return null; + + if (obj is DerBmpString derBmpString) + return derBmpString; + + if (obj is IAsn1Convertible asn1Convertible) + { + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is DerBmpString converted) + return converted; + } + else if (obj is byte[] bytes) { - return (DerBmpString)obj; + try + { + return (DerBmpString)Meta.Instance.FromByteArray(bytes); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct BMP string from byte[]: " + e.Message); + } } - throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } /** * return a BMP 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. + * @param taggedObject the tagged object holding the object we want + * @param declaredExplicit true if the object is meant to be explicitly tagged false otherwise. + * @exception ArgumentException if the tagged object cannot be converted. */ - public static DerBmpString GetInstance( - Asn1TaggedObject obj, - bool isExplicit) + public static DerBmpString GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - Asn1Object o = obj.GetObject(); - - if (isExplicit || o is DerBmpString) - { - return GetInstance(o); - } - - return new DerBmpString(Asn1OctetString.GetInstance(o).GetOctets()); + return (DerBmpString)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); } - /** - * basic constructor - byte encoded string. - */ + private readonly string m_str; - public DerBmpString(byte[] str) + internal DerBmpString(byte[] contents) { - if (str == null) - throw new ArgumentNullException("str"); + if (null == contents) + throw new ArgumentNullException("contents"); - int byteLen = str.Length; + int byteLen = contents.Length; if (0 != (byteLen & 1)) - throw new ArgumentException("malformed BMPString encoding encountered", "str"); + throw new ArgumentException("malformed BMPString encoding encountered", "contents"); int charLen = byteLen / 2; char[] cs = new char[charLen]; for (int i = 0; i != charLen; i++) { - cs[i] = (char)((str[2 * i] << 8) | (str[2 * i + 1] & 0xff)); + cs[i] = (char)((contents[2 * i] << 8) | (contents[2 * i + 1] & 0xff)); } - this.str = new string(cs); + m_str = new string(cs); } internal DerBmpString(char[] str) @@ -83,7 +99,7 @@ internal DerBmpString(char[] str) if (str == null) throw new ArgumentNullException("str"); - this.str = new string(str); + m_str = new string(str); } /** @@ -94,42 +110,59 @@ public DerBmpString(string str) if (str == null) throw new ArgumentNullException("str"); - this.str = str; + m_str = str; } public override string GetString() { - return str; + return m_str; } - protected override bool Asn1Equals( - Asn1Object asn1Object) + protected override bool Asn1Equals(Asn1Object asn1Object) { - DerBmpString other = asn1Object as DerBmpString; + DerBmpString that = asn1Object as DerBmpString; + return null != that + && this.m_str.Equals(that.m_str); + } - if (other == null) - return false; + protected override int Asn1GetHashCode() + { + return m_str.GetHashCode(); + } - return this.str.Equals(other.str); + internal override IAsn1Encoding GetEncoding(int encoding) + { + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.BmpString, GetContents()); } - internal override int EncodedLength(bool withID) + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, str.Length * 2); + return new PrimitiveEncoding(tagClass, tagNo, GetContents()); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) + private byte[] GetContents() { - char[] c = str.ToCharArray(); + char[] c = m_str.ToCharArray(); byte[] b = new byte[c.Length * 2]; - for (int i = 0; i != c.Length; i++) + for (int i = 0; i != c.Length; i++) { b[2 * i] = (byte)(c[i] >> 8); b[2 * i + 1] = (byte)c[i]; } - asn1Out.WriteEncodingDL(withID, Asn1Tags.BmpString, b); + return b; + } + + internal static DerBmpString CreatePrimitive(byte[] contents) + { + return new DerBmpString(contents); + } + + internal static DerBmpString CreatePrimitive(char[] str) + { + // TODO[asn1] Asn1InputStream has a validator/converter that should be unified in this class somehow + return new DerBmpString(str); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerBitString.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerBitString.cs index 1616582..9313cc9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerBitString.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerBitString.cs @@ -2,6 +2,7 @@ #pragma warning disable using System; using System.Diagnostics; +using System.IO; using System.Text; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; @@ -10,9 +11,26 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 { public class DerBitString - : DerStringBase - { - private static readonly char[] table + : DerStringBase, Asn1BitStringParser + { + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(DerBitString), Asn1Tags.BitString) { } + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return CreatePrimitive(octetString.GetOctets()); + } + + internal override Asn1Object FromImplicitConstructed(Asn1Sequence sequence) + { + return sequence.ToAsn1BitString(); + } + } + + private static readonly char[] table = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; /** @@ -22,23 +40,31 @@ private static readonly char[] table */ public static DerBitString GetInstance(object obj) { - if (obj == null || obj is DerBitString) - { - return (DerBitString) obj; - } - if (obj is byte[]) + if (obj == null) + return null; + + if (obj is DerBitString derBitString) + return derBitString; + + if (obj is IAsn1Convertible asn1Convertible) + { + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is DerBitString converted) + return converted; + } + else if (obj is byte[] bytes) { try { - return (DerBitString)FromByteArray((byte[])obj); + return GetInstance(FromByteArray(bytes)); } - catch (Exception e) + catch (IOException e) { - throw new ArgumentException("encoding error in GetInstance: " + e.ToString()); + throw new ArgumentException("failed to construct BIT STRING from byte[]: " + e.Message); } } - throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } /** @@ -102,7 +128,7 @@ public DerBitString(int namedBits) return; } - int bits = BigInteger.BitLen(namedBits); + int bits = 32 - Integers.NumberOfLeadingZeros(namedBits); int bytes = (bits + 7) / 8; Debug.Assert(0 < bytes && bytes <= 4); @@ -210,29 +236,37 @@ public virtual int IntValue } } - internal override int EncodedLength(bool withID) + internal override IAsn1Encoding GetEncoding(int encoding) { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, contents.Length); - } - - internal override void Encode(Asn1OutputStream asn1Out, bool withID) - { int padBits = contents[0]; - int length = contents.Length; - int last = length - 1; - - byte lastOctet = contents[last]; - byte lastOctetDer = (byte)(contents[last] & (0xFF << padBits)); - - if (lastOctet == lastOctetDer) + if (padBits != 0) { - asn1Out.WriteEncodingDL(withID, Asn1Tags.BitString, contents); + int last = contents.Length - 1; + byte lastBer = contents[last]; + byte lastDer = (byte)(lastBer & (0xFF << padBits)); + + if (lastBer != lastDer) + return new PrimitiveEncodingSuffixed(Asn1Tags.Universal, Asn1Tags.BitString, contents, lastDer); } - else + + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.BitString, contents); + } + + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + int padBits = contents[0]; + if (padBits != 0) { - asn1Out.WriteEncodingDL(withID, Asn1Tags.BitString, contents, 0, last, lastOctetDer); + int last = contents.Length - 1; + byte lastBer = contents[last]; + byte lastDer = (byte)(lastBer & (0xFF << padBits)); + + if (lastBer != lastDer) + return new PrimitiveEncodingSuffixed(tagClass, tagNo, contents, lastDer); } - } + + return new PrimitiveEncoding(tagClass, tagNo, contents); + } protected override int Asn1GetHashCode() { @@ -242,11 +276,11 @@ protected override int Asn1GetHashCode() int padBits = contents[0]; int last = contents.Length - 1; - byte lastOctetDer = (byte)(contents[last] & (0xFF << padBits)); + byte lastDer = (byte)(contents[last] & (0xFF << padBits)); int hc = Arrays.GetHashCode(contents, 0, last); hc *= 257; - hc ^= lastOctetDer; + hc ^= lastDer; return hc; } @@ -272,43 +306,48 @@ protected override bool Asn1Equals(Asn1Object asn1Object) } int padBits = thisContents[0]; - byte thisLastOctetDer = (byte)(thisContents[last] & (0xFF << padBits)); - byte thatLastOctetDer = (byte)(thatContents[last] & (0xFF << padBits)); + byte thisLastDer = (byte)(thisContents[last] & (0xFF << padBits)); + byte thatLastDer = (byte)(thatContents[last] & (0xFF << padBits)); - return thisLastOctetDer == thatLastOctetDer; + return thisLastDer == thatLastDer; } - public override string GetString() - { - StringBuilder buffer = new StringBuilder("#"); - - byte[] str = GetDerEncoded(); - - for (int i = 0; i != str.Length; i++) - { - uint ubyte = str[i]; - buffer.Append(table[(ubyte >> 4) & 0xf]); - buffer.Append(table[str[i] & 0xf]); - } - - return buffer.ToString(); - } - - internal static int EncodedLength(bool withID, int contentsLength) + public Stream GetBitStream() { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, contentsLength); + return new MemoryStream(contents, 1, contents.Length - 1, false); } - internal static void Encode(Asn1OutputStream asn1Out, bool withID, byte[] buf, int off, int len) + public Stream GetOctetStream() { - asn1Out.WriteEncodingDL(withID, Asn1Tags.BitString, buf, off, len); + int padBits = contents[0] & 0xFF; + if (0 != padBits) + throw new IOException("expected octet-aligned bitstring, but found padBits: " + padBits); + + return GetBitStream(); } - internal static void Encode(Asn1OutputStream asn1Out, bool withID, byte pad, byte[] buf, int off, int len) + public Asn1BitStringParser Parser { - asn1Out.WriteEncodingDL(withID, Asn1Tags.BitString, pad, buf, off, len); + get { return this; } } + public override string GetString() + { + byte[] str = GetDerEncoded(); + + StringBuilder buffer = PlatformSupport.Text.StringBuilderPool.Get(1 + str.Length * 2); //new StringBuilder(1 + str.Length * 2); + buffer.Append('#'); + + for (int i = 0; i != str.Length; i++) + { + uint u8 = str[i]; + buffer.Append(table[u8 >> 4]); + buffer.Append(table[u8 & 0xF]); + } + + return PlatformSupport.Text.StringBuilderPool.ReleaseAndGrab(buffer); + } + internal static DerBitString CreatePrimitive(byte[] contents) { int length = contents.Length; @@ -323,9 +362,7 @@ internal static DerBitString CreatePrimitive(byte[] contents) byte finalOctet = contents[length - 1]; if (finalOctet != (byte)(finalOctet & (0xFF << padBits))) - { - return new BerBitString(contents, false); - } + return new DLBitString(contents, false); } return new DerBitString(contents, false); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerBoolean.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerBoolean.cs index c64d070..5da77ef 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerBoolean.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerBoolean.cs @@ -1,6 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -9,7 +10,17 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public class DerBoolean : Asn1Object { - private readonly byte value; + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(DerBoolean), Asn1Tags.Boolean) {} + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return CreatePrimitive(octetString.GetOctets()); + } + } public static readonly DerBoolean False = new DerBoolean(false); public static readonly DerBoolean True = new DerBoolean(true); @@ -19,49 +30,59 @@ public class DerBoolean * * @exception ArgumentException if the object cannot be converted. */ - public static DerBoolean GetInstance( - object obj) + public static DerBoolean GetInstance(object obj) { - if (obj == null || obj is DerBoolean) + if (obj == null) + return null; + + if (obj is DerBoolean derBoolean) + return derBoolean; + + if (obj is IAsn1Convertible asn1Convertible) + { + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is DerBoolean converted) + return converted; + } + else if (obj is byte[] bytes) { - return (DerBoolean) obj; + try + { + return (DerBoolean)Meta.Instance.FromByteArray(bytes); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct boolean from byte[]: " + e.Message); + } } - throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } - /** - * return a DerBoolean from the passed in bool. - */ - public static DerBoolean GetInstance( - bool value) + public static DerBoolean GetInstance(bool value) { return value ? True : False; } + public static DerBoolean GetInstance(int value) + { + return value != 0 ? True : False; + } + /** * return a Boolean 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. + * @param taggedObject the tagged object holding the object we want + * @param declaredExplicit true if the object is meant to be explicitly tagged false otherwise. + * @exception ArgumentException if the tagged object cannot be converted. */ - public static DerBoolean GetInstance( - Asn1TaggedObject obj, - bool isExplicit) + public static DerBoolean GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - Asn1Object o = obj.GetObject(); - - if (isExplicit || o is DerBoolean) - { - return GetInstance(o); - } - - return FromOctetString(((Asn1OctetString)o).GetOctets()); + return (DerBoolean)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); } + private readonly byte value; + public DerBoolean( byte[] val) { @@ -83,15 +104,14 @@ public bool IsTrue get { return value != 0; } } - internal override int EncodedLength(bool withID) + internal override IAsn1Encoding GetEncoding(int encoding) { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, 1); + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.Boolean, GetContents(encoding)); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) { - // TODO Should we make sure the byte value is one of '0' or '0xff' here? - asn1Out.WriteEncodingDL(withID, Asn1Tags.Boolean, value); + return new PrimitiveEncoding(tagClass, tagNo, GetContents(encoding)); } protected override bool Asn1Equals( @@ -115,16 +135,25 @@ public override string ToString() return IsTrue ? "TRUE" : "FALSE"; } - internal static DerBoolean FromOctetString(byte[] value) + internal static DerBoolean CreatePrimitive(byte[] contents) { - if (value.Length != 1) + if (contents.Length != 1) + throw new ArgumentException("BOOLEAN value should have 1 byte in it", "contents"); + + byte b = contents[0]; + + return b == 0 ? False : b == 0xFF ? True : new DerBoolean(contents); + } + + private byte[] GetContents(int encoding) + { + byte contents = value; + if (Asn1OutputStream.EncodingDer == encoding && IsTrue) { - throw new ArgumentException("BOOLEAN value should have 1 byte in it", "value"); + contents = 0xFF; } - byte b = value[0]; - - return b == 0 ? False : b == 0xFF ? True : new DerBoolean(value); + return new byte[]{ contents }; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerEnumerated.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerEnumerated.cs index 3147eec..bbaade9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerEnumerated.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerEnumerated.cs @@ -1,6 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -10,54 +11,73 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public class DerEnumerated : Asn1Object { - private readonly byte[] bytes; - private readonly int start; + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(DerEnumerated), Asn1Tags.Enumerated) {} + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return CreatePrimitive(octetString.GetOctets(), false); + } + } /** * return an integer from the passed in object * * @exception ArgumentException if the object cannot be converted. */ - public static DerEnumerated GetInstance( - object obj) + public static DerEnumerated GetInstance(object obj) { - if (obj == null || obj is DerEnumerated) + if (obj == null) + return null; + + if (obj is DerEnumerated derEnumerated) + return derEnumerated; + + if (obj is IAsn1Convertible asn1Convertible) + { + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is DerEnumerated converted) + return converted; + } + else if (obj is byte[] bytes) { - return (DerEnumerated)obj; + try + { + return (DerEnumerated)Meta.Instance.FromByteArray(bytes); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct enumerated from byte[]: " + e.Message); + } } - throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } /** * return an Enumerated 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. + * @param taggedObject the tagged object holding the object we want + * @param declaredExplicit true if the object is meant to be explicitly tagged false otherwise. + * @exception ArgumentException if the tagged object cannot be converted. */ - public static DerEnumerated GetInstance( - Asn1TaggedObject obj, - bool isExplicit) + public static DerEnumerated GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - Asn1Object o = obj.GetObject(); - - if (isExplicit || o is DerEnumerated) - { - return GetInstance(o); - } - - return FromOctetString(((Asn1OctetString)o).GetOctets()); + return (DerEnumerated)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); } + private readonly byte[] contents; + private readonly int start; + public DerEnumerated(int val) { if (val < 0) throw new ArgumentException("enumerated must be non-negative", "val"); - this.bytes = BigInteger.ValueOf(val).ToByteArray(); + this.contents = BigInteger.ValueOf(val).ToByteArray(); this.start = 0; } @@ -66,7 +86,7 @@ public DerEnumerated(long val) if (val < 0L) throw new ArgumentException("enumerated must be non-negative", "val"); - this.bytes = BigInteger.ValueOf(val).ToByteArray(); + this.contents = BigInteger.ValueOf(val).ToByteArray(); this.start = 0; } @@ -75,37 +95,42 @@ public DerEnumerated(BigInteger val) if (val.SignValue < 0) throw new ArgumentException("enumerated must be non-negative", "val"); - this.bytes = val.ToByteArray(); + this.contents = val.ToByteArray(); this.start = 0; } - public DerEnumerated(byte[] bytes) + public DerEnumerated(byte[] contents) + : this(contents, true) + { + } + + internal DerEnumerated(byte[] contents, bool clone) { - if (DerInteger.IsMalformed(bytes)) - throw new ArgumentException("malformed enumerated", "bytes"); - if (0 != (bytes[0] & 0x80)) - throw new ArgumentException("enumerated must be non-negative", "bytes"); + if (DerInteger.IsMalformed(contents)) + throw new ArgumentException("malformed enumerated", "contents"); + if (0 != (contents[0] & 0x80)) + throw new ArgumentException("enumerated must be non-negative", "contents"); - this.bytes = Arrays.Clone(bytes); - this.start = DerInteger.SignBytesToSkip(bytes); + this.contents = clone ? Arrays.Clone(contents) : contents; + this.start = DerInteger.SignBytesToSkip(this.contents); } public BigInteger Value { - get { return new BigInteger(bytes); } + get { return new BigInteger(contents); } } public bool HasValue(int x) { - return (bytes.Length - start) <= 4 - && DerInteger.IntValue(bytes, start, DerInteger.SignExtSigned) == x; + return (contents.Length - start) <= 4 + && DerInteger.IntValue(contents, start, DerInteger.SignExtSigned) == x; } public bool HasValue(BigInteger x) { return null != x // Fast check to avoid allocation - && DerInteger.IntValue(bytes, start, DerInteger.SignExtSigned) == x.IntValue + && DerInteger.IntValue(contents, start, DerInteger.SignExtSigned) == x.IntValue && Value.Equals(x); } @@ -113,22 +138,22 @@ public int IntValueExact { get { - int count = bytes.Length - start; + int count = contents.Length - start; if (count > 4) throw new ArithmeticException("ASN.1 Enumerated out of int range"); - return DerInteger.IntValue(bytes, start, DerInteger.SignExtSigned); + return DerInteger.IntValue(contents, start, DerInteger.SignExtSigned); } } - internal override int EncodedLength(bool withID) + internal override IAsn1Encoding GetEncoding(int encoding) { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, bytes.Length); + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.Enumerated, contents); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) { - asn1Out.WriteEncodingDL(withID, Asn1Tags.Enumerated, bytes); + return new PrimitiveEncoding(tagClass, tagNo, contents); } protected override bool Asn1Equals(Asn1Object asn1Object) @@ -137,31 +162,31 @@ protected override bool Asn1Equals(Asn1Object asn1Object) if (other == null) return false; - return Arrays.AreEqual(this.bytes, other.bytes); + return Arrays.AreEqual(this.contents, other.contents); } protected override int Asn1GetHashCode() { - return Arrays.GetHashCode(bytes); + return Arrays.GetHashCode(contents); } private static readonly DerEnumerated[] cache = new DerEnumerated[12]; - internal static DerEnumerated FromOctetString(byte[] enc) + internal static DerEnumerated CreatePrimitive(byte[] contents, bool clone) { - if (enc.Length > 1) - return new DerEnumerated(enc); - if (enc.Length == 0) - throw new ArgumentException("ENUMERATED has zero length", "enc"); + if (contents.Length > 1) + return new DerEnumerated(contents, clone); + if (contents.Length == 0) + throw new ArgumentException("ENUMERATED has zero length", "contents"); - int value = enc[0]; + int value = contents[0]; if (value >= cache.Length) - return new DerEnumerated(enc); + return new DerEnumerated(contents, clone); DerEnumerated possibleMatch = cache[value]; if (possibleMatch == null) { - cache[value] = possibleMatch = new DerEnumerated(enc); + cache[value] = possibleMatch = new DerEnumerated(contents, clone); } return possibleMatch; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerGeneralString.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerGeneralString.cs index 0827372..f302ab5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerGeneralString.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerGeneralString.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Text; +using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -10,78 +10,110 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public class DerGeneralString : DerStringBase { - private readonly string str; - - public static DerGeneralString GetInstance( - object obj) + internal class Meta : Asn1UniversalType { - if (obj == null || obj is DerGeneralString) + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(DerGeneralString), Asn1Tags.GeneralString) {} + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) { - return (DerGeneralString) obj; + return CreatePrimitive(octetString.GetOctets()); } - - throw new ArgumentException("illegal object in GetInstance: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } - public static DerGeneralString GetInstance( - Asn1TaggedObject obj, - bool isExplicit) + public static DerGeneralString GetInstance(object obj) { - Asn1Object o = obj.GetObject(); + if (obj == null) + return null; - if (isExplicit || o is DerGeneralString) - { - return GetInstance(o); - } + if (obj is DerGeneralString derGeneralString) + return derGeneralString; - return new DerGeneralString(((Asn1OctetString)o).GetOctets()); + if (obj is IAsn1Convertible asn1Convertible) + { + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is DerGeneralString converted) + return converted; + } + else if (obj is byte[] bytes) + { + try + { + return (DerGeneralString)Meta.Instance.FromByteArray(bytes); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct general string from byte[]: " + e.Message); + } + } + + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } - public DerGeneralString( - byte[] str) - : this(Strings.FromAsciiByteArray(str)) + public static DerGeneralString GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { + return (DerGeneralString)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); } - public DerGeneralString( - string str) + private readonly byte[] m_contents; + + public DerGeneralString(string str) { if (str == null) throw new ArgumentNullException("str"); - this.str = str; + m_contents = Strings.ToAsciiByteArray(str); + } + + public DerGeneralString(byte[] contents) + : this(contents, true) + { + } + + internal DerGeneralString(byte[] contents, bool clone) + { + if (null == contents) + throw new ArgumentNullException("contents"); + + m_contents = clone ? Arrays.Clone(contents) : contents; } public override string GetString() { - return str; + return Strings.FromAsciiByteArray(m_contents); } public byte[] GetOctets() { - return Strings.ToAsciiByteArray(str); + return Arrays.Clone(m_contents); } - internal override int EncodedLength(bool withID) + internal override IAsn1Encoding GetEncoding(int encoding) { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, str.Length); + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.GeneralString, m_contents); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) { - asn1Out.WriteEncodingDL(withID, Asn1Tags.GeneralString, GetOctets()); + return new PrimitiveEncoding(tagClass, tagNo, m_contents); } - protected override bool Asn1Equals( - Asn1Object asn1Object) + protected override bool Asn1Equals(Asn1Object asn1Object) { - DerGeneralString other = asn1Object as DerGeneralString; + DerGeneralString that = asn1Object as DerGeneralString; + return null != that + && Arrays.AreEqual(this.m_contents, that.m_contents); + } - if (other == null) - return false; + protected override int Asn1GetHashCode() + { + return Arrays.GetHashCode(m_contents); + } - return this.str.Equals(other.str); + internal static DerGeneralString CreatePrimitive(byte[] contents) + { + return new DerGeneralString(contents, false); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerGeneralizedTime.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerGeneralizedTime.cs index d3985e6..659c22f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerGeneralizedTime.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerGeneralizedTime.cs @@ -1,326 +1,36 @@ #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 { - /** - * Generalized time object. - */ public class DerGeneralizedTime - : Asn1Object + : Asn1GeneralizedTime { - private readonly string time; - - /** - * return a generalized time from the passed in object - * - * @exception ArgumentException if the object cannot be converted. - */ - public static DerGeneralizedTime GetInstance( - object obj) - { - if (obj == null || obj is DerGeneralizedTime) - { - return (DerGeneralizedTime)obj; - } - - throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); - } - - /** - * return a Generalized Time object 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 DerGeneralizedTime GetInstance( - Asn1TaggedObject obj, - bool isExplicit) - { - Asn1Object o = obj.GetObject(); - - if (isExplicit || o is DerGeneralizedTime) - { - return GetInstance(o); - } - - return new DerGeneralizedTime(((Asn1OctetString)o).GetOctets()); - } - - /** - * The correct format for this is YYYYMMDDHHMMSS[.f]Z, or without the Z - * for local time, or Z+-HHMM on the end, for difference between local - * time and UTC time. The fractional second amount f must consist of at - * least one number with trailing zeroes removed. - * - * @param time the time string. - * @exception ArgumentException if string is an illegal format. - */ - public DerGeneralizedTime( - string time) - { - this.time = time; - - try - { - ToDateTime(); - } - catch (FormatException e) - { - throw new ArgumentException("invalid date string: " + e.Message); - } - } - - /** - * base constructor from a local time object - */ - public DerGeneralizedTime( - DateTime time) - { -#if PORTABLE || NETFX_CORE - this.time = time.ToUniversalTime().ToString(@"yyyyMMddHHmmss\Z"); -#else - this.time = time.ToString(@"yyyyMMddHHmmss\Z"); -#endif - } - - internal DerGeneralizedTime( - byte[] bytes) - { - // - // explicitly convert to characters - // - this.time = Strings.FromAsciiByteArray(bytes); - } - - /** - * Return the time. - * @return The time string as it appeared in the encoded object. - */ - public string TimeString - { - get { return time; } - } - - /** - * return the time - always in the form of - * YYYYMMDDhhmmssGMT(+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("yyyyMMddHHmmssz");
-         * 
- * To read in the time and Get a date which is compatible with our local - * time zone.

- */ - 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) + public DerGeneralizedTime(string timeString) + : base(timeString) { - /* - * 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 + public DerGeneralizedTime(DateTime dateTime) + : base(dateTime) { - get { return time.IndexOf('.') == 14; } } - private byte[] GetOctets() + internal DerGeneralizedTime(byte[] contents) + : base(contents) { - return Strings.ToAsciiByteArray(time); } - internal override int EncodedLength(bool withID) + internal override IAsn1Encoding GetEncoding(int encoding) { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, time.Length); - } - - internal override void Encode(Asn1OutputStream asn1Out, bool withID) - { - asn1Out.WriteEncodingDL(withID, 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); + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.GeneralizedTime, + GetContents(Asn1OutputStream.EncodingDer)); } - protected override int Asn1GetHashCode() + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) { - return time.GetHashCode(); + return new PrimitiveEncoding(tagClass, tagNo, GetContents(Asn1OutputStream.EncodingDer)); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerGraphicString.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerGraphicString.cs index d36f0a6..5b2e362 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerGraphicString.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerGraphicString.cs @@ -1,6 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -9,7 +10,17 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public class DerGraphicString : DerStringBase { - private readonly byte[] mString; + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(DerGraphicString), Asn1Tags.GraphicString) {} + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return CreatePrimitive(octetString.GetOctets()); + } + } /** * return a Graphic String from the passed in object @@ -20,91 +31,96 @@ public class DerGraphicString */ public static DerGraphicString GetInstance(object obj) { - if (obj == null || obj is DerGraphicString) + if (obj == null) + return null; + + if (obj is DerGraphicString derGraphicString) + return derGraphicString; + + if (obj is IAsn1Convertible asn1Convertible) { - return (DerGraphicString)obj; + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is DerGraphicString converted) + return converted; } - - if (obj is byte[]) + else if (obj is byte[] bytes) { try { - return (DerGraphicString)FromByteArray((byte[])obj); + return (DerGraphicString)Meta.Instance.FromByteArray(bytes); } - catch (Exception e) + catch (IOException e) { - throw new ArgumentException("encoding error in GetInstance: " + e.ToString(), "obj"); + throw new ArgumentException("failed to construct graphic string from byte[]: " + e.Message); } } - throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("illegal object in GetInstance: " + 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. + * @param taggedObject the tagged object holding the object we want + * @param declaredExplicit 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) + public static DerGraphicString GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - Asn1Object o = obj.GetObject(); + return (DerGraphicString)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); + } - if (isExplicit || o is DerGraphicString) - { - return GetInstance(o); - } + private readonly byte[] m_contents; - return new DerGraphicString(((Asn1OctetString)o).GetOctets()); + public DerGraphicString(byte[] contents) + : this(contents, true) + { } - /** - * basic constructor - with bytes. - * @param string the byte encoding of the characters making up the string. - */ - public DerGraphicString(byte[] encoding) + internal DerGraphicString(byte[] contents, bool clone) { - this.mString = Arrays.Clone(encoding); + if (null == contents) + throw new ArgumentNullException("contents"); + + this.m_contents = clone ? Arrays.Clone(contents) : contents; } public override string GetString() { - return Strings.FromByteArray(mString); + return Strings.FromByteArray(m_contents); } public byte[] GetOctets() { - return Arrays.Clone(mString); + return Arrays.Clone(m_contents); } - internal override int EncodedLength(bool withID) + internal override IAsn1Encoding GetEncoding(int encoding) { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, mString.Length); + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.GraphicString, m_contents); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) { - asn1Out.WriteEncodingDL(withID, Asn1Tags.GraphicString, mString); + return new PrimitiveEncoding(tagClass, tagNo, m_contents); } protected override int Asn1GetHashCode() { - return Arrays.GetHashCode(mString); + return Arrays.GetHashCode(m_contents); } - protected override bool Asn1Equals( - Asn1Object asn1Object) + protected override bool Asn1Equals(Asn1Object asn1Object) { - DerGraphicString other = asn1Object as DerGraphicString; - - if (other == null) - return false; + DerGraphicString that = asn1Object as DerGraphicString; + return null != that + && Arrays.AreEqual(this.m_contents, that.m_contents); + } - return Arrays.AreEqual(mString, other.mString); + internal static DerGraphicString CreatePrimitive(byte[] contents) + { + return new DerGraphicString(contents, false); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerIA5String.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerIA5String.cs index 2666456..7949895 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerIA5String.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerIA5String.cs @@ -1,73 +1,79 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Text; +using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 { /** - * Der IA5String object - this is an ascii string. + * IA5String object - this is an Ascii string. */ public class DerIA5String : DerStringBase { - private readonly string str; + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(DerIA5String), Asn1Tags.IA5String) {} + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return CreatePrimitive(octetString.GetOctets()); + } + } /** - * return a IA5 string from the passed in object + * return an IA5 string from the passed in object * * @exception ArgumentException if the object cannot be converted. */ - public static DerIA5String GetInstance( - object obj) + public static DerIA5String GetInstance(object obj) { - if (obj == null || obj is DerIA5String) + if (obj == null) + return null; + + if (obj is DerIA5String derIA5String) + return derIA5String; + + if (obj is IAsn1Convertible asn1Convertible) { - return (DerIA5String)obj; + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is DerIA5String converted) + return converted; + } + else if (obj is byte[] bytes) + { + try + { + return (DerIA5String)Meta.Instance.FromByteArray(bytes); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct IA5 string from byte[]: " + e.Message); + } } - throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("illegal object in GetInstance: " + 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. + * @param taggedObject the tagged object holding the object we want + * @param declaredExplicit 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) + public static DerIA5String GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - Asn1Object o = obj.GetObject(); - - if (isExplicit || o is DerIA5String) - { - return GetInstance(o); - } - - return new DerIA5String(((Asn1OctetString)o).GetOctets()); + return (DerIA5String)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); } - /** - * basic constructor - with bytes. - */ - public DerIA5String( - byte[] str) - : this(Strings.FromAsciiByteArray(str), false) - { - } + private readonly byte[] m_contents; - /** - * basic constructor - without validation. - */ - public DerIA5String( - string str) + public DerIA5String(string str) : this(str, false) { } @@ -80,74 +86,83 @@ public DerIA5String( * @throws ArgumentException if validate is true and the string * contains characters that should not be in an IA5String. */ - public DerIA5String( - string str, - bool validate) + 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; + m_contents = Strings.ToAsciiByteArray(str); } - public override string GetString() + public DerIA5String(byte[] contents) + : this(contents, true) { - return str; } - public byte[] GetOctets() + internal DerIA5String(byte[] contents, bool clone) { - return Strings.ToAsciiByteArray(str); + if (null == contents) + throw new ArgumentNullException("contents"); + + m_contents = clone ? Arrays.Clone(contents) : contents; } - internal override int EncodedLength(bool withID) + public override string GetString() { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, str.Length); + return Strings.FromAsciiByteArray(m_contents); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) + public byte[] GetOctets() { - asn1Out.WriteEncodingDL(withID, Asn1Tags.IA5String, GetOctets()); + return Arrays.Clone(m_contents); } - protected override int Asn1GetHashCode() - { - return this.str.GetHashCode(); + internal override IAsn1Encoding GetEncoding(int encoding) + { + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.IA5String, m_contents); } - protected override bool Asn1Equals( - Asn1Object asn1Object) + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) { - DerIA5String other = asn1Object as DerIA5String; + return new PrimitiveEncoding(tagClass, tagNo, m_contents); + } - if (other == null) - return false; + protected override bool Asn1Equals(Asn1Object asn1Object) + { + DerIA5String that = asn1Object as DerIA5String; + return null != that + && Arrays.AreEqual(this.m_contents, that.m_contents); + } - return this.str.Equals(other.str); + protected override int Asn1GetHashCode() + { + return Arrays.GetHashCode(m_contents); } - /** + /** * 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) + public static bool IsIA5String(string str) { foreach (char ch in str) { if (ch > 0x007f) - { return false; - } } return true; } - } + + internal static DerIA5String CreatePrimitive(byte[] contents) + { + return new DerIA5String(contents, false); + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerInteger.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerInteger.cs index c168193..621bb16 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerInteger.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerInteger.cs @@ -1,6 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -10,12 +11,24 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public class DerInteger : Asn1Object { + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(DerInteger), Asn1Tags.Integer) {} + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return CreatePrimitive(octetString.GetOctets()); + } + } + 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); + string allowUnsafeValue = Org.BouncyCastle.Utilities.Platform.GetEnvironmentVariable(AllowUnsafeProperty); + return allowUnsafeValue != null && Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase("true", allowUnsafeValue); } internal const int SignExtSigned = -1; @@ -29,41 +42,45 @@ internal static bool AllowUnsafe() * * @exception ArgumentException if the object cannot be converted. */ - public static DerInteger GetInstance( - object obj) + public static DerInteger GetInstance(object obj) { - if (obj == null || obj is DerInteger) + if (obj == null) + return null; + + if (obj is DerInteger derInteger) + return derInteger; + + if (obj is IAsn1Convertible asn1Convertible) { - return (DerInteger)obj; + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is DerInteger converted) + return converted; + } + else if (obj is byte[] bytes) + { + try + { + return (DerInteger)Meta.Instance.FromByteArray(bytes); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct integer from byte[]: " + e.Message); + } } - throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("illegal object in GetInstance: " + 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. + * @param taggedObject the tagged object holding the object we want + * @param declaredExplicit 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) + public static DerInteger GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - 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()); + return (DerInteger)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); } public DerInteger(int value) @@ -171,17 +188,17 @@ public long LongValueExact } } - internal override int EncodedLength(bool withID) + internal override IAsn1Encoding GetEncoding(int encoding) { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, bytes.Length); + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.Integer, bytes); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) { - asn1Out.WriteEncodingDL(withID, Asn1Tags.Integer, bytes); + return new PrimitiveEncoding(tagClass, tagNo, bytes); } - protected override int Asn1GetHashCode() + protected override int Asn1GetHashCode() { return Arrays.GetHashCode(bytes); } @@ -200,6 +217,11 @@ public override string ToString() return Value.ToString(); } + internal static DerInteger CreatePrimitive(byte[] contents) + { + return new DerInteger(contents, false); + } + internal static int IntValue(byte[] bytes, int start, int signExt) { int length = bytes.Length; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerNull.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerNull.cs index ccb3192..377ccd9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerNull.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerNull.cs @@ -18,14 +18,14 @@ protected internal DerNull() { } - internal override int EncodedLength(bool withID) + internal override IAsn1Encoding GetEncoding(int encoding) { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, 0); + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.Null, ZeroBytes); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) - { - asn1Out.WriteEncodingDL(withID, Asn1Tags.Null, ZeroBytes); + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + return new PrimitiveEncoding(tagClass, tagNo, ZeroBytes); } protected override bool Asn1Equals(Asn1Object asn1Object) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerNumericString.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerNumericString.cs index bb60263..e9ad1f8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerNumericString.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerNumericString.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Text; +using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -13,66 +13,72 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public class DerNumericString : DerStringBase { - private readonly string str; + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(DerNumericString), Asn1Tags.NumericString) {} + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return CreatePrimitive(octetString.GetOctets()); + } + } /** - * return a Numeric string from the passed in object + * return a numeric string from the passed in object * * @exception ArgumentException if the object cannot be converted. */ - public static DerNumericString GetInstance( - object obj) + public static DerNumericString GetInstance(object obj) { - if (obj == null || obj is DerNumericString) + if (obj == null) + return null; + + if (obj is DerNumericString derNumericString) + return derNumericString; + + if (obj is IAsn1Convertible asn1Convertible) + { + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is DerNumericString converted) + return converted; + } + else if (obj is byte[] bytes) { - return (DerNumericString)obj; + try + { + return (DerNumericString)Meta.Instance.FromByteArray(bytes); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct numeric string from byte[]: " + e.Message); + } } - throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } /** - * return an Numeric string from a tagged object. + * return a 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. + * @param taggedObject the tagged object holding the object we want + * @param declaredExplicit 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) + public static DerNumericString GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - Asn1Object o = obj.GetObject(); - - if (isExplicit || o is DerNumericString) - { - return GetInstance(o); - } - - return new DerNumericString(Asn1OctetString.GetInstance(o).GetOctets()); + return (DerNumericString)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); } - /** - * basic constructor - with bytes. - */ - public DerNumericString( - byte[] str) - : this(Strings.FromAsciiByteArray(str), false) - { - } + private readonly byte[] m_contents; - /** - * basic constructor - without validation.. - */ - public DerNumericString( - string str) - : this(str, false) - { - } + public DerNumericString(string str) + : this(str, false) + { + } - /** + /** * Constructor with optional validation. * * @param string the base string to wrap. @@ -80,57 +86,68 @@ public DerNumericString( * @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"); + 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"); + + m_contents = Strings.ToAsciiByteArray(str); + } - this.str = str; + public DerNumericString(byte[] contents) + : this(contents, true) + { } - public override string GetString() + internal DerNumericString(byte[] contents, bool clone) + { + if (null == contents) + throw new ArgumentNullException("contents"); + + m_contents = clone ? Arrays.Clone(contents) : contents; + } + + public override string GetString() { - return str; + return Strings.FromAsciiByteArray(m_contents); } public byte[] GetOctets() { - return Strings.ToAsciiByteArray(str); + return Arrays.Clone(m_contents); } - internal override int EncodedLength(bool withID) + internal override IAsn1Encoding GetEncoding(int encoding) { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, str.Length); + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.NumericString, m_contents); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) { - asn1Out.WriteEncodingDL(withID, Asn1Tags.NumericString, GetOctets()); + return new PrimitiveEncoding(tagClass, tagNo, m_contents); } - protected override bool Asn1Equals( - Asn1Object asn1Object) + protected override bool Asn1Equals(Asn1Object asn1Object) { - DerNumericString other = asn1Object as DerNumericString; - - if (other == null) - return false; + DerNumericString that = asn1Object as DerNumericString; + return null != that + && Arrays.AreEqual(this.m_contents, that.m_contents); + } - return this.str.Equals(other.str); + protected override int Asn1GetHashCode() + { + return Arrays.GetHashCode(m_contents); } - /** + /** * 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) + public static bool IsNumericString(string str) { foreach (char ch in str) { @@ -140,7 +157,41 @@ public static bool IsNumericString( return true; } - } + + internal static bool IsNumericString(byte[] contents) + { + for (int i = 0; i < contents.Length; ++i) + { + switch (contents[i]) + { + case 0x20: + case 0x30: + case 0x31: + case 0x32: + case 0x33: + case 0x34: + case 0x35: + case 0x36: + case 0x37: + case 0x38: + case 0x39: + break; + default: + return false; + } + } + + return true; + } + + internal static DerNumericString CreatePrimitive(byte[] contents) + { + // TODO Validation - sort out exception types + //if (!IsNumericString(contents)) + + return new DerNumericString(contents, false); + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerObjectIdentifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerObjectIdentifier.cs index 48c37f8..9101799 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerObjectIdentifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerObjectIdentifier.cs @@ -3,7 +3,6 @@ using System; using System.IO; using System.Text; -using System.Text.RegularExpressions; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -13,63 +12,82 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public class DerObjectIdentifier : Asn1Object { + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(DerObjectIdentifier), Asn1Tags.ObjectIdentifier) {} + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return CreatePrimitive(octetString.GetOctets(), false); + } + } + public static DerObjectIdentifier FromContents(byte[] contents) { return CreatePrimitive(contents, true); } - private readonly string identifier; - private byte[] contents; - /** - * return an Oid from the passed in object + * 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 == null) + return null; - if (obj is Asn1Encodable) - { - Asn1Object asn1Obj = ((Asn1Encodable)obj).ToAsn1Object(); + if (obj is DerObjectIdentifier derObjectIdentifier) + return derObjectIdentifier; - if (asn1Obj is DerObjectIdentifier) - return (DerObjectIdentifier)asn1Obj; + if (obj is IAsn1Convertible asn1Convertible) + { + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is DerObjectIdentifier converted) + return converted; + } + else if (obj is byte[] bytes) + { + try + { + return (DerObjectIdentifier)Meta.Instance.FromByteArray(bytes); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct object identifier from byte[]: " + e.Message); + } } - if (obj is byte[]) - return (DerObjectIdentifier)FromByteArray((byte[])obj); - - throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("illegal object in GetInstance: " + 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) + public static DerObjectIdentifier GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - Asn1Object o = obj.GetObject(); - - if (explicitly || o is DerObjectIdentifier) + /* + * TODO[asn1] This block here is for backward compatibility, but should eventually be removed. + * + * - see https://github.com/bcgit/bc-java/issues/1015 + */ + if (!declaredExplicit && !taggedObject.IsParsed()) { - return GetInstance(o); + Asn1Object baseObject = taggedObject.GetObject(); + if (!(baseObject is DerObjectIdentifier)) + return FromContents(Asn1OctetString.GetInstance(baseObject).GetOctets()); } - return FromContents(Asn1OctetString.GetInstance(o).GetOctets()); + return (DerObjectIdentifier)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); } - public DerObjectIdentifier( - string identifier) + private const long LongLimit = (long.MaxValue >> 7) - 0x7F; + + private static readonly DerObjectIdentifier[] cache = new DerObjectIdentifier[1024]; + + private readonly string identifier; + private byte[] contents; + + public DerObjectIdentifier(string identifier) { if (identifier == null) throw new ArgumentNullException("identifier"); @@ -79,18 +97,18 @@ public DerObjectIdentifier( this.identifier = identifier; } - internal DerObjectIdentifier(DerObjectIdentifier oid, string branchID) + private DerObjectIdentifier(DerObjectIdentifier oid, string branchID) { - if (!IsValidBranchID(branchID, 0)) + if (!Asn1RelativeOid.IsValidIdentifier(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 + private DerObjectIdentifier(byte[] contents, bool clone) { - get { return identifier; } + this.identifier = ParseContents(contents); + this.contents = clone ? Arrays.Clone(contents) : contents; } public virtual DerObjectIdentifier Branch(string branchID) @@ -98,6 +116,11 @@ public virtual DerObjectIdentifier Branch(string branchID) return new DerObjectIdentifier(this, branchID); } + public string Id + { + get { return identifier; } + } + /** * 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. @@ -106,51 +129,34 @@ public virtual DerObjectIdentifier Branch(string branchID) 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); + return id.Length > stemId.Length && id[stemId.Length] == '.' && Org.BouncyCastle.Utilities.Platform.StartsWith(id, stemId); } - internal DerObjectIdentifier(byte[] contents, bool clone) + public override string ToString() { - this.identifier = MakeOidStringFromBytes(contents); - this.contents = clone ? Arrays.Clone(contents) : contents; + return identifier; } - private void WriteField( - Stream outputStream, - long fieldValue) + protected override bool Asn1Equals(Asn1Object asn1Object) { - 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); + DerObjectIdentifier that = asn1Object as DerObjectIdentifier; + return null != that + && this.identifier == that.identifier; } - private void WriteField( - Stream outputStream, - BigInteger fieldValue) + protected override int Asn1GetHashCode() { - 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); - } + return identifier.GetHashCode(); + } + + internal override IAsn1Encoding GetEncoding(int encoding) + { + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.ObjectIdentifier, GetContents()); + } + + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + return new PrimitiveEncoding(tagClass, tagNo, GetContents()); } private void DoOutput(MemoryStream bOut) @@ -163,11 +169,11 @@ private void DoOutput(MemoryStream bOut) token = tok.NextToken(); if (token.Length <= 18) { - WriteField(bOut, first + Int64.Parse(token)); + Asn1RelativeOid.WriteField(bOut, first + long.Parse(token)); } else { - WriteField(bOut, new BigInteger(token).Add(BigInteger.ValueOf(first))); + Asn1RelativeOid.WriteField(bOut, new BigInteger(token).Add(BigInteger.ValueOf(first))); } while (tok.HasMoreTokens) @@ -175,11 +181,11 @@ private void DoOutput(MemoryStream bOut) token = tok.NextToken(); if (token.Length <= 18) { - WriteField(bOut, Int64.Parse(token)); + Asn1RelativeOid.WriteField(bOut, long.Parse(token)); } else { - WriteField(bOut, new BigInteger(token)); + Asn1RelativeOid.WriteField(bOut, new BigInteger(token)); } } } @@ -199,67 +205,21 @@ private byte[] GetContents() } } - internal override int EncodedLength(bool withID) - { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, GetContents().Length); - } - - internal override void Encode(Asn1OutputStream asn1Out, bool withID) - { - asn1Out.WriteEncodingDL(withID, Asn1Tags.ObjectIdentifier, GetContents()); - } - - 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) + internal static DerObjectIdentifier CreatePrimitive(byte[] contents, bool clone) { - int digitCount = 0; + int hashCode = Arrays.GetHashCode(contents); + int first = hashCode & 1023; - int pos = branchID.Length; - while (--pos >= start) + lock (cache) { - char ch = branchID[pos]; - - if (ch == '.') - { - if (0 == digitCount || (digitCount > 1 && branchID[pos + 1] == '0')) - return false; - - digitCount = 0; - } - else if ('0' <= ch && ch <= '9') - { - ++digitCount; - } - else + DerObjectIdentifier entry = cache[first]; + if (entry != null && Arrays.AreEqual(contents, entry.GetContents())) { - return false; + return entry; } - } - if (0 == digitCount || (digitCount > 1 && branchID[pos + 1] == '0')) - return false; - - return true; + return cache[first] = new DerObjectIdentifier(contents, clone); + } } private static bool IsValidIdentifier(string identifier) @@ -271,27 +231,24 @@ private static bool IsValidIdentifier(string identifier) if (first < '0' || first > '2') return false; - return IsValidBranchID(identifier, 2); + return Asn1RelativeOid.IsValidIdentifier(identifier, 2); } - private const long LONG_LIMIT = (long.MaxValue >> 7) - 0x7f; - - private static string MakeOidStringFromBytes( - byte[] bytes) + private static string ParseContents(byte[] contents) { - StringBuilder objId = new StringBuilder(); - long value = 0; - BigInteger bigValue = null; - bool first = true; + StringBuilder objId = new StringBuilder(); + long value = 0; + BigInteger bigValue = null; + bool first = true; - for (int i = 0; i != bytes.Length; i++) + for (int i = 0; i != contents.Length; i++) { - int b = bytes[i]; + int b = contents[i]; - if (value <= LONG_LIMIT) + if (value <= LongLimit) { - value += (b & 0x7f); - if ((b & 0x80) == 0) // end of number reached + value += b & 0x7F; + if ((b & 0x80) == 0) { if (first) { @@ -327,7 +284,7 @@ private static string MakeOidStringFromBytes( { bigValue = BigInteger.ValueOf(value); } - bigValue = bigValue.Or(BigInteger.ValueOf(b & 0x7f)); + bigValue = bigValue.Or(BigInteger.ValueOf(b & 0x7F)); if ((b & 0x80) == 0) { if (first) @@ -351,25 +308,6 @@ private static string MakeOidStringFromBytes( return objId.ToString(); } - - private static readonly DerObjectIdentifier[] cache = new DerObjectIdentifier[1024]; - - internal static DerObjectIdentifier CreatePrimitive(byte[] contents, bool clone) - { - int hashCode = Arrays.GetHashCode(contents); - int first = hashCode & 1023; - - lock (cache) - { - DerObjectIdentifier entry = cache[first]; - if (entry != null && Arrays.AreEqual(contents, entry.GetContents())) - { - return entry; - } - - return cache[first] = new DerObjectIdentifier(contents, clone); - } - } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerOctetString.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerOctetString.cs index 11c8396..741b376 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerOctetString.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerOctetString.cs @@ -7,10 +7,9 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public class DerOctetString : Asn1OctetString { - /// The octets making up the octet string. - public DerOctetString( - byte[] str) - : base(str) + /// The octets making up the octet string. + public DerOctetString(byte[] contents) + : base(contents) { } @@ -24,25 +23,39 @@ public DerOctetString(Asn1Encodable obj) { } - internal override int EncodedLength(bool withID) + internal override IAsn1Encoding GetEncoding(int encoding) { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, str.Length); + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.OctetString, contents); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) { - asn1Out.WriteEncodingDL(withID, Asn1Tags.OctetString, str); + return new PrimitiveEncoding(tagClass, tagNo, contents); } - internal static void Encode(Asn1OutputStream asn1Out, bool withID, byte[] buf, int off, int len) + internal static void Encode(Asn1OutputStream asn1Out, byte[] buf, int off, int len) { - asn1Out.WriteEncodingDL(withID, Asn1Tags.OctetString, buf, off, len); - } + asn1Out.WriteIdentifier(Asn1Tags.Universal, Asn1Tags.OctetString); + asn1Out.WriteDL(len); + asn1Out.Write(buf, off, len); + } - internal static int EncodedLength(bool withID, int contentsLength) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal static void Encode(Asn1OutputStream asn1Out, ReadOnlySpan buf) { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, contentsLength); + asn1Out.WriteIdentifier(Asn1Tags.Universal, Asn1Tags.OctetString); + asn1Out.WriteDL(buf.Length); + asn1Out.Write(buf); } + + internal static void Encode(Asn1OutputStream asn1Out, ReadOnlySpan buf1, ReadOnlySpan buf2) + { + asn1Out.WriteIdentifier(Asn1Tags.Universal, Asn1Tags.OctetString); + asn1Out.WriteDL(buf1.Length + buf2.Length); + asn1Out.Write(buf1); + asn1Out.Write(buf2); + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerOutputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerOutputStream.cs index 4ead42a..08a531c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerOutputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerOutputStream.cs @@ -3,57 +3,19 @@ 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) - { - } - - public virtual void WriteObject(Asn1Encodable encodable) - { - Asn1OutputStream.Create(s, Asn1Encodable.Der).WriteObject(encodable); - } - - public virtual void WriteObject(Asn1Object primitive) - { - Asn1OutputStream.Create(s, Asn1Encodable.Der).WriteObject(primitive); - } - } - - internal class DerOutputStreamNew + internal class DerOutputStream : Asn1OutputStream { - internal DerOutputStreamNew(Stream os) + internal DerOutputStream(Stream os) : base(os) { } - internal override bool IsBer + internal override int Encoding { - get { return false; } - } - - internal override void WritePrimitive(Asn1Object primitive, bool withID) - { - Asn1Set asn1Set = primitive as Asn1Set; - if (null != asn1Set) - { - /* - * NOTE: Even a DerSet isn't necessarily already in sorted order (particularly from DerSetParser), - * so all sets have to be converted here. - */ - primitive = new DerSet(asn1Set.elements); - } - - primitive.Encode(this, withID); + get { return EncodingDer; } } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerPrintableString.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerPrintableString.cs index c34f345..0c2ff1e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerPrintableString.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerPrintableString.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Text; +using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -13,61 +13,67 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public class DerPrintableString : DerStringBase { - private readonly string str; + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(DerPrintableString), Asn1Tags.PrintableString) {} + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return CreatePrimitive(octetString.GetOctets()); + } + } /** * return a printable string from the passed in object. * * @exception ArgumentException if the object cannot be converted. */ - public static DerPrintableString GetInstance( - object obj) + public static DerPrintableString GetInstance(object obj) { - if (obj == null || obj is DerPrintableString) + if (obj == null) + return null; + + if (obj is DerPrintableString derPrintableString) + return derPrintableString; + + if (obj is IAsn1Convertible asn1Convertible) + { + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is DerPrintableString converted) + return converted; + } + else if (obj is byte[] bytes) { - return (DerPrintableString)obj; + try + { + return (DerPrintableString)Meta.Instance.FromByteArray(bytes); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct printable string from byte[]: " + e.Message); + } } - throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } /** - * return a Printable string from a tagged object. + * 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. + * @param taggedObject the tagged object holding the object we want + * @param declaredExplicit 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) + public static DerPrintableString GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - Asn1Object o = obj.GetObject(); - - if (isExplicit || o is DerPrintableString) - { - return GetInstance(o); - } - - return new DerPrintableString(Asn1OctetString.GetInstance(o).GetOctets()); + return (DerPrintableString)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); } - /** - * basic constructor - byte encoded string. - */ - public DerPrintableString( - byte[] str) - : this(Strings.FromAsciiByteArray(str), false) - { - } + private readonly byte[] m_contents; - /** - * basic constructor - this does not validate the string - */ - public DerPrintableString( - string str) + public DerPrintableString(string str) : this(str, false) { } @@ -80,57 +86,69 @@ public DerPrintableString( * @throws ArgumentException if validate is true and the string * contains characters that should not be in a PrintableString. */ - public DerPrintableString( - string str, - bool validate) + 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; + m_contents = Strings.ToAsciiByteArray(str); } - public override string GetString() + public DerPrintableString(byte[] contents) + : this(contents, true) + { + } + + internal DerPrintableString(byte[] contents, bool clone) + { + if (null == contents) + throw new ArgumentNullException("contents"); + + m_contents = clone ? Arrays.Clone(contents) : contents; + } + + public override string GetString() { - return str; + return Strings.FromAsciiByteArray(m_contents); } - public byte[] GetOctets() + public byte[] GetOctets() { - return Strings.ToAsciiByteArray(str); + return Arrays.Clone(m_contents); } - internal override int EncodedLength(bool withID) + internal override IAsn1Encoding GetEncoding(int encoding) { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, str.Length); + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.PrintableString, m_contents); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) { - asn1Out.WriteEncodingDL(withID, Asn1Tags.PrintableString, GetOctets()); + return new PrimitiveEncoding(tagClass, tagNo, m_contents); } - protected override bool Asn1Equals( + protected override bool Asn1Equals( Asn1Object asn1Object) { - DerPrintableString other = asn1Object as DerPrintableString; - - if (other == null) - return false; + DerPrintableString that = asn1Object as DerPrintableString; + return null != that + && Arrays.AreEqual(this.m_contents, that.m_contents); + } - return this.str.Equals(other.str); + protected override int Asn1GetHashCode() + { + return Arrays.GetHashCode(m_contents); } - /** + /** * 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) + public static bool IsPrintableString(string str) { foreach (char ch in str) { @@ -165,7 +183,12 @@ public static bool IsPrintableString( return true; } - } + + internal static DerPrintableString CreatePrimitive(byte[] contents) + { + return new DerPrintableString(contents, false); + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerSequence.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerSequence.cs index 919d3cb..e333c08 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerSequence.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerSequence.cs @@ -1,10 +1,6 @@ #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 { @@ -18,10 +14,10 @@ public static DerSequence FromVector(Asn1EncodableVector elementVector) return elementVector.Count < 1 ? Empty : new DerSequence(elementVector); } - /** + /** * create an empty sequence */ - public DerSequence() + public DerSequence() : base() { } @@ -34,7 +30,15 @@ public DerSequence(Asn1Encodable element) { } - public DerSequence(params Asn1Encodable[] elements) + /** + * create a sequence containing two objects + */ + public DerSequence(Asn1Encodable element1, Asn1Encodable element2) + : base(element1, element2) + { + } + + public DerSequence(params Asn1Encodable[] elements) : base(elements) { } @@ -47,44 +51,42 @@ public DerSequence(Asn1EncodableVector elementVector) { } - internal override int EncodedLength(bool withID) + internal DerSequence(Asn1Encodable[] elements, bool clone) + : base(elements, clone) { - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("DerSequence.EncodedLength"); } - /* - * 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(Asn1OutputStream asn1Out, bool withID) + internal override IAsn1Encoding GetEncoding(int encoding) { - if (Count < 1) - { - asn1Out.WriteEncodingDL(withID, Asn1Tags.Constructed | Asn1Tags.Sequence, Asn1OctetString.EmptyOctets); - return; - } + return new ConstructedDLEncoding(Asn1Tags.Universal, Asn1Tags.Sequence, + Asn1OutputStream.GetContentsEncodings(Asn1OutputStream.EncodingDer, elements)); + } - // TODO Intermediate buffer could be avoided if we could calculate expected length - MemoryStream bOut = new MemoryStream(); - Asn1OutputStream dOut = Asn1OutputStream.Create(bOut, Der); - dOut.WriteElements(elements); - dOut.Flush(); + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + return new ConstructedDLEncoding(tagClass, tagNo, + Asn1OutputStream.GetContentsEncodings(Asn1OutputStream.EncodingDer, elements)); + } -#if PORTABLE || NETFX_CORE - byte[] bytes = bOut.ToArray(); - int length = bytes.Length; -#else - byte[] bytes = bOut.GetBuffer(); - int length = (int)bOut.Position; -#endif + internal override DerBitString ToAsn1BitString() + { + return new DerBitString(BerBitString.FlattenBitStrings(GetConstructedBitStrings()), false); + } - asn1Out.WriteEncodingDL(withID, Asn1Tags.Constructed | Asn1Tags.Sequence, bytes, 0, length); + internal override DerExternal ToAsn1External() + { + return new DerExternal(this); + } - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(dOut); + internal override Asn1OctetString ToAsn1OctetString() + { + return new DerOctetString(BerOctetString.FlattenOctetStrings(GetConstructedOctetStrings())); + } + + internal override Asn1Set ToAsn1Set() + { + // NOTE: DLSet is intentional, we don't want sorting + return new DLSet(false, elements); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerSet.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerSet.cs index a7e5684..463e87d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerSet.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerSet.cs @@ -1,9 +1,6 @@ #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 { @@ -20,15 +17,10 @@ public static DerSet FromVector(Asn1EncodableVector elementVector) return elementVector.Count < 1 ? Empty : new DerSet(elementVector); } - internal static DerSet FromVector(Asn1EncodableVector elementVector, bool needsSorting) - { - return elementVector.Count < 1 ? Empty : new DerSet(elementVector, needsSorting); - } - - /** + /** * create an empty set */ - public DerSet() + public DerSet() : base() { } @@ -41,67 +33,59 @@ public DerSet(Asn1Encodable element) { } - public DerSet(params Asn1Encodable[] elements) - : base(elements) + public DerSet(params Asn1Encodable[] elements) + : base(elements, true) + { + } + + internal DerSet(Asn1Encodable[] elements, bool doSort) + : base(elements, doSort) { - Sort(); } /** * @param v - a vector of objects making up the set. */ public DerSet(Asn1EncodableVector elementVector) - : this(elementVector, true) + : base(elementVector, true) { } - internal DerSet(Asn1EncodableVector elementVector, bool needsSorting) - : base(elementVector) + internal DerSet(Asn1EncodableVector elementVector, bool doSort) + : base(elementVector, doSort) { - if (needsSorting) - { - Sort(); - } } - internal override int EncodedLength(bool withID) + internal DerSet(bool isSorted, Asn1Encodable[] elements) + : base(isSorted, elements) { - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("DerSet.EncodedLength"); } - /* - * 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(Asn1OutputStream asn1Out, bool withID) + internal override IAsn1Encoding GetEncoding(int encoding) { - if (Count < 1) - { - asn1Out.WriteEncodingDL(withID, Asn1Tags.Constructed | Asn1Tags.Set, Asn1OctetString.EmptyOctets); - return; - } + return new ConstructedDLEncoding(Asn1Tags.Universal, Asn1Tags.Set, + Asn1OutputStream.GetContentsEncodings(Asn1OutputStream.EncodingDer, GetSortedElements())); + } - // TODO Intermediate buffer could be avoided if we could calculate expected length - MemoryStream bOut = new MemoryStream(); - Asn1OutputStream dOut = Asn1OutputStream.Create(bOut, Der); - dOut.WriteElements(elements); - dOut.Flush(); + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + return new ConstructedDLEncoding(tagClass, tagNo, + Asn1OutputStream.GetContentsEncodings(Asn1OutputStream.EncodingDer, GetSortedElements())); + } -#if PORTABLE || NETFX_CORE - byte[] bytes = bOut.ToArray(); - int length = bytes.Length; -#else - byte[] bytes = bOut.GetBuffer(); - int length = (int)bOut.Position; -#endif + private Asn1Encodable[] GetSortedElements() + { + if (isSorted) + return elements; - asn1Out.WriteEncodingDL(withID, Asn1Tags.Constructed | Asn1Tags.Set, bytes, 0, length); + int count = elements.Length; + Asn1Object[] asn1Objects = new Asn1Object[count]; + for (int i = 0; i < count; ++i) + { + asn1Objects[i] = elements[i].ToAsn1Object(); + } - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(dOut); + return Sort(asn1Objects); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerT61String.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerT61String.cs index e828a99..951b9a8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerT61String.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerT61String.cs @@ -1,6 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -12,99 +13,124 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public class DerT61String : DerStringBase { - private readonly string str; + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(DerT61String), Asn1Tags.T61String) {} + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return CreatePrimitive(octetString.GetOctets()); + } + } /** * return a T61 string from the passed in object. * * @exception ArgumentException if the object cannot be converted. */ - public static DerT61String GetInstance( - object obj) + public static DerT61String GetInstance(object obj) { - if (obj == null || obj is DerT61String) + if (obj == null) + return null; + + if (obj is DerT61String derT61String) + return derT61String; + + if (obj is IAsn1Convertible asn1Convertible) + { + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is DerT61String converted) + return converted; + } + else if (obj is byte[] bytes) { - return (DerT61String)obj; + try + { + return (DerT61String)Meta.Instance.FromByteArray(bytes); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct T61 string from byte[]: " + e.Message); + } } - throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } /** - * return an T61 string from a tagged object. + * return a 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. + * @param taggedObject the tagged object holding the object we want + * @param declaredExplicit 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) + public static DerT61String GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - Asn1Object o = obj.GetObject(); + return (DerT61String)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); + } - if (isExplicit || o is DerT61String) - { - return GetInstance(o); - } + private readonly byte[] m_contents; - return new DerT61String(Asn1OctetString.GetInstance(o).GetOctets()); + public DerT61String(string str) + { + if (str == null) + throw new ArgumentNullException("str"); + + m_contents = Strings.ToByteArray(str); } - /** - * basic constructor - with bytes. - */ - public DerT61String( - byte[] str) - : this(Strings.FromByteArray(str)) - { + public DerT61String(byte[] contents) + : this(contents, true) + { } - /** - * basic constructor - with string. - */ - public DerT61String( - string str) + internal DerT61String(byte[] contents, bool clone) { - if (str == null) - throw new ArgumentNullException("str"); + if (null == contents) + throw new ArgumentNullException("contents"); - this.str = str; + m_contents = clone ? Arrays.Clone(contents) : contents; } - public override string GetString() + public override string GetString() { - return str; + return Strings.FromByteArray(m_contents); } - internal override int EncodedLength(bool withID) + internal override IAsn1Encoding GetEncoding(int encoding) { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, str.Length); + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.T61String, m_contents); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) { - asn1Out.WriteEncodingDL(withID, Asn1Tags.T61String, GetOctets()); + return new PrimitiveEncoding(tagClass, tagNo, m_contents); } public byte[] GetOctets() { - return Strings.ToByteArray(str); + return Arrays.Clone(m_contents); } - protected override bool Asn1Equals( - Asn1Object asn1Object) - { - DerT61String other = asn1Object as DerT61String; + protected override bool Asn1Equals(Asn1Object asn1Object) + { + DerT61String that = asn1Object as DerT61String; + return null != that + && Arrays.AreEqual(this.m_contents, that.m_contents); + } - if (other == null) - return false; + protected override int Asn1GetHashCode() + { + return Arrays.GetHashCode(m_contents); + } - return this.str.Equals(other.str); + internal static DerT61String CreatePrimitive(byte[] contents) + { + return new DerT61String(contents, false); } - } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerTaggedObject.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerTaggedObject.cs index 8a4a296..9cc288f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerTaggedObject.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerTaggedObject.cs @@ -2,8 +2,6 @@ #pragma warning disable using System; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; - namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 { /** @@ -14,76 +12,75 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 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) + public DerTaggedObject(int tagNo, Asn1Encodable obj) + : base(true, tagNo, obj) { } - /** - * @param explicitly true if an explicitly tagged object. + public DerTaggedObject(int tagClass, int tagNo, Asn1Encodable obj) + : base(true, tagClass, tagNo, obj) + { + } + + /** + * @param isExplicit 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) + public DerTaggedObject(bool isExplicit, int tagNo, Asn1Encodable obj) + : base(isExplicit, tagNo, obj) { } - /** - * create an implicitly tagged object that contains a zero - * length sequence. - */ - public DerTaggedObject( - int tagNo) - : base(false, tagNo, DerSequence.Empty) - { - } + public DerTaggedObject(bool isExplicit, int tagClass, int tagNo, Asn1Encodable obj) + : base(isExplicit, tagClass, tagNo, obj) + { + } - internal override int EncodedLength(bool withID) + internal DerTaggedObject(int explicitness, int tagClass, int tagNo, Asn1Encodable obj) + : base(explicitness, tagClass, tagNo, obj) { - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("DerTaggedObject.EncodedLength"); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) - { - if (!IsEmpty()) - { - byte[] bytes = obj.GetDerEncoded(); - - if (explicitly) - { - asn1Out.WriteEncodingDL(withID, Asn1Tags.Constructed | Asn1Tags.ContextSpecific, tagNo, bytes); - } - else - { - // - // need to mark constructed types... (preserve Constructed tag) - // - if (withID) - { - int flags = (bytes[0] & Asn1Tags.Constructed) | Asn1Tags.ContextSpecific; - asn1Out.WriteIdentifier(true, flags, tagNo); - } - - asn1Out.Write(bytes, 1, bytes.Length - 1); - } - } - else - { - asn1Out.WriteEncodingDL(withID, Asn1Tags.Constructed | Asn1Tags.ContextSpecific, tagNo, - Asn1OctetString.EmptyOctets); - } - } - } + internal override string Asn1Encoding + { + get { return Der; } + } + + internal override IAsn1Encoding GetEncoding(int encoding) + { + encoding = Asn1OutputStream.EncodingDer; + + Asn1Object baseObject = GetBaseObject().ToAsn1Object(); + + if (!IsExplicit()) + return baseObject.GetEncodingImplicit(encoding, TagClass, TagNo); + + return new ConstructedDLEncoding(TagClass, TagNo, new IAsn1Encoding[]{ baseObject.GetEncoding(encoding) }); + } + + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + encoding = Asn1OutputStream.EncodingDer; + + Asn1Object baseObject = GetBaseObject().ToAsn1Object(); + + if (!IsExplicit()) + return baseObject.GetEncodingImplicit(encoding, tagClass, tagNo); + + return new ConstructedDLEncoding(tagClass, tagNo, new IAsn1Encoding[]{ baseObject.GetEncoding(encoding) }); + } + + internal override Asn1Sequence RebuildConstructed(Asn1Object asn1Object) + { + return new DerSequence(asn1Object); + } + + internal override Asn1TaggedObject ReplaceTag(int tagClass, int tagNo) + { + return new DerTaggedObject(explicitness, tagClass, tagNo, obj); + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerUTCTime.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerUTCTime.cs index 79d2ad1..6416202 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerUTCTime.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerUTCTime.cs @@ -1,275 +1,44 @@ #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 + : Asn1UtcTime { - 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) + public DerUtcTime(string timeString) + : base(timeString) { - 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) + public DerUtcTime(DateTime dateTime) + : base(dateTime) { - 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 + public DerUtcTime(DateTime dateTime, int twoDigitYearMax) + : base(dateTime, twoDigitYearMax) { - 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); - } - } - } } - - 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() + internal DerUtcTime(byte[] contents) + : base(contents) { - return Strings.ToAsciiByteArray(time); } - internal override int EncodedLength(bool withID) + internal override IAsn1Encoding GetEncoding(int encoding) { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, time.Length); + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.UtcTime, + GetContents(Asn1OutputStream.EncodingDer)); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) { - asn1Out.WriteEncodingDL(withID, 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(); + return new PrimitiveEncoding(tagClass, tagNo, GetContents(Asn1OutputStream.EncodingDer)); } - - public override string ToString() - { - return time; - } - } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerUTF8String.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerUTF8String.cs index 6e9a9f6..55da1bd 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerUTF8String.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerUTF8String.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Text; +using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -13,92 +13,114 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public class DerUtf8String : DerStringBase { - private readonly string str; + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(DerUtf8String), Asn1Tags.Utf8String) {} + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return CreatePrimitive(octetString.GetOctets()); + } + } /** * return an UTF8 string from the passed in object. * * @exception ArgumentException if the object cannot be converted. */ - public static DerUtf8String GetInstance( - object obj) + public static DerUtf8String GetInstance(object obj) { - if (obj == null || obj is DerUtf8String) + if (obj == null) + return null; + + if (obj is DerUtf8String derUtf8String) + return derUtf8String; + + if (obj is IAsn1Convertible asn1Convertible) + { + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is DerUtf8String converted) + return converted; + } + else if (obj is byte[] bytes) { - return (DerUtf8String)obj; + try + { + return (DerUtf8String)Meta.Instance.FromByteArray(bytes); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct UTF8 string from byte[]: " + e.Message); + } } - throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } /** - * return an UTF8 string from a tagged object. + * return a 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. + * @param taggedObject the tagged object holding the object we want + * @param declaredExplicit 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) + public static DerUtf8String GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - Asn1Object o = obj.GetObject(); + return (DerUtf8String)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); + } - if (isExplicit || o is DerUtf8String) - { - return GetInstance(o); - } + private readonly byte[] m_contents; - return new DerUtf8String(Asn1OctetString.GetInstance(o).GetOctets()); + public DerUtf8String(string str) + : this(Strings.ToUtf8ByteArray(str), false) + { } - /** - * basic constructor - byte encoded string. - */ - public DerUtf8String( - byte[] str) - : this(Encoding.UTF8.GetString(str, 0, str.Length)) + public DerUtf8String(byte[] contents) + : this(contents, true) { } - /** - * basic constructor - */ - public DerUtf8String( - string str) + internal DerUtf8String(byte[] contents, bool clone) { - if (str == null) - throw new ArgumentNullException("str"); + if (null == contents) + throw new ArgumentNullException("contents"); - this.str = str; + m_contents = clone ? Arrays.Clone(contents) : contents; } - public override string GetString() + public override string GetString() { - return str; + return Strings.FromUtf8ByteArray(m_contents); } - protected override bool Asn1Equals( - Asn1Object asn1Object) + protected override bool Asn1Equals(Asn1Object asn1Object) { - DerUtf8String other = asn1Object as DerUtf8String; + DerUtf8String that = asn1Object as DerUtf8String; + return null != that + && Arrays.AreEqual(this.m_contents, that.m_contents); + } - if (other == null) - return false; + protected override int Asn1GetHashCode() + { + return Arrays.GetHashCode(m_contents); + } - return this.str.Equals(other.str); + internal override IAsn1Encoding GetEncoding(int encoding) + { + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.Utf8String, m_contents); } - internal override int EncodedLength(bool withID) + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, Encoding.UTF8.GetByteCount(str)); + return new PrimitiveEncoding(tagClass, tagNo, m_contents); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) + internal static DerUtf8String CreatePrimitive(byte[] contents) { - asn1Out.WriteEncodingDL(withID, Asn1Tags.Utf8String, Encoding.UTF8.GetBytes(str)); + return new DerUtf8String(contents, false); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerUniversalString.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerUniversalString.cs index a1a19f9..4952841 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerUniversalString.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerUniversalString.cs @@ -1,6 +1,8 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Diagnostics; +using System.IO; using System.Text; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -8,106 +10,166 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 { /** - * Der UniversalString object. + * 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' }; + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(DerUniversalString), Asn1Tags.UniversalString) {} + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return CreatePrimitive(octetString.GetOctets()); + } + } - private readonly byte[] str; + private static readonly char[] table = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; /** - * return a Universal string from the passed in object. + * return a universal string from the passed in object. * * @exception ArgumentException if the object cannot be converted. */ - public static DerUniversalString GetInstance( - object obj) + public static DerUniversalString GetInstance(object obj) { - if (obj == null || obj is DerUniversalString) + if (obj == null) + return null; + + if (obj is DerUniversalString derUniversalString) + return derUniversalString; + + if (obj is IAsn1Convertible asn1Convertible) { - return (DerUniversalString)obj; + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is DerUniversalString converted) + return converted; + } + else if (obj is byte[] bytes) + { + try + { + return (DerUniversalString)Meta.Instance.FromByteArray(bytes); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct universal string from byte[]: " + e.Message); + } } - throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } /** - * return a Universal string from a tagged object. + * 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. + * @param taggedObject the tagged object holding the object we want + * @param declaredExplicit 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) + public static DerUniversalString GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - Asn1Object o = obj.GetObject(); + return (DerUniversalString)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); + } - if (isExplicit || o is DerUniversalString) - { - return GetInstance(o); - } + private readonly byte[] m_contents; - return new DerUniversalString(Asn1OctetString.GetInstance(o).GetOctets()); + public DerUniversalString(byte[] contents) + : this(contents, true) + { } - /** - * basic constructor - byte encoded string. - */ - public DerUniversalString( - byte[] str) + internal DerUniversalString(byte[] contents, bool clone) { - if (str == null) - throw new ArgumentNullException("str"); + if (null == contents) + throw new ArgumentNullException("contents"); - this.str = str; + m_contents = clone ? Arrays.Clone(contents) : contents; } public override string GetString() { - StringBuilder buffer = new StringBuilder("#"); - byte[] enc = GetDerEncoded(); + int dl = m_contents.Length; + int capacity = 3 + 2 * (Asn1OutputStream.GetLengthOfDL(dl) + dl); + StringBuilder buf = new StringBuilder("#1C", capacity); + EncodeHexDL(buf, dl); - for (int i = 0; i != enc.Length; i++) - { - uint ubyte = enc[i]; - buffer.Append(table[(ubyte >> 4) & 0xf]); - buffer.Append(table[enc[i] & 0xf]); - } + for (int i = 0; i < dl; ++i) + { + EncodeHexByte(buf, m_contents[i]); + } - return buffer.ToString(); + Debug.Assert(buf.Length == capacity); + return buf.ToString(); } - public byte[] GetOctets() + public byte[] GetOctets() { - return (byte[]) str.Clone(); + return Arrays.Clone(m_contents); } - internal override int EncodedLength(bool withID) + internal override IAsn1Encoding GetEncoding(int encoding) { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, this.str.Length); + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.UniversalString, m_contents); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) { - asn1Out.WriteEncodingDL(withID, Asn1Tags.UniversalString, this.str); + return new PrimitiveEncoding(tagClass, tagNo, m_contents); } - protected override bool Asn1Equals( - Asn1Object asn1Object) - { - DerUniversalString other = asn1Object as DerUniversalString; + protected override bool Asn1Equals(Asn1Object asn1Object) + { + DerUniversalString that = asn1Object as DerUniversalString; + return null != that + && Arrays.AreEqual(this.m_contents, that.m_contents); + } - if (other == null) - return false; + protected override int Asn1GetHashCode() + { + return Arrays.GetHashCode(m_contents); + } + + internal static DerUniversalString CreatePrimitive(byte[] contents) + { + return new DerUniversalString(contents, false); + } -// return this.GetString().Equals(other.GetString()); - return Arrays.AreEqual(this.str, other.str); + private static void EncodeHexByte(StringBuilder buf, int i) + { + buf.Append(table[(i >> 4) & 0xF]); + buf.Append(table[i & 0xF]); + } + + private static void EncodeHexDL(StringBuilder buf, int dl) + { + if (dl < 128) + { + EncodeHexByte(buf, dl); + return; + } + + byte[] stack = new byte[5]; + int pos = 5; + + do + { + stack[--pos] = (byte)dl; + dl >>= 8; + } + while (dl != 0); + + int count = stack.Length - pos; + stack[--pos] = (byte)(0x80 | count); + + do + { + EncodeHexByte(buf, stack[pos++]); + } + while (pos < stack.Length); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerVideotexString.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerVideotexString.cs index d55b304..b1e5d9a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerVideotexString.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerVideotexString.cs @@ -1,6 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -9,10 +10,20 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public class DerVideotexString : DerStringBase { - private readonly byte[] mString; + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(DerVideotexString), Asn1Tags.VideotexString) {} + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return CreatePrimitive(octetString.GetOctets()); + } + } /** - * return a Videotex String from the passed in object + * 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. @@ -20,91 +31,96 @@ public class DerVideotexString */ public static DerVideotexString GetInstance(object obj) { - if (obj == null || obj is DerVideotexString) + if (obj == null) + return null; + + if (obj is DerVideotexString derVideotexString) + return derVideotexString; + + if (obj is IAsn1Convertible asn1Convertible) { - return (DerVideotexString)obj; + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is DerVideotexString converted) + return converted; } - - if (obj is byte[]) + else if (obj is byte[] bytes) { try { - return (DerVideotexString)FromByteArray((byte[])obj); + return (DerVideotexString)Meta.Instance.FromByteArray(bytes); } - catch (Exception e) + catch (IOException e) { - throw new ArgumentException("encoding error in GetInstance: " + e.ToString(), "obj"); + throw new ArgumentException("failed to construct videotex string from byte[]: " + e.Message); } } - throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** - * return a Videotex String from a tagged object. + * 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. + * @param taggedObject the tagged object holding the object we want + * @param declaredExplicit 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) + public static DerVideotexString GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - Asn1Object o = obj.GetObject(); + return (DerVideotexString)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); + } - if (isExplicit || o is DerVideotexString) - { - return GetInstance(o); - } + private readonly byte[] m_contents; - return new DerVideotexString(((Asn1OctetString)o).GetOctets()); + public DerVideotexString(byte[] contents) + : this(contents, true) + { } - /** - * basic constructor - with bytes. - * @param string the byte encoding of the characters making up the string. - */ - public DerVideotexString(byte[] encoding) + internal DerVideotexString(byte[] contents, bool clone) { - this.mString = Arrays.Clone(encoding); + if (null == contents) + throw new ArgumentNullException("contents"); + + m_contents = clone ? Arrays.Clone(contents) : contents; } public override string GetString() { - return Strings.FromByteArray(mString); + return Strings.FromByteArray(m_contents); } public byte[] GetOctets() { - return Arrays.Clone(mString); + return Arrays.Clone(m_contents); } - internal override int EncodedLength(bool withID) + internal override IAsn1Encoding GetEncoding(int encoding) { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, mString.Length); + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.VideotexString, m_contents); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) { - asn1Out.WriteEncodingDL(withID, Asn1Tags.VideotexString, mString); + return new PrimitiveEncoding(tagClass, tagNo, m_contents); } - protected override int Asn1GetHashCode() - { - return Arrays.GetHashCode(mString); + protected override bool Asn1Equals(Asn1Object asn1Object) + { + DerVideotexString that = asn1Object as DerVideotexString; + return null != that + && Arrays.AreEqual(this.m_contents, that.m_contents); } - protected override bool Asn1Equals( - Asn1Object asn1Object) + protected override int Asn1GetHashCode() { - DerVideotexString other = asn1Object as DerVideotexString; - - if (other == null) - return false; + return Arrays.GetHashCode(m_contents); + } - return Arrays.AreEqual(mString, other.mString); + internal static DerVideotexString CreatePrimitive(byte[] contents) + { + return new DerVideotexString(contents, false); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerVisibleString.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerVisibleString.cs index 231dba1..ed1a6c0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerVisibleString.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/DerVisibleString.cs @@ -1,117 +1,134 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Text; +using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 { /** - * Der VisibleString object. + * VisibleString object. */ public class DerVisibleString : DerStringBase { - private readonly string str; + internal class Meta : Asn1UniversalType + { + internal static readonly Asn1UniversalType Instance = new Meta(); + + private Meta() : base(typeof(DerVisibleString), Asn1Tags.VisibleString) {} + + internal override Asn1Object FromImplicitPrimitive(DerOctetString octetString) + { + return CreatePrimitive(octetString.GetOctets()); + } + } /** - * return a Visible string from the passed in object. + * return a visible string from the passed in object. * * @exception ArgumentException if the object cannot be converted. */ - public static DerVisibleString GetInstance( - object obj) + public static DerVisibleString GetInstance(object obj) { - if (obj == null || obj is DerVisibleString) - { - return (DerVisibleString)obj; - } + if (obj == null) + return null; + + if (obj is DerVisibleString derVisibleString) + return derVisibleString; - if (obj is Asn1OctetString) + if (obj is IAsn1Convertible asn1Convertible) { - return new DerVisibleString(((Asn1OctetString)obj).GetOctets()); + Asn1Object asn1Object = asn1Convertible.ToAsn1Object(); + if (asn1Object is DerVisibleString converted) + return converted; } - - if (obj is Asn1TaggedObject) + else if (obj is byte[] bytes) { - return GetInstance(((Asn1TaggedObject)obj).GetObject()); + try + { + return (DerVisibleString)Meta.Instance.FromByteArray(bytes); + } + catch (IOException e) + { + throw new ArgumentException("failed to construct visible string from byte[]: " + e.Message); + } } - throw new ArgumentException("illegal object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("illegal object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } /** - * return a Visible string from a tagged object. + * 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. + * @param taggedObject the tagged object holding the object we want + * @param declaredExplicit 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) + public static DerVisibleString GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - return GetInstance(obj.GetObject()); + return (DerVisibleString)Meta.Instance.GetContextInstance(taggedObject, declaredExplicit); } - /** - * basic constructor - byte encoded string. - */ - public DerVisibleString( - byte[] str) - : this(Strings.FromAsciiByteArray(str)) - { - } + private readonly byte[] m_contents; - /** - * basic constructor - */ - public DerVisibleString( - string str) + public DerVisibleString(string str) { if (str == null) throw new ArgumentNullException("str"); - this.str = str; + m_contents = Strings.ToAsciiByteArray(str); } - public override string GetString() + public DerVisibleString(byte[] contents) + : this(contents, true) { - return str; } - public byte[] GetOctets() + internal DerVisibleString(byte[] contents, bool clone) { - return Strings.ToAsciiByteArray(str); + if (null == contents) + throw new ArgumentNullException("contents"); + + m_contents = clone ? Arrays.Clone(contents) : contents; } - internal override int EncodedLength(bool withID) + public override string GetString() { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, str.Length); + return Strings.FromAsciiByteArray(m_contents); } - internal override void Encode(Asn1OutputStream asn1Out, bool withID) + public byte[] GetOctets() { - asn1Out.WriteEncodingDL(withID, Asn1Tags.VisibleString, GetOctets()); + return Arrays.Clone(m_contents); } - protected override bool Asn1Equals( - Asn1Object asn1Object) - { - DerVisibleString other = asn1Object as DerVisibleString; + internal override IAsn1Encoding GetEncoding(int encoding) + { + return new PrimitiveEncoding(Asn1Tags.Universal, Asn1Tags.VisibleString, m_contents); + } - if (other == null) - return false; + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + return new PrimitiveEncoding(tagClass, tagNo, m_contents); + } + + protected override bool Asn1Equals(Asn1Object asn1Object) + { + DerVisibleString that = asn1Object as DerVisibleString; + return null != that + && Arrays.AreEqual(this.m_contents, that.m_contents); + } - return this.str.Equals(other.str); + protected override int Asn1GetHashCode() + { + return Arrays.GetHashCode(m_contents); } - protected override int Asn1GetHashCode() - { - return this.str.GetHashCode(); + internal static DerVisibleString CreatePrimitive(byte[] contents) + { + return new DerVisibleString(contents, false); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/IAsn1Encoding.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/IAsn1Encoding.cs new file mode 100644 index 0000000..55e0466 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/IAsn1Encoding.cs @@ -0,0 +1,15 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + internal interface IAsn1Encoding + { + void Encode(Asn1OutputStream asn1Out); + + int GetLength(); + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/IAsn1Encoding.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/IAsn1Encoding.cs.meta new file mode 100644 index 0000000..164a391 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/IAsn1Encoding.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 949eb025ceb7cc645baca227261703ac +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/IndefiniteLengthInputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/IndefiniteLengthInputStream.cs index 991d6f8..49db125 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/IndefiniteLengthInputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/IndefiniteLengthInputStream.cs @@ -11,61 +11,47 @@ class IndefiniteLengthInputStream private int _lookAhead; private bool _eofOn00 = true; - internal IndefiniteLengthInputStream( - Stream inStream, - int limit) + internal IndefiniteLengthInputStream(Stream inStream, int limit) : base(inStream, limit) { _lookAhead = RequireByte(); - CheckForEof(); - } - internal void SetEofOn00( - bool eofOn00) - { - _eofOn00 = eofOn00; - if (_eofOn00) + if (0 == _lookAhead) { - CheckForEof(); + CheckEndOfContents(); } } - private bool CheckForEof() + internal void SetEofOn00(bool eofOn00) { - if (_lookAhead == 0x00) + _eofOn00 = eofOn00; + if (_eofOn00 && 0 == _lookAhead) { - int extra = RequireByte(); - if (extra != 0) - { - throw new IOException("malformed end-of-contents marker"); - } - - _lookAhead = -1; - SetParentEofDetect(true); - return true; + CheckEndOfContents(); } - return _lookAhead < 0; } - public override int Read( - byte[] buffer, - int offset, - int count) - { - // Only use this optimisation if we aren't checking for 00 - if (_eofOn00 || count <= 1) + private void CheckEndOfContents() + { + if (0 != RequireByte()) + throw new IOException("malformed end-of-contents marker"); + + _lookAhead = -1; + SetParentEofDetect(); + } + + public override int Read(byte[] buffer, int offset, int count) + { + // Only use this optimisation if we aren't checking for 00 + if (_eofOn00 || count <= 1) return base.Read(buffer, offset, count); if (_lookAhead < 0) return 0; int numRead = _in.Read(buffer, offset + 1, count - 1); - if (numRead <= 0) - { - // Corrupted stream throw new EndOfStreamException(); - } buffer[offset] = (byte)_lookAhead; _lookAhead = RequireByte(); @@ -73,10 +59,37 @@ public override int Read( return numRead + 1; } - public override int ReadByte() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int Read(Span buffer) + { + // Only use this optimisation if we aren't checking for 00 + if (_eofOn00 || buffer.Length <= 1) + return base.Read(buffer); + + if (_lookAhead < 0) + return 0; + + int numRead = _in.Read(buffer[1..]); + if (numRead <= 0) + throw new EndOfStreamException(); + + buffer[0] = (byte)_lookAhead; + _lookAhead = RequireByte(); + + return numRead + 1; + } +#endif + + public override int ReadByte() { - if (_eofOn00 && CheckForEof()) - return -1; + if (_eofOn00 && _lookAhead <= 0) + { + if (0 == _lookAhead) + { + CheckEndOfContents(); + } + return -1; + } int result = _lookAhead; _lookAhead = RequireByte(); @@ -87,88 +100,11 @@ private int RequireByte() { int b = _in.ReadByte(); if (b < 0) - { - // Corrupted stream throw new EndOfStreamException(); - } + return b; } } } - -//using System; -//using System.IO; - -//namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 -//{ -// class IndefiniteLengthInputStream -// : LimitedInputStream -// { -// private bool _eofReached = false; -// private bool _eofOn00 = true; - -// internal IndefiniteLengthInputStream( -// Stream inStream, -// int limit) -// : base(inStream, limit) -// { -// } - -// internal void SetEofOn00( -// bool eofOn00) -// { -// _eofOn00 = eofOn00; -// } - -// public override int Read( -// byte[] buffer, -// int offset, -// int count) -// { -// if (_eofReached) -// return 0; - -// if (_eofOn00) -// return base.Read(buffer, offset, count); - -// int numRead = _in.Read(buffer, offset, count); - -// if (numRead <= 0) -// throw new EndOfStreamException(); - -// return numRead; -// } - -// public override int ReadByte() -// { -// if (_eofReached) -// return -1; - -// int b1 = _in.ReadByte(); - -// if (b1 < 0) -// throw new EndOfStreamException(); - -// if (b1 == 0 && _eofOn00) -// { -// int b2 = _in.ReadByte(); - -// if (b2 < 0) -// throw new EndOfStreamException(); - -// if (b2 == 0) -// { -// _eofReached = true; -// SetParentEofDetect(true); -// return -1; -// } - -// throw new InvalidDataException(); -// } - -// return b1; -// } -// } -//} #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyASN1InputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyASN1InputStream.cs index dd088a2..b3e32cc 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyASN1InputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyASN1InputStream.cs @@ -8,14 +8,12 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 public class LazyAsn1InputStream : Asn1InputStream { - public LazyAsn1InputStream( - byte[] input) + public LazyAsn1InputStream(byte[] input) : base(input) { } - public LazyAsn1InputStream( - Stream inputStream) + public LazyAsn1InputStream(Stream inputStream) : base(inputStream) { } @@ -25,16 +23,14 @@ internal LazyAsn1InputStream(Stream input, int limit, byte[][] tmpBuffers) { } - internal override DerSequence CreateDerSequence( - DefiniteLengthInputStream dIn) + internal override Asn1Sequence CreateDLSequence(DefiniteLengthInputStream defIn) { - return new LazyDerSequence(dIn.ToArray()); + return new LazyDLSequence(defIn.ToArray()); } - internal override DerSet CreateDerSet( - DefiniteLengthInputStream dIn) + internal override Asn1Set CreateDLSet(DefiniteLengthInputStream defIn) { - return new LazyDerSet(dIn.ToArray()); + return new LazyDLSet(defIn.ToArray()); } internal override Asn1EncodableVector ReadVector(DefiniteLengthInputStream defIn) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDERSequence.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDERSequence.cs index bf784a7..0454b34 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDERSequence.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDERSequence.cs @@ -1,96 +1,3 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) -#pragma warning disable -using System; -using System.Collections; -namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 -{ - internal class LazyDerSequence - : DerSequence - { - private byte[] encoded; - - internal LazyDerSequence(byte[] encoded) - : base() - { - if (null == encoded) - throw new ArgumentNullException("encoded"); - - this.encoded = encoded; - } - - private void Parse() - { - lock (this) - { - if (null != encoded) - { - Asn1InputStream e = new LazyAsn1InputStream(encoded); - Asn1EncodableVector v = e.ReadVector(); - - this.elements = v.TakeElements(); - this.encoded = null; - } - } - } - - public override Asn1Encodable this[int index] - { - get - { - Parse(); - - return base[index]; - } - } - - public override IEnumerator GetEnumerator() - { - Parse(); - - return base.GetEnumerator(); - } - - public override int Count - { - get - { - Parse(); - - return base.Count; - } - } - - internal override int EncodedLength(bool withID) - { - lock (this) - { - if (encoded == null) - { - return base.EncodedLength(withID); - } - else - { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, encoded.Length); - } - } - } - - internal override void Encode(Asn1OutputStream asn1Out, bool withID) - { - lock (this) - { - if (encoded == null) - { - base.Encode(asn1Out, withID); - } - else - { - asn1Out.WriteEncodingDL(withID, Asn1Tags.Constructed | Asn1Tags.Sequence, encoded); - } - } - } - } -} -#pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDERSequence.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDERSequence.cs.meta index e266c26..db7f567 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDERSequence.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDERSequence.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 05b54ca5e1058684db4f666dfd635913 +guid: cbdd39fdc49876048aef91ae0de8ced9 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDERSet.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDERSet.cs index 596a93c..0454b34 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDERSet.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDERSet.cs @@ -1,96 +1,3 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) -#pragma warning disable -using System; -using System.Collections; -namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 -{ - internal class LazyDerSet - : DerSet - { - private byte[] encoded; - - internal LazyDerSet(byte[] encoded) - : base() - { - if (null == encoded) - throw new ArgumentNullException("encoded"); - - this.encoded = encoded; - } - - private void Parse() - { - lock (this) - { - if (encoded != null) - { - Asn1InputStream e = new LazyAsn1InputStream(encoded); - Asn1EncodableVector v = e.ReadVector(); - - this.elements = v.TakeElements(); - this.encoded = null; - } - } - } - - public override Asn1Encodable this[int index] - { - get - { - Parse(); - - return base[index]; - } - } - - public override IEnumerator GetEnumerator() - { - Parse(); - - return base.GetEnumerator(); - } - - public override int Count - { - get - { - Parse(); - - return base.Count; - } - } - - internal override int EncodedLength(bool withID) - { - lock (this) - { - if (encoded == null) - { - return base.EncodedLength(withID); - } - else - { - return Asn1OutputStream.GetLengthOfEncodingDL(withID, encoded.Length); - } - } - } - - internal override void Encode(Asn1OutputStream asn1Out, bool withID) - { - lock (this) - { - if (encoded == null) - { - base.Encode(asn1Out, withID); - } - else - { - asn1Out.WriteEncodingDL(withID, Asn1Tags.Constructed | Asn1Tags.Set, encoded); - } - } - } - } -} -#pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDERSet.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDERSet.cs.meta index 25ae00b..0c29184 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDERSet.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDERSet.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 76bf92893e66b884594d31a9693939d6 +guid: 8cc1ad753f557e943a6a5397371c9680 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDLEnumerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDLEnumerator.cs new file mode 100644 index 0000000..9408820 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDLEnumerator.cs @@ -0,0 +1,69 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.Collections.Generic; +using System.IO; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + internal class LazyDLEnumerator + : IEnumerator + { + private readonly byte[] m_contents; + + private Asn1InputStream m_input; + private Asn1Object m_current; + + internal LazyDLEnumerator(byte[] contents) + { + this.m_contents = contents; + + Reset(); + } + + object System.Collections.IEnumerator.Current + { + get { return Current; } + } + + public Asn1Encodable Current + { + get + { + if (null == m_current) + throw new InvalidOperationException(); + + return m_current; + } + } + + public virtual void Dispose() + { + } + + public bool MoveNext() + { + return null != (this.m_current = ReadObject()); + } + + public void Reset() + { + this.m_input = new LazyAsn1InputStream(m_contents); + this.m_current = null; + } + + private Asn1Object ReadObject() + { + try + { + return m_input.ReadObject(); + } + catch (IOException e) + { + throw new Asn1ParsingException("malformed ASN.1: " + e.Message, e); + } + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDLEnumerator.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDLEnumerator.cs.meta new file mode 100644 index 0000000..49d5be0 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDLEnumerator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e013eba2cec788241b17adad97d20283 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDLSequence.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDLSequence.cs new file mode 100644 index 0000000..60e20af --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDLSequence.cs @@ -0,0 +1,129 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.Collections.Generic; +using System.IO; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + internal class LazyDLSequence + : DLSequence + { + private byte[] encoded; + + internal LazyDLSequence(byte[] encoded) + : base() + { + if (null == encoded) + throw new ArgumentNullException("encoded"); + + this.encoded = encoded; + } + + public override Asn1Encodable this[int index] + { + get + { + Force(); + + return base[index]; + } + } + + public override IEnumerator GetEnumerator() + { + byte[] encoded = GetContents(); + if (null != encoded) + { + return new LazyDLEnumerator(encoded); + } + + return base.GetEnumerator(); + } + + public override int Count + { + get + { + Force(); + + return base.Count; + } + } + + public override Asn1Encodable[] ToArray() + { + Force(); + + return base.ToArray(); + } + + public override string ToString() + { + Force(); + + return base.ToString(); + } + + internal override IAsn1Encoding GetEncoding(int encoding) + { + if (Asn1OutputStream.EncodingBer == encoding) + { + byte[] encoded = GetContents(); + if (encoded != null) + return new ConstructedLazyDLEncoding(Asn1Tags.Universal, Asn1Tags.Sequence, encoded); + } + else + { + Force(); + } + + return base.GetEncoding(encoding); + } + + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + if (Asn1OutputStream.EncodingBer == encoding) + { + byte[] encoded = GetContents(); + if (encoded != null) + return new ConstructedLazyDLEncoding(tagClass, tagNo, encoded); + } + else + { + Force(); + } + + return base.GetEncodingImplicit(encoding, tagClass, tagNo); + } + + private void Force() + { + lock (this) + { + if (null != encoded) + { + Asn1InputStream input = new LazyAsn1InputStream(encoded); + try + { + Asn1EncodableVector v = input.ReadVector(); + + this.elements = v.TakeElements(); + this.encoded = null; + } + catch (IOException e) + { + throw new Asn1ParsingException("malformed ASN.1: " + e.Message, e); + } + } + } + } + + private byte[] GetContents() + { + lock (this) return encoded; + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDLSequence.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDLSequence.cs.meta new file mode 100644 index 0000000..c46d40c --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDLSequence.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7f4a719db5e2c874eb236ba3f734acca +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDLSet.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDLSet.cs new file mode 100644 index 0000000..fe5de4c --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDLSet.cs @@ -0,0 +1,128 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.Collections.Generic; +using System.IO; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + internal class LazyDLSet + : DLSet + { + private byte[] encoded; + + internal LazyDLSet(byte[] encoded) + : base() + { + if (null == encoded) + throw new ArgumentNullException("encoded"); + + this.encoded = encoded; + } + + public override Asn1Encodable this[int index] + { + get + { + Force(); + + return base[index]; + } + } + + public override IEnumerator GetEnumerator() + { + byte[] encoded = GetContents(); + if (null != encoded) + return new LazyDLEnumerator(encoded); + + return base.GetEnumerator(); + } + + public override int Count + { + get + { + Force(); + + return base.Count; + } + } + + public override Asn1Encodable[] ToArray() + { + Force(); + + return base.ToArray(); + } + + public override string ToString() + { + Force(); + + return base.ToString(); + } + + internal override IAsn1Encoding GetEncoding(int encoding) + { + if (Asn1OutputStream.EncodingBer == encoding) + { + byte[] encoded = GetContents(); + if (null != encoded) + return new ConstructedLazyDLEncoding(Asn1Tags.Universal, Asn1Tags.Set, encoded); + } + else + { + Force(); + } + + return base.GetEncoding(encoding); + } + + internal override IAsn1Encoding GetEncodingImplicit(int encoding, int tagClass, int tagNo) + { + if (Asn1OutputStream.EncodingBer == encoding) + { + byte[] encoded = GetContents(); + if (null != encoded) + return new ConstructedLazyDLEncoding(tagClass, tagNo, encoded); + } + else + { + Force(); + } + + return base.GetEncodingImplicit(encoding, tagClass, tagNo); + } + + private void Force() + { + lock (this) + { + if (null != encoded) + { + Asn1InputStream input = new LazyAsn1InputStream(encoded); + try + { + Asn1EncodableVector v = input.ReadVector(); + + this.elements = v.TakeElements(); + this.isSorted = elements.Length < 2; + this.encoded = null; + } + catch (IOException e) + { + throw new Asn1ParsingException("malformed ASN.1: " + e.Message, e); + } + } + } + } + + private byte[] GetContents() + { + lock (this) return encoded; + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDLSet.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDLSet.cs.meta new file mode 100644 index 0000000..1d4592c --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LazyDLSet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b2a69dabb4519d84a9de7f3158fe1588 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LimitedInputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LimitedInputStream.cs index f97cd24..9e4dd13 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LimitedInputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/LimitedInputStream.cs @@ -23,11 +23,11 @@ internal virtual int Limit get { return _limit; } } - protected virtual void SetParentEofDetect(bool on) + protected void SetParentEofDetect() { if (_in is IndefiniteLengthInputStream) { - ((IndefiniteLengthInputStream)_in).SetEofOn00(on); + ((IndefiniteLengthInputStream)_in).SetEofOn00(true); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/PrimitiveEncoding.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/PrimitiveEncoding.cs new file mode 100644 index 0000000..9bdd08b --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/PrimitiveEncoding.cs @@ -0,0 +1,37 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + internal class PrimitiveEncoding + : IAsn1Encoding + { + private readonly int m_tagClass; + private readonly int m_tagNo; + private readonly byte[] m_contentsOctets; + + internal PrimitiveEncoding(int tagClass, int tagNo, byte[] contentsOctets) + { + m_tagClass = tagClass; + m_tagNo = tagNo; + m_contentsOctets = contentsOctets; + } + + void IAsn1Encoding.Encode(Asn1OutputStream asn1Out) + { + asn1Out.WriteIdentifier(m_tagClass, m_tagNo); + asn1Out.WriteDL(m_contentsOctets.Length); + asn1Out.Write(m_contentsOctets, 0, m_contentsOctets.Length); + } + + int IAsn1Encoding.GetLength() + { + return Asn1OutputStream.GetLengthOfIdentifier(m_tagNo) + + Asn1OutputStream.GetLengthOfDL(m_contentsOctets.Length) + + m_contentsOctets.Length; + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/PrimitiveEncoding.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/PrimitiveEncoding.cs.meta new file mode 100644 index 0000000..11d0603 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/PrimitiveEncoding.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9d78fe1945b88734e92a3fb89251c0d8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/PrimitiveEncodingSuffixed.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/PrimitiveEncodingSuffixed.cs new file mode 100644 index 0000000..c399c53 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/PrimitiveEncodingSuffixed.cs @@ -0,0 +1,40 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1 +{ + internal class PrimitiveEncodingSuffixed + : IAsn1Encoding + { + private readonly int m_tagClass; + private readonly int m_tagNo; + private readonly byte[] m_contentsOctets; + private readonly byte m_contentsSuffix; + + internal PrimitiveEncodingSuffixed(int tagClass, int tagNo, byte[] contentsOctets, byte contentsSuffix) + { + m_tagClass = tagClass; + m_tagNo = tagNo; + m_contentsOctets = contentsOctets; + m_contentsSuffix = contentsSuffix; + } + + void IAsn1Encoding.Encode(Asn1OutputStream asn1Out) + { + asn1Out.WriteIdentifier(m_tagClass, m_tagNo); + asn1Out.WriteDL(m_contentsOctets.Length); + asn1Out.Write(m_contentsOctets, 0, m_contentsOctets.Length - 1); + asn1Out.WriteByte(m_contentsSuffix); + } + + int IAsn1Encoding.GetLength() + { + return Asn1OutputStream.GetLengthOfIdentifier(m_tagNo) + + Asn1OutputStream.GetLengthOfDL(m_contentsOctets.Length) + + m_contentsOctets.Length; + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/PrimitiveEncodingSuffixed.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/PrimitiveEncodingSuffixed.cs.meta new file mode 100644 index 0000000..76c5fab --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/PrimitiveEncodingSuffixed.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ce5b5c34049b0fe4ca5b509fb2b50cd2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/anssi/ANSSINamedCurves.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/anssi/ANSSINamedCurves.cs index b1b6531..a30d65d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/anssi/ANSSINamedCurves.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/anssi/ANSSINamedCurves.cs @@ -1,19 +1,19 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9; 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.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Anssi { - public class AnssiNamedCurves + /// Elliptic curve registry for ANSSI. + public static class AnssiNamedCurves { private static X9ECPoint ConfigureBasepoint(ECCurve curve, string encoding) { @@ -32,9 +32,6 @@ private static BigInteger FromHex(string hex) return new BigInteger(1, Hex.DecodeStrict(hex)); } - /* - * FRP256v1 - */ internal class Frp256v1Holder : X9ECParametersHolder { @@ -42,34 +39,39 @@ private Frp256v1Holder() {} internal static readonly X9ECParametersHolder Instance = new Frp256v1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger p = FromHex("F1FD178C0B3AD58F10126DE8CE42435B3961ADBCABC8CA6DE8FCF353D86E9C03"); BigInteger a = FromHex("F1FD178C0B3AD58F10126DE8CE42435B3961ADBCABC8CA6DE8FCF353D86E9C00"); BigInteger b = FromHex("EE353FCA5428A9300D4ABA754A44C00FDFEC0C9AE4B1A1803075ED967B7BB73F"); - byte[] S = null; BigInteger n = FromHex("F1FD178C0B3AD58F10126DE8CE42435B53DC67E140D2BF941FFDD459C6D655E1"); BigInteger h = BigInteger.One; - ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); + return ConfigureCurve(new FpCurve(p, a, b, n, h, true)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; + X9ECPoint G = ConfigureBasepoint(curve, "04B6B3D4C356C139EB31183D4749D423958C27D2DCAF98B70164C97A2DD98F5CFF6142E0F7C8B204911F9271F0F3ECEF8C2701C307E8E4C9E183115A1554062CFB"); - return new X9ECParameters(curve, G, n, h, S); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } - }; - + } - private static readonly IDictionary objIds = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private static readonly IDictionary curves = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private static readonly IDictionary names = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + private static readonly Dictionary objIds = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly Dictionary curves = + new Dictionary(); + private static readonly Dictionary names = + new Dictionary(); - private static void DefineCurve( - string name, - DerObjectIdentifier oid, - X9ECParametersHolder holder) + private static void DefineCurve(string name, DerObjectIdentifier oid, X9ECParametersHolder holder) { - objIds.Add(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(name), oid); + objIds.Add(name, oid); names.Add(oid, name); curves.Add(oid, holder); } @@ -79,54 +81,64 @@ static AnssiNamedCurves() DefineCurve("FRP256v1", AnssiObjectIdentifiers.FRP256v1, Frp256v1Holder.Instance); } - public static X9ECParameters GetByName( - string name) + /// Look up the for the curve with the given name. + /// The name of the curve. + public static X9ECParameters GetByName(string name) { DerObjectIdentifier oid = GetOid(name); return oid == null ? null : GetByOid(oid); } - /** - * return the X9ECParameters object for the named curve represented by - * the passed in object identifier. Null if the curve isn't present. - * - * @param oid an object identifier representing a named curve, if present. - */ - public static X9ECParameters GetByOid( - DerObjectIdentifier oid) + /// Look up an for the curve with the given name. + /// + /// Allows accessing the curve without necessarily triggering the creation of the + /// full . + /// + /// The name of the curve. + public static X9ECParametersHolder GetByNameLazy(string name) + { + DerObjectIdentifier oid = GetOid(name); + return oid == null ? null : GetByOidLazy(oid); + } + + /// Look up the for the curve with the given + /// OID. + /// The OID for the curve. + public static X9ECParameters GetByOid(DerObjectIdentifier oid) + { + return GetByOidLazy(oid)?.Parameters; + } + + /// Look up an for the curve with the given + /// OID. + /// + /// Allows accessing the curve without necessarily triggering the creation of the + /// full . + /// + /// The OID for the curve. + public static X9ECParametersHolder GetByOidLazy(DerObjectIdentifier oid) { - X9ECParametersHolder holder = (X9ECParametersHolder)curves[oid]; - return holder == null ? null : holder.Parameters; + return CollectionUtilities.GetValueOrNull(curves, oid); } - /** - * return the object identifier signified by the passed in name. Null - * if there is no object identifier associated with name. - * - * @return the object identifier associated with name, if present. - */ - public static DerObjectIdentifier GetOid( - string name) + /// Look up the name of the curve with the given OID. + /// The OID for the curve. + public static string GetName(DerObjectIdentifier oid) { - return (DerObjectIdentifier)objIds[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(name)]; + return CollectionUtilities.GetValueOrNull(names, oid); } - /** - * return the named curve name represented by the given object identifier. - */ - public static string GetName( - DerObjectIdentifier oid) + /// Look up the OID of the curve with the given name. + /// The name of the curve. + public static DerObjectIdentifier GetOid(string name) { - return (string)names[oid]; + return CollectionUtilities.GetValueOrNull(objIds, name); } - /** - * returns an enumeration containing the name strings for curves - * contained in this structure. - */ - public static IEnumerable Names + /// Enumerate the available curve names in this registry. + public static IEnumerable Names { - get { return new EnumerableProxy(names.Values); } + get { return CollectionUtilities.Proxy(objIds.Keys); } } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/bc/BCObjectIdentifiers.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/bc/BCObjectIdentifiers.cs index ff2ccbc..e5950f2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/bc/BCObjectIdentifiers.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/bc/BCObjectIdentifiers.cs @@ -93,6 +93,53 @@ public abstract class BCObjectIdentifiers 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"); + + /** + * SPHINCS+ + */ + public static readonly DerObjectIdentifier sphincsPlus = bc_sig.Branch("5"); + public static readonly DerObjectIdentifier sphincsPlus_shake_256 = sphincsPlus.Branch("1"); + public static readonly DerObjectIdentifier sphincsPlus_sha_256 = sphincsPlus.Branch("2"); + public static readonly DerObjectIdentifier sphincsPlus_sha_512 = sphincsPlus.Branch("3"); + + /** + * Picnic + */ + public static readonly DerObjectIdentifier picnic = bc_sig.Branch("6"); + public static readonly DerObjectIdentifier picnicl1fs = picnic.Branch("1"); + public static readonly DerObjectIdentifier picnicl1ur = picnic.Branch("2"); + public static readonly DerObjectIdentifier picnicl3fs = picnic.Branch("3"); + public static readonly DerObjectIdentifier picnicl3ur = picnic.Branch("4"); + public static readonly DerObjectIdentifier picnicl5fs = picnic.Branch("5"); + public static readonly DerObjectIdentifier picnicl5ur = picnic.Branch("6"); + public static readonly DerObjectIdentifier picnic3l1 = picnic.Branch("7"); + public static readonly DerObjectIdentifier picnic3l3 = picnic.Branch("8"); + public static readonly DerObjectIdentifier picnic3l5 = picnic.Branch("9"); + public static readonly DerObjectIdentifier picnicl1full = picnic.Branch("10"); + public static readonly DerObjectIdentifier picnicl3full = picnic.Branch("11"); + public static readonly DerObjectIdentifier picnicl5full = picnic.Branch("12"); + + /* + * Falcon + */ + public static readonly DerObjectIdentifier falcon = bc_sig.Branch("7"); + + public static readonly DerObjectIdentifier falcon_512 = new DerObjectIdentifier("1.3.9999.3.1"); // falcon.branch("1"); + public static readonly DerObjectIdentifier falcon_1024 = new DerObjectIdentifier("1.3.9999.3.4"); // falcon.branch("2"); + + /* + * Dilithium + */ + public static readonly DerObjectIdentifier dilithium = bc_sig.Branch("8"); + + // OpenSSL OIDs + public static readonly DerObjectIdentifier dilithium2 = new DerObjectIdentifier("1.3.6.1.4.1.2.267.7.4.4"); // dilithium.branch("1"); + public static readonly DerObjectIdentifier dilithium3 = new DerObjectIdentifier("1.3.6.1.4.1.2.267.7.6.5"); // dilithium.branch("2"); + public static readonly DerObjectIdentifier dilithium5 = new DerObjectIdentifier("1.3.6.1.4.1.2.267.7.8.7"); // dilithium.branch("3"); + public static readonly DerObjectIdentifier dilithium2_aes = new DerObjectIdentifier("1.3.6.1.4.1.2.267.11.4.4"); // dilithium.branch("4"); + public static readonly DerObjectIdentifier dilithium3_aes = new DerObjectIdentifier("1.3.6.1.4.1.2.267.11.6.5"); // dilithium.branch("5"); + public static readonly DerObjectIdentifier dilithium5_aes = new DerObjectIdentifier("1.3.6.1.4.1.2.267.11.8.7"); // dilithium.branch("6"); + /** * key_exchange(3) algorithms @@ -106,13 +153,100 @@ public abstract class BCObjectIdentifiers /** * X.509 extension(4) values - *

+ *

* 1.3.6.1.4.1.22554.4 */ public static readonly DerObjectIdentifier bc_ext = bc.Branch("4"); public static readonly DerObjectIdentifier linkedCertificate = bc_ext.Branch("1"); - } + + /** + * KEM(4) algorithms + */ + public static readonly DerObjectIdentifier bc_kem = bc.Branch("5"); + + /** + * Classic McEliece + */ + public static readonly DerObjectIdentifier pqc_kem_mceliece = bc_kem.Branch("1"); + + public static readonly DerObjectIdentifier mceliece348864_r3 = pqc_kem_mceliece.Branch("1"); + public static readonly DerObjectIdentifier mceliece348864f_r3 = pqc_kem_mceliece.Branch("2"); + public static readonly DerObjectIdentifier mceliece460896_r3 = pqc_kem_mceliece.Branch("3"); + public static readonly DerObjectIdentifier mceliece460896f_r3 = pqc_kem_mceliece.Branch("4"); + public static readonly DerObjectIdentifier mceliece6688128_r3 = pqc_kem_mceliece.Branch("5"); + public static readonly DerObjectIdentifier mceliece6688128f_r3 = pqc_kem_mceliece.Branch("6"); + public static readonly DerObjectIdentifier mceliece6960119_r3 = pqc_kem_mceliece.Branch("7"); + public static readonly DerObjectIdentifier mceliece6960119f_r3 = pqc_kem_mceliece.Branch("8"); + public static readonly DerObjectIdentifier mceliece8192128_r3 = pqc_kem_mceliece.Branch("9"); + public static readonly DerObjectIdentifier mceliece8192128f_r3 = pqc_kem_mceliece.Branch("10"); + + /** + * SABER + */ + public static readonly DerObjectIdentifier pqc_kem_saber = bc_kem.Branch("3"); + public static readonly DerObjectIdentifier lightsaberkem128r3 = pqc_kem_saber.Branch("1"); + public static readonly DerObjectIdentifier saberkem128r3 = pqc_kem_saber.Branch("2"); + public static readonly DerObjectIdentifier firesaberkem128r3 = pqc_kem_saber.Branch("3"); + public static readonly DerObjectIdentifier lightsaberkem192r3 = pqc_kem_saber.Branch("4"); + public static readonly DerObjectIdentifier saberkem192r3 = pqc_kem_saber.Branch("5"); + public static readonly DerObjectIdentifier firesaberkem192r3 = pqc_kem_saber.Branch("6"); + public static readonly DerObjectIdentifier lightsaberkem256r3 = pqc_kem_saber.Branch("7"); + public static readonly DerObjectIdentifier saberkem256r3 = pqc_kem_saber.Branch("8"); + public static readonly DerObjectIdentifier firesaberkem256r3 = pqc_kem_saber.Branch("9"); + public static readonly DerObjectIdentifier ulightsaberkemr3 = pqc_kem_saber.Branch("10"); + public static readonly DerObjectIdentifier usaberkemr3 = pqc_kem_saber.Branch("11"); + public static readonly DerObjectIdentifier ufiresaberkemr3 = pqc_kem_saber.Branch("12"); + public static readonly DerObjectIdentifier lightsaberkem90sr3 = pqc_kem_saber.Branch("13"); + public static readonly DerObjectIdentifier saberkem90sr3 = pqc_kem_saber.Branch("14"); + public static readonly DerObjectIdentifier firesaberkem90sr3 = pqc_kem_saber.Branch("15"); + public static readonly DerObjectIdentifier ulightsaberkem90sr3 = pqc_kem_saber.Branch("16"); + public static readonly DerObjectIdentifier usaberkem90sr3 = pqc_kem_saber.Branch("17"); + public static readonly DerObjectIdentifier ufiresaberkem90sr3 = pqc_kem_saber.Branch("18"); + + /** + * SIKE + */ + public static readonly DerObjectIdentifier pqc_kem_sike = bc_kem.Branch("4"); + public static readonly DerObjectIdentifier sikep434 = pqc_kem_sike.Branch("1"); + public static readonly DerObjectIdentifier sikep503 = pqc_kem_sike.Branch("2"); + public static readonly DerObjectIdentifier sikep610 = pqc_kem_sike.Branch("3"); + public static readonly DerObjectIdentifier sikep751 = pqc_kem_sike.Branch("4"); + public static readonly DerObjectIdentifier sikep434_compressed = pqc_kem_sike.Branch("5"); + public static readonly DerObjectIdentifier sikep503_compressed = pqc_kem_sike.Branch("6"); + public static readonly DerObjectIdentifier sikep610_compressed = pqc_kem_sike.Branch("7"); + public static readonly DerObjectIdentifier sikep751_compressed = pqc_kem_sike.Branch("8"); + + /** + * Kyber + */ + public static readonly DerObjectIdentifier pqc_kem_kyber = bc_kem.Branch("6"); + + public static readonly DerObjectIdentifier kyber512 = new DerObjectIdentifier("1.3.6.1.4.1.2.267.8.2.2"); // pqc_kem_kyber.Branch("1"); + public static readonly DerObjectIdentifier kyber768 = new DerObjectIdentifier("1.3.6.1.4.1.2.267.8.3.3"); // pqc_kem_kyber.Branch("2"); + public static readonly DerObjectIdentifier kyber1024 = new DerObjectIdentifier("1.3.6.1.4.1.2.267.8.4.4"); // pqc_kem_kyber.Branch("3"); + public static readonly DerObjectIdentifier kyber512_aes = new DerObjectIdentifier("1.3.6.1.4.1.2.267.10.2.2"); // pqc_kem_kyber.Branch("4"); + public static readonly DerObjectIdentifier kyber768_aes = new DerObjectIdentifier("1.3.6.1.4.1.2.267.10.3.3"); // pqc_kem_kyber.Branch("5"); + public static readonly DerObjectIdentifier kyber1024_aes = new DerObjectIdentifier("1.3.6.1.4.1.2.267.10.4.4"); // pqc_kem_kyber.Branch("6"); + + /** + * BIKE + */ + public static readonly DerObjectIdentifier pqc_kem_bike = bc_kem.Branch("8"); + + public static readonly DerObjectIdentifier bike128 = pqc_kem_bike.Branch("1"); + public static readonly DerObjectIdentifier bike192 = pqc_kem_bike.Branch("2"); + public static readonly DerObjectIdentifier bike256 = pqc_kem_bike.Branch("3"); + + /** + * HQC + */ + public static readonly DerObjectIdentifier pqc_kem_hqc = bc_kem.Branch("9"); + + public static readonly DerObjectIdentifier hqc128 = pqc_kem_hqc.Branch("1"); + public static readonly DerObjectIdentifier hqc192 = pqc_kem_hqc.Branch("2"); + public static readonly DerObjectIdentifier hqc256 = pqc_kem_hqc.Branch("3"); + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CAKeyUpdAnnContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CAKeyUpdAnnContent.cs index 84ee8c3..b690548 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CAKeyUpdAnnContent.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CAKeyUpdAnnContent.cs @@ -9,42 +9,33 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp public class CAKeyUpdAnnContent : Asn1Encodable { - private readonly CmpCertificate oldWithNew; - private readonly CmpCertificate newWithOld; - private readonly CmpCertificate newWithNew; + public static CAKeyUpdAnnContent GetInstance(object obj) + { + if (obj is CAKeyUpdAnnContent content) + return content; - private CAKeyUpdAnnContent(Asn1Sequence seq) - { - oldWithNew = CmpCertificate.GetInstance(seq[0]); - newWithOld = CmpCertificate.GetInstance(seq[1]); - newWithNew = CmpCertificate.GetInstance(seq[2]); - } + if (obj is Asn1Sequence seq) + return new CAKeyUpdAnnContent(seq); - public static CAKeyUpdAnnContent GetInstance(object obj) - { - if (obj is CAKeyUpdAnnContent) - return (CAKeyUpdAnnContent)obj; + throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), nameof(obj)); + } - if (obj is Asn1Sequence) - return new CAKeyUpdAnnContent((Asn1Sequence)obj); + private readonly CmpCertificate m_oldWithNew; + private readonly CmpCertificate m_newWithOld; + private readonly CmpCertificate m_newWithNew; - 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 + private CAKeyUpdAnnContent(Asn1Sequence seq) { - get { return newWithOld; } + m_oldWithNew = CmpCertificate.GetInstance(seq[0]); + m_newWithOld = CmpCertificate.GetInstance(seq[1]); + m_newWithNew = CmpCertificate.GetInstance(seq[2]); } - public virtual CmpCertificate NewWithNew - { - get { return newWithNew; } - } + public virtual CmpCertificate OldWithNew => m_oldWithNew; + + public virtual CmpCertificate NewWithOld => m_newWithOld; + + public virtual CmpCertificate NewWithNew => m_newWithNew; /** *

@@ -58,7 +49,7 @@ public virtual CmpCertificate NewWithNew
 		 */
 		public override Asn1Object ToAsn1Object()
 		{
-			return new DerSequence(oldWithNew, newWithOld, newWithNew);
+			return new DerSequence(m_oldWithNew, m_newWithOld, m_newWithNew);
 		}
 	}
 }
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertAnnContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertAnnContent.cs
new file mode 100644
index 0000000..f3f2106
--- /dev/null
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertAnnContent.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.X509;
+using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
+
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp
+{
+    /**
+     *  CertAnnContent ::= CMPCertificate
+     */
+    public class CertAnnContent
+        : CmpCertificate
+    {
+        public static new CertAnnContent GetInstance(object obj)
+        {
+            // TODO[cmp]
+            if (obj == null)
+                return null;
+
+            if (obj is CertAnnContent content)
+                return content;
+
+            if (obj is CmpCertificate cmpCertificate)
+                return GetInstance(cmpCertificate.GetEncoded());
+
+            if (obj is byte[] bs)
+            {
+                try
+                {
+                    obj = Asn1Object.FromByteArray(bs);
+                }
+                catch (IOException)
+                {
+                    throw new ArgumentException("Invalid encoding in CertAnnContent");
+                }
+            }
+
+            if (obj is Asn1Sequence)
+                return new CertAnnContent(X509CertificateStructure.GetInstance(obj));
+
+            // TODO[cmp]
+            if (obj is Asn1TaggedObject taggedObject)
+                return new CertAnnContent(taggedObject.TagNo, taggedObject.GetObject());
+
+            throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), nameof(obj));
+        }
+
+        public static new CertAnnContent GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit)
+        {
+            // TODO[cmp]
+            if (taggedObject == null)
+                return null;
+
+            if (!declaredExplicit)
+                throw new ArgumentException("tag must be explicit");
+
+            // TODO[cmp]
+            return GetInstance(taggedObject.GetObject());
+        }
+
+        public CertAnnContent(int type, Asn1Object otherCert)
+            : base(type, otherCert)
+        {
+        }
+
+        public CertAnnContent(X509CertificateStructure x509v3PKCert)
+            : base(x509v3PKCert)
+        {
+        }
+    }
+}
+#pragma warning restore
+#endif
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertAnnContent.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertAnnContent.cs.meta
new file mode 100644
index 0000000..0755ed3
--- /dev/null
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertAnnContent.cs.meta	
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: ac1d7e1613f79474e99c1cb95dbda39d
+MonoImporter:
+  externalObjects: {}
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertConfirmContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertConfirmContent.cs
index 77d8852..018537b 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertConfirmContent.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertConfirmContent.cs	
@@ -9,32 +9,27 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp
 	public class CertConfirmContent
 		: Asn1Encodable
 	{
-		private readonly Asn1Sequence content;
-
-		private CertConfirmContent(Asn1Sequence seq)
-		{
-			content = seq;
-		}
-
 		public static CertConfirmContent GetInstance(object obj)
 		{
-			if (obj is CertConfirmContent)
-				return (CertConfirmContent)obj;
+			if (obj is CertConfirmContent content)
+				return content;
 
-			if (obj is Asn1Sequence)
-				return new CertConfirmContent((Asn1Sequence)obj);
+			if (obj is Asn1Sequence seq)
+				return new CertConfirmContent(seq);
 
-            throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+            throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), nameof(obj));
 		}
 
-		public virtual CertStatus[] ToCertStatusArray()
+        private readonly Asn1Sequence m_content;
+
+        private CertConfirmContent(Asn1Sequence seq)
+        {
+            m_content = seq;
+        }
+
+        public virtual CertStatus[] ToCertStatusArray()
 		{
-			CertStatus[] result = new CertStatus[content.Count];
-			for (int i = 0; i != result.Length; i++)
-			{
-				result[i] = CertStatus.GetInstance(content[i]);
-			}
-			return result;
+			return m_content.MapElements(CertStatus.GetInstance);
 		}
 
 		/**
@@ -45,7 +40,7 @@ public virtual CertStatus[] ToCertStatusArray()
 		 */
 		public override Asn1Object ToAsn1Object()
 		{
-			return content;
+			return m_content;
 		}
 	}
 }
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertOrEncCert.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertOrEncCert.cs
index 05bc6a3..837feec 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertOrEncCert.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertOrEncCert.cs	
@@ -10,79 +10,79 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp
 	public class CertOrEncCert
 		: Asn1Encodable, IAsn1Choice
 	{
-		private readonly CmpCertificate certificate;
-		private readonly EncryptedValue encryptedCert;
+        public static CertOrEncCert GetInstance(object obj)
+        {
+            if (obj is CertOrEncCert certOrEncCert)
+                return certOrEncCert;
 
-		private CertOrEncCert(Asn1TaggedObject tagged)
+            if (obj is Asn1TaggedObject taggedObject)
+                return new CertOrEncCert(taggedObject);
+
+            throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), nameof(obj));
+        }
+
+        private readonly CmpCertificate m_certificate;
+		private readonly EncryptedKey m_encryptedCert;
+
+		private CertOrEncCert(Asn1TaggedObject taggedObject)
 		{
-			if (tagged.TagNo == 0)
+			if (taggedObject.TagNo == 0)
 			{
-				certificate = CmpCertificate.GetInstance(tagged.GetObject());
+				m_certificate = CmpCertificate.GetInstance(taggedObject.GetObject());
 			}
-			else if (tagged.TagNo == 1)
+			else if (taggedObject.TagNo == 1)
 			{
-				encryptedCert = EncryptedValue.GetInstance(tagged.GetObject());
+                m_encryptedCert = EncryptedKey.GetInstance(taggedObject.GetObject());
 			}
 			else
 			{
-				throw new ArgumentException("unknown tag: " + tagged.TagNo, "tagged");
-			}
-		}
-		
-		public static CertOrEncCert GetInstance(object obj)
-		{
-			if (obj is CertOrEncCert)
-				return (CertOrEncCert)obj;
-
-			if (obj is Asn1TaggedObject)
-				return new CertOrEncCert((Asn1TaggedObject)obj);
-
-			throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
-		}
+				throw new ArgumentException("unknown tag: " + taggedObject.TagNo, nameof(taggedObject));
+            }
+        }
 
 		public CertOrEncCert(CmpCertificate certificate)
 		{
 			if (certificate == null)
-				throw new ArgumentNullException("certificate");
+				throw new ArgumentNullException(nameof(certificate));
 
-			this.certificate = certificate;
+			m_certificate = certificate;
 		}
 
-		public CertOrEncCert(EncryptedValue encryptedCert)
+		public CertOrEncCert(EncryptedValue encryptedValue)
 		{
-			if (encryptedCert == null)
-				throw new ArgumentNullException("encryptedCert");
+			if (encryptedValue == null)
+				throw new ArgumentNullException(nameof(encryptedValue));
 
-			this.encryptedCert = encryptedCert;
+			m_encryptedCert = new EncryptedKey(encryptedValue);
 		}
 
-		public virtual CmpCertificate Certificate
-		{
-			get { return certificate; }
-		}
+        public CertOrEncCert(EncryptedKey encryptedKey)
+        {
+            if (encryptedKey == null)
+                throw new ArgumentNullException(nameof(encryptedKey));
 
-		public virtual EncryptedValue EncryptedCert
-		{
-			get { return encryptedCert; }
-		}
+            m_encryptedCert = encryptedKey;
+        }
 
-		/**
+		public virtual CmpCertificate Certificate => m_certificate;
+
+		public virtual EncryptedKey EncryptedCert => m_encryptedCert;
+
+        /**
 		 * 
 		 * CertOrEncCert ::= CHOICE {
 		 *                      certificate     [0] CMPCertificate,
-		 *                      encryptedCert   [1] EncryptedValue
+		 *                      encryptedCert   [1] EncryptedKey
 		 *           }
 		 * 
* @return a basic ASN.1 object representation. */ - public override Asn1Object ToAsn1Object() + public override Asn1Object ToAsn1Object() { - if (certificate != null) - { - return new DerTaggedObject(true, 0, certificate); - } + if (m_certificate != null) + return new DerTaggedObject(true, 0, m_certificate); - return new DerTaggedObject(true, 1, encryptedCert); + return new DerTaggedObject(true, 1, m_encryptedCert); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertRepMessage.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertRepMessage.cs index b82337a..cbf551f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertRepMessage.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertRepMessage.cs @@ -9,8 +9,19 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp public class CertRepMessage : Asn1Encodable { - private readonly Asn1Sequence caPubs; - private readonly Asn1Sequence response; + public static CertRepMessage GetInstance(object obj) + { + if (obj is CertRepMessage certRepMessage) + return certRepMessage; + + if (obj != null) + return new CertRepMessage(Asn1Sequence.GetInstance(obj)); + + return null; + } + + private readonly Asn1Sequence m_caPubs; + private readonly Asn1Sequence m_response; private CertRepMessage(Asn1Sequence seq) { @@ -18,57 +29,33 @@ private CertRepMessage(Asn1Sequence seq) if (seq.Count > 1) { - caPubs = Asn1Sequence.GetInstance((Asn1TaggedObject)seq[index++], true); + m_caPubs = Asn1Sequence.GetInstance((Asn1TaggedObject)seq[index++], true); } - response = Asn1Sequence.GetInstance(seq[index]); - } - - public static CertRepMessage GetInstance(object obj) - { - if (obj is CertRepMessage) - return (CertRepMessage)obj; - - if (obj is Asn1Sequence) - return new CertRepMessage((Asn1Sequence)obj); - - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + m_response = Asn1Sequence.GetInstance(seq[index]); } public CertRepMessage(CmpCertificate[] caPubs, CertResponse[] response) { if (response == null) - throw new ArgumentNullException("response"); + throw new ArgumentNullException(nameof(response)); if (caPubs != null) { - this.caPubs = new DerSequence(caPubs); + m_caPubs = new DerSequence(caPubs); } - this.response = new DerSequence(response); + m_response = new DerSequence(response); } public virtual CmpCertificate[] GetCAPubs() { - if (caPubs == null) - return null; - - CmpCertificate[] results = new CmpCertificate[caPubs.Count]; - for (int i = 0; i != results.Length; ++i) - { - results[i] = CmpCertificate.GetInstance(caPubs[i]); - } - return results; + return m_caPubs == null ? null : m_caPubs.MapElements(CmpCertificate.GetInstance); } public virtual CertResponse[] GetResponse() { - CertResponse[] results = new CertResponse[response.Count]; - for (int i = 0; i != results.Length; ++i) - { - results[i] = CertResponse.GetInstance(response[i]); - } - return results; + return m_response.MapElements(CertResponse.GetInstance); } /** @@ -83,9 +70,9 @@ public virtual CertResponse[] GetResponse() */ public override Asn1Object ToAsn1Object() { - Asn1EncodableVector v = new Asn1EncodableVector(); - v.AddOptionalTagged(true, 1, caPubs); - v.Add(response); + Asn1EncodableVector v = new Asn1EncodableVector(2); + v.AddOptionalTagged(true, 1, m_caPubs); + v.Add(m_response); return new DerSequence(v); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertReqTemplateContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertReqTemplateContent.cs new file mode 100644 index 0000000..497050d --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertReqTemplateContent.cs @@ -0,0 +1,71 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Crmf; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp +{ + /** + * GenMsg: {id-it 19}, < absent > + * GenRep: {id-it 19}, CertReqTemplateContent | < absent > + *

+ * CertReqTemplateValue ::= CertReqTemplateContent + *

+ * CertReqTemplateContent ::= SEQUENCE { + * certTemplate CertTemplate, + * keySpec Controls OPTIONAL } + *

+ * Controls ::= SEQUENCE SIZE (1..MAX) OF AttributeTypeAndValue + *

+ */ + public class CertReqTemplateContent + : Asn1Encodable + { + public static CertReqTemplateContent GetInstance(object obj) + { + if (obj is CertReqTemplateContent certReqTemplateContent) + return certReqTemplateContent; + + if (obj != null) + return new CertReqTemplateContent(Asn1Sequence.GetInstance(obj)); + + return null; + } + + private readonly CertTemplate m_certTemplate; + private readonly Asn1Sequence m_keySpec; + + private CertReqTemplateContent(Asn1Sequence seq) + { + if (seq.Count != 1 && seq.Count != 2) + throw new ArgumentException("expected sequence size of 1 or 2"); + + m_certTemplate = CertTemplate.GetInstance(seq[0]); + + if (seq.Count > 1) + { + m_keySpec = Asn1Sequence.GetInstance(seq[1]); + } + } + + public CertReqTemplateContent(CertTemplate certTemplate, Asn1Sequence keySpec) + { + m_certTemplate = certTemplate; + m_keySpec = keySpec; + } + + public virtual CertTemplate CertTemplate => m_certTemplate; + + public virtual Asn1Sequence KeySpec => m_keySpec; + + public override Asn1Object ToAsn1Object() + { + Asn1EncodableVector v = new Asn1EncodableVector(m_certTemplate); + v.AddOptional(m_keySpec); + return new DerSequence(v); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertReqTemplateContent.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertReqTemplateContent.cs.meta new file mode 100644 index 0000000..281d5e2 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertReqTemplateContent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: be9a5338c205ad742b1ecd78f88ba2b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertResponse.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertResponse.cs index 0e7d4cd..ed392de 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertResponse.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertResponse.cs @@ -2,22 +2,31 @@ #pragma warning disable using System; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; - namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp { public class CertResponse : Asn1Encodable { - private readonly DerInteger certReqId; - private readonly PkiStatusInfo status; - private readonly CertifiedKeyPair certifiedKeyPair; - private readonly Asn1OctetString rspInfo; + public static CertResponse GetInstance(object obj) + { + if (obj is CertResponse certResponse) + return certResponse; + + if (obj != null) + return new CertResponse(Asn1Sequence.GetInstance(obj)); + + return null; + } + + private readonly DerInteger m_certReqId; + private readonly PkiStatusInfo m_status; + private readonly CertifiedKeyPair m_certifiedKeyPair; + private readonly Asn1OctetString m_rspInfo; private CertResponse(Asn1Sequence seq) { - certReqId = DerInteger.GetInstance(seq[0]); - status = PkiStatusInfo.GetInstance(seq[1]); + m_certReqId = DerInteger.GetInstance(seq[0]); + m_status = PkiStatusInfo.GetInstance(seq[1]); if (seq.Count >= 3) { @@ -26,71 +35,46 @@ private CertResponse(Asn1Sequence seq) Asn1Encodable o = seq[2]; if (o is Asn1OctetString) { - rspInfo = Asn1OctetString.GetInstance(o); + m_rspInfo = Asn1OctetString.GetInstance(o); } else { - certifiedKeyPair = CertifiedKeyPair.GetInstance(o); + m_certifiedKeyPair = CertifiedKeyPair.GetInstance(o); } } else { - certifiedKeyPair = CertifiedKeyPair.GetInstance(seq[2]); - rspInfo = Asn1OctetString.GetInstance(seq[3]); + m_certifiedKeyPair = CertifiedKeyPair.GetInstance(seq[2]); + m_rspInfo = Asn1OctetString.GetInstance(seq[3]); } } } - public static CertResponse GetInstance(object obj) - { - if (obj is CertResponse) - return (CertResponse)obj; - - if (obj is Asn1Sequence) - return new CertResponse((Asn1Sequence)obj); - - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); - } - - public CertResponse( - DerInteger certReqId, - PkiStatusInfo status) + public CertResponse(DerInteger certReqId, PkiStatusInfo status) : this(certReqId, status, null, null) { } - public CertResponse( - DerInteger certReqId, - PkiStatusInfo status, - CertifiedKeyPair certifiedKeyPair, - Asn1OctetString rspInfo) - { - if (certReqId == null) - throw new ArgumentNullException("certReqId"); + public CertResponse(DerInteger certReqId, PkiStatusInfo status, CertifiedKeyPair certifiedKeyPair, + Asn1OctetString rspInfo) + { + if (certReqId == null) + throw new ArgumentNullException(nameof(certReqId)); if (status == null) - throw new ArgumentNullException("status"); + throw new ArgumentNullException(nameof(status)); - this.certReqId = certReqId; - this.status = status; - this.certifiedKeyPair = certifiedKeyPair; - this.rspInfo = rspInfo; + m_certReqId = certReqId; + m_status = status; + m_certifiedKeyPair = certifiedKeyPair; + m_rspInfo = rspInfo; } - public virtual DerInteger CertReqID - { - get { return certReqId; } - } + public virtual DerInteger CertReqID => m_certReqId; - public virtual PkiStatusInfo Status - { - get { return status; } - } + public virtual PkiStatusInfo Status => m_status; - public virtual CertifiedKeyPair CertifiedKeyPair - { - get { return certifiedKeyPair; } - } + public virtual CertifiedKeyPair CertifiedKeyPair => m_certifiedKeyPair; /** *
@@ -110,8 +94,8 @@ public virtual CertifiedKeyPair CertifiedKeyPair
 		 */
 		public override Asn1Object ToAsn1Object()
 		{
-			Asn1EncodableVector v = new Asn1EncodableVector(certReqId, status);
-			v.AddOptional(certifiedKeyPair, rspInfo);
+			Asn1EncodableVector v = new Asn1EncodableVector(m_certReqId, m_status);
+			v.AddOptional(m_certifiedKeyPair, m_rspInfo);
 			return new DerSequence(v);
 		}
 	}
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertStatus.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertStatus.cs
index 8b64711..646fa56 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertStatus.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertStatus.cs	
@@ -2,85 +2,103 @@
 #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.Cmp
 {
 	public class CertStatus
 		: Asn1Encodable
 	{
-		private readonly Asn1OctetString certHash;
-		private readonly DerInteger certReqId;
-		private readonly PkiStatusInfo statusInfo;
+        public static CertStatus GetInstance(object obj)
+        {
+			if (obj is CertStatus certStatus)
+				return certStatus;
 
-		private CertStatus(Asn1Sequence seq)
+			if (obj != null)
+				return new CertStatus(Asn1Sequence.GetInstance(obj));
+
+			return null;
+        }
+
+        private readonly Asn1OctetString m_certHash;
+		private readonly DerInteger m_certReqID;
+		private readonly PkiStatusInfo m_statusInfo;
+        private readonly AlgorithmIdentifier m_hashAlg;
+
+        private CertStatus(Asn1Sequence seq)
 		{
-			certHash = Asn1OctetString.GetInstance(seq[0]);
-			certReqId = DerInteger.GetInstance(seq[1]);
+			m_certHash = Asn1OctetString.GetInstance(seq[0]);
+			m_certReqID = DerInteger.GetInstance(seq[1]);
 
 			if (seq.Count > 2)
 			{
-				statusInfo = PkiStatusInfo.GetInstance(seq[2]);
+				for (int t = 2; t < seq.Count; t++)
+				{
+					Asn1Object p = seq[t].ToAsn1Object();
+					if (p is Asn1Sequence s)
+					{
+						m_statusInfo = PkiStatusInfo.GetInstance(s);
+					}
+					if (p is Asn1TaggedObject dto)
+					{
+						if (dto.TagNo != 0)
+							throw new ArgumentException("unknown tag " + dto.TagNo);
+
+						m_hashAlg = AlgorithmIdentifier.GetInstance(dto, true);
+					}
+				}
 			}
 		}
 
-		public CertStatus(byte[] certHash, BigInteger certReqId)
+		public CertStatus(byte[] certHash, BigInteger certReqID)
 		{
-			this.certHash = new DerOctetString(certHash);
-			this.certReqId = new DerInteger(certReqId);
+			m_certHash = new DerOctetString(certHash);
+			m_certReqID = new DerInteger(certReqID);
 		}
 
-		public CertStatus(byte[] certHash, BigInteger certReqId, PkiStatusInfo statusInfo)
+		public CertStatus(byte[] certHash, BigInteger certReqID, PkiStatusInfo statusInfo)
 		{
-			this.certHash = new DerOctetString(certHash);
-			this.certReqId = new DerInteger(certReqId);
-			this.statusInfo = statusInfo;
+            m_certHash = new DerOctetString(certHash);
+            m_certReqID = new DerInteger(certReqID);
+            m_statusInfo = statusInfo;
 		}
 
-		public static CertStatus GetInstance(object obj)
-		{
-			if (obj is CertStatus)
-				return (CertStatus)obj;
+        public CertStatus(byte[] certHash, BigInteger certReqID, PkiStatusInfo statusInfo, AlgorithmIdentifier hashAlg)
+        {
+            m_certHash = new DerOctetString(certHash);
+            m_certReqID = new DerInteger(certReqID);
+            m_statusInfo = statusInfo;
+            m_hashAlg = hashAlg;
+        }
 
-			if (obj is Asn1Sequence)
-				return new CertStatus((Asn1Sequence)obj);
+        public virtual Asn1OctetString CertHash => m_certHash;
 
-            throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
-		}
+		public virtual DerInteger CertReqID => m_certReqID;
 
-		public virtual Asn1OctetString CertHash
-		{
-			get { return certHash; }
-		}
-
-		public virtual DerInteger CertReqID
-		{
-			get { return certReqId; }
-		}
+		public virtual PkiStatusInfo StatusInfo => m_statusInfo;
 
-		public virtual PkiStatusInfo StatusInfo
-		{
-			get { return statusInfo; }
-		}
+		public virtual AlgorithmIdentifier HashAlg => m_hashAlg;
 
-		/**
-		 * 
-		 * 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
-		 * }
-		 * 
- * @return a basic ASN.1 object representation. - */ - public override Asn1Object ToAsn1Object() + /** + *
+         *
+         *  CertStatus ::= SEQUENCE {
+         *     certHash    OCTET STRING,
+         *     certReqId   INTEGER,
+         *     statusInfo  PKIStatusInfo OPTIONAL,
+         *     hashAlg [0] AlgorithmIdentifier{DIGEST-ALGORITHM, {...}} OPTIONAL
+         *   }
+         *
+         * 
+ * + * @return a basic ASN.1 object representation. + */ + public override Asn1Object ToAsn1Object() { - Asn1EncodableVector v = new Asn1EncodableVector(certHash, certReqId); - v.AddOptional(statusInfo); + Asn1EncodableVector v = new Asn1EncodableVector(m_certHash, m_certReqID); + v.AddOptional(m_statusInfo); + v.AddOptionalTagged(true, 0, m_hashAlg); return new DerSequence(v); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertifiedKeyPair.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertifiedKeyPair.cs index 6b28ea7..a446ec9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertifiedKeyPair.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CertifiedKeyPair.cs @@ -3,20 +3,30 @@ using System; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Crmf; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp { public class CertifiedKeyPair : Asn1Encodable { - private readonly CertOrEncCert certOrEncCert; - private readonly EncryptedValue privateKey; - private readonly PkiPublicationInfo publicationInfo; + public static CertifiedKeyPair GetInstance(object obj) + { + if (obj is CertifiedKeyPair certifiedKeyPair) + return certifiedKeyPair; - private CertifiedKeyPair(Asn1Sequence seq) + if (obj != null) + return new CertifiedKeyPair(Asn1Sequence.GetInstance(obj)); + + return null; + } + + private readonly CertOrEncCert m_certOrEncCert; + private readonly EncryptedKey m_privateKey; + private readonly PkiPublicationInfo m_publicationInfo; + + private CertifiedKeyPair(Asn1Sequence seq) { - certOrEncCert = CertOrEncCert.GetInstance(seq[0]); + m_certOrEncCert = CertOrEncCert.GetInstance(seq[0]); if (seq.Count >= 2) { @@ -25,66 +35,48 @@ private CertifiedKeyPair(Asn1Sequence seq) Asn1TaggedObject tagged = Asn1TaggedObject.GetInstance(seq[1]); if (tagged.TagNo == 0) { - privateKey = EncryptedValue.GetInstance(tagged.GetObject()); + m_privateKey = EncryptedKey.GetInstance(tagged.GetObject()); } else { - publicationInfo = PkiPublicationInfo.GetInstance(tagged.GetObject()); + m_publicationInfo = PkiPublicationInfo.GetInstance(tagged.GetObject()); } } else { - privateKey = EncryptedValue.GetInstance(Asn1TaggedObject.GetInstance(seq[1])); - publicationInfo = PkiPublicationInfo.GetInstance(Asn1TaggedObject.GetInstance(seq[2])); + m_privateKey = EncryptedKey.GetInstance(Asn1TaggedObject.GetInstance(seq[1]).GetObject()); + m_publicationInfo = PkiPublicationInfo.GetInstance(Asn1TaggedObject.GetInstance(seq[2]).GetObject()); } } } - public static CertifiedKeyPair GetInstance(object obj) + public CertifiedKeyPair(CertOrEncCert certOrEncCert) + : this(certOrEncCert, (EncryptedKey)null, null) { - if (obj is CertifiedKeyPair) - return (CertifiedKeyPair)obj; - - if (obj is Asn1Sequence) - return new CertifiedKeyPair((Asn1Sequence)obj); - - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } - public CertifiedKeyPair( - CertOrEncCert certOrEncCert) - : this(certOrEncCert, null, null) - { - } + public CertifiedKeyPair(CertOrEncCert certOrEncCert, EncryptedValue privateKey, + PkiPublicationInfo publicationInfo) + : this(certOrEncCert, privateKey == null ? null : new EncryptedKey(privateKey), publicationInfo) + { + } - public CertifiedKeyPair( - CertOrEncCert certOrEncCert, - EncryptedValue privateKey, - PkiPublicationInfo publicationInfo - ) - { + public CertifiedKeyPair(CertOrEncCert certOrEncCert, EncryptedKey privateKey, + PkiPublicationInfo publicationInfo) + { if (certOrEncCert == null) - throw new ArgumentNullException("certOrEncCert"); + throw new ArgumentNullException(nameof(certOrEncCert)); - this.certOrEncCert = certOrEncCert; - this.privateKey = privateKey; - this.publicationInfo = publicationInfo; - } + m_certOrEncCert = certOrEncCert; + m_privateKey = privateKey; + m_publicationInfo = publicationInfo; + } - public virtual CertOrEncCert CertOrEncCert - { - get { return certOrEncCert; } - } + public virtual CertOrEncCert CertOrEncCert => m_certOrEncCert; - public virtual EncryptedValue PrivateKey - { - get { return privateKey; } - } + public virtual EncryptedKey PrivateKey => m_privateKey; - public virtual PkiPublicationInfo PublicationInfo - { - get { return publicationInfo; } - } + public virtual PkiPublicationInfo PublicationInfo => m_publicationInfo; /** *
@@ -99,9 +91,9 @@ public virtual PkiPublicationInfo PublicationInfo
 		 */
 		public override Asn1Object ToAsn1Object()
 		{
-			Asn1EncodableVector v = new Asn1EncodableVector(certOrEncCert);
-            v.AddOptionalTagged(true, 0, privateKey);
-            v.AddOptionalTagged(true, 1, publicationInfo);
+			Asn1EncodableVector v = new Asn1EncodableVector(m_certOrEncCert);
+            v.AddOptionalTagged(true, 0, m_privateKey);
+            v.AddOptionalTagged(true, 1, m_publicationInfo);
 			return new DerSequence(v);
 		}
 	}
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/Challenge.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/Challenge.cs
index 72af824..093ea91 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/Challenge.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/Challenge.cs	
@@ -3,16 +3,52 @@
 using System;
 
 using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509;
-using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
 
 namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp
 {
-	public class Challenge
+    /**
+     * 
+     * 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)
+     *          --   }
+     *      }
+     *      
+ */ + public class Challenge : Asn1Encodable { - private readonly AlgorithmIdentifier owf; - private readonly Asn1OctetString witness; - private readonly Asn1OctetString challenge; + public static Challenge GetInstance(object obj) + { + if (obj is Challenge challenge) + return challenge; + + if (obj != null) + return new Challenge(Asn1Sequence.GetInstance(obj)); + + return null; + } + + private readonly AlgorithmIdentifier m_owf; + private readonly Asn1OctetString m_witness; + private readonly Asn1OctetString m_challenge; private Challenge(Asn1Sequence seq) { @@ -20,30 +56,32 @@ private Challenge(Asn1Sequence seq) if (seq.Count == 3) { - owf = AlgorithmIdentifier.GetInstance(seq[index++]); + m_owf = AlgorithmIdentifier.GetInstance(seq[index++]); } - witness = Asn1OctetString.GetInstance(seq[index++]); - challenge = Asn1OctetString.GetInstance(seq[index]); + m_witness = Asn1OctetString.GetInstance(seq[index++]); + m_challenge = Asn1OctetString.GetInstance(seq[index]); } - public static Challenge GetInstance(object obj) - { - if (obj is Challenge) - return (Challenge)obj; + public Challenge(byte[] witness, byte[] challenge) + : this(null, witness, challenge) + { + } - if (obj is Asn1Sequence) - return new Challenge((Asn1Sequence)obj); + public Challenge(AlgorithmIdentifier owf, byte[] witness, byte[] challenge) + { + m_owf = owf; + m_witness = new DerOctetString(witness); + m_challenge = new DerOctetString(challenge); + } - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); - } + public virtual AlgorithmIdentifier Owf => m_owf; - public virtual AlgorithmIdentifier Owf - { - get { return owf; } - } + public virtual Asn1OctetString Witness => m_witness; + + public virtual Asn1OctetString ChallengeValue => m_challenge; - /** + /** *
 		 * Challenge ::= SEQUENCE {
 		 *                 owf                 AlgorithmIdentifier  OPTIONAL,
@@ -70,13 +108,58 @@ public virtual AlgorithmIdentifier Owf
 		 * 
* @return a basic ASN.1 object representation. */ - public override Asn1Object ToAsn1Object() + public override Asn1Object ToAsn1Object() { Asn1EncodableVector v = new Asn1EncodableVector(); - v.AddOptional(owf); - v.Add(witness, challenge); + v.AddOptional(m_owf); + v.Add(m_witness, m_challenge); return new DerSequence(v); } + + /** + * Rand is the inner type + */ + public class Rand + : Asn1Encodable + { + public static Rand GetInstance(object obj) + { + if (obj is Rand rand) + return rand; + + if (obj != null) + return new Rand(Asn1Sequence.GetInstance(obj)); + + return null; + } + + private readonly DerInteger m_intVal; + private readonly GeneralName m_sender; + + public Rand(DerInteger intVal, GeneralName sender) + { + m_intVal = intVal; + m_sender = sender; + } + + public Rand(Asn1Sequence seq) + { + if (seq.Count != 2) + throw new ArgumentException("expected sequence size of 2"); + + m_intVal = DerInteger.GetInstance(seq[0]); + m_sender = GeneralName.GetInstance(seq[1]); + } + + public virtual DerInteger IntVal => m_intVal; + + public virtual GeneralName Sender => m_sender; + + public override Asn1Object ToAsn1Object() + { + return new DerSequence(m_intVal, m_sender); + } + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CmpCertificate.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CmpCertificate.cs index e45dd31..daf7c8c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CmpCertificate.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CmpCertificate.cs @@ -1,6 +1,7 @@ #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; @@ -10,54 +11,84 @@ 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) + public static CmpCertificate GetInstance(object obj) { - this.x509v2AttrCert = x509v2AttrCert; - } + // TODO[cmp] Review this whole metho - public CmpCertificate(X509CertificateStructure x509v3PKCert) - { - if (x509v3PKCert.Version != 3) - throw new ArgumentException("only version 3 certificates allowed", "x509v3PKCert"); + if (obj == null) + return null; - this.x509v3PKCert = x509v3PKCert; - } + if (obj is CmpCertificate cmpCertificate) + return cmpCertificate; - public static CmpCertificate GetInstance(object obj) - { - if (obj is CmpCertificate) - return (CmpCertificate)obj; + if (obj is byte[] bs) + { + try + { + obj = Asn1Object.FromByteArray(bs); + } + catch (IOException) + { + throw new ArgumentException("Invalid encoding in CmpCertificate"); + } + } if (obj is Asn1Sequence) return new CmpCertificate(X509CertificateStructure.GetInstance(obj)); - if (obj is Asn1TaggedObject) - return new CmpCertificate(AttributeCertificate.GetInstance(((Asn1TaggedObject)obj).GetObject())); + if (obj is Asn1TaggedObject taggedObject) + return new CmpCertificate(taggedObject.TagNo, taggedObject.GetObject()); - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), nameof(obj)); } - public virtual bool IsX509v3PKCert + public static CmpCertificate GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - get { return x509v3PKCert != null; } + // TODO[cmp] + if (taggedObject == null) + return null; + + if (!declaredExplicit) + throw new ArgumentException("tag must be explicit"); + + // TODO[cmp] + return GetInstance(taggedObject.GetObject()); } - public virtual X509CertificateStructure X509v3PKCert + private readonly X509CertificateStructure m_x509v3PKCert; + + private readonly int m_otherTagValue; + private readonly Asn1Encodable m_otherCert; + + /** + * Note: the addition of other certificates is a BC extension. If you use this constructor they + * will be added with an explicit tag value of type. + * + * @param type the type of the certificate (used as a tag value). + * @param otherCert the object representing the certificate + */ + public CmpCertificate(int type, Asn1Encodable otherCert) { - get { return x509v3PKCert; } + m_otherTagValue = type; + m_otherCert = otherCert; } - public virtual AttributeCertificate X509v2AttrCert + public CmpCertificate(X509CertificateStructure x509v3PKCert) { - get { return x509v2AttrCert; } + if (x509v3PKCert.Version != 3) + throw new ArgumentException("only version 3 certificates allowed", nameof(x509v3PKCert)); + + m_x509v3PKCert = x509v3PKCert; } + public virtual bool IsX509v3PKCert => m_x509v3PKCert != null; + + public virtual X509CertificateStructure X509v3PKCert => m_x509v3PKCert; + + public virtual int OtherCertTag => m_otherTagValue; + + public virtual Asn1Encodable OtherCert => m_otherCert; + /** *
          * CMPCertificate ::= CHOICE {
@@ -71,13 +102,13 @@ public virtual AttributeCertificate X509v2AttrCert
          */
         public override Asn1Object ToAsn1Object()
         {
-            if (x509v2AttrCert != null)
+            if (m_otherCert != null)
             {
                 // explicit following CMP conventions
-                return new DerTaggedObject(true, 1, x509v2AttrCert);
+                return new DerTaggedObject(true, m_otherTagValue, m_otherCert);
             }
 
-            return x509v3PKCert.ToAsn1Object();
+            return m_x509v3PKCert.ToAsn1Object();
         }
     }
 }
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CmpObjectIdentifiers.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CmpObjectIdentifiers.cs
index e7ff694..8f06d3d 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CmpObjectIdentifiers.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CmpObjectIdentifiers.cs	
@@ -4,106 +4,258 @@
 
 namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp
 {
-	public abstract class CmpObjectIdentifiers
+	public static class CmpObjectIdentifiers
 	{
-		// RFC 4210
-
-		// id-PasswordBasedMac OBJECT IDENTIFIER ::= {1 2 840 113533 7 66 13}
-		public static readonly DerObjectIdentifier passwordBasedMac = new DerObjectIdentifier("1.2.840.113533.7.66.13");
-
-		// id-DHBasedMac OBJECT IDENTIFIER ::= {1 2 840 113533 7 66 30}
-		public static readonly DerObjectIdentifier dhBasedMac = new DerObjectIdentifier("1.2.840.113533.7.66.30");
-
-		// Example InfoTypeAndValue contents include, but are not limited
-		// to, the following (un-comment in this ASN.1 module and use as
-		// appropriate for a given environment):
-		//
-		// id-it-caProtEncCert OBJECT IDENTIFIER ::= {id-it 1}
-		// CAProtEncCertValue ::= CMPCertificate
-		// id-it-signKeyPairTypes OBJECT IDENTIFIER ::= {id-it 2}
-		// SignKeyPairTypesValue ::= SEQUENCE OF AlgorithmIdentifier
-		// id-it-encKeyPairTypes OBJECT IDENTIFIER ::= {id-it 3}
-		// EncKeyPairTypesValue ::= SEQUENCE OF AlgorithmIdentifier
-		// id-it-preferredSymmAlg OBJECT IDENTIFIER ::= {id-it 4}
-		// PreferredSymmAlgValue ::= AlgorithmIdentifier
-		// id-it-caKeyUpdateInfo OBJECT IDENTIFIER ::= {id-it 5}
-		// CAKeyUpdateInfoValue ::= CAKeyUpdAnnContent
-		// id-it-currentCRL OBJECT IDENTIFIER ::= {id-it 6}
-		// CurrentCRLValue ::= CertificateList
-		// id-it-unsupportedOIDs OBJECT IDENTIFIER ::= {id-it 7}
-		// UnsupportedOIDsValue ::= SEQUENCE OF OBJECT IDENTIFIER
-		// id-it-keyPairParamReq OBJECT IDENTIFIER ::= {id-it 10}
-		// KeyPairParamReqValue ::= OBJECT IDENTIFIER
-		// id-it-keyPairParamRep OBJECT IDENTIFIER ::= {id-it 11}
-		// KeyPairParamRepValue ::= AlgorithmIdentifer
-		// id-it-revPassphrase OBJECT IDENTIFIER ::= {id-it 12}
-		// RevPassphraseValue ::= EncryptedValue
-		// id-it-implicitConfirm OBJECT IDENTIFIER ::= {id-it 13}
-		// ImplicitConfirmValue ::= NULL
-		// id-it-confirmWaitTime OBJECT IDENTIFIER ::= {id-it 14}
-		// ConfirmWaitTimeValue ::= GeneralizedTime
-		// id-it-origPKIMessage OBJECT IDENTIFIER ::= {id-it 15}
-		// OrigPKIMessageValue ::= PKIMessages
-		// id-it-suppLangTags OBJECT IDENTIFIER ::= {id-it 16}
-		// SuppLangTagsValue ::= SEQUENCE OF UTF8String
-		//
-		// where
-		//
-		// id-pkix OBJECT IDENTIFIER ::= {
-		// iso(1) identified-organization(3)
-		// dod(6) internet(1) security(5) mechanisms(5) pkix(7)}
-		// and
-		// id-it OBJECT IDENTIFIER ::= {id-pkix 4}
-		public static readonly DerObjectIdentifier it_caProtEncCert = new DerObjectIdentifier("1.3.6.1.5.5.7.4.1");
-		public static readonly DerObjectIdentifier it_signKeyPairTypes = new DerObjectIdentifier("1.3.6.1.5.5.7.4.2");
-		public static readonly DerObjectIdentifier it_encKeyPairTypes = new DerObjectIdentifier("1.3.6.1.5.5.7.4.3");
-		public static readonly DerObjectIdentifier it_preferredSymAlg = new DerObjectIdentifier("1.3.6.1.5.5.7.4.4");
-		public static readonly DerObjectIdentifier it_caKeyUpdateInfo = new DerObjectIdentifier("1.3.6.1.5.5.7.4.5");
-		public static readonly DerObjectIdentifier it_currentCRL = new DerObjectIdentifier("1.3.6.1.5.5.7.4.6");
-		public static readonly DerObjectIdentifier it_unsupportedOIDs = new DerObjectIdentifier("1.3.6.1.5.5.7.4.7");
-		public static readonly DerObjectIdentifier it_keyPairParamReq = new DerObjectIdentifier("1.3.6.1.5.5.7.4.10");
-		public static readonly DerObjectIdentifier it_keyPairParamRep = new DerObjectIdentifier("1.3.6.1.5.5.7.4.11");
-		public static readonly DerObjectIdentifier it_revPassphrase = new DerObjectIdentifier("1.3.6.1.5.5.7.4.12");
-		public static readonly DerObjectIdentifier it_implicitConfirm = new DerObjectIdentifier("1.3.6.1.5.5.7.4.13");
-		public static readonly DerObjectIdentifier it_confirmWaitTime = new DerObjectIdentifier("1.3.6.1.5.5.7.4.14");
-		public static readonly DerObjectIdentifier it_origPKIMessage = new DerObjectIdentifier("1.3.6.1.5.5.7.4.15");
-		public static readonly DerObjectIdentifier it_suppLangTags = new DerObjectIdentifier("1.3.6.1.5.5.7.4.16");
-
-		// RFC 4211
-
-		// id-pkix OBJECT IDENTIFIER ::= { iso(1) identified-organization(3)
-		// dod(6) internet(1) security(5) mechanisms(5) pkix(7) }
-		//
-		// arc for Internet X.509 PKI protocols and their components
-		// id-pkip OBJECT IDENTIFIER :: { id-pkix pkip(5) }
-		//
-		// arc for Registration Controls in CRMF
-		// id-regCtrl OBJECT IDENTIFIER ::= { id-pkip regCtrl(1) }
-		//
-		// arc for Registration Info in CRMF
-		// id-regInfo OBJECT IDENTIFIER ::= { id-pkip id-regInfo(2) }
-
-		public static readonly DerObjectIdentifier regCtrl_regToken = new DerObjectIdentifier("1.3.6.1.5.5.7.5.1.1");
-		public static readonly DerObjectIdentifier regCtrl_authenticator = new DerObjectIdentifier("1.3.6.1.5.5.7.5.1.2");
-		public static readonly DerObjectIdentifier regCtrl_pkiPublicationInfo = new DerObjectIdentifier("1.3.6.1.5.5.7.5.1.3");
-		public static readonly DerObjectIdentifier regCtrl_pkiArchiveOptions = new DerObjectIdentifier("1.3.6.1.5.5.7.5.1.4");
-		public static readonly DerObjectIdentifier regCtrl_oldCertID = new DerObjectIdentifier("1.3.6.1.5.5.7.5.1.5");
-		public static readonly DerObjectIdentifier regCtrl_protocolEncrKey = new DerObjectIdentifier("1.3.6.1.5.5.7.5.1.6");
-
-		// From RFC4210:
-		// id-regCtrl-altCertTemplate OBJECT IDENTIFIER ::= {id-regCtrl 7}
-		public static readonly DerObjectIdentifier regCtrl_altCertTemplate = new DerObjectIdentifier("1.3.6.1.5.5.7.5.1.7");
-
-		public static readonly DerObjectIdentifier regInfo_utf8Pairs = new DerObjectIdentifier("1.3.6.1.5.5.7.5.2.1");
-		public static readonly DerObjectIdentifier regInfo_certReq = new DerObjectIdentifier("1.3.6.1.5.5.7.5.2.2");
-
-		// id-smime OBJECT IDENTIFIER ::= { iso(1) member-body(2)
-		// us(840) rsadsi(113549) pkcs(1) pkcs9(9) 16 }
-		//
-		// id-ct OBJECT IDENTIFIER ::= { id-smime 1 } -- content types
-		//
-		// id-ct-encKeyWithID OBJECT IDENTIFIER ::= {id-ct 21}
-		public static readonly DerObjectIdentifier ct_encKeyWithID = new DerObjectIdentifier("1.2.840.113549.1.9.16.1.21");
+        // RFC 4210
+
+        /**
+         * id-PasswordBasedMac OBJECT IDENTIFIER ::= {1 2 840 113533 7 66 13}
+         */
+        public static readonly DerObjectIdentifier passwordBasedMac = new DerObjectIdentifier("1.2.840.113533.7.66.13");
+
+        /**
+         * id-DHBasedMac OBJECT IDENTIFIER ::= {1 2 840 113533 7 66 30}
+         */
+        public static readonly DerObjectIdentifier dhBasedMac = new DerObjectIdentifier("1.2.840.113533.7.66.30");
+
+        // Example InfoTypeAndValue contents include, but are not limited
+        // to, the following (un-comment in this ASN.1 module and use as
+        // appropriate for a given environment):
+        //
+        //   id-it-caProtEncCert    OBJECT IDENTIFIER ::= {id-it 1}
+        //      CAProtEncCertValue      ::= CMPCertificate
+        //   id-it-signKeyPairTypes OBJECT IDENTIFIER ::= {id-it 2}
+        //      SignKeyPairTypesValue   ::= SEQUENCE OF AlgorithmIdentifier
+        //   id-it-encKeyPairTypes  OBJECT IDENTIFIER ::= {id-it 3}
+        //      EncKeyPairTypesValue    ::= SEQUENCE OF AlgorithmIdentifier
+        //   id-it-preferredSymmAlg OBJECT IDENTIFIER ::= {id-it 4}
+        //      PreferredSymmAlgValue   ::= AlgorithmIdentifier
+        //   id-it-caKeyUpdateInfo  OBJECT IDENTIFIER ::= {id-it 5}
+        //      CAKeyUpdateInfoValue    ::= CAKeyUpdAnnContent
+        //   id-it-currentCRL       OBJECT IDENTIFIER ::= {id-it 6}
+        //      CurrentCRLValue         ::= CertificateList
+        //   id-it-unsupportedOIDs  OBJECT IDENTIFIER ::= {id-it 7}
+        //      UnsupportedOIDsValue    ::= SEQUENCE OF OBJECT IDENTIFIER
+        //   id-it-keyPairParamReq  OBJECT IDENTIFIER ::= {id-it 10}
+        //      KeyPairParamReqValue    ::= OBJECT IDENTIFIER
+        //   id-it-keyPairParamRep  OBJECT IDENTIFIER ::= {id-it 11}
+        //      KeyPairParamRepValue    ::= AlgorithmIdentifer
+        //   id-it-revPassphrase    OBJECT IDENTIFIER ::= {id-it 12}
+        //      RevPassphraseValue      ::= EncryptedValue
+        //   id-it-implicitConfirm  OBJECT IDENTIFIER ::= {id-it 13}
+        //      ImplicitConfirmValue    ::= NULL
+        //   id-it-confirmWaitTime  OBJECT IDENTIFIER ::= {id-it 14}
+        //      ConfirmWaitTimeValue    ::= GeneralizedTime
+        //   id-it-origPKIMessage   OBJECT IDENTIFIER ::= {id-it 15}
+        //      OrigPKIMessageValue     ::= PKIMessages
+        //   id-it-suppLangTags     OBJECT IDENTIFIER ::= {id-it 16}
+        //      SuppLangTagsValue       ::= SEQUENCE OF UTF8String
+        //   id-it-certProfile  OBJECT IDENTIFIER ::= {id-it 21}
+        //      CertProfileValue ::= SEQUENCE SIZE (1..MAX) OF UTF8String
+        // where
+        //
+        //   id-pkix OBJECT IDENTIFIER ::= {
+        //      iso(1) identified-organization(3)
+        //      dod(6) internet(1) security(5) mechanisms(5) pkix(7)}
+        // and
+        //   id-it   OBJECT IDENTIFIER ::= {id-pkix 4}
+
+        /** RFC 4120: it-id: PKIX.4 = 1.3.6.1.5.5.7.4 */
+
+
+        /**
+         * RFC 4120: 1.3.6.1.5.5.7.4.1
+         */
+        public static readonly DerObjectIdentifier it_caProtEncCert = new DerObjectIdentifier("1.3.6.1.5.5.7.4.1");
+        /**
+         * RFC 4120: 1.3.6.1.5.5.7.4.2
+         */
+        public static readonly DerObjectIdentifier it_signKeyPairTypes = new DerObjectIdentifier("1.3.6.1.5.5.7.4.2");
+        /**
+         * RFC 4120: 1.3.6.1.5.5.7.4.3
+         */
+        public static readonly DerObjectIdentifier it_encKeyPairTypes = new DerObjectIdentifier("1.3.6.1.5.5.7.4.3");
+        /**
+         * RFC 4120: 1.3.6.1.5.5.7.4.4
+         */
+        public static readonly DerObjectIdentifier it_preferredSymAlg = new DerObjectIdentifier("1.3.6.1.5.5.7.4.4");
+        /**
+         * RFC 4120: 1.3.6.1.5.5.7.4.5
+         */
+        public static readonly DerObjectIdentifier it_caKeyUpdateInfo = new DerObjectIdentifier("1.3.6.1.5.5.7.4.5");
+        /**
+         * RFC 4120: 1.3.6.1.5.5.7.4.6
+         */
+        public static readonly DerObjectIdentifier it_currentCRL = new DerObjectIdentifier("1.3.6.1.5.5.7.4.6");
+        /**
+         * RFC 4120: 1.3.6.1.5.5.7.4.7
+         */
+        public static readonly DerObjectIdentifier it_unsupportedOIDs = new DerObjectIdentifier("1.3.6.1.5.5.7.4.7");
+        /**
+         * RFC 4120: 1.3.6.1.5.5.7.4.10
+         */
+        public static readonly DerObjectIdentifier it_keyPairParamReq = new DerObjectIdentifier("1.3.6.1.5.5.7.4.10");
+        /**
+         * RFC 4120: 1.3.6.1.5.5.7.4.11
+         */
+        public static readonly DerObjectIdentifier it_keyPairParamRep = new DerObjectIdentifier("1.3.6.1.5.5.7.4.11");
+        /**
+         * RFC 4120: 1.3.6.1.5.5.7.4.12
+         */
+        public static readonly DerObjectIdentifier it_revPassphrase = new DerObjectIdentifier("1.3.6.1.5.5.7.4.12");
+        /**
+         * RFC 4120: 1.3.6.1.5.5.7.4.13
+         */
+        public static readonly DerObjectIdentifier it_implicitConfirm = new DerObjectIdentifier("1.3.6.1.5.5.7.4.13");
+        /**
+         * RFC 4120: 1.3.6.1.5.5.7.4.14
+         */
+        public static readonly DerObjectIdentifier it_confirmWaitTime = new DerObjectIdentifier("1.3.6.1.5.5.7.4.14");
+        /**
+         * RFC 4120: 1.3.6.1.5.5.7.4.15
+         */
+        public static readonly DerObjectIdentifier it_origPKIMessage = new DerObjectIdentifier("1.3.6.1.5.5.7.4.15");
+        /**
+         * RFC 4120: 1.3.6.1.5.5.7.4.16
+         */
+        public static readonly DerObjectIdentifier it_suppLangTags = new DerObjectIdentifier("1.3.6.1.5.5.7.4.16");
+
+        /**
+         * Update 16, RFC 4210
+         * {id-it 17}
+         */
+        public static readonly DerObjectIdentifier id_it_caCerts = new DerObjectIdentifier("1.3.6.1.5.5.7.4.17");
+
+
+        /**
+         * Update 16, RFC 4210
+         * GenRep:    {id-it 18}, RootCaKeyUpdateContent
+         */
+        public static readonly DerObjectIdentifier id_it_rootCaKeyUpdate = new DerObjectIdentifier("1.3.6.1.5.5.7.4.18");
+
+
+        /**
+         * Update 16, RFC 4210
+         * {id-it 19}
+         */
+        public static readonly DerObjectIdentifier id_it_certReqTemplate = new DerObjectIdentifier("1.3.6.1.5.5.7.4.19");
+
+
+        /**
+         * Update 16, RFC 4210
+         * GenMsg:    {id-it 20}, RootCaCertValue
+         */
+        public static readonly DerObjectIdentifier id_it_rootCaCert = new DerObjectIdentifier("1.3.6.1.5.5.7.4.20");
+
+        /**
+         * Update-16 to RFC 4210
+         * id-it-certProfile  OBJECT IDENTIFIER ::= {id-it 21}
+         */
+        public static readonly DerObjectIdentifier id_it_certProfile = new DerObjectIdentifier("1.3.6.1.5.5.7.4.21");
+
+        public static readonly DerObjectIdentifier id_it_crlStatusList = new DerObjectIdentifier("1.3.6.1.5.5.7.4.22");
+
+        public static readonly DerObjectIdentifier id_it_crls = new DerObjectIdentifier("1.3.6.1.5.5.7.4.23");
+
+        // Not yet formally defined.
+
+        //public static readonly DerObjectIdentifier id_it_crlStatusList = null;
+        //public static readonly DerObjectIdentifier id_it_crls = null;
+
+
+        // RFC 4211
+
+        // id-pkix  OBJECT IDENTIFIER  ::= { iso(1) identified-organization(3)
+        //     dod(6) internet(1) security(5) mechanisms(5) pkix(7) }
+        //
+        // arc for Internet X.509 PKI protocols and their components
+        // id-pkip  OBJECT IDENTIFIER :: { id-pkix pkip(5) }
+        //
+        // arc for Registration Controls in CRMF
+        // id-regCtrl  OBJECT IDENTIFIER ::= { id-pkip regCtrl(1) }
+        //
+        // arc for Registration Info in CRMF
+        // id-regInfo       OBJECT IDENTIFIER ::= { id-pkip id-regInfo(2) }
+
+        /**
+         * RFC 4211: it-pkip: PKIX.5 = 1.3.6.1.5.5.7.5
+         */
+        public static readonly DerObjectIdentifier id_pkip = new DerObjectIdentifier("1.3.6.1.5.5.7.5");
+
+        /**
+         * RFC 4211: it-regCtrl: 1.3.6.1.5.5.7.5.1
+         */
+        public static readonly DerObjectIdentifier id_regCtrl = new DerObjectIdentifier("1.3.6.1.5.5.7.5.1");
+        /**
+         * RFC 4211: it-regInfo: 1.3.6.1.5.5.7.5.2
+         */
+        public static readonly DerObjectIdentifier id_regInfo = new DerObjectIdentifier("1.3.6.1.5.5.7.5.2");
+
+
+        /**
+         * 1.3.6.1.5.5.7.5.1.1
+         */
+        public static readonly DerObjectIdentifier regCtrl_regToken = new DerObjectIdentifier("1.3.6.1.5.5.7.5.1.1");
+        /**
+         * 1.3.6.1.5.5.7.5.1.2
+         */
+        public static readonly DerObjectIdentifier regCtrl_authenticator = new DerObjectIdentifier("1.3.6.1.5.5.7.5.1.2");
+        /**
+         * 1.3.6.1.5.5.7.5.1.3
+         */
+        public static readonly DerObjectIdentifier regCtrl_pkiPublicationInfo = new DerObjectIdentifier("1.3.6.1.5.5.7.5.1.3");
+        /**
+         * 1.3.6.1.5.5.7.5.1.4
+         */
+        public static readonly DerObjectIdentifier regCtrl_pkiArchiveOptions = new DerObjectIdentifier("1.3.6.1.5.5.7.5.1.4");
+        /**
+         * 1.3.6.1.5.5.7.5.1.5
+         */
+        public static readonly DerObjectIdentifier regCtrl_oldCertID = new DerObjectIdentifier("1.3.6.1.5.5.7.5.1.5");
+        /**
+         * 1.3.6.1.5.5.7.5.1.6
+         */
+        public static readonly DerObjectIdentifier regCtrl_protocolEncrKey = new DerObjectIdentifier("1.3.6.1.5.5.7.5.1.6");
+
+        /**
+         * From RFC4210:
+         * id-regCtrl-altCertTemplate OBJECT IDENTIFIER ::= {id-regCtrl 7}; 1.3.6.1.5.5.7.1.7
+         */
+        public static readonly DerObjectIdentifier regCtrl_altCertTemplate = new DerObjectIdentifier("1.3.6.1.5.5.7.5.1.7");
+
+        /**
+         * RFC 4211: it-regInfo-utf8Pairs: 1.3.6.1.5.5.7.5.2.1
+         */
+        public static readonly DerObjectIdentifier regInfo_utf8Pairs = new DerObjectIdentifier("1.3.6.1.5.5.7.5.2.1");
+        /**
+         * RFC 4211: it-regInfo-certReq: 1.3.6.1.5.5.7.5.2.1
+         */
+        public static readonly DerObjectIdentifier regInfo_certReq = new DerObjectIdentifier("1.3.6.1.5.5.7.5.2.2");
+
+        /**
+         * 1.2.840.113549.1.9.16.1.21
+         * 

+ * id-ct OBJECT IDENTIFIER ::= { id-smime 1 } -- content types + *

+ * id-ct-encKeyWithID OBJECT IDENTIFIER ::= {id-ct 21} + *

+ */ + public static readonly DerObjectIdentifier ct_encKeyWithID = new DerObjectIdentifier("1.2.840.113549.1.9.16.1.21"); + + + /** + * id-regCtrl-algId OBJECT IDENTIFIER ::= { iso(1) + * identified-organization(3) dod(6) internet(1) security(5) + * mechanisms(5) pkix(7) pkip(5) regCtrl(1) 11 } + */ + public static readonly DerObjectIdentifier id_regCtrl_algId = id_pkip.Branch("1.11"); + + /** + * id-regCtrl-rsaKeyLen OBJECT IDENTIFIER ::= { iso(1) + * identified-organization(3) dod(6) internet(1) security(5) + * mechanisms(5) pkix(7) pkip(5) regCtrl(1) 12 } + */ + public static readonly DerObjectIdentifier id_regCtrl_rsaKeyLen = id_pkip.Branch("1.12"); } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CrlAnnContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CrlAnnContent.cs index 11c94fa..cb98bba 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CrlAnnContent.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CrlAnnContent.cs @@ -1,41 +1,38 @@ #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 CrlAnnContent : Asn1Encodable { - private readonly Asn1Sequence content; + public static CrlAnnContent GetInstance(object obj) + { + if (obj is CrlAnnContent crlAnnContent) + return crlAnnContent; - private CrlAnnContent(Asn1Sequence seq) - { - content = seq; - } + if (obj != null) + return new CrlAnnContent(Asn1Sequence.GetInstance(obj)); - public static CrlAnnContent GetInstance(object obj) - { - if (obj is CrlAnnContent) - return (CrlAnnContent)obj; + return null; + } - if (obj is Asn1Sequence) - return new CrlAnnContent((Asn1Sequence)obj); + private readonly Asn1Sequence m_content; - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + private CrlAnnContent(Asn1Sequence seq) + { + m_content = seq; } - public virtual CertificateList[] ToCertificateListArray() + public CrlAnnContent(CertificateList crl) + { + m_content = new DerSequence(crl); + } + + public virtual CertificateList[] ToCertificateListArray() { - CertificateList[] result = new CertificateList[content.Count]; - for (int i = 0; i != result.Length; ++ i) - { - result[i] = CertificateList.GetInstance(content[i]); - } - return result; + return m_content.MapElements(CertificateList.GetInstance); } /** @@ -46,7 +43,7 @@ public virtual CertificateList[] ToCertificateListArray() */ public override Asn1Object ToAsn1Object() { - return content; + return m_content; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CrlSource.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CrlSource.cs new file mode 100644 index 0000000..9f908bd --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CrlSource.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.X509; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp +{ + /** + * GenMsg: {id-it TBD1}, SEQUENCE SIZE (1..MAX) OF CRLStatus + * GenRep: {id-it TBD2}, SEQUENCE SIZE (1..MAX) OF + * CertificateList | < absent > + *

+ * CRLSource ::= CHOICE { + * dpn [0] DistributionPointName, + * issuer [1] GeneralNames } + *

+ */ + public class CrlSource + : Asn1Encodable, IAsn1Choice + { + public static CrlSource GetInstance(object obj) + { + if (obj is CrlSource crlSource) + return crlSource; + + if (obj != null) + return new CrlSource(Asn1TaggedObject.GetInstance(obj)); + + return null; + } + + private readonly DistributionPointName m_dpn; + private readonly GeneralNames m_issuer; + + private CrlSource(Asn1TaggedObject taggedObject) + { + switch (taggedObject.TagNo) + { + case 0: + m_dpn = DistributionPointName.GetInstance(taggedObject, true); + m_issuer = null; + break; + case 1: + m_dpn = null; + m_issuer = GeneralNames.GetInstance(taggedObject, true); + break; + default: + throw new ArgumentException("unknown tag: " + Asn1Utilities.GetTagText(taggedObject)); + } + } + + public CrlSource(DistributionPointName dpn, GeneralNames issuer) + { + if ((dpn == null) == (issuer == null)) + throw new ArgumentException("either dpn or issuer must be set"); + + m_dpn = dpn; + m_issuer = issuer; + } + + public virtual DistributionPointName Dpn => m_dpn; + + public virtual GeneralNames Issuer => m_issuer; + + public override Asn1Object ToAsn1Object() + { + if (m_dpn != null) + return new DerTaggedObject(true, 0, m_dpn); + + return new DerTaggedObject(true, 1, m_issuer); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CrlSource.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CrlSource.cs.meta new file mode 100644 index 0000000..f267307 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CrlSource.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: afe000dd78e06d0488222d24f2979eb3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CrlStatus.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CrlStatus.cs new file mode 100644 index 0000000..27f97d2 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CrlStatus.cs @@ -0,0 +1,65 @@ +#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.Asn1.Cmp +{ + /** + * CRLStatus ::= SEQUENCE { + * source CRLSource, + * thisUpdate Time OPTIONAL } + */ + public class CrlStatus + : Asn1Encodable + { + public static CrlStatus GetInstance(object obj) + { + if (obj is CrlStatus crlStatus) + return crlStatus; + + if (obj != null) + return new CrlStatus(Asn1Sequence.GetInstance(obj)); + + return null; + } + + private readonly CrlSource m_source; + private readonly Time m_thisUpdate; + + private CrlStatus(Asn1Sequence sequence) + { + int count = sequence.Count; + if (count < 1 || count > 2) + throw new ArgumentException("expected sequence size of 1 or 2, got " + count); + + m_source = CrlSource.GetInstance(sequence[0]); + + if (sequence.Count == 2) + { + m_thisUpdate = Time.GetInstance(sequence[1]); + } + } + + public CrlStatus(CrlSource source, Time thisUpdate) + { + m_source = source; + m_thisUpdate = thisUpdate; + } + + public virtual CrlSource Source => m_source; + + public virtual Time ThisUpdate => m_thisUpdate; + + public override Asn1Object ToAsn1Object() + { + if (m_thisUpdate == null) + return new DerSequence(m_source); + + return new DerSequence(m_source, m_thisUpdate); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CrlStatus.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CrlStatus.cs.meta new file mode 100644 index 0000000..7d895c4 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/CrlStatus.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3052d842bf432244e83cfd2c826ef98b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/DhbmParameter.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/DhbmParameter.cs new file mode 100644 index 0000000..858a59e --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/DhbmParameter.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.X509; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp +{ + /** + * DHBMParameter ::= SEQUENCE { + * owf AlgorithmIdentifier, + * -- AlgId for a One-Way Function (SHA-1 recommended) + * mac AlgorithmIdentifier + * -- the MAC AlgId (e.g., DES-MAC, Triple-DES-MAC [PKCS11], + * } -- or HMAC [RFC2104, RFC2202]) + */ + public class DhbmParameter + : Asn1Encodable + { + public static DhbmParameter GetInstance(object obj) + { + if (obj is DhbmParameter dhbmParameter) + return dhbmParameter; + + if (obj != null) + return new DhbmParameter(Asn1Sequence.GetInstance(obj)); + + return null; + } + + private readonly AlgorithmIdentifier m_owf; + private readonly AlgorithmIdentifier m_mac; + + private DhbmParameter(Asn1Sequence sequence) + { + if (sequence.Count != 2) + throw new ArgumentException("expecting sequence size of 2"); + + m_owf = AlgorithmIdentifier.GetInstance(sequence[0]); + m_mac = AlgorithmIdentifier.GetInstance(sequence[1]); + } + + public DhbmParameter(AlgorithmIdentifier owf, AlgorithmIdentifier mac) + { + m_owf = owf; + m_mac = mac; + } + + public virtual AlgorithmIdentifier Owf => m_owf; + + public virtual AlgorithmIdentifier Mac => m_mac; + + public override Asn1Object ToAsn1Object() + { + return new DerSequence(m_owf, m_mac); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/DhbmParameter.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/DhbmParameter.cs.meta new file mode 100644 index 0000000..b71da34 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/DhbmParameter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 99e6138334c46e04e879fb85b6991bc7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/ErrorMsgContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/ErrorMsgContent.cs index aa8e052..07b304c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/ErrorMsgContent.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/ErrorMsgContent.cs @@ -2,46 +2,55 @@ #pragma warning disable using System; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; - namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp { - public class ErrorMsgContent + /** + *
+     *      ErrorMsgContent ::= SEQUENCE {
+     *          pKIStatusInfo          PKIStatusInfo,
+     *          errorCode              INTEGER           OPTIONAL,
+     *          -- implementation-specific error codes
+     *          errorDetails           PKIFreeText       OPTIONAL
+     *          -- implementation-specific error details
+     *      }
+     * 
+ */ + public class ErrorMsgContent : Asn1Encodable { - private readonly PkiStatusInfo pkiStatusInfo; - private readonly DerInteger errorCode; - private readonly PkiFreeText errorDetails; + public static ErrorMsgContent GetInstance(object obj) + { + if (obj is ErrorMsgContent errorMsgContent) + return errorMsgContent; + + if (obj != null) + return new ErrorMsgContent(Asn1Sequence.GetInstance(obj)); + + return null; + } + + private readonly PkiStatusInfo m_pkiStatusInfo; + private readonly DerInteger m_errorCode; + private readonly PkiFreeText m_errorDetails; private ErrorMsgContent(Asn1Sequence seq) { - pkiStatusInfo = PkiStatusInfo.GetInstance(seq[0]); + m_pkiStatusInfo = PkiStatusInfo.GetInstance(seq[0]); for (int pos = 1; pos < seq.Count; ++pos) { Asn1Encodable ae = seq[pos]; if (ae is DerInteger) { - errorCode = DerInteger.GetInstance(ae); + m_errorCode = DerInteger.GetInstance(ae); } else { - errorDetails = PkiFreeText.GetInstance(ae); + m_errorDetails = PkiFreeText.GetInstance(ae); } } } - public static ErrorMsgContent GetInstance(object obj) - { - if (obj is ErrorMsgContent) - return (ErrorMsgContent)obj; - - if (obj is Asn1Sequence) - return new ErrorMsgContent((Asn1Sequence)obj); - - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); - } - public ErrorMsgContent(PkiStatusInfo pkiStatusInfo) : this(pkiStatusInfo, null, null) { @@ -53,27 +62,18 @@ public ErrorMsgContent( PkiFreeText errorDetails) { if (pkiStatusInfo == null) - throw new ArgumentNullException("pkiStatusInfo"); + throw new ArgumentNullException(nameof(pkiStatusInfo)); - this.pkiStatusInfo = pkiStatusInfo; - this.errorCode = errorCode; - this.errorDetails = errorDetails; - } - - public virtual PkiStatusInfo PkiStatusInfo - { - get { return pkiStatusInfo; } + m_pkiStatusInfo = pkiStatusInfo; + m_errorCode = errorCode; + m_errorDetails = errorDetails; } - public virtual DerInteger ErrorCode - { - get { return errorCode; } - } + public virtual PkiStatusInfo PkiStatusInfo => m_pkiStatusInfo; - public virtual PkiFreeText ErrorDetails - { - get { return errorDetails; } - } + public virtual DerInteger ErrorCode => m_errorCode; + + public virtual PkiFreeText ErrorDetails => m_errorDetails; /** *
@@ -89,8 +89,8 @@ public virtual PkiFreeText ErrorDetails
 		 */
 		public override Asn1Object ToAsn1Object()
 		{
-			Asn1EncodableVector v = new Asn1EncodableVector(pkiStatusInfo);
-			v.AddOptional(errorCode, errorDetails);
+			Asn1EncodableVector v = new Asn1EncodableVector(m_pkiStatusInfo);
+			v.AddOptional(m_errorCode, m_errorDetails);
 			return new DerSequence(v);
 		}
 	}
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/GenMsgContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/GenMsgContent.cs
index 096e7c7..acdf173 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/GenMsgContent.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/GenMsgContent.cs	
@@ -1,45 +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.Asn1.Cmp
 {
-	public class GenMsgContent
+    /**
+     * 
GenMsgContent ::= SEQUENCE OF InfoTypeAndValue
+ */ + public class GenMsgContent : Asn1Encodable { - private readonly Asn1Sequence content; + public static GenMsgContent GetInstance(object obj) + { + if (obj is GenMsgContent genMsgContent) + return genMsgContent; - private GenMsgContent(Asn1Sequence seq) - { - content = seq; - } + if (obj != null) + return new GenMsgContent(Asn1Sequence.GetInstance(obj)); - public static GenMsgContent GetInstance(object obj) - { - if (obj is GenMsgContent) - return (GenMsgContent)obj; + return null; + } - if (obj is Asn1Sequence) - return new GenMsgContent((Asn1Sequence)obj); + private readonly Asn1Sequence m_content; - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + private GenMsgContent(Asn1Sequence seq) + { + m_content = seq; } - public GenMsgContent(params InfoTypeAndValue[] itv) + public GenMsgContent(InfoTypeAndValue itv) + { + m_content = new DerSequence(itv); + } + + public GenMsgContent(params InfoTypeAndValue[] itvs) { - content = new DerSequence(itv); + m_content = new DerSequence(itvs); } public virtual InfoTypeAndValue[] ToInfoTypeAndValueArray() { - InfoTypeAndValue[] result = new InfoTypeAndValue[content.Count]; - for (int i = 0; i != result.Length; ++i) - { - result[i] = InfoTypeAndValue.GetInstance(content[i]); - } - return result; + return m_content.MapElements(InfoTypeAndValue.GetInstance); } /** @@ -50,7 +49,7 @@ public virtual InfoTypeAndValue[] ToInfoTypeAndValueArray() */ public override Asn1Object ToAsn1Object() { - return content; + return m_content; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/GenRepContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/GenRepContent.cs index ff6fa19..50f7296 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/GenRepContent.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/GenRepContent.cs @@ -1,45 +1,41 @@ #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 GenRepContent : Asn1Encodable { - private readonly Asn1Sequence content; + public static GenRepContent GetInstance(object obj) + { + if (obj is GenRepContent genRepContent) + return genRepContent; - private GenRepContent(Asn1Sequence seq) - { - content = seq; - } + if (obj != null) + return new GenRepContent(Asn1Sequence.GetInstance(obj)); - public static GenRepContent GetInstance(object obj) - { - if (obj is GenRepContent) - return (GenRepContent)obj; + return null; + } - if (obj is Asn1Sequence) - return new GenRepContent((Asn1Sequence)obj); + private readonly Asn1Sequence m_content; - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + private GenRepContent(Asn1Sequence seq) + { + m_content = seq; } - public GenRepContent(params InfoTypeAndValue[] itv) + public GenRepContent(InfoTypeAndValue itv) + { + m_content = new DerSequence(itv); + } + + public GenRepContent(params InfoTypeAndValue[] itvs) { - content = new DerSequence(itv); + m_content = new DerSequence(itvs); } public virtual InfoTypeAndValue[] ToInfoTypeAndValueArray() { - InfoTypeAndValue[] result = new InfoTypeAndValue[content.Count]; - for (int i = 0; i != result.Length; ++i) - { - result[i] = InfoTypeAndValue.GetInstance(content[i]); - } - return result; + return m_content.MapElements(InfoTypeAndValue.GetInstance); } /** @@ -50,7 +46,7 @@ public virtual InfoTypeAndValue[] ToInfoTypeAndValueArray() */ public override Asn1Object ToAsn1Object() { - return content; + return m_content; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/InfoTypeAndValue.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/InfoTypeAndValue.cs index c7d2b7b..e004812 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/InfoTypeAndValue.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/InfoTypeAndValue.cs @@ -52,54 +52,47 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp public class InfoTypeAndValue : Asn1Encodable { - private readonly DerObjectIdentifier infoType; - private readonly Asn1Encodable infoValue; + private readonly DerObjectIdentifier m_infoType; + private readonly Asn1Encodable m_infoValue; private InfoTypeAndValue(Asn1Sequence seq) { - infoType = DerObjectIdentifier.GetInstance(seq[0]); + m_infoType = DerObjectIdentifier.GetInstance(seq[0]); if (seq.Count > 1) { - infoValue = (Asn1Encodable)seq[1]; + m_infoValue = seq[1]; } } public static InfoTypeAndValue GetInstance(object obj) { - if (obj is InfoTypeAndValue) - return (InfoTypeAndValue)obj; + if (obj is InfoTypeAndValue infoTypeAndValue) + return infoTypeAndValue; - if (obj is Asn1Sequence) - return new InfoTypeAndValue((Asn1Sequence)obj); + if (obj != null) + return new InfoTypeAndValue(Asn1Sequence.GetInstance(obj)); - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + return null; } - public InfoTypeAndValue( - DerObjectIdentifier infoType) + public InfoTypeAndValue(DerObjectIdentifier infoType) + : this(infoType, null) { - this.infoType = infoType; - this.infoValue = null; } - public InfoTypeAndValue( - DerObjectIdentifier infoType, - Asn1Encodable optionalValue) + public InfoTypeAndValue(DerObjectIdentifier infoType, Asn1Encodable infoValue) { - this.infoType = infoType; - this.infoValue = optionalValue; - } + if (infoType == null) + throw new ArgumentNullException(nameof(infoType)); - public virtual DerObjectIdentifier InfoType - { - get { return infoType; } + m_infoType = infoType; + m_infoValue = infoValue; } - public virtual Asn1Encodable InfoValue - { - get { return infoValue; } - } + public virtual DerObjectIdentifier InfoType => m_infoType; + + public virtual Asn1Encodable InfoValue => m_infoValue; /** *
@@ -112,9 +105,10 @@ public virtual Asn1Encodable InfoValue
          */
         public override Asn1Object ToAsn1Object()
         {
-            Asn1EncodableVector v = new Asn1EncodableVector(infoType);
-            v.AddOptional(infoValue);
-            return new DerSequence(v);
+            if (m_infoValue == null)
+                return new DerSequence(m_infoType);
+
+            return new DerSequence(m_infoType, m_infoValue);
         }
     }
 }
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/KeyRecRepContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/KeyRecRepContent.cs
index 21d0d72..c8cd2bd 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/KeyRecRepContent.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/KeyRecRepContent.cs	
@@ -2,21 +2,30 @@
 #pragma warning disable
 using System;
 
-using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
-
 namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp
 {
 	public class KeyRecRepContent
 		: Asn1Encodable
 	{
-		private readonly PkiStatusInfo status;
-		private readonly CmpCertificate newSigCert;
-		private readonly Asn1Sequence caCerts;
-		private readonly Asn1Sequence keyPairHist;
+        public static KeyRecRepContent GetInstance(object obj)
+        {
+			if (obj is KeyRecRepContent keyRecRepContent)
+				return keyRecRepContent;
+
+			if (obj != null)
+				return new KeyRecRepContent(Asn1Sequence.GetInstance(obj));
+
+			return null;
+        }
+
+        private readonly PkiStatusInfo m_status;
+		private readonly CmpCertificate m_newSigCert;
+		private readonly Asn1Sequence m_caCerts;
+		private readonly Asn1Sequence m_keyPairHist;
 
 		private KeyRecRepContent(Asn1Sequence seq)
 		{
-			status = PkiStatusInfo.GetInstance(seq[0]);
+			m_status = PkiStatusInfo.GetInstance(seq[0]);
 
 			for (int pos = 1; pos < seq.Count; ++pos)
 			{
@@ -24,66 +33,39 @@ private KeyRecRepContent(Asn1Sequence seq)
 
 				switch (tObj.TagNo)
 				{
-					case 0:
-						newSigCert = CmpCertificate.GetInstance(tObj.GetObject());
-						break;
-					case 1:
-						caCerts = Asn1Sequence.GetInstance(tObj.GetObject());
-						break;
-					case 2:
-						keyPairHist = Asn1Sequence.GetInstance(tObj.GetObject());
-						break;
-					default:
-						throw new ArgumentException("unknown tag number: " + tObj.TagNo, "seq");
+				case 0:
+					m_newSigCert = CmpCertificate.GetInstance(tObj.GetObject());
+					break;
+				case 1:
+					m_caCerts = Asn1Sequence.GetInstance(tObj.GetObject());
+					break;
+				case 2:
+					m_keyPairHist = Asn1Sequence.GetInstance(tObj.GetObject());
+					break;
+				default:
+					throw new ArgumentException("unknown tag number: " + tObj.TagNo, "seq");
 				}
 			}
 		}
 
-		public static KeyRecRepContent GetInstance(object obj)
-		{
-			if (obj is KeyRecRepContent)
-				return (KeyRecRepContent)obj;
+		public virtual PkiStatusInfo Status => m_status;
 
-			if (obj is Asn1Sequence)
-				return new KeyRecRepContent((Asn1Sequence)obj);
-
-            throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
-		}
-
-		public virtual PkiStatusInfo Status
-		{
-			get { return status; }
-		}
-
-		public virtual CmpCertificate NewSigCert
-		{
-			get { return newSigCert; }
-		}
+		public virtual CmpCertificate NewSigCert => m_newSigCert;
 
 		public virtual CmpCertificate[] GetCACerts()
 		{
-			if (caCerts == null)
+			if (m_caCerts == null)
 				return null;
 
-			CmpCertificate[] results = new CmpCertificate[caCerts.Count];
-			for (int i = 0; i != results.Length; ++i)
-			{
-				results[i] = CmpCertificate.GetInstance(caCerts[i]);
-			}
-			return results;
+			return m_caCerts.MapElements(CmpCertificate.GetInstance);
 		}
 
 		public virtual CertifiedKeyPair[] GetKeyPairHist()
 		{
-			if (keyPairHist == null)
+			if (m_keyPairHist == null)
 				return null;
 
-			CertifiedKeyPair[] results = new CertifiedKeyPair[keyPairHist.Count];
-			for (int i = 0; i != results.Length; ++i)
-			{
-				results[i] = CertifiedKeyPair.GetInstance(keyPairHist[i]);
-			}
-			return results;
+			return m_keyPairHist.MapElements(CertifiedKeyPair.GetInstance);
 		}
 
 		/**
@@ -101,10 +83,10 @@ public virtual CertifiedKeyPair[] GetKeyPairHist()
 		 */
 		public override Asn1Object ToAsn1Object()
 		{
-			Asn1EncodableVector v = new Asn1EncodableVector(status);
-            v.AddOptionalTagged(true, 0, newSigCert);
-            v.AddOptionalTagged(true, 1, caCerts);
-            v.AddOptionalTagged(true, 2, keyPairHist);
+			Asn1EncodableVector v = new Asn1EncodableVector(m_status);
+            v.AddOptionalTagged(true, 0, m_newSigCert);
+            v.AddOptionalTagged(true, 1, m_caCerts);
+            v.AddOptionalTagged(true, 2, m_keyPairHist);
 			return new DerSequence(v);
 		}
 	}
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/NestedMessageContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/NestedMessageContent.cs
new file mode 100644
index 0000000..87d5a24
--- /dev/null
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/NestedMessageContent.cs	
@@ -0,0 +1,39 @@
+#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
+#pragma warning disable
+namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp
+{
+    /**
+     * NestedMessageContent ::= PKIMessages
+     */
+    public class NestedMessageContent
+        : PkiMessages
+    {
+        public static new NestedMessageContent GetInstance(object obj)
+        {
+            if (obj is NestedMessageContent nestedMessageContent)
+                return nestedMessageContent;
+
+            if (obj != null)
+                return new NestedMessageContent(Asn1Sequence.GetInstance(obj));
+
+            return null;
+        }
+
+        public NestedMessageContent(PkiMessage msg)
+            : base(msg)
+        {
+        }
+
+        public NestedMessageContent(PkiMessage[] msgs)
+            : base(msgs)
+        {
+        }
+
+        public NestedMessageContent(Asn1Sequence seq)
+            : base(seq)
+        {
+        }
+    }
+}
+#pragma warning restore
+#endif
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/NestedMessageContent.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/NestedMessageContent.cs.meta
new file mode 100644
index 0000000..7b72a34
--- /dev/null
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/NestedMessageContent.cs.meta	
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1d5b9fe9255383040a52bb7e4465d3e5
+MonoImporter:
+  externalObjects: {}
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/OobCert.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/OobCert.cs
new file mode 100644
index 0000000..c2e1e1d
--- /dev/null
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/OobCert.cs	
@@ -0,0 +1,72 @@
+#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.Cmp
+{
+    /**
+     * OOBCert ::= CMPCertificate
+     */
+    public class OobCert
+        : CmpCertificate
+    {
+        public static new OobCert GetInstance(object obj)
+        {
+            if (obj == null)
+                return null;
+
+            if (obj is OobCert oobCert)
+                return oobCert;
+
+            if (obj is CmpCertificate cmpCertificate)
+                return GetInstance(cmpCertificate.GetEncoded());
+
+            if (obj is byte[] bs)
+            {
+                try
+                {
+                    obj = Asn1Object.FromByteArray(bs);
+                }
+                catch (IOException)
+                {
+                    throw new ArgumentException("Invalid encoding in OobCert");
+                }
+            }
+
+            if (obj is Asn1Sequence seq)
+                return new OobCert(X509CertificateStructure.GetInstance(obj));
+
+            if (obj is Asn1TaggedObject taggedObject)
+                return new OobCert(taggedObject.TagNo, taggedObject.GetObject());
+
+            throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), nameof(obj));
+        }
+
+        public static new OobCert GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit)
+        {
+            if (taggedObject == null)
+                return null;
+
+            if (!declaredExplicit)
+                throw new ArgumentException("tag must be explicit");
+
+            return GetInstance(taggedObject.GetObject());
+        }
+
+        public OobCert(int type, Asn1Encodable otherCert)
+            : base(type, otherCert)
+        {
+        }
+
+        public OobCert(X509CertificateStructure x509v3PKCert)
+            : base(x509v3PKCert)
+        {
+        }
+    }
+}
+#pragma warning restore
+#endif
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/OobCert.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/OobCert.cs.meta
new file mode 100644
index 0000000..fb69ef2
--- /dev/null
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/OobCert.cs.meta	
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1a4a3d68d7cd11b4f81f94409f6b94be
+MonoImporter:
+  externalObjects: {}
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/OobCertHash.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/OobCertHash.cs
index c0d5ab5..f1d8dcc 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/OobCertHash.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/OobCertHash.cs	
@@ -8,18 +8,40 @@
 
 namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp
 {
-	public class OobCertHash
+    /**
+     * 
+     * OOBCertHash ::= SEQUENCE {
+     * hashAlg     [0] AlgorithmIdentifier     OPTIONAL,
+     * certId      [1] CertId                  OPTIONAL,
+     * hashVal         BIT STRING
+     * -- hashVal is calculated over the DER encoding of the
+     * -- self-signed certificate with the identifier certID.
+     * }
+     * 
+ */ + public class OobCertHash : Asn1Encodable { - private readonly AlgorithmIdentifier hashAlg; - private readonly CertId certId; - private readonly DerBitString hashVal; + public static OobCertHash GetInstance(object obj) + { + if (obj is OobCertHash oobCertHash) + return oobCertHash; + + if (obj != null) + return new OobCertHash(Asn1Sequence.GetInstance(obj)); + + return null; + } + + private readonly AlgorithmIdentifier m_hashAlg; + private readonly CertId m_certId; + private readonly DerBitString m_hashVal; private OobCertHash(Asn1Sequence seq) { int index = seq.Count - 1; - hashVal = DerBitString.GetInstance(seq[index--]); + m_hashVal = DerBitString.GetInstance(seq[index--]); for (int i = index; i >= 0; i--) { @@ -27,36 +49,21 @@ private OobCertHash(Asn1Sequence seq) if (tObj.TagNo == 0) { - hashAlg = AlgorithmIdentifier.GetInstance(tObj, true); + m_hashAlg = AlgorithmIdentifier.GetInstance(tObj, true); } else { - certId = CertId.GetInstance(tObj, true); + m_certId = CertId.GetInstance(tObj, true); } } } - public static OobCertHash GetInstance(object obj) - { - if (obj is OobCertHash) - return (OobCertHash)obj; + public virtual CertId CertID => m_certId; - if (obj is Asn1Sequence) - return new OobCertHash((Asn1Sequence)obj); + public virtual AlgorithmIdentifier HashAlg => m_hashAlg; + + public virtual DerBitString HashVal => m_hashVal; - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); - } - - public virtual AlgorithmIdentifier HashAlg - { - get { return hashAlg; } - } - - public virtual CertId CertID - { - get { return certId; } - } - /** *
 		 * OobCertHash ::= SEQUENCE {
@@ -72,9 +79,9 @@ public virtual CertId CertID
 		public override Asn1Object ToAsn1Object()
 		{
 			Asn1EncodableVector v = new Asn1EncodableVector();
-            v.AddOptionalTagged(true, 0, hashAlg);
-            v.AddOptionalTagged(true, 1, certId);
-			v.Add(hashVal);
+            v.AddOptionalTagged(true, 0, m_hashAlg);
+            v.AddOptionalTagged(true, 1, m_certId);
+			v.Add(m_hashVal);
 			return new DerSequence(v);
 		}
 	}
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIBody.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIBody.cs
index 0ed2ad9..5f49ff0 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIBody.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIBody.cs	
@@ -8,6 +8,37 @@
 
 namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp
 {
+    /**
+     * PKIBody ::= CHOICE {       -- message-specific body elements
+     *          ir       [0]  CertReqMessages,        --Initialization Request
+     *          ip       [1]  CertRepMessage,         --Initialization Response
+     *          cr       [2]  CertReqMessages,        --Certification Request
+     *          cp       [3]  CertRepMessage,         --Certification Response
+     *          p10cr    [4]  CertificationRequest,   --imported from [PKCS10]
+     *          popdecc  [5]  POPODecKeyChallContent, --pop Challenge
+     *          popdecr  [6]  POPODecKeyRespContent,  --pop Response
+     *          kur      [7]  CertReqMessages,        --Key Update Request
+     *          kup      [8]  CertRepMessage,         --Key Update Response
+     *          krr      [9]  CertReqMessages,        --Key Recovery Request
+     *          krp      [10] KeyRecRepContent,       --Key Recovery Response
+     *          rr       [11] RevReqContent,          --Revocation Request
+     *          rp       [12] RevRepContent,          --Revocation Response
+     *          ccr      [13] CertReqMessages,        --Cross-Cert. Request
+     *          ccp      [14] CertRepMessage,         --Cross-Cert. Response
+     *          ckuann   [15] CAKeyUpdAnnContent,     --CA Key Update Ann.
+     *          cann     [16] CertAnnContent,         --Certificate Ann.
+     *          rann     [17] RevAnnContent,          --Revocation Ann.
+     *          crlann   [18] CRLAnnContent,          --CRL Announcement
+     *          pkiconf  [19] PKIConfirmContent,      --Confirmation
+     *          nested   [20] NestedMessageContent,   --Nested Message
+     *          genm     [21] GenMsgContent,          --General Message
+     *          genp     [22] GenRepContent,          --General Response
+     *          error    [23] ErrorMsgContent,        --Error Message
+     *          certConf [24] CertConfirmContent,     --Certificate confirm
+     *          pollReq  [25] PollReqContent,         --Polling request
+     *          pollRep  [26] PollRepContent          --Polling response
+     *      }
+     */
     public class PkiBody
         : Asn1Encodable, IAsn1Choice
     {
@@ -39,24 +70,27 @@ public class PkiBody
         public const int TYPE_POLL_REQ = 25;
         public const int TYPE_POLL_REP = 26;
 
-        private int tagNo;
-        private Asn1Encodable body;
-
         public static PkiBody GetInstance(object obj)
         {
-            if (obj is PkiBody)
-                return (PkiBody)obj;
+            if (obj == null)
+                return null;
+
+            if (obj is PkiBody pkiBody)
+                return pkiBody;
 
-            if (obj is Asn1TaggedObject)
-                return new PkiBody((Asn1TaggedObject)obj);
+            if (obj is Asn1TaggedObject taggedObject)
+                return new PkiBody(taggedObject);
 
-            throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+            throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), nameof(obj));
         }
 
-        private PkiBody(Asn1TaggedObject tagged)
+        private readonly int m_tagNo;
+        private readonly Asn1Encodable m_body;
+
+        private PkiBody(Asn1TaggedObject taggedObject)
         {
-            tagNo = tagged.TagNo;
-            body = GetBodyForType(tagNo, tagged.GetObject());
+            m_tagNo = taggedObject.TagNo;
+            m_body = GetBodyForType(m_tagNo, taggedObject.GetObject());
         }
 
         /**
@@ -64,88 +98,78 @@ private PkiBody(Asn1TaggedObject tagged)
          * @param type one of the TYPE_* constants
          * @param content message content
          */
-        public PkiBody(
-            int type,
-            Asn1Encodable content)
+        public PkiBody(int type, Asn1Encodable content)
         {
-            tagNo = type;
-            body = GetBodyForType(type, content);
+            m_tagNo = type;
+            m_body = GetBodyForType(type, content);
         }
 
-        private static Asn1Encodable GetBodyForType(
-            int type,
-            Asn1Encodable o)
+        private static Asn1Encodable GetBodyForType(int type, Asn1Encodable o)
         {
             switch (type)
             {
-                case TYPE_INIT_REQ:
-                    return CertReqMessages.GetInstance(o);
-	            case TYPE_INIT_REP:
-	                return CertRepMessage.GetInstance(o);
-                case TYPE_CERT_REQ:
-                    return CertReqMessages.GetInstance(o);
-	            case TYPE_CERT_REP:
-	                return CertRepMessage.GetInstance(o);
-	            case TYPE_P10_CERT_REQ:
-	                return CertificationRequest.GetInstance(o);
-	            case TYPE_POPO_CHALL:
-	                return PopoDecKeyChallContent.GetInstance(o);
-	            case TYPE_POPO_REP:
-	                return PopoDecKeyRespContent.GetInstance(o);
-                case TYPE_KEY_UPDATE_REQ:
-                    return CertReqMessages.GetInstance(o);
-	            case TYPE_KEY_UPDATE_REP:
-	                return CertRepMessage.GetInstance(o);
-                case TYPE_KEY_RECOVERY_REQ:
-                    return CertReqMessages.GetInstance(o);
-	            case TYPE_KEY_RECOVERY_REP:
-	                return KeyRecRepContent.GetInstance(o);
-	            case TYPE_REVOCATION_REQ:
-	                return RevReqContent.GetInstance(o);
-	            case TYPE_REVOCATION_REP:
-	                return RevRepContent.GetInstance(o);
-                case TYPE_CROSS_CERT_REQ:
-                    return CertReqMessages.GetInstance(o);
-	            case TYPE_CROSS_CERT_REP:
-	                return CertRepMessage.GetInstance(o);
-	            case TYPE_CA_KEY_UPDATE_ANN:
-	                return CAKeyUpdAnnContent.GetInstance(o);
-	            case TYPE_CERT_ANN:
-	                return CmpCertificate.GetInstance(o);
-	            case TYPE_REVOCATION_ANN:
-	                return RevAnnContent.GetInstance(o);
-	            case TYPE_CRL_ANN:
-	                return CrlAnnContent.GetInstance(o);
-	            case TYPE_CONFIRM:
-	                return PkiConfirmContent.GetInstance(o);
-                case TYPE_NESTED:
-                    return PkiMessages.GetInstance(o);
-	            case TYPE_GEN_MSG:
-	                return GenMsgContent.GetInstance(o);
-	            case TYPE_GEN_REP:
-	                return GenRepContent.GetInstance(o);
-	            case TYPE_ERROR:
-	                return ErrorMsgContent.GetInstance(o);
-	            case TYPE_CERT_CONFIRM:
-	                return CertConfirmContent.GetInstance(o);
-	            case TYPE_POLL_REQ:
-	                return PollReqContent.GetInstance(o);
-	            case TYPE_POLL_REP:
-	                return PollRepContent.GetInstance(o);
-	            default:
-	                throw new ArgumentException("unknown tag number: " + type, "type");
+            case TYPE_INIT_REQ:
+                return CertReqMessages.GetInstance(o);
+            case TYPE_INIT_REP:
+                return CertRepMessage.GetInstance(o);
+            case TYPE_CERT_REQ:
+                return CertReqMessages.GetInstance(o);
+            case TYPE_CERT_REP:
+                return CertRepMessage.GetInstance(o);
+            case TYPE_P10_CERT_REQ:
+                return CertificationRequest.GetInstance(o);
+            case TYPE_POPO_CHALL:
+                return PopoDecKeyChallContent.GetInstance(o);
+            case TYPE_POPO_REP:
+                return PopoDecKeyRespContent.GetInstance(o);
+            case TYPE_KEY_UPDATE_REQ:
+                return CertReqMessages.GetInstance(o);
+            case TYPE_KEY_UPDATE_REP:
+                return CertRepMessage.GetInstance(o);
+            case TYPE_KEY_RECOVERY_REQ:
+                return CertReqMessages.GetInstance(o);
+            case TYPE_KEY_RECOVERY_REP:
+                return KeyRecRepContent.GetInstance(o);
+            case TYPE_REVOCATION_REQ:
+                return RevReqContent.GetInstance(o);
+            case TYPE_REVOCATION_REP:
+                return RevRepContent.GetInstance(o);
+            case TYPE_CROSS_CERT_REQ:
+                return CertReqMessages.GetInstance(o);
+            case TYPE_CROSS_CERT_REP:
+                return CertRepMessage.GetInstance(o);
+            case TYPE_CA_KEY_UPDATE_ANN:
+                return CAKeyUpdAnnContent.GetInstance(o);
+            case TYPE_CERT_ANN:
+                return CmpCertificate.GetInstance(o);
+            case TYPE_REVOCATION_ANN:
+                return RevAnnContent.GetInstance(o);
+            case TYPE_CRL_ANN:
+                return CrlAnnContent.GetInstance(o);
+            case TYPE_CONFIRM:
+                return PkiConfirmContent.GetInstance(o);
+            case TYPE_NESTED:
+                return PkiMessages.GetInstance(o);
+            case TYPE_GEN_MSG:
+                return GenMsgContent.GetInstance(o);
+            case TYPE_GEN_REP:
+                return GenRepContent.GetInstance(o);
+            case TYPE_ERROR:
+                return ErrorMsgContent.GetInstance(o);
+            case TYPE_CERT_CONFIRM:
+                return CertConfirmContent.GetInstance(o);
+            case TYPE_POLL_REQ:
+                return PollReqContent.GetInstance(o);
+            case TYPE_POLL_REP:
+                return PollRepContent.GetInstance(o);
+            default:
+	            throw new ArgumentException("unknown tag number: " + type, nameof(type));
             }
         }
 
-        public virtual int Type
-        {
-            get { return tagNo; }
-        }
+        public virtual Asn1Encodable Content => m_body;
 
-        public virtual Asn1Encodable Content
-        {
-            get { return body; }
-        }
+        public virtual int Type => m_tagNo;
 
         /**
          * 
@@ -183,7 +207,7 @@ public virtual Asn1Encodable Content
          */
         public override Asn1Object ToAsn1Object()
         {
-            return new DerTaggedObject(true, tagNo, body);
+            return new DerTaggedObject(true, m_tagNo, m_body);
         }
     }
 }
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIConfirmContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIConfirmContent.cs
index c799519..93508be 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIConfirmContent.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIConfirmContent.cs	
@@ -6,24 +6,38 @@
 
 namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp
 {
-	public class PkiConfirmContent
+    /**
+     *  PKIConfirmContent ::= NULL
+     */
+    public class PkiConfirmContent
 		: Asn1Encodable
 	{
 		public static PkiConfirmContent GetInstance(object obj)
 		{
-			if (obj is PkiConfirmContent)
-				return (PkiConfirmContent)obj;
+			if (obj == null)
+				return null;
 
-			if (obj is Asn1Null)
-				return new PkiConfirmContent();
+			if (obj is PkiConfirmContent pkiConfirmContent)
+				return pkiConfirmContent;
 
-            throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
-		}
+			if (obj is Asn1Null asn1Null)
+				return new PkiConfirmContent(asn1Null);
 
-		public PkiConfirmContent()
-		{
+            throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), nameof(obj));
 		}
 
+        private readonly Asn1Null m_val;
+
+        public PkiConfirmContent()
+            : this(DerNull.Instance)
+        {
+        }
+
+        private PkiConfirmContent(Asn1Null val)
+        {
+            m_val = val;
+        }
+
 		/**
 		 * 
 		 * PkiConfirmContent ::= NULL
@@ -32,7 +46,7 @@ public PkiConfirmContent()
 		 */
 		public override Asn1Object ToAsn1Object()
 		{
-			return DerNull.Instance;
+			return m_val;
 		}
 	}
 }
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIFailureInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIFailureInfo.cs
index f55d119..2f762ac 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIFailureInfo.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIFailureInfo.cs	
@@ -23,7 +23,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp
      * certRevoked         (10),
      * certConfirmed       (11),
      * wrongIntegrity      (12),
-     * badRecipientNonce   (13), 
+     * badRecipientNonce   (13),
      * timeNotAvailable    (14),
      *   -- the TSA's time source is not available
      * unacceptedPolicy    (15),
@@ -39,13 +39,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp
      * transactionIdInUse  (21),
      * unsupportedVersion  (22),
      * notAuthorized       (23),
-     * systemUnavail       (24),    
+     * systemUnavail       (24),
      * systemFailure       (25),
      *   -- the request cannot be handled due to system failure
-     * duplicateCertReq    (26) 
+     * duplicateCertReq    (26)
      * 
*/ - public class PkiFailureInfo + public class PkiFailureInfo : DerBitString { public const int BadAlg = (1 << 7); // unrecognized or unsupported Algorithm Identifier diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIFreeText.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIFreeText.cs index 32c15fc..94c9f41 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIFreeText.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIFreeText.cs @@ -1,75 +1,68 @@ #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) + public static PkiFreeText GetInstance(object obj) { - return GetInstance(Asn1Sequence.GetInstance(obj, isExplicit)); - } + if (obj is PkiFreeText pkiFreeText) + return pkiFreeText; - public static PkiFreeText GetInstance( - object obj) - { - if (obj is PkiFreeText) - { - return (PkiFreeText)obj; - } - else if (obj is Asn1Sequence) - { - return new PkiFreeText((Asn1Sequence)obj); - } + if (obj != null) + return new PkiFreeText(Asn1Sequence.GetInstance(obj)); - throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + return null; } - public PkiFreeText( - Asn1Sequence seq) + public static PkiFreeText GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) + { + return GetInstance(Asn1Sequence.GetInstance(taggedObject, declaredExplicit)); + } + + internal Asn1Sequence m_strings; + + internal PkiFreeText(Asn1Sequence seq) { - foreach (object o in seq) + foreach (var element in seq) { - if (!(o is DerUtf8String)) - { + if (!(element is DerUtf8String)) throw new ArgumentException("attempt to insert non UTF8 STRING into PkiFreeText"); - } } - this.strings = seq; + m_strings = seq; } - public PkiFreeText( - DerUtf8String p) + public PkiFreeText(DerUtf8String p) { - strings = new DerSequence(p); + m_strings = new DerSequence(p); } - /** - * Return the number of string elements present. - * - * @return number of elements present. - */ + public PkiFreeText(string p) + : this(new DerUtf8String(p)) + { + } - public int Size + public PkiFreeText(DerUtf8String[] strs) { - get { return strings.Count; } + m_strings = new DerSequence(strs); } - public int Count + public PkiFreeText(string[] strs) { - get { return strings.Count; } + Asn1EncodableVector v = new Asn1EncodableVector(strs.Length); + for (int i = 0; i < strs.Length; i++) + { + v.Add(new DerUtf8String(strs[i])); + } + m_strings = new DerSequence(v); } + public virtual int Count => m_strings.Count; + /** * Return the UTF8STRING at index. * @@ -78,14 +71,7 @@ public int Count */ public DerUtf8String this[int index] { - get { return (DerUtf8String) strings[index]; } - } - - - public DerUtf8String GetStringAt( - int index) - { - return this[index]; + get { return (DerUtf8String)m_strings[index]; } } /** @@ -95,7 +81,7 @@ public DerUtf8String GetStringAt( */ public override Asn1Object ToAsn1Object() { - return strings; + return m_strings; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIHeader.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIHeader.cs index 0c5697f..85bb50d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIHeader.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIHeader.cs @@ -21,7 +21,7 @@ public class PkiHeader private readonly DerInteger pvno; private readonly GeneralName sender; private readonly GeneralName recipient; - private readonly DerGeneralizedTime messageTime; + private readonly Asn1GeneralizedTime messageTime; private readonly AlgorithmIdentifier protectionAlg; private readonly Asn1OctetString senderKID; // KeyIdentifier private readonly Asn1OctetString recipKID; // KeyIdentifier @@ -43,35 +43,35 @@ private PkiHeader(Asn1Sequence seq) switch (tObj.TagNo) { - case 0: - messageTime = DerGeneralizedTime.GetInstance(tObj, true); - break; - case 1: - protectionAlg = AlgorithmIdentifier.GetInstance(tObj, true); - break; - case 2: - senderKID = Asn1OctetString.GetInstance(tObj, true); - break; - case 3: - recipKID = Asn1OctetString.GetInstance(tObj, true); - break; - case 4: - transactionID = Asn1OctetString.GetInstance(tObj, true); - break; - case 5: - senderNonce = Asn1OctetString.GetInstance(tObj, true); - break; - case 6: - recipNonce = Asn1OctetString.GetInstance(tObj, true); - break; - case 7: - freeText = PkiFreeText.GetInstance(tObj, true); - break; - case 8: - generalInfo = Asn1Sequence.GetInstance(tObj, true); - break; - default: - throw new ArgumentException("unknown tag number: " + tObj.TagNo, "seq"); + case 0: + messageTime = Asn1GeneralizedTime.GetInstance(tObj, true); + break; + case 1: + protectionAlg = AlgorithmIdentifier.GetInstance(tObj, true); + break; + case 2: + senderKID = Asn1OctetString.GetInstance(tObj, true); + break; + case 3: + recipKID = Asn1OctetString.GetInstance(tObj, true); + break; + case 4: + transactionID = Asn1OctetString.GetInstance(tObj, true); + break; + case 5: + senderNonce = Asn1OctetString.GetInstance(tObj, true); + break; + case 6: + recipNonce = Asn1OctetString.GetInstance(tObj, true); + break; + case 7: + freeText = PkiFreeText.GetInstance(tObj, true); + break; + case 8: + generalInfo = Asn1Sequence.GetInstance(tObj, true); + break; + default: + throw new ArgumentException("unknown tag number: " + tObj.TagNo, nameof(seq)); } } } @@ -84,7 +84,7 @@ public static PkiHeader GetInstance(object obj) if (obj is Asn1Sequence) return new PkiHeader((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public PkiHeader( @@ -120,7 +120,7 @@ public virtual GeneralName Recipient get { return recipient; } } - public virtual DerGeneralizedTime MessageTime + public virtual Asn1GeneralizedTime MessageTime { get { return messageTime; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIHeaderBuilder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIHeaderBuilder.cs index b341928..70c79b1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIHeaderBuilder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIHeaderBuilder.cs @@ -11,7 +11,7 @@ public class PkiHeaderBuilder private DerInteger pvno; private GeneralName sender; private GeneralName recipient; - private DerGeneralizedTime messageTime; + private Asn1GeneralizedTime messageTime; private AlgorithmIdentifier protectionAlg; private Asn1OctetString senderKID; // KeyIdentifier private Asn1OctetString recipKID; // KeyIdentifier @@ -39,7 +39,7 @@ private PkiHeaderBuilder( this.recipient = recipient; } - public virtual PkiHeaderBuilder SetMessageTime(DerGeneralizedTime time) + public virtual PkiHeaderBuilder SetMessageTime(Asn1GeneralizedTime time) { messageTime = time; return this; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIMessages.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIMessages.cs index 0eee398..9719ab9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIMessages.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIMessages.cs @@ -11,7 +11,7 @@ public class PkiMessages { private Asn1Sequence content; - private PkiMessages(Asn1Sequence seq) + internal PkiMessages(Asn1Sequence seq) { content = seq; } @@ -24,7 +24,7 @@ public static PkiMessages GetInstance(object obj) if (obj is Asn1Sequence) return new PkiMessages((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public PkiMessages(params PkiMessage[] msgs) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIStatus.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIStatus.cs index da591a6..406f35e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIStatus.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIStatus.cs @@ -49,7 +49,7 @@ public static PkiStatusEncodable GetInstance(object obj) if (obj is DerInteger) return new PkiStatusEncodable((DerInteger)obj); - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public virtual BigInteger Value diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIStatusInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIStatusInfo.cs index 643bc75..e9fd17f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIStatusInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PKIStatusInfo.cs @@ -33,7 +33,7 @@ public static PkiStatusInfo GetInstance( return new PkiStatusInfo((Asn1Sequence)obj); } - throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public PkiStatusInfo( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PbmParameter.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PbmParameter.cs index b242734..1acc555 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PbmParameter.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PbmParameter.cs @@ -3,77 +3,74 @@ using System; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp { + /** + * 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]) + */ public class PbmParameter : Asn1Encodable { - private Asn1OctetString salt; - private AlgorithmIdentifier owf; - private DerInteger iterationCount; - private AlgorithmIdentifier mac; - - private PbmParameter(Asn1Sequence seq) - { - salt = Asn1OctetString.GetInstance(seq[0]); - owf = AlgorithmIdentifier.GetInstance(seq[1]); - iterationCount = DerInteger.GetInstance(seq[2]); - mac = AlgorithmIdentifier.GetInstance(seq[3]); - } - public static PbmParameter GetInstance(object obj) { - if (obj is PbmParameter) - return (PbmParameter)obj; + if (obj is PbmParameter pbmParameter) + return pbmParameter; - if (obj is Asn1Sequence) - return new PbmParameter((Asn1Sequence)obj); + if (obj != null) + return new PbmParameter(Asn1Sequence.GetInstance(obj)); - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + return null; } - public PbmParameter( - byte[] salt, - AlgorithmIdentifier owf, - int iterationCount, - AlgorithmIdentifier mac) - : this(new DerOctetString(salt), owf, new DerInteger(iterationCount), mac) - { - } + private readonly Asn1OctetString m_salt; + private readonly AlgorithmIdentifier m_owf; + private readonly DerInteger m_iterationCount; + private readonly AlgorithmIdentifier m_mac; - public PbmParameter( - Asn1OctetString salt, - AlgorithmIdentifier owf, - DerInteger iterationCount, - AlgorithmIdentifier mac) + private PbmParameter(Asn1Sequence seq) { - this.salt = salt; - this.owf = owf; - this.iterationCount = iterationCount; - this.mac = mac; + m_salt = Asn1OctetString.GetInstance(seq[0]); + m_owf = AlgorithmIdentifier.GetInstance(seq[1]); + m_iterationCount = DerInteger.GetInstance(seq[2]); + m_mac = AlgorithmIdentifier.GetInstance(seq[3]); } - public virtual Asn1OctetString Salt + public PbmParameter(byte[] salt, AlgorithmIdentifier owf, int iterationCount, AlgorithmIdentifier mac) + : this(new DerOctetString(salt), owf, new DerInteger(iterationCount), mac) { - get { return salt; } } - public virtual AlgorithmIdentifier Owf + public PbmParameter(Asn1OctetString salt, AlgorithmIdentifier owf, DerInteger iterationCount, + AlgorithmIdentifier mac) { - get { return owf; } + m_salt = salt; + m_owf = owf; + m_iterationCount = iterationCount; + m_mac = mac; } - public virtual DerInteger IterationCount - { - get { return iterationCount; } - } + public virtual DerInteger IterationCount => m_iterationCount; - public virtual AlgorithmIdentifier Mac - { - get { return mac; } - } + public virtual AlgorithmIdentifier Mac => m_mac; + + public virtual AlgorithmIdentifier Owf => m_owf; + + public virtual Asn1OctetString Salt => m_salt; /** *
@@ -97,7 +94,7 @@ public virtual AlgorithmIdentifier Mac
          */
         public override Asn1Object ToAsn1Object()
         {
-            return new DerSequence(salt, owf, iterationCount, mac);
+            return new DerSequence(m_salt, m_owf, m_iterationCount, m_mac);
         }
     }
 }
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PollRepContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PollRepContent.cs
index c383c97..d344d56 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PollRepContent.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PollRepContent.cs	
@@ -1,73 +1,71 @@
 #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 PollRepContent
+    /**
+     * PollRepContent ::= SEQUENCE OF SEQUENCE {
+     * certReqId    INTEGER,
+     * checkAfter   INTEGER,  -- time in seconds
+     * reason       PKIFreeText OPTIONAL }
+     */
+    public class PollRepContent
 		: Asn1Encodable
 	{
-		private readonly DerInteger certReqId;
-		private readonly DerInteger checkAfter;
-		private readonly PkiFreeText reason;
+        public static PollRepContent GetInstance(object obj)
+        {
+			if (obj is PollRepContent pollRepContent)
+				return pollRepContent;
+
+			if (obj != null)
+				return new PollRepContent(Asn1Sequence.GetInstance(obj));
+
+			return null;
+        }
+
+        private readonly DerInteger[] m_certReqID;
+		private readonly DerInteger[] m_checkAfter;
+		private readonly PkiFreeText[] m_reason;
 
 		private PollRepContent(Asn1Sequence seq)
 		{
-			certReqId = DerInteger.GetInstance(seq[0]);
-			checkAfter = DerInteger.GetInstance(seq[1]);
+			int count = seq.Count;
+			m_certReqID = new DerInteger[count];
+			m_checkAfter = new DerInteger[count];
+			m_reason = new PkiFreeText[count];
 
-			if (seq.Count > 2)
+			for (int i = 0; i != count; i++)
 			{
-				reason = PkiFreeText.GetInstance(seq[2]);
-			}
-		}
-
-		public static PollRepContent GetInstance(object obj)
-		{
-			if (obj is PollRepContent)
-				return (PollRepContent)obj;
+				Asn1Sequence s = Asn1Sequence.GetInstance(seq[i]);
 
-			if (obj is Asn1Sequence)
-				return new PollRepContent((Asn1Sequence)obj);
+				m_certReqID[i] = DerInteger.GetInstance(s[0]);
+				m_checkAfter[i] = DerInteger.GetInstance(s[1]);
 
-            throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+				if (s.Count > 2)
+				{
+					m_reason[i] = PkiFreeText.GetInstance(s[2]);
+				}
+			}
 		}
 
-	    public PollRepContent(
-	        DerInteger certReqId,
-	        DerInteger checkAfter)
+	    public PollRepContent(DerInteger certReqID, DerInteger checkAfter)
+			: this(certReqID, checkAfter, null)
 	    {
-	        this.certReqId = certReqId;
-	        this.checkAfter = checkAfter;
-	        this.reason = null;
 	    }
 
-        public PollRepContent(
-	        DerInteger certReqId,
-	        DerInteger checkAfter,
-	        PkiFreeText reason)
+        public PollRepContent(DerInteger certReqID, DerInteger checkAfter, PkiFreeText reason)
 	    {
-	        this.certReqId = certReqId;
-	        this.checkAfter = checkAfter;
-	        this.reason = reason;
-	    }
+            m_certReqID = new DerInteger[1]{ certReqID };
+            m_checkAfter = new DerInteger[1]{ checkAfter };
+            m_reason = new PkiFreeText[1]{ reason };
+        }
 
-		public virtual DerInteger CertReqID
-		{
-			get { return certReqId; }
-		}
+        public virtual int Count => m_certReqID.Length;
 
-		public virtual DerInteger CheckAfter
-		{
-			get { return checkAfter; }
-		}
+        public virtual DerInteger GetCertReqID(int index) => m_certReqID[index];
 
-		public virtual PkiFreeText Reason
-		{
-			get { return reason; }
-		}
+		public virtual DerInteger GetCheckAfter(int index) => m_checkAfter[index];
+
+		public virtual PkiFreeText GetReason(int index) => m_reason[index];
 
 		/**
 		 * 
@@ -81,9 +79,20 @@ public virtual PkiFreeText Reason
 		 */
 		public override Asn1Object ToAsn1Object()
 		{
-			Asn1EncodableVector v = new Asn1EncodableVector(certReqId, checkAfter);
-			v.AddOptional(reason);
-			return new DerSequence(v);
+			Asn1EncodableVector outer = new Asn1EncodableVector(m_certReqID.Length);
+
+			for (int i = 0; i != m_certReqID.Length; i++)
+			{
+				Asn1EncodableVector v = new Asn1EncodableVector(3);
+
+				v.Add(m_certReqID[i]);
+				v.Add(m_checkAfter[i]);
+				v.AddOptional(m_reason[i]);
+
+				outer.Add(new DerSequence(v));
+			}
+
+			return new DerSequence(outer);
 		}
 	}
 }
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PollReqContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PollReqContent.cs
index 0ac731b..6761677 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PollReqContent.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PollReqContent.cs	
@@ -1,53 +1,93 @@
 #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.Math;
 
 namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp
 {
 	public class PollReqContent
 		: Asn1Encodable
 	{
-		private readonly Asn1Sequence content;
+        public static PollReqContent GetInstance(object obj)
+        {
+			if (obj is PollReqContent pollReqContent)
+				return pollReqContent;
+
+			if (obj != null)
+				return new PollReqContent(Asn1Sequence.GetInstance(obj));
+
+			return null;
+        }
+
+        private readonly Asn1Sequence m_content;
 
 		private PollReqContent(Asn1Sequence seq)
 		{
-			content = seq;
+			m_content = seq;
 		}
 
-		public static PollReqContent GetInstance(object obj)
+		/**
+		 * Create a pollReqContent for a single certReqId.
+		 *
+		 * @param certReqId the certificate request ID.
+		 */
+		public PollReqContent(DerInteger certReqId)
+			: this(new DerSequence(new DerSequence(certReqId)))
 		{
-			if (obj is PollReqContent)
-				return (PollReqContent)obj;
+		}
 
-			if (obj is Asn1Sequence)
-				return new PollReqContent((Asn1Sequence)obj);
+		/**
+		 * Create a pollReqContent for a multiple certReqIds.
+		 *
+		 * @param certReqIds the certificate request IDs.
+		 */
+		public PollReqContent(DerInteger[] certReqIds)
+			: this(new DerSequence(IntsToSequence(certReqIds)))
+		{
+		}
 
-            throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+		/**
+		 * Create a pollReqContent for a single certReqId.
+		 *
+		 * @param certReqId the certificate request ID.
+		 */
+		public PollReqContent(BigInteger certReqId)
+			: this(new DerInteger(certReqId))
+		{
 		}
 
-		public virtual DerInteger[][] GetCertReqIDs()
+		/**
+		 * Create a pollReqContent for a multiple certReqIds.
+		 *
+		 * @param certReqIds the certificate request IDs.
+		 */
+		public PollReqContent(BigInteger[] certReqIds)
+			: this(IntsToAsn1(certReqIds))
 		{
-			DerInteger[][] result = new DerInteger[content.Count][];
-			for (int i = 0; i != result.Length; ++i)
-			{
-				result[i] = SequenceToDerIntegerArray((Asn1Sequence)content[i]);
-			}
-			return result;
 		}
 
-		private static DerInteger[] SequenceToDerIntegerArray(Asn1Sequence seq)
+		public virtual DerInteger[][] GetCertReqIDs()
 		{
-			DerInteger[] result = new DerInteger[seq.Count];
+			DerInteger[][] result = new DerInteger[m_content.Count][];
 			for (int i = 0; i != result.Length; ++i)
 			{
-				result[i] = DerInteger.GetInstance(seq[i]);
+				result[i] = SequenceToDerIntegerArray((Asn1Sequence)m_content[i]);
 			}
 			return result;
 		}
 
-		/**
+        public virtual BigInteger[] GetCertReqIDValues()
+        {
+            BigInteger[] result = new BigInteger[m_content.Count];
+
+            for (int i = 0; i != result.Length; i++)
+            {
+                result[i] = DerInteger.GetInstance(Asn1Sequence.GetInstance(m_content[i])[0]).Value;
+            }
+
+            return result;
+        }
+
+        /**
 		 * 
 		 * PollReqContent ::= SEQUENCE OF SEQUENCE {
 		 *                        certReqId              INTEGER
@@ -55,9 +95,38 @@ private static DerInteger[] SequenceToDerIntegerArray(Asn1Sequence seq)
 		 * 
* @return a basic ASN.1 object representation. */ - public override Asn1Object ToAsn1Object() + public override Asn1Object ToAsn1Object() + { + return m_content; + } + + private static DerInteger[] SequenceToDerIntegerArray(Asn1Sequence seq) + { + return seq.MapElements(DerInteger.GetInstance); + } + + private static DerSequence[] IntsToSequence(DerInteger[] ids) { - return content; + DerSequence[] result = new DerSequence[ids.Length]; + + for (int i = 0; i != result.Length; i++) + { + result[i] = new DerSequence(ids[i]); + } + + return result; + } + + private static DerInteger[] IntsToAsn1(BigInteger[] ids) + { + DerInteger[] result = new DerInteger[ids.Length]; + + for (int i = 0; i != result.Length; i++) + { + result[i] = new DerInteger(ids[i]); + } + + return result; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PopoDecKeyChallContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PopoDecKeyChallContent.cs index c04381a..e662a7a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PopoDecKeyChallContent.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PopoDecKeyChallContent.cs @@ -2,39 +2,32 @@ #pragma warning disable using System; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; - namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp { public class PopoDecKeyChallContent : Asn1Encodable { - private readonly Asn1Sequence content; + public static PopoDecKeyChallContent GetInstance(object obj) + { + if (obj is PopoDecKeyChallContent popoDecKeyChallContent) + return popoDecKeyChallContent; - private PopoDecKeyChallContent(Asn1Sequence seq) - { - content = seq; - } + if (obj != null) + return new PopoDecKeyChallContent(Asn1Sequence.GetInstance(obj)); - public static PopoDecKeyChallContent GetInstance(object obj) - { - if (obj is PopoDecKeyChallContent) - return (PopoDecKeyChallContent)obj; + return null; + } - if (obj is Asn1Sequence) - return new PopoDecKeyChallContent((Asn1Sequence)obj); + private readonly Asn1Sequence m_content; - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + private PopoDecKeyChallContent(Asn1Sequence seq) + { + m_content = seq; } public virtual Challenge[] ToChallengeArray() { - Challenge[] result = new Challenge[content.Count]; - for (int i = 0; i != result.Length; ++i) - { - result[i] = Challenge.GetInstance(content[i]); - } - return result; + return m_content.MapElements(Challenge.GetInstance); } /** @@ -45,7 +38,7 @@ public virtual Challenge[] ToChallengeArray() */ public override Asn1Object ToAsn1Object() { - return content; + return m_content; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PopoDecKeyRespContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PopoDecKeyRespContent.cs index bf59de1..0341c14 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PopoDecKeyRespContent.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/PopoDecKeyRespContent.cs @@ -1,40 +1,31 @@ #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 PopoDecKeyRespContent : Asn1Encodable { - private readonly Asn1Sequence content; + public static PopoDecKeyRespContent GetInstance(object obj) + { + if (obj is PopoDecKeyRespContent popoDecKeyRespContent) + return popoDecKeyRespContent; - private PopoDecKeyRespContent(Asn1Sequence seq) - { - content = seq; - } + if (obj != null) + return new PopoDecKeyRespContent(Asn1Sequence.GetInstance(obj)); - public static PopoDecKeyRespContent GetInstance(object obj) - { - if (obj is PopoDecKeyRespContent) - return (PopoDecKeyRespContent)obj; + return null; + } - if (obj is Asn1Sequence) - return new PopoDecKeyRespContent((Asn1Sequence)obj); + private readonly Asn1Sequence m_content; - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + private PopoDecKeyRespContent(Asn1Sequence seq) + { + m_content = seq; } - public virtual DerInteger[] ToDerIntegerArray() + public virtual DerInteger[] ToIntegerArray() { - DerInteger[] result = new DerInteger[content.Count]; - for (int i = 0; i != result.Length; ++i) - { - result[i] = DerInteger.GetInstance(content[i]); - } - return result; + return m_content.MapElements(DerInteger.GetInstance); } /** @@ -45,7 +36,7 @@ public virtual DerInteger[] ToDerIntegerArray() */ public override Asn1Object ToAsn1Object() { - return content; + return m_content; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/ProtectedPart.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/ProtectedPart.cs index a7f4fdb..6bf2ce6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/ProtectedPart.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/ProtectedPart.cs @@ -1,49 +1,39 @@ #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 ProtectedPart : Asn1Encodable { - private readonly PkiHeader header; - private readonly PkiBody body; - - private ProtectedPart(Asn1Sequence seq) - { - header = PkiHeader.GetInstance(seq[0]); - body = PkiBody.GetInstance(seq[1]); - } + public static ProtectedPart GetInstance(object obj) + { + if (obj is ProtectedPart protectedPart) + return protectedPart; - public static ProtectedPart GetInstance(object obj) - { - if (obj is ProtectedPart) - return (ProtectedPart)obj; + if (obj != null) + return new ProtectedPart(Asn1Sequence.GetInstance(obj)); - if (obj is Asn1Sequence) - return new ProtectedPart((Asn1Sequence)obj); + return null; + } - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); - } + private readonly PkiHeader m_header; + private readonly PkiBody m_body; - public ProtectedPart(PkiHeader header, PkiBody body) + private ProtectedPart(Asn1Sequence seq) { - this.header = header; - this.body = body; + m_header = PkiHeader.GetInstance(seq[0]); + m_body = PkiBody.GetInstance(seq[1]); } - public virtual PkiHeader Header + public ProtectedPart(PkiHeader header, PkiBody body) { - get { return header; } + m_header = header; + m_body = body; } - public virtual PkiBody Body - { - get { return body; } - } + public virtual PkiHeader Header => m_header; + + public virtual PkiBody Body => m_body; /** *
@@ -56,7 +46,7 @@ public virtual PkiBody Body
 		 */
 		public override Asn1Object ToAsn1Object()
 		{
-			return new DerSequence(header, body);
+			return new DerSequence(m_header, m_body);
 		}
 	}
 }
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevAnnContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevAnnContent.cs
index 0a02b55..3af7a4f 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevAnnContent.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevAnnContent.cs	
@@ -1,70 +1,68 @@
 #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 RevAnnContent
 		: Asn1Encodable
 	{
-		private readonly PkiStatusEncodable status;
-		private readonly CertId certId;
-		private readonly DerGeneralizedTime willBeRevokedAt;
-		private readonly DerGeneralizedTime badSinceDate;
-		private readonly X509Extensions crlDetails;
+        public static RevAnnContent GetInstance(object obj)
+        {
+			if (obj is RevAnnContent revAnnContent)
+				return revAnnContent;
 
-		private RevAnnContent(Asn1Sequence seq)
-		{
-			status = PkiStatusEncodable.GetInstance(seq[0]);
-			certId = CertId.GetInstance(seq[1]);
-			willBeRevokedAt = DerGeneralizedTime.GetInstance(seq[2]);
-			badSinceDate = DerGeneralizedTime.GetInstance(seq[3]);
+			if (obj != null)
+				return new RevAnnContent(Asn1Sequence.GetInstance(obj));
 
-			if (seq.Count > 4)
-			{
-				crlDetails = X509Extensions.GetInstance(seq[4]);
-			}
-		}
+			return null;
+        }
 
-		public static RevAnnContent GetInstance(object obj)
-		{
-			if (obj is RevAnnContent)
-				return (RevAnnContent)obj;
-
-			if (obj is Asn1Sequence)
-				return new RevAnnContent((Asn1Sequence)obj);
+        private readonly PkiStatusEncodable m_status;
+		private readonly CertId m_certID;
+		private readonly Asn1GeneralizedTime m_willBeRevokedAt;
+		private readonly Asn1GeneralizedTime m_badSinceDate;
+		private readonly X509Extensions m_crlDetails;
 
-            throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+        public RevAnnContent(PkiStatusEncodable status, CertId certID, Asn1GeneralizedTime willBeRevokedAt,
+            Asn1GeneralizedTime badSinceDate)
+            : this(status, certID, willBeRevokedAt, badSinceDate, null)
+        {
 		}
 
-		public virtual PkiStatusEncodable Status
-		{
-			get { return status; }
-		}
+        public RevAnnContent(PkiStatusEncodable status, CertId certID, Asn1GeneralizedTime willBeRevokedAt,
+            Asn1GeneralizedTime badSinceDate, X509Extensions crlDetails)
+        {
+            m_status = status;
+            m_certID = certID;
+            m_willBeRevokedAt = willBeRevokedAt;
+            m_badSinceDate = badSinceDate;
+            m_crlDetails = crlDetails;
+        }
 
-		public virtual CertId CertID
+        private RevAnnContent(Asn1Sequence seq)
 		{
-			get { return certId; }
-		}
+			m_status = PkiStatusEncodable.GetInstance(seq[0]);
+			m_certID = CertId.GetInstance(seq[1]);
+			m_willBeRevokedAt = Asn1GeneralizedTime.GetInstance(seq[2]);
+			m_badSinceDate = Asn1GeneralizedTime.GetInstance(seq[3]);
 
-		public virtual DerGeneralizedTime WillBeRevokedAt
-		{
-			get { return willBeRevokedAt; }
+			if (seq.Count > 4)
+			{
+				m_crlDetails = X509Extensions.GetInstance(seq[4]);
+			}
 		}
 
-		public virtual DerGeneralizedTime BadSinceDate
-		{
-			get { return badSinceDate; }
-		}
+		public virtual PkiStatusEncodable Status => m_status;
 
-		public virtual X509Extensions CrlDetails
-		{
-			get { return crlDetails; }
-		}
+		public virtual CertId CertID => m_certID;
+
+		public virtual Asn1GeneralizedTime WillBeRevokedAt => m_willBeRevokedAt;
+
+		public virtual Asn1GeneralizedTime BadSinceDate => m_badSinceDate;
+
+		public virtual X509Extensions CrlDetails => m_crlDetails;
 
 		/**
 		 * 
@@ -81,8 +79,8 @@ public virtual X509Extensions CrlDetails
 		 */
 		public override Asn1Object ToAsn1Object()
 		{
-			Asn1EncodableVector v = new Asn1EncodableVector(status, certId, willBeRevokedAt, badSinceDate);
-			v.AddOptional(crlDetails);
+			Asn1EncodableVector v = new Asn1EncodableVector(m_status, m_certID, m_willBeRevokedAt, m_badSinceDate);
+			v.AddOptional(m_crlDetails);
 			return new DerSequence(v);
 		}
 	}
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevDetails.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevDetails.cs
index bee4aa3..72bcd10 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevDetails.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevDetails.cs	
@@ -1,58 +1,63 @@
 #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 RevDetails
+    /**
+     * 
+     * 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
+     *      }
+     * 
+ */ + public class RevDetails : Asn1Encodable { - private readonly CertTemplate certDetails; - private readonly X509Extensions crlEntryDetails; + public static RevDetails GetInstance(object obj) + { + if (obj is RevDetails revDetails) + return revDetails; - private RevDetails(Asn1Sequence seq) - { - certDetails = CertTemplate.GetInstance(seq[0]); - crlEntryDetails = seq.Count <= 1 - ? null - : X509Extensions.GetInstance(seq[1]); - } + if (obj != null) + return new RevDetails(Asn1Sequence.GetInstance(obj)); - public static RevDetails GetInstance(object obj) - { - if (obj is RevDetails) - return (RevDetails)obj; + return null; + } - if (obj is Asn1Sequence) - return new RevDetails((Asn1Sequence)obj); + private readonly CertTemplate m_certDetails; + private readonly X509Extensions m_crlEntryDetails; - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + private RevDetails(Asn1Sequence seq) + { + m_certDetails = CertTemplate.GetInstance(seq[0]); + + if (seq.Count > 1) + { + m_crlEntryDetails = X509Extensions.GetInstance(seq[1]); + } } public RevDetails(CertTemplate certDetails) - : this(certDetails, null) + : this(certDetails, null) { } public RevDetails(CertTemplate certDetails, X509Extensions crlEntryDetails) { - this.certDetails = certDetails; - this.crlEntryDetails = crlEntryDetails; + m_certDetails = certDetails; + m_crlEntryDetails = crlEntryDetails; } - public virtual CertTemplate CertDetails - { - get { return certDetails; } - } + public virtual CertTemplate CertDetails => m_certDetails; - public virtual X509Extensions CrlEntryDetails - { - get { return crlEntryDetails; } - } + public virtual X509Extensions CrlEntryDetails => m_crlEntryDetails; /** *
@@ -69,8 +74,8 @@ public virtual X509Extensions CrlEntryDetails
 		*/
 		public override Asn1Object ToAsn1Object()
 		{
-			Asn1EncodableVector v = new Asn1EncodableVector(certDetails);
-			v.AddOptional(crlEntryDetails);
+			Asn1EncodableVector v = new Asn1EncodableVector(m_certDetails);
+			v.AddOptional(m_crlEntryDetails);
 			return new DerSequence(v);
 		}
 	}
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevRepContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevRepContent.cs
index 95e6473..8f7f27f 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevRepContent.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevRepContent.cs	
@@ -1,23 +1,45 @@
 #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
+    /**
+     * 
+     * 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)
+     *      }
+     *
+ */ + public class RevRepContent : Asn1Encodable { - private readonly Asn1Sequence status; - private readonly Asn1Sequence revCerts; - private readonly Asn1Sequence crls; + public static RevRepContent GetInstance(object obj) + { + if (obj is RevRepContent revRepContent) + return revRepContent; + + if (obj != null) + return new RevRepContent(Asn1Sequence.GetInstance(obj)); + + return null; + } + + private readonly Asn1Sequence m_status; + private readonly Asn1Sequence m_revCerts; + private readonly Asn1Sequence m_crls; private RevRepContent(Asn1Sequence seq) { - status = Asn1Sequence.GetInstance(seq[0]); + m_status = Asn1Sequence.GetInstance(seq[0]); for (int pos = 1; pos < seq.Count; ++pos) { @@ -25,60 +47,34 @@ private RevRepContent(Asn1Sequence seq) if (tObj.TagNo == 0) { - revCerts = Asn1Sequence.GetInstance(tObj, true); + m_revCerts = Asn1Sequence.GetInstance(tObj, true); } else { - crls = Asn1Sequence.GetInstance(tObj, true); + m_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; + return m_status.MapElements(PkiStatusInfo.GetInstance); } public virtual CertId[] GetRevCerts() { - if (revCerts == null) + if (m_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; + return m_revCerts.MapElements(CertId.GetInstance); } public virtual CertificateList[] GetCrls() { - if (crls == null) + if (m_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; + return m_crls.MapElements(CertificateList.GetInstance); } /** @@ -97,9 +93,9 @@ public virtual CertificateList[] GetCrls() */ public override Asn1Object ToAsn1Object() { - Asn1EncodableVector v = new Asn1EncodableVector(status); - v.AddOptionalTagged(true, 0, revCerts); - v.AddOptionalTagged(true, 1, crls); + Asn1EncodableVector v = new Asn1EncodableVector(m_status); + v.AddOptionalTagged(true, 0, m_revCerts); + v.AddOptionalTagged(true, 1, m_crls); return new DerSequence(v); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevRepContentBuilder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevRepContentBuilder.cs index 3d82c6f..15e8867 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevRepContentBuilder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevRepContentBuilder.cs @@ -9,29 +9,29 @@ 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(); + private readonly Asn1EncodableVector m_status = new Asn1EncodableVector(); + private readonly Asn1EncodableVector m_revCerts = new Asn1EncodableVector(); + private readonly Asn1EncodableVector m_crls = new Asn1EncodableVector(); public virtual RevRepContentBuilder Add(PkiStatusInfo status) { - this.status.Add(status); + m_status.Add(status); return this; } public virtual RevRepContentBuilder Add(PkiStatusInfo status, CertId certId) { - if (this.status.Count != this.revCerts.Count) + if (m_status.Count != m_revCerts.Count) throw new InvalidOperationException("status and revCerts sequence must be in common order"); - this.status.Add(status); - this.revCerts.Add(certId); + m_status.Add(status); + m_revCerts.Add(certId); return this; } public virtual RevRepContentBuilder AddCrl(CertificateList crl) { - this.crls.Add(crl); + m_crls.Add(crl); return this; } @@ -39,16 +39,16 @@ public virtual RevRepContent Build() { Asn1EncodableVector v = new Asn1EncodableVector(); - v.Add(new DerSequence(status)); + v.Add(new DerSequence(m_status)); - if (revCerts.Count != 0) + if (m_revCerts.Count != 0) { - v.Add(new DerTaggedObject(true, 0, new DerSequence(revCerts))); + v.Add(new DerTaggedObject(true, 0, new DerSequence(m_revCerts))); } - if (crls.Count != 0) + if (m_crls.Count != 0) { - v.Add(new DerTaggedObject(true, 1, new DerSequence(crls))); + v.Add(new DerTaggedObject(true, 1, new DerSequence(m_crls))); } return RevRepContent.GetInstance(new DerSequence(v)); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevReqContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevReqContent.cs index 8ac7dad..a7f61c9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevReqContent.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RevReqContent.cs @@ -9,37 +9,37 @@ 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 revReqContent) + return revReqContent; - public static RevReqContent GetInstance(object obj) - { - if (obj is RevReqContent) - return (RevReqContent)obj; + if (obj != null) + return new RevReqContent(Asn1Sequence.GetInstance(obj)); - if (obj is Asn1Sequence) - return new RevReqContent((Asn1Sequence)obj); + return null; + } - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + private readonly Asn1Sequence m_content; + + private RevReqContent(Asn1Sequence seq) + { + m_content = seq; } - public RevReqContent(params RevDetails[] revDetails) + public RevReqContent(RevDetails revDetails) + { + m_content = new DerSequence(revDetails); + } + + public RevReqContent(params RevDetails[] revDetailsArray) { - this.content = new DerSequence(revDetails); + m_content = new DerSequence(revDetailsArray); } 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; + return m_content.MapElements(RevDetails.GetInstance); } /** @@ -50,7 +50,7 @@ public virtual RevDetails[] ToRevDetailsArray() */ public override Asn1Object ToAsn1Object() { - return content; + return m_content; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RootCaKeyUpdateContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RootCaKeyUpdateContent.cs new file mode 100644 index 0000000..53080c1 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RootCaKeyUpdateContent.cs @@ -0,0 +1,95 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp +{ + /** + * GenMsg: {id-it 20}, RootCaCertValue | < absent > + * GenRep: {id-it 18}, RootCaKeyUpdateContent | < absent > + *

+ * RootCaCertValue ::= CMPCertificate + *

+ * RootCaKeyUpdateValue ::= RootCaKeyUpdateContent + *

+ * RootCaKeyUpdateContent ::= SEQUENCE { + * newWithNew CMPCertificate, + * newWithOld [0] CMPCertificate OPTIONAL, + * oldWithNew [1] CMPCertificate OPTIONAL + * } + *

+ */ + public class RootCaKeyUpdateContent + : Asn1Encodable + { + public static RootCaKeyUpdateContent GetInstance(object obj) + { + if (obj is RootCaKeyUpdateContent rootCaKeyUpdateContent) + return rootCaKeyUpdateContent; + + if (obj != null) + return new RootCaKeyUpdateContent(Asn1Sequence.GetInstance(obj)); + + return null; + } + + private readonly CmpCertificate m_newWithNew; + private readonly CmpCertificate m_newWithOld; + private readonly CmpCertificate m_oldWithNew; + + public RootCaKeyUpdateContent(CmpCertificate newWithNew, CmpCertificate newWithOld, CmpCertificate oldWithNew) + { + if (newWithNew == null) + throw new ArgumentNullException(nameof(newWithNew)); + + m_newWithNew = newWithNew; + m_newWithOld = newWithOld; + m_oldWithNew = oldWithNew; + } + + private RootCaKeyUpdateContent(Asn1Sequence seq) + { + if (seq.Count < 1 || seq.Count > 3) + throw new ArgumentException("expected sequence of 1 to 3 elements only"); + + CmpCertificate newWithNew; + CmpCertificate newWithOld = null; + CmpCertificate oldWithNew = null; + + newWithNew = CmpCertificate.GetInstance(seq[0]); + + for (int pos = 1; pos < seq.Count; ++pos) + { + Asn1TaggedObject ato = Asn1TaggedObject.GetInstance(seq[pos]); + if (ato.TagNo == 0) + { + newWithOld = CmpCertificate.GetInstance(ato, true); + } + else if (ato.TagNo == 1) + { + oldWithNew = CmpCertificate.GetInstance(ato, true); + } + } + + m_newWithNew = newWithNew; + m_newWithOld = newWithOld; + m_oldWithNew = oldWithNew; + } + + public virtual CmpCertificate NewWithNew => m_newWithNew; + + public virtual CmpCertificate NewWithOld => m_newWithOld; + + public virtual CmpCertificate OldWithNew => m_oldWithNew; + + public override Asn1Object ToAsn1Object() + { + Asn1EncodableVector v = new Asn1EncodableVector(m_newWithNew); + v.AddOptionalTagged(true, 0, m_newWithOld); + v.AddOptionalTagged(true, 1, m_oldWithNew); + return new DerSequence(v); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RootCaKeyUpdateContent.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RootCaKeyUpdateContent.cs.meta new file mode 100644 index 0000000..64587e7 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cmp/RootCaKeyUpdateContent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f84c9fabbf2c01545acaf4b36e0c6e20 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/Attribute.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/Attribute.cs index 2baee6e..a493b7a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/Attribute.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/Attribute.cs @@ -27,7 +27,7 @@ public static Attribute GetInstance( 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"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public Attribute( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AttributeTable.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AttributeTable.cs index f9d9816..af711d3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AttributeTable.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AttributeTable.cs @@ -1,94 +1,70 @@ #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; +using System.Collections.Generic; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms { public class AttributeTable { - private readonly IDictionary attributes; - -#if !(SILVERLIGHT || PORTABLE || NETFX_CORE) - [Obsolete] - public AttributeTable( - Hashtable attrs) - { - this.attributes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(attrs); - } -#endif + private readonly Dictionary m_attributes; - public AttributeTable( - IDictionary attrs) + public AttributeTable(IDictionary attrs) { - this.attributes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(attrs); + m_attributes = new Dictionary(attrs); } - public AttributeTable( - Asn1EncodableVector v) + public AttributeTable(Asn1EncodableVector v) { - this.attributes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(v.Count); + m_attributes = new Dictionary(v.Count); - foreach (Asn1Encodable o in v) + foreach (Asn1Encodable e in v) { - Attribute a = Attribute.GetInstance(o); - - AddAttribute(a); + AddAttribute(Attribute.GetInstance(e)); } } - public AttributeTable( - Asn1Set s) + public AttributeTable(Asn1Set s) { - this.attributes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(s.Count); + m_attributes = new Dictionary(s.Count); - for (int i = 0; i != s.Count; i++) + foreach (Asn1Encodable e in s) { - Attribute a = Attribute.GetInstance(s[i]); - - AddAttribute(a); + AddAttribute(Attribute.GetInstance(e)); } } - public AttributeTable( - Attributes attrs) + public AttributeTable(Attributes attrs) : this(Asn1Set.GetInstance(attrs.ToAsn1Object())) { } - private void AddAttribute( - Attribute a) + private void AddAttribute(Attribute a) { DerObjectIdentifier oid = a.AttrType; - object obj = attributes[oid]; - if (obj == null) + if (!m_attributes.TryGetValue(oid, out object existingValue)) { - attributes[oid] = a; + m_attributes[oid] = a; + return; } - else - { - IList v; - if (obj is Attribute) - { - v = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); - - v.Add(obj); - v.Add(a); - } - else - { - v = (IList) obj; - - v.Add(a); - } + if (existingValue is IList existingList) + { + existingList.Add(a); + return; + } - attributes[oid] = v; + if (existingValue is Attribute existingAttr) + { + var newList = new List(); + newList.Add(existingAttr); + newList.Add(a); + m_attributes[oid] = newList; + return; } + + throw new InvalidOperationException(); } /// Return the first attribute matching the given OBJECT IDENTIFIER @@ -96,22 +72,17 @@ public Attribute this[DerObjectIdentifier oid] { get { - object obj = attributes[oid]; + if (!m_attributes.TryGetValue(oid, out object existingValue)) + return null; - if (obj is IList) - { - return (Attribute)((IList)obj)[0]; - } - - return (Attribute) obj; - } - } + if (existingValue is IList existingList) + return existingList[0]; + if (existingValue is Attribute existingAttr) + return existingAttr; - public Attribute Get( - DerObjectIdentifier oid) - { - return this[oid]; + throw new InvalidOperationException(); + } } /** @@ -121,26 +92,30 @@ public Attribute Get( * @param oid type of attribute required. * @return a vector of all the attributes found of type oid. */ - public Asn1EncodableVector GetAll( - DerObjectIdentifier oid) + public Asn1EncodableVector GetAll(DerObjectIdentifier oid) { Asn1EncodableVector v = new Asn1EncodableVector(); - object obj = attributes[oid]; - - if (obj is IList) + if (m_attributes.TryGetValue(oid, out object existingValue)) { - foreach (Attribute a in (IList)obj) + if (existingValue is IList existingList) { - v.Add(a); + foreach (var attr in existingList) + { + v.Add(attr); + } + } + else if (existingValue is Attribute existingAttr) + { + v.Add(existingAttr); + } + else + { + throw new InvalidOperationException(); } - } - else if (obj != null) - { - v.Add((Attribute) obj); } - return v; + return v; } public int Count @@ -149,72 +124,86 @@ public int Count { int total = 0; - foreach (object o in attributes.Values) - { - if (o is IList) - { - total += ((IList)o).Count; - } - else - { - ++total; - } - } + foreach (object existingValue in m_attributes.Values) + { + if (existingValue is IList existingList) + { + total += existingList.Count; + } + else if (existingValue is Attribute existingAttr) + { + ++total; + } + else + { + throw new InvalidOperationException(); + } + } return total; } } - public IDictionary ToDictionary() - { - return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(attributes); - } - -#if !(SILVERLIGHT || PORTABLE || NETFX_CORE) - - public Hashtable ToHashtable() + public IDictionary ToDictionary() { - return new Hashtable(attributes); + return new Dictionary(m_attributes); } -#endif public Asn1EncodableVector ToAsn1EncodableVector() { Asn1EncodableVector v = new Asn1EncodableVector(); - foreach (object obj in attributes.Values) + foreach (object existingValue in m_attributes.Values) { - if (obj is IList) + if (existingValue is IList existingList) { - foreach (object el in (IList)obj) + foreach (Attribute existingAttr in existingList) { - v.Add(Attribute.GetInstance(el)); + v.Add(existingAttr); } } + else if (existingValue is Attribute existingAttr) + { + v.Add(existingAttr); + } else { - v.Add(Attribute.GetInstance(obj)); + throw new InvalidOperationException(); } } - return v; + return v; } public Attributes ToAttributes() { - return new Attributes(this.ToAsn1EncodableVector()); + return new Attributes(ToAsn1EncodableVector()); } - /** + public AttributeTable Add(params Attribute[] attributes) + { + if (attributes == null || attributes.Length < 1) + return this; + + var newTable = new AttributeTable(m_attributes); + foreach (Attribute attribute in attributes) + { + newTable.AddAttribute(attribute); + } + + return newTable; + } + + /** * Return a new table with the passed in attribute added. * * @param attrType * @param attrValue * @return */ - public AttributeTable Add(DerObjectIdentifier attrType, Asn1Encodable attrValue) + public AttributeTable Add(DerObjectIdentifier attrType, Asn1Encodable attrValue) { - AttributeTable newTable = new AttributeTable(attributes); + AttributeTable newTable = new AttributeTable(m_attributes); newTable.AddAttribute(new Attribute(attrType, new DerSet(attrValue))); @@ -223,9 +212,9 @@ public AttributeTable Add(DerObjectIdentifier attrType, Asn1Encodable attrValue) public AttributeTable Remove(DerObjectIdentifier attrType) { - AttributeTable newTable = new AttributeTable(attributes); + AttributeTable newTable = new AttributeTable(m_attributes); - newTable.attributes.Remove(attrType); + newTable.m_attributes.Remove(attrType); return newTable; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AuthEnvelopedData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AuthEnvelopedData.cs index 6b7c934..c38f04d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AuthEnvelopedData.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AuthEnvelopedData.cs @@ -134,7 +134,7 @@ public static AuthEnvelopedData GetInstance( if (obj is Asn1Sequence) return new AuthEnvelopedData((Asn1Sequence)obj); - throw new ArgumentException("Invalid AuthEnvelopedData: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("Invalid AuthEnvelopedData: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } public DerInteger Version diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AuthEnvelopedDataParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AuthEnvelopedDataParser.cs index 7b360e1..5acd346 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AuthEnvelopedDataParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AuthEnvelopedDataParser.cs @@ -51,11 +51,14 @@ public OriginatorInfo GetOriginatorInfo() nextObject = seq.ReadObject(); } - if (nextObject is Asn1TaggedObjectParser && ((Asn1TaggedObjectParser)nextObject).TagNo == 0) + if (nextObject is Asn1TaggedObjectParser o) { - Asn1SequenceParser originatorInfo = (Asn1SequenceParser) ((Asn1TaggedObjectParser)nextObject).GetObjectParser(Asn1Tags.Sequence, false); - nextObject = null; - return OriginatorInfo.GetInstance(originatorInfo.ToAsn1Object()); + if (o.HasContextTag(0)) + { + Asn1SequenceParser originatorInfo = (Asn1SequenceParser)o.ParseBaseUniversal(false, Asn1Tags.Sequence); + nextObject = null; + return OriginatorInfo.GetInstance(originatorInfo.ToAsn1Object()); + } } return null; @@ -104,15 +107,13 @@ public Asn1SetParser GetAuthAttrs() nextObject = seq.ReadObject(); } - if (nextObject is Asn1TaggedObjectParser) + if (nextObject is Asn1TaggedObjectParser o) { - IAsn1Convertible o = nextObject; nextObject = null; - return (Asn1SetParser)((Asn1TaggedObjectParser)o).GetObjectParser(Asn1Tags.Set, false); + return (Asn1SetParser)Asn1Utilities.ParseContextBaseUniversal(o, 1, false, Asn1Tags.SetOf); } - // "The authAttrs MUST be present if the content type carried in - // EncryptedContentInfo is not id-data." + // "The authAttrs MUST be present if the content type carried in EncryptedContentInfo is not id-data." if (!isData) throw new Asn1ParsingException("authAttrs must be present with non-data content"); @@ -141,9 +142,9 @@ public Asn1SetParser GetUnauthAttrs() if (nextObject != null) { - IAsn1Convertible o = nextObject; + Asn1TaggedObjectParser o = (Asn1TaggedObjectParser)nextObject; nextObject = null; - return (Asn1SetParser)((Asn1TaggedObjectParser)o).GetObjectParser(Asn1Tags.Set, false); + return (Asn1SetParser)Asn1Utilities.ParseContextBaseUniversal(o, 2, false, Asn1Tags.SetOf); } return null; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AuthenticatedData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AuthenticatedData.cs index ba19188..195ce12 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AuthenticatedData.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AuthenticatedData.cs @@ -126,7 +126,7 @@ public static AuthenticatedData GetInstance( return new AuthenticatedData((Asn1Sequence)obj); } - throw new ArgumentException("Invalid AuthenticatedData: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("Invalid AuthenticatedData: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } public DerInteger Version diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AuthenticatedDataParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AuthenticatedDataParser.cs index 307751c..46c31d2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AuthenticatedDataParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/AuthenticatedDataParser.cs @@ -55,12 +55,15 @@ public OriginatorInfo GetOriginatorInfo() nextObject = seq.ReadObject(); } - if (nextObject is Asn1TaggedObjectParser && ((Asn1TaggedObjectParser)nextObject).TagNo == 0) - { - Asn1SequenceParser originatorInfo = (Asn1SequenceParser) ((Asn1TaggedObjectParser)nextObject).GetObjectParser(Asn1Tags.Sequence, false); - nextObject = null; - return OriginatorInfo.GetInstance(originatorInfo.ToAsn1Object()); - } + if (nextObject is Asn1TaggedObjectParser o) + { + if (o.HasContextTag(0)) + { + Asn1SequenceParser originatorInfo = (Asn1SequenceParser)o.ParseBaseUniversal(false, Asn1Tags.Sequence); + nextObject = null; + return OriginatorInfo.GetInstance(originatorInfo.ToAsn1Object()); + } + } return null; } @@ -141,12 +144,11 @@ public Asn1SetParser GetAuthAttrs() nextObject = seq.ReadObject(); } - if (nextObject is Asn1TaggedObjectParser) - { - IAsn1Convertible o = nextObject; - nextObject = null; - return (Asn1SetParser)((Asn1TaggedObjectParser)o).GetObjectParser(Asn1Tags.Set, false); - } + if (nextObject is Asn1TaggedObjectParser o) + { + nextObject = null; + return (Asn1SetParser)Asn1Utilities.ParseContextBaseUniversal(o, 2, false, Asn1Tags.SetOf); + } return null; } @@ -171,12 +173,12 @@ public Asn1SetParser GetUnauthAttrs() nextObject = seq.ReadObject(); } - if (nextObject != null) - { - IAsn1Convertible o = nextObject; - nextObject = null; - return (Asn1SetParser)((Asn1TaggedObjectParser)o).GetObjectParser(Asn1Tags.Set, false); - } + if (nextObject != null) + { + Asn1TaggedObject o = (Asn1TaggedObject)nextObject; + nextObject = null; + return (Asn1SetParser)Asn1Utilities.ParseContextBaseUniversal(o, 3, false, Asn1Tags.SetOf); + } return null; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/CMSObjectIdentifiers.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/CMSObjectIdentifiers.cs index c9124b8..379549d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/CMSObjectIdentifiers.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/CMSObjectIdentifiers.cs @@ -15,7 +15,8 @@ public abstract class CmsObjectIdentifiers public static readonly DerObjectIdentifier AuthenticatedData = PkcsObjectIdentifiers.IdCTAuthData; public static readonly DerObjectIdentifier CompressedData = PkcsObjectIdentifiers.IdCTCompressedData; public static readonly DerObjectIdentifier AuthEnvelopedData = PkcsObjectIdentifiers.IdCTAuthEnvelopedData; - public static readonly DerObjectIdentifier timestampedData = PkcsObjectIdentifiers.IdCTTimestampedData; + public static readonly DerObjectIdentifier TimestampedData = PkcsObjectIdentifiers.IdCTTimestampedData; + public static readonly DerObjectIdentifier ZlibCompress = PkcsObjectIdentifiers.IdAlgZlibCompress; /** * The other Revocation Info arc diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/CompressedData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/CompressedData.cs index 7157198..a4ccfb6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/CompressedData.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/CompressedData.cs @@ -72,7 +72,7 @@ public static CompressedData GetInstance( if (obj is Asn1Sequence) return new CompressedData((Asn1Sequence) obj); - throw new ArgumentException("Invalid CompressedData: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("Invalid CompressedData: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } public DerInteger Version diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/ContentInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/ContentInfo.cs index ddf3b3a..ca5869a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/ContentInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/ContentInfo.cs @@ -1,7 +1,6 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -22,7 +21,7 @@ public static ContentInfo GetInstance( if (obj is Asn1Sequence) return new ContentInfo((Asn1Sequence) obj); - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } public static ContentInfo GetInstance(Asn1TaggedObject obj, bool isExplicit) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/ContentInfoParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/ContentInfoParser.cs index d9a79e9..6925466 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/ContentInfoParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/ContentInfoParser.cs @@ -15,29 +15,29 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms */ public class ContentInfoParser { - private DerObjectIdentifier contentType; - private Asn1TaggedObjectParser content; + private readonly DerObjectIdentifier m_contentType; + private readonly Asn1TaggedObjectParser m_content; - public ContentInfoParser( - Asn1SequenceParser seq) + public ContentInfoParser(Asn1SequenceParser seq) { - contentType = (DerObjectIdentifier)seq.ReadObject(); - content = (Asn1TaggedObjectParser)seq.ReadObject(); + m_contentType = (DerObjectIdentifier)seq.ReadObject(); + m_content = (Asn1TaggedObjectParser)seq.ReadObject(); } public DerObjectIdentifier ContentType { - get { return contentType; } + get { return m_contentType; } } - public IAsn1Convertible GetContent( - int tag) + public IAsn1Convertible GetContent(int tag) { - if (content == null) + if (null == m_content) return null; - return content.GetObjectParser(tag, true); - } + // TODO[cms] Ideally we could enforce the claimed tag + //return Asn1Utilities.ParseContextBaseUniversal(content, 0, true, tag); + return Asn1Utilities.ParseExplicitContextBaseObject(m_content, 0); + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EncryptedContentInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EncryptedContentInfo.cs index c595a36..24495c1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EncryptedContentInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EncryptedContentInfo.cs @@ -52,7 +52,7 @@ public static EncryptedContentInfo GetInstance( if (obj is Asn1Sequence) return new EncryptedContentInfo((Asn1Sequence)obj); - throw new ArgumentException("Invalid EncryptedContentInfo: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("Invalid EncryptedContentInfo: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } public DerObjectIdentifier ContentType diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EncryptedContentInfoParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EncryptedContentInfoParser.cs index 2450b22..ce95baf 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EncryptedContentInfoParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EncryptedContentInfoParser.cs @@ -42,7 +42,7 @@ public AlgorithmIdentifier ContentEncryptionAlgorithm public IAsn1Convertible GetEncryptedContent( int tag) { - return _encryptedContent.GetObjectParser(tag, false); + return Asn1Utilities.ParseContextBaseUniversal(_encryptedContent, 0, false, tag); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EncryptedData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EncryptedData.cs index b9eb970..74f9a69 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EncryptedData.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EncryptedData.cs @@ -22,7 +22,7 @@ public static EncryptedData GetInstance( if (obj is Asn1Sequence) return new EncryptedData((Asn1Sequence) obj); - throw new ArgumentException("Invalid EncryptedData: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("Invalid EncryptedData: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } public EncryptedData( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EnvelopedData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EnvelopedData.cs index 9f973af..9688931 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EnvelopedData.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EnvelopedData.cs @@ -1,9 +1,6 @@ #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.Cms { @@ -42,9 +39,7 @@ public EnvelopedData( this.unprotectedAttrs = Asn1Set.GetInstance(unprotectedAttrs); } - - public EnvelopedData( - Asn1Sequence seq) + private EnvelopedData(Asn1Sequence seq) { int index = 0; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EnvelopedDataParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EnvelopedDataParser.cs index 3ad716e..067f681 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EnvelopedDataParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/EnvelopedDataParser.cs @@ -44,12 +44,14 @@ public OriginatorInfo GetOriginatorInfo() _nextObject = _seq.ReadObject(); } - if (_nextObject is Asn1TaggedObjectParser && ((Asn1TaggedObjectParser)_nextObject).TagNo == 0) + if (_nextObject is Asn1TaggedObjectParser o) { - Asn1SequenceParser originatorInfo = (Asn1SequenceParser) - ((Asn1TaggedObjectParser)_nextObject).GetObjectParser(Asn1Tags.Sequence, false); - _nextObject = null; - return OriginatorInfo.GetInstance(originatorInfo.ToAsn1Object()); + if (o.HasContextTag(0)) + { + Asn1SequenceParser originatorInfo = (Asn1SequenceParser)o.ParseBaseUniversal(false, Asn1Tags.Sequence); + _nextObject = null; + return OriginatorInfo.GetInstance(originatorInfo.ToAsn1Object()); + } } return null; @@ -98,11 +100,11 @@ public Asn1SetParser GetUnprotectedAttrs() if (_nextObject != null) { - IAsn1Convertible o = _nextObject; + Asn1TaggedObjectParser o = (Asn1TaggedObjectParser)_nextObject; _nextObject = null; - return (Asn1SetParser)((Asn1TaggedObjectParser)o).GetObjectParser(Asn1Tags.Set, false); + return (Asn1SetParser)Asn1Utilities.ParseContextBaseUniversal(o, 1, false, Asn1Tags.SetOf); } - + return null; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/Evidence.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/Evidence.cs index b25fd5e..5a45ba8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/Evidence.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/Evidence.cs @@ -45,7 +45,7 @@ public static Evidence GetInstance(object obj) if (obj is Asn1TaggedObject) return new Evidence(Asn1TaggedObject.GetInstance(obj)); - throw new ArgumentException("Unknown object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Unknown object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public static Evidence GetInstance(Asn1TaggedObject obj, bool isExplicit) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/IssuerAndSerialNumber.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/IssuerAndSerialNumber.cs index c8cb7da..631ac04 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/IssuerAndSerialNumber.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/IssuerAndSerialNumber.cs @@ -2,7 +2,6 @@ #pragma warning disable using System; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; @@ -24,9 +23,7 @@ public static IssuerAndSerialNumber GetInstance(object obj) return new IssuerAndSerialNumber(Asn1Sequence.GetInstance(obj)); } - - public IssuerAndSerialNumber( - Asn1Sequence seq) + private IssuerAndSerialNumber(Asn1Sequence seq) { this.name = X509Name.GetInstance(seq[0]); this.serialNumber = (DerInteger) seq[1]; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KEKIdentifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KEKIdentifier.cs index 33cf621..5812cd3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KEKIdentifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KEKIdentifier.cs @@ -10,12 +10,12 @@ public class KekIdentifier : Asn1Encodable { private Asn1OctetString keyIdentifier; - private DerGeneralizedTime date; + private Asn1GeneralizedTime date; private OtherKeyAttribute other; public KekIdentifier( byte[] keyIdentifier, - DerGeneralizedTime date, + Asn1GeneralizedTime date, OtherKeyAttribute other) { this.keyIdentifier = new DerOctetString(keyIdentifier); @@ -33,9 +33,9 @@ public KekIdentifier( case 1: break; case 2: - if (seq[1] is DerGeneralizedTime) + if (seq[1] is Asn1GeneralizedTime) { - date = (DerGeneralizedTime) seq[1]; + date = (Asn1GeneralizedTime) seq[1]; } else { @@ -43,7 +43,7 @@ public KekIdentifier( } break; case 3: - date = (DerGeneralizedTime) seq[1]; + date = (Asn1GeneralizedTime) seq[1]; other = OtherKeyAttribute.GetInstance(seq[2]); break; default: @@ -82,7 +82,7 @@ public static KekIdentifier GetInstance( if (obj is Asn1Sequence) return new KekIdentifier((Asn1Sequence)obj); - throw new ArgumentException("Invalid KekIdentifier: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("Invalid KekIdentifier: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } public Asn1OctetString KeyIdentifier @@ -90,7 +90,7 @@ public Asn1OctetString KeyIdentifier get { return keyIdentifier; } } - public DerGeneralizedTime Date + public Asn1GeneralizedTime Date { get { return date; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KEKRecipientInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KEKRecipientInfo.cs index fa11d59..beb2a51 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KEKRecipientInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KEKRecipientInfo.cs @@ -66,7 +66,7 @@ public static KekRecipientInfo GetInstance( if(obj is Asn1Sequence) return new KekRecipientInfo((Asn1Sequence)obj); - throw new ArgumentException("Invalid KekRecipientInfo: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("Invalid KekRecipientInfo: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } public DerInteger Version diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KeyAgreeRecipientIdentifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KeyAgreeRecipientIdentifier.cs index a753c58..29f2e21 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KeyAgreeRecipientIdentifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KeyAgreeRecipientIdentifier.cs @@ -46,7 +46,7 @@ public static KeyAgreeRecipientIdentifier GetInstance( (Asn1TaggedObject)obj, false)); } - throw new ArgumentException("Invalid KeyAgreeRecipientIdentifier: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Invalid KeyAgreeRecipientIdentifier: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } private readonly IssuerAndSerialNumber issuerSerial; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KeyAgreeRecipientInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KeyAgreeRecipientInfo.cs index 4683c77..bbb857e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KeyAgreeRecipientInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KeyAgreeRecipientInfo.cs @@ -82,7 +82,7 @@ public static KeyAgreeRecipientInfo GetInstance( return new KeyAgreeRecipientInfo((Asn1Sequence)obj); throw new ArgumentException( - "Illegal object in KeyAgreeRecipientInfo: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + "Illegal object in KeyAgreeRecipientInfo: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KeyTransRecipientInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KeyTransRecipientInfo.cs index eabcd2f..9541a12 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KeyTransRecipientInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/KeyTransRecipientInfo.cs @@ -59,7 +59,7 @@ public static KeyTransRecipientInfo GetInstance( return new KeyTransRecipientInfo((Asn1Sequence) obj); throw new ArgumentException( - "Illegal object in KeyTransRecipientInfo: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + "Illegal object in KeyTransRecipientInfo: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } public DerInteger Version diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OriginatorIdentifierOrKey.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OriginatorIdentifierOrKey.cs index 79dd6b6..2dd4004 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OriginatorIdentifierOrKey.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OriginatorIdentifierOrKey.cs @@ -10,42 +10,24 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms public class OriginatorIdentifierOrKey : Asn1Encodable, IAsn1Choice { - private Asn1Encodable id; + private readonly Asn1Encodable id; - public OriginatorIdentifierOrKey( - IssuerAndSerialNumber id) + public OriginatorIdentifierOrKey(IssuerAndSerialNumber id) { this.id = id; } - - public OriginatorIdentifierOrKey( - Asn1OctetString id) - : this(new SubjectKeyIdentifier(id)) - { - } - - public OriginatorIdentifierOrKey( - SubjectKeyIdentifier id) + public OriginatorIdentifierOrKey(SubjectKeyIdentifier id) { this.id = new DerTaggedObject(false, 0, id); } - public OriginatorIdentifierOrKey( - OriginatorPublicKey id) + public OriginatorIdentifierOrKey(OriginatorPublicKey id) { this.id = new DerTaggedObject(false, 1, id); } - - public OriginatorIdentifierOrKey( - Asn1Object id) - { - this.id = id; - } - - private OriginatorIdentifierOrKey( - Asn1TaggedObject id) + private OriginatorIdentifierOrKey(Asn1TaggedObject id) { // TODO Add validation this.id = id; @@ -97,7 +79,7 @@ public static OriginatorIdentifierOrKey GetInstance( if (o is Asn1TaggedObject) return new OriginatorIdentifierOrKey((Asn1TaggedObject)o); - throw new ArgumentException("Invalid OriginatorIdentifierOrKey: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); + throw new ArgumentException("Invalid OriginatorIdentifierOrKey: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); } public Asn1Encodable ID @@ -131,12 +113,6 @@ public SubjectKeyIdentifier SubjectKeyIdentifier } } - - public OriginatorPublicKey OriginatorKey - { - get { return OriginatorPublicKey; } - } - public OriginatorPublicKey OriginatorPublicKey { get diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OriginatorInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OriginatorInfo.cs index ea6965c..fd798d8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OriginatorInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OriginatorInfo.cs @@ -81,7 +81,7 @@ public static OriginatorInfo GetInstance( if (obj is Asn1Sequence) return new OriginatorInfo((Asn1Sequence)obj); - throw new ArgumentException("Invalid OriginatorInfo: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("Invalid OriginatorInfo: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } public Asn1Set Certificates diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OriginatorPublicKey.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OriginatorPublicKey.cs index 399dbb0..5cf96ef 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OriginatorPublicKey.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OriginatorPublicKey.cs @@ -21,9 +21,7 @@ public OriginatorPublicKey( this.mPublicKey = new DerBitString(publicKey); } - - public OriginatorPublicKey( - Asn1Sequence seq) + private OriginatorPublicKey(Asn1Sequence seq) { this.mAlgorithm = AlgorithmIdentifier.GetInstance(seq[0]); this.mPublicKey = DerBitString.GetInstance(seq[1]); @@ -60,7 +58,7 @@ public static OriginatorPublicKey GetInstance( if (obj is Asn1Sequence) return new OriginatorPublicKey(Asn1Sequence.GetInstance(obj)); - throw new ArgumentException("Invalid OriginatorPublicKey: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("Invalid OriginatorPublicKey: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } public AlgorithmIdentifier Algorithm diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OtherKeyAttribute.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OtherKeyAttribute.cs index 80eda6f..19f0628 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OtherKeyAttribute.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OtherKeyAttribute.cs @@ -27,7 +27,7 @@ public static OtherKeyAttribute GetInstance( if (obj is Asn1Sequence) return new OtherKeyAttribute((Asn1Sequence) obj); - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public OtherKeyAttribute( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OtherRecipientInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OtherRecipientInfo.cs index e606dcc..809e110 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OtherRecipientInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OtherRecipientInfo.cs @@ -18,9 +18,7 @@ public OtherRecipientInfo( this.oriValue = oriValue; } - - public OtherRecipientInfo( - Asn1Sequence seq) + private OtherRecipientInfo(Asn1Sequence seq) { oriType = DerObjectIdentifier.GetInstance(seq[0]); oriValue = seq[1]; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OtherRevocationInfoFormat.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OtherRevocationInfoFormat.cs index ab007c9..9f1aed9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OtherRevocationInfoFormat.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/OtherRevocationInfoFormat.cs @@ -1,7 +1,5 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System; - namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms { public class OtherRevocationInfoFormat @@ -46,8 +44,8 @@ public static OtherRevocationInfoFormat GetInstance(Asn1TaggedObject obj, bool i */ public static OtherRevocationInfoFormat GetInstance(object obj) { - if (obj is OtherRevocationInfoFormat) - return (OtherRevocationInfoFormat)obj; + if (obj is OtherRevocationInfoFormat otherRevocationInfoFormat) + return otherRevocationInfoFormat; if (obj != null) return new OtherRevocationInfoFormat(Asn1Sequence.GetInstance(obj)); return null; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/PasswordRecipientInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/PasswordRecipientInfo.cs index bf1a479..63485e8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/PasswordRecipientInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/PasswordRecipientInfo.cs @@ -84,7 +84,7 @@ public static PasswordRecipientInfo GetInstance( if (obj is Asn1Sequence) return new PasswordRecipientInfo((Asn1Sequence) obj); - throw new ArgumentException("Invalid PasswordRecipientInfo: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("Invalid PasswordRecipientInfo: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } public DerInteger Version diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/RecipientEncryptedKey.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/RecipientEncryptedKey.cs index 2524988..59d2021 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/RecipientEncryptedKey.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/RecipientEncryptedKey.cs @@ -54,7 +54,7 @@ public static RecipientEncryptedKey GetInstance( return new RecipientEncryptedKey((Asn1Sequence) obj); } - throw new ArgumentException("Invalid RecipientEncryptedKey: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Invalid RecipientEncryptedKey: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public RecipientEncryptedKey( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/RecipientIdentifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/RecipientIdentifier.cs index 3e03a3a..0b06411 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/RecipientIdentifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/RecipientIdentifier.cs @@ -51,7 +51,7 @@ public static RecipientIdentifier GetInstance( return new RecipientIdentifier((Asn1Object) o); throw new ArgumentException( - "Illegal object in RecipientIdentifier: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); + "Illegal object in RecipientIdentifier: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); } public bool IsTagged diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/RecipientInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/RecipientInfo.cs index b639267..8a05607 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/RecipientInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/RecipientInfo.cs @@ -59,7 +59,7 @@ public static RecipientInfo GetInstance( if (o is Asn1TaggedObject) return new RecipientInfo((Asn1TaggedObject) o); - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); } public DerInteger Version diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/RecipientKeyIdentifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/RecipientKeyIdentifier.cs index e338e5c..821b178 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/RecipientKeyIdentifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/RecipientKeyIdentifier.cs @@ -10,12 +10,12 @@ public class RecipientKeyIdentifier : Asn1Encodable { private Asn1OctetString subjectKeyIdentifier; - private DerGeneralizedTime date; + private Asn1GeneralizedTime date; private OtherKeyAttribute other; public RecipientKeyIdentifier( Asn1OctetString subjectKeyIdentifier, - DerGeneralizedTime date, + Asn1GeneralizedTime date, OtherKeyAttribute other) { this.subjectKeyIdentifier = subjectKeyIdentifier; @@ -31,7 +31,7 @@ public RecipientKeyIdentifier( public RecipientKeyIdentifier( byte[] subjectKeyIdentifier, - DerGeneralizedTime date, + Asn1GeneralizedTime date, OtherKeyAttribute other) { this.subjectKeyIdentifier = new DerOctetString(subjectKeyIdentifier); @@ -50,9 +50,9 @@ public RecipientKeyIdentifier( case 1: break; case 2: - if (seq[1] is DerGeneralizedTime) + if (seq[1] is Asn1GeneralizedTime) { - date = (DerGeneralizedTime) seq[1]; + date = (Asn1GeneralizedTime)seq[1]; } else { @@ -60,7 +60,7 @@ public RecipientKeyIdentifier( } break; case 3: - date = (DerGeneralizedTime) seq[1]; + date = (Asn1GeneralizedTime)seq[1]; other = OtherKeyAttribute.GetInstance(seq[2]); break; default: @@ -99,7 +99,7 @@ public static RecipientKeyIdentifier GetInstance( if (obj is Asn1Sequence) return new RecipientKeyIdentifier((Asn1Sequence) obj); - throw new ArgumentException("Invalid RecipientKeyIdentifier: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("Invalid RecipientKeyIdentifier: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } public Asn1OctetString SubjectKeyIdentifier @@ -107,7 +107,7 @@ public Asn1OctetString SubjectKeyIdentifier get { return subjectKeyIdentifier; } } - public DerGeneralizedTime Date + public Asn1GeneralizedTime Date { get { return date; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/SignedData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/SignedData.cs index 44d7c30..9dd7bf6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/SignedData.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/SignedData.cs @@ -1,9 +1,6 @@ #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.Cms { @@ -142,8 +139,7 @@ private DerInteger CalculateVersion( return Version1; } - private bool CheckForVersion3( - Asn1Set signerInfs) + private bool CheckForVersion3(Asn1Set signerInfs) { foreach (object obj in signerInfs) { @@ -158,45 +154,42 @@ private bool CheckForVersion3( return false; } - private SignedData( - Asn1Sequence seq) + private SignedData(Asn1Sequence seq) { - IEnumerator e = seq.GetEnumerator(); + var e = seq.GetEnumerator(); e.MoveNext(); version = (DerInteger)e.Current; e.MoveNext(); - digestAlgorithms = ((Asn1Set)e.Current); + digestAlgorithms = (Asn1Set)e.Current.ToAsn1Object(); e.MoveNext(); - contentInfo = ContentInfo.GetInstance(e.Current); + contentInfo = ContentInfo.GetInstance(e.Current.ToAsn1Object()); while (e.MoveNext()) { - Asn1Object o = (Asn1Object)e.Current; + Asn1Object o = e.Current.ToAsn1Object(); // // an interesting feature of SignedData is that there appear // to be varying implementations... // for the moment we ignore anything which doesn't fit. // - if (o is Asn1TaggedObject) + if (o is Asn1TaggedObject tagged) { - Asn1TaggedObject tagged = (Asn1TaggedObject)o; - switch (tagged.TagNo) { - case 0: - certsBer = tagged is BerTaggedObject; - certificates = Asn1Set.GetInstance(tagged, false); - break; - case 1: - crlsBer = tagged is BerTaggedObject; - crls = Asn1Set.GetInstance(tagged, false); - break; - default: - throw new ArgumentException("unknown tag value " + tagged.TagNo); + case 0: + certsBer = tagged is BerTaggedObject; + certificates = Asn1Set.GetInstance(tagged, false); + break; + case 1: + crlsBer = tagged is BerTaggedObject; + crls = Asn1Set.GetInstance(tagged, false); + break; + default: + throw new ArgumentException("unknown tag value " + tagged.TagNo); } } else diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/SignedDataParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/SignedDataParser.cs index 6422e90..f860e46 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/SignedDataParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/SignedDataParser.cs @@ -36,7 +36,7 @@ public static SignedDataParser GetInstance( if (o is Asn1SequenceParser) return new SignedDataParser((Asn1SequenceParser)o); - throw new IOException("unknown object encountered: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); + throw new IOException("unknown object encountered: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); } public SignedDataParser( @@ -66,12 +66,14 @@ public Asn1SetParser GetCertificates() _certsCalled = true; _nextObject = _seq.ReadObject(); - if (_nextObject is Asn1TaggedObjectParser && ((Asn1TaggedObjectParser)_nextObject).TagNo == 0) + if (_nextObject is Asn1TaggedObjectParser o) { - Asn1SetParser certs = (Asn1SetParser)((Asn1TaggedObjectParser)_nextObject).GetObjectParser(Asn1Tags.Set, false); - _nextObject = null; - - return certs; + if (o.HasContextTag(0)) + { + Asn1SetParser certs = (Asn1SetParser)o.ParseBaseUniversal(false, Asn1Tags.SetOf); + _nextObject = null; + return certs; + } } return null; @@ -89,16 +91,18 @@ public Asn1SetParser GetCrls() _nextObject = _seq.ReadObject(); } - if (_nextObject is Asn1TaggedObjectParser && ((Asn1TaggedObjectParser)_nextObject).TagNo == 1) + if (_nextObject is Asn1TaggedObjectParser o) { - Asn1SetParser crls = (Asn1SetParser)((Asn1TaggedObjectParser)_nextObject).GetObjectParser(Asn1Tags.Set, false); - _nextObject = null; - - return crls; + if (o.HasContextTag(1)) + { + Asn1SetParser crls = (Asn1SetParser)o.ParseBaseUniversal(false, Asn1Tags.SetOf); + _nextObject = null; + return crls; + } } - return null; - } + return null; + } public Asn1SetParser GetSignerInfos() { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/SignerIdentifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/SignerIdentifier.cs index 29aaaa4..a164f27 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/SignerIdentifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/SignerIdentifier.cs @@ -51,7 +51,7 @@ public static SignerIdentifier GetInstance( return new SignerIdentifier((Asn1Object) o); throw new ArgumentException( - "Illegal object in SignerIdentifier: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); + "Illegal object in SignerIdentifier: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); } public bool IsTagged diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/SignerInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/SignerInfo.cs index ee1cb89..74a72b5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/SignerInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/SignerInfo.cs @@ -1,7 +1,6 @@ #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.Utilities; @@ -19,8 +18,7 @@ public class SignerInfo private Asn1OctetString encryptedDigest; private Asn1Set unauthenticatedAttributes; - public static SignerInfo GetInstance( - object obj) + public static SignerInfo GetInstance(object obj) { if (obj == null || obj is SignerInfo) return (SignerInfo) obj; @@ -28,7 +26,7 @@ public static SignerInfo GetInstance( if (obj is Asn1Sequence) return new SignerInfo((Asn1Sequence) obj); - throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public SignerInfo( @@ -65,30 +63,28 @@ public SignerInfo( this.unauthenticatedAttributes = Asn1Set.GetInstance(unauthenticatedAttributes); } - - public SignerInfo( - Asn1Sequence seq) + private SignerInfo(Asn1Sequence seq) { - IEnumerator e = seq.GetEnumerator(); + var e = seq.GetEnumerator(); e.MoveNext(); - version = (DerInteger) e.Current; + version = (DerInteger)e.Current; e.MoveNext(); - sid = SignerIdentifier.GetInstance(e.Current); + sid = SignerIdentifier.GetInstance(e.Current.ToAsn1Object()); e.MoveNext(); - digAlgorithm = AlgorithmIdentifier.GetInstance(e.Current); + digAlgorithm = AlgorithmIdentifier.GetInstance(e.Current.ToAsn1Object()); e.MoveNext(); - object obj = e.Current; + var obj = e.Current.ToAsn1Object(); - if (obj is Asn1TaggedObject) + if (obj is Asn1TaggedObject tagged) { - authenticatedAttributes = Asn1Set.GetInstance((Asn1TaggedObject) obj, false); + authenticatedAttributes = Asn1Set.GetInstance(tagged, false); e.MoveNext(); - digEncryptionAlgorithm = AlgorithmIdentifier.GetInstance(e.Current); + digEncryptionAlgorithm = AlgorithmIdentifier.GetInstance(e.Current.ToAsn1Object()); } else { @@ -97,11 +93,11 @@ public SignerInfo( } e.MoveNext(); - encryptedDigest = DerOctetString.GetInstance(e.Current); + encryptedDigest = Asn1OctetString.GetInstance(e.Current.ToAsn1Object()); if (e.MoveNext()) { - unauthenticatedAttributes = Asn1Set.GetInstance((Asn1TaggedObject) e.Current, false); + unauthenticatedAttributes = Asn1Set.GetInstance((Asn1TaggedObject)e.Current.ToAsn1Object(), false); } else { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/Time.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/Time.cs index 4308d4b..592ae9e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/Time.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/Time.cs @@ -10,24 +10,41 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms public class Time : Asn1Encodable, IAsn1Choice { - private readonly Asn1Object time; + public static Time GetInstance(object obj) + { + if (obj == null) + return null; + if (obj is Time time) + return time; + if (obj is Asn1UtcTime utcTime) + return new Time(utcTime); + if (obj is Asn1GeneralizedTime generalizedTime) + return new Time(generalizedTime); + + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), nameof(obj)); + } + + public static Time GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) + { + return GetInstance(taggedObject.GetObject()); + } - public static Time GetInstance( - Asn1TaggedObject obj, - bool explicitly) + private readonly Asn1Object m_timeObject; + + public Time(Asn1GeneralizedTime generalizedTime) { - return GetInstance(obj.GetObject()); + this.m_timeObject = generalizedTime ?? throw new ArgumentNullException(nameof(generalizedTime)); } - public Time( - Asn1Object time) + public Time(Asn1UtcTime utcTime) { - if (time == null) - throw new ArgumentNullException("time"); - if (!(time is DerUtcTime) && !(time is DerGeneralizedTime)) - throw new ArgumentException("unknown object passed to Time"); + if (utcTime == null) + throw new ArgumentNullException(nameof(utcTime)); + + // Validate utcTime is in the appropriate year range + utcTime.ToDateTime(2049); - this.time = time; + this.m_timeObject = utcTime; } /** @@ -35,71 +52,38 @@ public Time( * and 2049 a UTCTime object is Generated, otherwise a GeneralizedTime * is used. */ - public Time( - DateTime date) + public Time(DateTime date) { - string d = date.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture) + "Z"; - - int year = int.Parse(d.Substring(0, 4)); + DateTime utc = date.ToUniversalTime(); - if (year < 1950 || year > 2049) + if (utc.Year < 1950 || utc.Year > 2049) { - time = new DerGeneralizedTime(d); + m_timeObject = new DerGeneralizedTime(utc); } else { - time = new DerUtcTime(d.Substring(2)); + m_timeObject = new DerUtcTime(utc, 2049); } } - public static Time GetInstance( - object obj) + public DateTime ToDateTime() { - if (obj == null || obj is Time) - return (Time)obj; - if (obj is DerUtcTime) - return new Time((DerUtcTime)obj); - if (obj is DerGeneralizedTime) - return new Time((DerGeneralizedTime)obj); - - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); - } + try + { + if (m_timeObject is Asn1UtcTime utcTime) + return utcTime.ToDateTime(2049); - public string TimeString - { - get - { - if (time is DerUtcTime) - { - return ((DerUtcTime)time).AdjustedTimeString; - } - else - { - return ((DerGeneralizedTime)time).GetTime(); - } - } + return ((Asn1GeneralizedTime)m_timeObject).ToDateTime(); + } + catch (FormatException e) + { + // this should never happen + throw new InvalidOperationException("invalid date string: " + e.Message); + } } - public DateTime Date - { - get - { - try - { - if (time is DerUtcTime) - { - return ((DerUtcTime)time).ToAdjustedDateTime(); - } - - return ((DerGeneralizedTime)time).ToDateTime(); - } - catch (FormatException e) - { - // this should never happen - throw new InvalidOperationException("invalid date string: " + e.Message); - } - } - } + + public DateTime Date => ToDateTime(); /** * Produce an object suitable for an Asn1OutputStream. @@ -111,7 +95,18 @@ public DateTime Date */ public override Asn1Object ToAsn1Object() { - return time; + return m_timeObject; + } + + public override string ToString() + { + if (m_timeObject is Asn1UtcTime utcTime) + return utcTime.ToDateTime(2049).ToString(@"yyyyMMddHHmmssK", DateTimeFormatInfo.InvariantInfo); + + if (m_timeObject is Asn1GeneralizedTime generalizedTime) + return generalizedTime.ToDateTime().ToString(@"yyyyMMddHHmmss.FFFFFFFK", DateTimeFormatInfo.InvariantInfo); + + throw new InvalidOperationException(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/ecc/MQVuserKeyingMaterial.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/ecc/MQVuserKeyingMaterial.cs index f86b60d..5948817 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/ecc/MQVuserKeyingMaterial.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cms/ecc/MQVuserKeyingMaterial.cs @@ -71,7 +71,7 @@ public static MQVuserKeyingMaterial GetInstance( return new MQVuserKeyingMaterial((Asn1Sequence)obj); } - throw new ArgumentException("Invalid MQVuserKeyingMaterial: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("Invalid MQVuserKeyingMaterial: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } public OriginatorPublicKey EphemeralPublicKey diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/AttributeTypeAndValue.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/AttributeTypeAndValue.cs index 8f4f4ad..0e2f203 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/AttributeTypeAndValue.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/AttributeTypeAndValue.cs @@ -26,7 +26,7 @@ public static AttributeTypeAndValue GetInstance(object obj) if (obj is Asn1Sequence) return new AttributeTypeAndValue((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public AttributeTypeAndValue( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/CertId.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/CertId.cs index d81a2be..47e9eb3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/CertId.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/CertId.cs @@ -27,7 +27,7 @@ public static CertId GetInstance(object obj) if (obj is Asn1Sequence) return new CertId((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public static CertId GetInstance(Asn1TaggedObject obj, bool isExplicit) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/CertReqMessages.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/CertReqMessages.cs index 86d90b1..ddffce6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/CertReqMessages.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/CertReqMessages.cs @@ -24,7 +24,7 @@ public static CertReqMessages GetInstance(object obj) if (obj is Asn1Sequence) return new CertReqMessages((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public CertReqMessages(params CertReqMsg[] msgs) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/Controls.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/Controls.cs index 81abf83..eb8e6ac 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/Controls.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/Controls.cs @@ -25,7 +25,7 @@ public static Controls GetInstance(object obj) if (obj is Asn1Sequence) return new Controls((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public Controls(params AttributeTypeAndValue[] atvs) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/EncryptedKey.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/EncryptedKey.cs index 6c4a34d..56ee5d2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/EncryptedKey.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/EncryptedKey.cs @@ -1,7 +1,5 @@ #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 @@ -9,52 +7,40 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Crmf public class EncryptedKey : Asn1Encodable, IAsn1Choice { - private readonly EnvelopedData envelopedData; - private readonly EncryptedValue encryptedValue; - - public static EncryptedKey GetInstance(object o) + public static EncryptedKey GetInstance(object obj) { - if (o is EncryptedKey) - { - return (EncryptedKey)o; - } - else if (o is Asn1TaggedObject) - { - return new EncryptedKey(EnvelopedData.GetInstance((Asn1TaggedObject)o, false)); - } - else if (o is EncryptedValue) - { - return new EncryptedKey((EncryptedValue)o); - } - else - { - return new EncryptedKey(EncryptedValue.GetInstance(o)); - } + if (obj is EncryptedKey encryptedKey) + return encryptedKey; + + if (obj is Asn1TaggedObject taggedObject) + return new EncryptedKey(EnvelopedData.GetInstance(taggedObject, false)); + + return new EncryptedKey(EncryptedValue.GetInstance(obj)); } + private readonly EnvelopedData m_envelopedData; + private readonly EncryptedValue m_encryptedValue; + public EncryptedKey(EnvelopedData envelopedData) { - this.envelopedData = envelopedData; + m_envelopedData = envelopedData; } public EncryptedKey(EncryptedValue encryptedValue) { - this.encryptedValue = encryptedValue; + m_encryptedValue = encryptedValue; } - public virtual bool IsEncryptedValue - { - get { return encryptedValue != null; } - } + public virtual bool IsEncryptedValue => m_encryptedValue != null; public virtual Asn1Encodable Value { get { - if (encryptedValue != null) - return encryptedValue; + if (m_encryptedValue != null) + return m_encryptedValue; - return envelopedData; + return m_envelopedData; } } @@ -69,12 +55,10 @@ public virtual Asn1Encodable Value */ public override Asn1Object ToAsn1Object() { - if (encryptedValue != null) - { - return encryptedValue.ToAsn1Object(); - } + if (m_encryptedValue != null) + return m_encryptedValue.ToAsn1Object(); - return new DerTaggedObject(false, 0, envelopedData); + return new DerTaggedObject(false, 0, m_envelopedData); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/EncryptedValue.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/EncryptedValue.cs index 7d646d2..155542e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/EncryptedValue.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/EncryptedValue.cs @@ -9,48 +9,10 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Crmf public class EncryptedValue : Asn1Encodable { - private readonly AlgorithmIdentifier intendedAlg; - private readonly AlgorithmIdentifier symmAlg; - private readonly DerBitString encSymmKey; - private readonly AlgorithmIdentifier keyAlg; - private readonly Asn1OctetString valueHint; - private readonly DerBitString encValue; - - private EncryptedValue(Asn1Sequence seq) - { - int index = 0; - while (seq[index] is Asn1TaggedObject) - { - Asn1TaggedObject tObj = (Asn1TaggedObject)seq[index]; - - switch (tObj.TagNo) - { - case 0: - intendedAlg = AlgorithmIdentifier.GetInstance(tObj, false); - break; - case 1: - symmAlg = AlgorithmIdentifier.GetInstance(tObj, false); - break; - case 2: - encSymmKey = DerBitString.GetInstance(tObj, false); - break; - case 3: - keyAlg = AlgorithmIdentifier.GetInstance(tObj, false); - break; - case 4: - valueHint = Asn1OctetString.GetInstance(tObj, false); - break; - } - ++index; - } - - encValue = DerBitString.GetInstance(seq[index]); - } - public static EncryptedValue GetInstance(object obj) { - if (obj is EncryptedValue) - return (EncryptedValue)obj; + if (obj is EncryptedValue encryptedValue) + return encryptedValue; if (obj != null) return new EncryptedValue(Asn1Sequence.GetInstance(obj)); @@ -58,59 +20,71 @@ public static EncryptedValue GetInstance(object obj) return null; } - public EncryptedValue( - AlgorithmIdentifier intendedAlg, - AlgorithmIdentifier symmAlg, - DerBitString encSymmKey, - AlgorithmIdentifier keyAlg, - Asn1OctetString valueHint, - DerBitString encValue) + private readonly AlgorithmIdentifier m_intendedAlg; + private readonly AlgorithmIdentifier m_symmAlg; + private readonly DerBitString m_encSymmKey; + private readonly AlgorithmIdentifier m_keyAlg; + private readonly Asn1OctetString m_valueHint; + private readonly DerBitString m_encValue; + + private EncryptedValue(Asn1Sequence seq) { - if (encValue == null) + int index = 0; + while (seq[index] is Asn1TaggedObject tObj) { - throw new ArgumentNullException("encValue"); + switch (tObj.TagNo) + { + case 0: + m_intendedAlg = AlgorithmIdentifier.GetInstance(tObj, false); + break; + case 1: + m_symmAlg = AlgorithmIdentifier.GetInstance(tObj, false); + break; + case 2: + m_encSymmKey = DerBitString.GetInstance(tObj, false); + break; + case 3: + m_keyAlg = AlgorithmIdentifier.GetInstance(tObj, false); + break; + case 4: + m_valueHint = Asn1OctetString.GetInstance(tObj, false); + break; + } + ++index; } - this.intendedAlg = intendedAlg; - this.symmAlg = symmAlg; - this.encSymmKey = encSymmKey; - this.keyAlg = keyAlg; - this.valueHint = valueHint; - this.encValue = encValue; + m_encValue = DerBitString.GetInstance(seq[index]); } - public virtual AlgorithmIdentifier IntendedAlg + public EncryptedValue(AlgorithmIdentifier intendedAlg, AlgorithmIdentifier symmAlg, DerBitString encSymmKey, + AlgorithmIdentifier keyAlg, Asn1OctetString valueHint, DerBitString encValue) { - get { return intendedAlg; } + if (encValue == null) + throw new ArgumentNullException(nameof(encValue)); + + m_intendedAlg = intendedAlg; + m_symmAlg = symmAlg; + m_encSymmKey = encSymmKey; + m_keyAlg = keyAlg; + m_valueHint = valueHint; + m_encValue = encValue; } - public virtual AlgorithmIdentifier SymmAlg - { - get { return symmAlg; } - } + public virtual AlgorithmIdentifier IntendedAlg => m_intendedAlg; - public virtual DerBitString EncSymmKey - { - get { return encSymmKey; } - } + public virtual AlgorithmIdentifier SymmAlg => m_symmAlg; - public virtual AlgorithmIdentifier KeyAlg - { - get { return keyAlg; } - } + public virtual DerBitString EncSymmKey => m_encSymmKey; - public virtual Asn1OctetString ValueHint - { - get { return valueHint; } - } + public virtual AlgorithmIdentifier KeyAlg => m_keyAlg; - public virtual DerBitString EncValue - { - get { return encValue; } - } + public virtual Asn1OctetString ValueHint => m_valueHint; + + public virtual DerBitString EncValue => m_encValue; /** *
+         * (IMPLICIT TAGS)
          * EncryptedValue ::= SEQUENCE {
          *                     intendedAlg   [0] AlgorithmIdentifier  OPTIONAL,
          *                     -- the intended algorithm for which the value will be used
@@ -133,12 +107,12 @@ public virtual DerBitString EncValue
         public override Asn1Object ToAsn1Object()
         {
             Asn1EncodableVector v = new Asn1EncodableVector();
-            v.AddOptionalTagged(false, 0, intendedAlg);
-            v.AddOptionalTagged(false, 1, symmAlg);
-            v.AddOptionalTagged(false, 2, encSymmKey);
-            v.AddOptionalTagged(false, 3, keyAlg);
-            v.AddOptionalTagged(false, 4, valueHint);
-            v.Add(encValue);
+            v.AddOptionalTagged(false, 0, m_intendedAlg);
+            v.AddOptionalTagged(false, 1, m_symmAlg);
+            v.AddOptionalTagged(false, 2, m_encSymmKey);
+            v.AddOptionalTagged(false, 3, m_keyAlg);
+            v.AddOptionalTagged(false, 4, m_valueHint);
+            v.Add(m_encValue);
             return new DerSequence(v);
         }
     }
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PKIArchiveOptions.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PKIArchiveOptions.cs
index d4a72da..5415b8a 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PKIArchiveOptions.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PKIArchiveOptions.cs	
@@ -23,7 +23,7 @@ public static PkiArchiveOptions GetInstance(object obj)
             if (obj is Asn1TaggedObject)
                 return new PkiArchiveOptions((Asn1TaggedObject)obj);
 
-            throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+            throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
         }
 
         private PkiArchiveOptions(Asn1TaggedObject tagged)
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PKIPublicationInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PKIPublicationInfo.cs
index 0f6f4ca..4bab73b 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PKIPublicationInfo.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PKIPublicationInfo.cs	
@@ -1,50 +1,93 @@
 #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.Math;
 
 namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Crmf
 {
+    /**
+     * 
+     * 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)
+     * 
+ */ public class PkiPublicationInfo : Asn1Encodable { - private readonly DerInteger action; - private readonly Asn1Sequence pubInfos; + public static readonly DerInteger DontPublish = new DerInteger(0); + public static readonly DerInteger PleasePublish = new DerInteger(1); + + public static PkiPublicationInfo GetInstance(object obj) + { + if (obj is PkiPublicationInfo pkiPublicationInfo) + return pkiPublicationInfo; + + if (obj != null) + return new PkiPublicationInfo(Asn1Sequence.GetInstance(obj)); + + return null; + } + + private readonly DerInteger m_action; + private readonly Asn1Sequence m_pubInfos; private PkiPublicationInfo(Asn1Sequence seq) { - action = DerInteger.GetInstance(seq[0]); - pubInfos = Asn1Sequence.GetInstance(seq[1]); + m_action = DerInteger.GetInstance(seq[0]); + if (seq.Count > 1) + { + m_pubInfos = Asn1Sequence.GetInstance(seq[1]); + } } - public static PkiPublicationInfo GetInstance(object obj) + public PkiPublicationInfo(BigInteger action) + : this(new DerInteger(action)) { - if (obj is PkiPublicationInfo) - return (PkiPublicationInfo)obj; + } - if (obj is Asn1Sequence) - return new PkiPublicationInfo((Asn1Sequence)obj); + public PkiPublicationInfo(DerInteger action) + { + m_action = action; + } - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + /** + * Constructor with a single pubInfo, assumes pleasePublish as the action. + * + * @param pubInfo the pubInfo to be published (can be null if don't care is required). + */ + public PkiPublicationInfo(SinglePubInfo pubInfo) + : this(pubInfo != null ? new SinglePubInfo[1]{ pubInfo } : null) + { } - public virtual DerInteger Action + /** + * Constructor with multiple pubInfo, assumes pleasePublish as the action. + * + * @param pubInfos the pubInfos to be published (can be null if don't care is required). + */ + public PkiPublicationInfo(SinglePubInfo[] pubInfos) { - get { return action; } + m_action = PleasePublish; + + if (pubInfos != null) + { + m_pubInfos = new DerSequence(pubInfos); + } } + public virtual DerInteger Action => m_action; + public virtual SinglePubInfo[] GetPubInfos() { - if (pubInfos == null) + if (m_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; + return m_pubInfos.MapElements(SinglePubInfo.GetInstance); } /** @@ -62,7 +105,10 @@ public virtual SinglePubInfo[] GetPubInfos() */ public override Asn1Object ToAsn1Object() { - return new DerSequence(action, pubInfos); + if (m_pubInfos == null) + return new DerSequence(m_action); + + return new DerSequence(m_action, m_pubInfos); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PKMacValue.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PKMacValue.cs index 5d0553e..2948888 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PKMacValue.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PKMacValue.cs @@ -31,7 +31,7 @@ public static PKMacValue GetInstance(object obj) if (obj is Asn1Sequence) return new PKMacValue((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public static PKMacValue GetInstance(Asn1TaggedObject obj, bool isExplicit) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PopoSigningKey.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PopoSigningKey.cs index e140afa..194bb29 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PopoSigningKey.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PopoSigningKey.cs @@ -40,7 +40,7 @@ public static PopoSigningKey GetInstance(object obj) if (obj is Asn1Sequence) return new PopoSigningKey((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public static PopoSigningKey GetInstance(Asn1TaggedObject obj, bool isExplicit) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PopoSigningKeyInput.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PopoSigningKeyInput.cs index 7d7d350..0d9c475 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PopoSigningKeyInput.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/PopoSigningKeyInput.cs @@ -43,7 +43,7 @@ public static PopoSigningKeyInput GetInstance(object obj) if (obj is Asn1Sequence) return new PopoSigningKeyInput((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** Creates a new PopoSigningKeyInput with sender name as authInfo. */ diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/ProofOfPossession.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/ProofOfPossession.cs index ad7ccbe..431c607 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/ProofOfPossession.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/ProofOfPossession.cs @@ -45,7 +45,7 @@ public static ProofOfPossession GetInstance(object obj) if (obj is Asn1TaggedObject) return new ProofOfPossession((Asn1TaggedObject)obj); - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** Creates a ProofOfPossession with type raVerified. */ diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/SinglePubInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/SinglePubInfo.cs index 8b70a97..208539b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/SinglePubInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/crmf/SinglePubInfo.cs @@ -31,7 +31,7 @@ public static SinglePubInfo GetInstance(object obj) if (obj is Asn1Sequence) return new SinglePubInfo((Asn1Sequence)obj); - throw new ArgumentException("Invalid object: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Invalid object: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public virtual GeneralName PubLocation diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptlib.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptlib.meta new file mode 100644 index 0000000..707c889 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptlib.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b7e94c4f09946be448be208a562e1104 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptlib/CryptlibObjectIdentifiers.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptlib/CryptlibObjectIdentifiers.cs new file mode 100644 index 0000000..4156271 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptlib/CryptlibObjectIdentifiers.cs @@ -0,0 +1,15 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cryptlib +{ + internal class CryptlibObjectIdentifiers + { + internal static readonly DerObjectIdentifier cryptlib = new DerObjectIdentifier("1.3.6.1.4.1.3029"); + + internal static readonly DerObjectIdentifier ecc = cryptlib.Branch("1.5"); + + internal static readonly DerObjectIdentifier curvey25519 = ecc.Branch("1"); + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptlib/CryptlibObjectIdentifiers.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptlib/CryptlibObjectIdentifiers.cs.meta new file mode 100644 index 0000000..1c89bd0 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptlib/CryptlibObjectIdentifiers.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 856b811f51fd661418a85bce2a11f35a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/CryptoProObjectIdentifiers.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/CryptoProObjectIdentifiers.cs index de57d5c..a4a0c4b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/CryptoProObjectIdentifiers.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/CryptoProObjectIdentifiers.cs @@ -15,7 +15,9 @@ public abstract class CryptoProObjectIdentifiers public static readonly DerObjectIdentifier GostR3411 = new DerObjectIdentifier(GostID + ".9"); public static readonly DerObjectIdentifier GostR3411Hmac = new DerObjectIdentifier(GostID + ".10"); - public static readonly DerObjectIdentifier GostR28147Cbc = new DerObjectIdentifier(GostID + ".21"); + public static readonly DerObjectIdentifier GostR28147Gcfb = new DerObjectIdentifier(GostID + ".21"); + + public static readonly DerObjectIdentifier GostR28147Cbc = GostR28147Gcfb; public static readonly DerObjectIdentifier ID_Gost28147_89_CryptoPro_A_ParamSet = new DerObjectIdentifier(GostID + ".31.1"); @@ -49,6 +51,10 @@ public abstract class CryptoProObjectIdentifiers public static readonly DerObjectIdentifier GostElSgDH3410Default = new DerObjectIdentifier(GostID + ".36.0"); public static readonly DerObjectIdentifier GostElSgDH3410x1 = new DerObjectIdentifier(GostID + ".36.1"); + + public static readonly DerObjectIdentifier GostR3410x2001CryptoProESDH = new DerObjectIdentifier(GostID + ".96"); + + public static readonly DerObjectIdentifier GostR3410x2001DH = new DerObjectIdentifier(GostID + ".98"); } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/ECGOST3410NamedCurves.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/ECGOST3410NamedCurves.cs index 066c32e..a5616bf 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/ECGOST3410NamedCurves.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/ECGOST3410NamedCurves.cs @@ -1,29 +1,26 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Rosstandart; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9; -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.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro { - /// - /// Table of the available named parameters for GOST 3410-2001 / 2012. - /// - public sealed class ECGost3410NamedCurves + /// Elliptic curve registry for GOST 3410-2001 / 2012. + public static class ECGost3410NamedCurves { - private static ECPoint ConfigureBasepoint(ECCurve curve, BigInteger x, BigInteger y) + private static X9ECPoint ConfigureBasepoint(ECCurve curve, BigInteger x, BigInteger y) { ECPoint G = curve.CreatePoint(x, y); WNafUtilities.ConfigureBasepoint(G); - return G; + return new X9ECPoint(G, false); } private static ECCurve ConfigureCurve(ECCurve curve) @@ -31,253 +28,370 @@ private static ECCurve ConfigureCurve(ECCurve curve) return curve; } - private ECGost3410NamedCurves() + private static BigInteger FromHex(string hex) { + return new BigInteger(1, Hex.DecodeStrict(hex)); } - internal static readonly IDictionary objIds = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - internal static readonly IDictionary parameters = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - internal static readonly IDictionary names = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + internal class Holder_gostR3410_2001_CryptoPro_A + : X9ECParametersHolder + { + private Holder_gostR3410_2001_CryptoPro_A() {} - static ECGost3410NamedCurves() + internal static readonly X9ECParametersHolder Instance = new Holder_gostR3410_2001_CryptoPro_A(); + + protected override ECCurve CreateCurve() + { + BigInteger mod_p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD97"); + BigInteger mod_q = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6C611070995AD10045841B09B761B893"); + + return ConfigureCurve(new FpCurve( + mod_p, + FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD94"), + FromHex("A6"), + mod_q, BigInteger.One, true)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; + + X9ECPoint G = ConfigureBasepoint(curve, + BigInteger.One, + FromHex("8D91E471E0989CDA27DF505A453F2B7635294F2DDF23E3B122ACC99C9E9F1E14")); + + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); + } + }; + + internal class Holder_gostR3410_2001_CryptoPro_B + : X9ECParametersHolder { - BigInteger mod_p = new BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639319"); - BigInteger mod_q = new BigInteger("115792089237316195423570985008687907853073762908499243225378155805079068850323"); - - ECCurve curve = ConfigureCurve(new FpCurve( - mod_p, // p - new BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639316"), // a - new BigInteger("166"), // b - mod_q, BigInteger.One)); - - ECDomainParameters ecParams = new ECDomainParameters( - curve, - ConfigureBasepoint(curve, - new BigInteger("1"), // x - new BigInteger("64033881142927202683649881450433473985931760268884941288852745803908878638612")), // y - mod_q, BigInteger.One); - - parameters[CryptoProObjectIdentifiers.GostR3410x2001CryptoProA] = ecParams; - - mod_p = new BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639319"); - mod_q = new BigInteger("115792089237316195423570985008687907853073762908499243225378155805079068850323"); - - curve = ConfigureCurve(new FpCurve( - mod_p, // p - new BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639316"), - new BigInteger("166"), - mod_q, BigInteger.One)); - - ecParams = new ECDomainParameters( - curve, - ConfigureBasepoint(curve, - new BigInteger("1"), // x - new BigInteger("64033881142927202683649881450433473985931760268884941288852745803908878638612")), // y - mod_q, BigInteger.One); - - parameters[CryptoProObjectIdentifiers.GostR3410x2001CryptoProXchA] = ecParams; - - mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564823193"); //p - mod_q = new BigInteger("57896044618658097711785492504343953927102133160255826820068844496087732066703"); //q - - curve = ConfigureCurve(new FpCurve( - mod_p, // p - new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564823190"), // a - new BigInteger("28091019353058090096996979000309560759124368558014865957655842872397301267595"), // b - mod_q, BigInteger.One)); - - ecParams = new ECDomainParameters( - curve, - ConfigureBasepoint(curve, - new BigInteger("1"), // x - new BigInteger("28792665814854611296992347458380284135028636778229113005756334730996303888124")), // y - mod_q, BigInteger.One); - - parameters[CryptoProObjectIdentifiers.GostR3410x2001CryptoProB] = ecParams; - - mod_p = new BigInteger("70390085352083305199547718019018437841079516630045180471284346843705633502619"); - mod_q = new BigInteger("70390085352083305199547718019018437840920882647164081035322601458352298396601"); - - curve = ConfigureCurve(new FpCurve( - mod_p, // p - new BigInteger("70390085352083305199547718019018437841079516630045180471284346843705633502616"), - new BigInteger("32858"), - mod_q, BigInteger.One)); - - ecParams = new ECDomainParameters( - curve, - ConfigureBasepoint(curve, - new BigInteger("0"), - new BigInteger("29818893917731240733471273240314769927240550812383695689146495261604565990247")), - mod_q, BigInteger.One); - - parameters[CryptoProObjectIdentifiers.GostR3410x2001CryptoProXchB] = ecParams; - - mod_p = new BigInteger("70390085352083305199547718019018437841079516630045180471284346843705633502619"); //p - mod_q = new BigInteger("70390085352083305199547718019018437840920882647164081035322601458352298396601"); //q - - curve = ConfigureCurve(new FpCurve( - mod_p, // p - new BigInteger("70390085352083305199547718019018437841079516630045180471284346843705633502616"), // a - new BigInteger("32858"), // b - mod_q, BigInteger.One)); - - ecParams = new ECDomainParameters( - curve, - ConfigureBasepoint(curve, - new BigInteger("0"), // x - new BigInteger("29818893917731240733471273240314769927240550812383695689146495261604565990247")), // y - mod_q, BigInteger.One); - - parameters[CryptoProObjectIdentifiers.GostR3410x2001CryptoProC] = ecParams; - - //GOST34.10 2012 - mod_p = new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD97", 16); //p - mod_q = new BigInteger("400000000000000000000000000000000FD8CDDFC87B6635C115AF556C360C67", 16); //q - - curve = ConfigureCurve(new FpCurve( - mod_p, // p - new BigInteger("C2173F1513981673AF4892C23035A27CE25E2013BF95AA33B22C656F277E7335", 16), // a - new BigInteger("295F9BAE7428ED9CCC20E7C359A9D41A22FCCD9108E17BF7BA9337A6F8AE9513", 16), // b - mod_q, BigInteger.Four)); - - ecParams = new ECDomainParameters( - curve, - ConfigureBasepoint(curve, - new BigInteger("91E38443A5E82C0D880923425712B2BB658B9196932E02C78B2582FE742DAA28", 16), // x - new BigInteger("32879423AB1A0375895786C4BB46E9565FDE0B5344766740AF268ADB32322E5C", 16)), // y - mod_q, BigInteger.Four); - - parameters[RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256_paramSetA] = ecParams; - - mod_p = new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDC7", 16); //p - mod_q = new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF27E69532F48D89116FF22B8D4E0560609B4B38ABFAD2B85DCACDB1411F10B275", 16); //q - - curve = ConfigureCurve(new FpCurve( - mod_p, // p - new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDC4", 16), // a - new BigInteger("E8C2505DEDFC86DDC1BD0B2B6667F1DA34B82574761CB0E879BD081CFD0B6265EE3CB090F30D27614CB4574010DA90DD862EF9D4EBEE4761503190785A71C760", 16), // b - mod_q, BigInteger.One)); - - ecParams = new ECDomainParameters( - curve, - ConfigureBasepoint(curve, - new BigInteger("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003"), // x - new BigInteger("7503CFE87A836AE3A61B8816E25450E6CE5E1C93ACF1ABC1778064FDCBEFA921DF1626BE4FD036E93D75E6A50E3A41E98028FE5FC235F5B889A589CB5215F2A4", 16)), // y - mod_q, BigInteger.One); - - parameters[RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512_paramSetA] = ecParams; - - mod_p = new BigInteger("8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006F", 16); //p - mod_q = new BigInteger("800000000000000000000000000000000000000000000000000000000000000149A1EC142565A545ACFDB77BD9D40CFA8B996712101BEA0EC6346C54374F25BD", 16); //q - - curve = ConfigureCurve(new FpCurve( - mod_p, // p - new BigInteger("8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006C", 16), // a - new BigInteger("687D1B459DC841457E3E06CF6F5E2517B97C7D614AF138BCBF85DC806C4B289F3E965D2DB1416D217F8B276FAD1AB69C50F78BEE1FA3106EFB8CCBC7C5140116", 16), // b - mod_q, BigInteger.One)); - - ecParams = new ECDomainParameters( - curve, - ConfigureBasepoint(curve, - new BigInteger("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002"), // x - new BigInteger("1A8F7EDA389B094C2C071E3647A8940F3C123B697578C213BE6DD9E6C8EC7335DCB228FD1EDF4A39152CBCAAF8C0398828041055F94CEEEC7E21340780FE41BD", 16)), // y - mod_q, BigInteger.One); - - parameters[RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512_paramSetB] = ecParams; - - mod_p = new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDC7", 16); //p - mod_q = new BigInteger("3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC98CDBA46506AB004C33A9FF5147502CC8EDA9E7A769A12694623CEF47F023ED", 16); //q - - curve = ConfigureCurve(new FpCurve( - mod_p, // p - new BigInteger("DC9203E514A721875485A529D2C722FB187BC8980EB866644DE41C68E143064546E861C0E2C9EDD92ADE71F46FCF50FF2AD97F951FDA9F2A2EB6546F39689BD3", 16), // a - new BigInteger("B4C4EE28CEBC6C2C8AC12952CF37F16AC7EFB6A9F69F4B57FFDA2E4F0DE5ADE038CBC2FFF719D2C18DE0284B8BFEF3B52B8CC7A5F5BF0A3C8D2319A5312557E1", 16), // b - mod_q, BigInteger.Four)); - - ecParams = new ECDomainParameters( - curve, - ConfigureBasepoint(curve, - new BigInteger("E2E31EDFC23DE7BDEBE241CE593EF5DE2295B7A9CBAEF021D385F7074CEA043AA27272A7AE602BF2A7B9033DB9ED3610C6FB85487EAE97AAC5BC7928C1950148", 16), // x - new BigInteger("F5CE40D95B5EB899ABBCCFF5911CB8577939804D6527378B8C108C3D2090FF9BE18E2D33E3021ED2EF32D85822423B6304F726AA854BAE07D0396E9A9ADDC40F", 16)), // y - mod_q, BigInteger.Four); - - parameters[RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512_paramSetC] = ecParams; - - objIds["GostR3410-2001-CryptoPro-A"] = CryptoProObjectIdentifiers.GostR3410x2001CryptoProA; - objIds["GostR3410-2001-CryptoPro-B"] = CryptoProObjectIdentifiers.GostR3410x2001CryptoProB; - objIds["GostR3410-2001-CryptoPro-C"] = CryptoProObjectIdentifiers.GostR3410x2001CryptoProC; - objIds["GostR3410-2001-CryptoPro-XchA"] = CryptoProObjectIdentifiers.GostR3410x2001CryptoProXchA; - objIds["GostR3410-2001-CryptoPro-XchB"] = CryptoProObjectIdentifiers.GostR3410x2001CryptoProXchB; - objIds["Tc26-Gost-3410-12-256-paramSetA"] = RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256_paramSetA; - objIds["Tc26-Gost-3410-12-512-paramSetA"] = RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512_paramSetA; - objIds["Tc26-Gost-3410-12-512-paramSetB"] = RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512_paramSetB; - objIds["Tc26-Gost-3410-12-512-paramSetC"] = RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512_paramSetC; - - names[CryptoProObjectIdentifiers.GostR3410x2001CryptoProA] = "GostR3410-2001-CryptoPro-A"; - names[CryptoProObjectIdentifiers.GostR3410x2001CryptoProB] = "GostR3410-2001-CryptoPro-B"; - names[CryptoProObjectIdentifiers.GostR3410x2001CryptoProC] = "GostR3410-2001-CryptoPro-C"; - names[CryptoProObjectIdentifiers.GostR3410x2001CryptoProXchA] = "GostR3410-2001-CryptoPro-XchA"; - names[CryptoProObjectIdentifiers.GostR3410x2001CryptoProXchB] = "GostR3410-2001-CryptoPro-XchB"; - names[RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256_paramSetA] = "Tc26-Gost-3410-12-256-paramSetA"; - names[RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512_paramSetA] = "Tc26-Gost-3410-12-512-paramSetA"; - names[RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512_paramSetB] = "Tc26-Gost-3410-12-512-paramSetB"; - names[RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512_paramSetC] = "Tc26-Gost-3410-12-512-paramSetC"; - } + private Holder_gostR3410_2001_CryptoPro_B() {} + + internal static readonly X9ECParametersHolder Instance = new Holder_gostR3410_2001_CryptoPro_B(); + + protected override ECCurve CreateCurve() + { + BigInteger mod_p = FromHex("8000000000000000000000000000000000000000000000000000000000000C99"); + BigInteger mod_q = FromHex("800000000000000000000000000000015F700CFFF1A624E5E497161BCC8A198F"); + + return ConfigureCurve(new FpCurve( + mod_p, + FromHex("8000000000000000000000000000000000000000000000000000000000000C96"), + FromHex("3E1AF419A269A5F866A7D3C25C3DF80AE979259373FF2B182F49D4CE7E1BBC8B"), + mod_q, BigInteger.One, true)); + } - /** - * return the ECDomainParameters object for the given OID, null if it - * isn't present. - * - * @param oid an object identifier representing a named parameters, if present. - */ + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; - public static ECDomainParameters GetByOid(DerObjectIdentifier oid) + X9ECPoint G = ConfigureBasepoint(curve, + BigInteger.One, + FromHex("3FA8124359F96680B83D1C3EB2C070E5C545C9858D03ECFB744BF8D717717EFC")); + + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); + } + }; + + internal class Holder_gostR3410_2001_CryptoPro_C + : X9ECParametersHolder { - return (ECDomainParameters)parameters[oid]; + private Holder_gostR3410_2001_CryptoPro_C() {} + + internal static readonly X9ECParametersHolder Instance = new Holder_gostR3410_2001_CryptoPro_C(); + + protected override ECCurve CreateCurve() + { + BigInteger mod_p = FromHex("9B9F605F5A858107AB1EC85E6B41C8AACF846E86789051D37998F7B9022D759B"); + BigInteger mod_q = FromHex("9B9F605F5A858107AB1EC85E6B41C8AA582CA3511EDDFB74F02F3A6598980BB9"); + + return ConfigureCurve(new FpCurve( + mod_p, + FromHex("9B9F605F5A858107AB1EC85E6B41C8AACF846E86789051D37998F7B9022D7598"), + FromHex("805A"), + mod_q, BigInteger.One, true)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; + + X9ECPoint G = ConfigureBasepoint(curve, + BigInteger.Zero, + FromHex("41ECE55743711A8C3CBF3783CD08C0EE4D4DC440D4641A8F366E550DFDB3BB67")); + + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); + } + }; + + internal class Holder_gostR3410_2001_CryptoPro_XchB + : X9ECParametersHolder + { + private Holder_gostR3410_2001_CryptoPro_XchB() {} + + internal static readonly X9ECParametersHolder Instance = new Holder_gostR3410_2001_CryptoPro_XchB(); + + protected override ECCurve CreateCurve() + { + BigInteger mod_p = FromHex("9B9F605F5A858107AB1EC85E6B41C8AACF846E86789051D37998F7B9022D759B"); + BigInteger mod_q = FromHex("9B9F605F5A858107AB1EC85E6B41C8AA582CA3511EDDFB74F02F3A6598980BB9"); + + return ConfigureCurve(new FpCurve( + mod_p, + FromHex("9B9F605F5A858107AB1EC85E6B41C8AACF846E86789051D37998F7B9022D7598"), + FromHex("805A"), + mod_q, BigInteger.One, true)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; + + X9ECPoint G = ConfigureBasepoint(curve, + BigInteger.Zero, + FromHex("41ECE55743711A8C3CBF3783CD08C0EE4D4DC440D4641A8F366E550DFDB3BB67")); + + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); + } + }; + + internal class Holder_id_tc26_gost_3410_12_256_paramSetA + : X9ECParametersHolder + { + private Holder_id_tc26_gost_3410_12_256_paramSetA() {} + + internal static readonly X9ECParametersHolder Instance = new Holder_id_tc26_gost_3410_12_256_paramSetA(); + + protected override ECCurve CreateCurve() + { + BigInteger mod_p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD97"); + BigInteger mod_q = FromHex("400000000000000000000000000000000FD8CDDFC87B6635C115AF556C360C67"); + + return ConfigureCurve(new FpCurve( + mod_p, + FromHex("C2173F1513981673AF4892C23035A27CE25E2013BF95AA33B22C656F277E7335"), + FromHex("295F9BAE7428ED9CCC20E7C359A9D41A22FCCD9108E17BF7BA9337A6F8AE9513"), + mod_q, BigInteger.Four, true)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; + + X9ECPoint G = ConfigureBasepoint(curve, + FromHex("91E38443A5E82C0D880923425712B2BB658B9196932E02C78B2582FE742DAA28"), + FromHex("32879423AB1A0375895786C4BB46E9565FDE0B5344766740AF268ADB32322E5C")); + + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); + } + }; + + internal class Holder_id_tc26_gost_3410_12_512_paramSetA + : X9ECParametersHolder + { + private Holder_id_tc26_gost_3410_12_512_paramSetA() {} + + internal static readonly X9ECParametersHolder Instance = new Holder_id_tc26_gost_3410_12_512_paramSetA(); + + protected override ECCurve CreateCurve() + { + BigInteger mod_p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDC7"); + BigInteger mod_q = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF27E69532F48D89116FF22B8D4E0560609B4B38ABFAD2B85DCACDB1411F10B275"); + + return ConfigureCurve(new FpCurve( + mod_p, + FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDC4"), + FromHex("E8C2505DEDFC86DDC1BD0B2B6667F1DA34B82574761CB0E879BD081CFD0B6265EE3CB090F30D27614CB4574010DA90DD862EF9D4EBEE4761503190785A71C760"), + mod_q, BigInteger.One, true)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; + + X9ECPoint G = ConfigureBasepoint(curve, + BigInteger.Three, + FromHex("7503CFE87A836AE3A61B8816E25450E6CE5E1C93ACF1ABC1778064FDCBEFA921DF1626BE4FD036E93D75E6A50E3A41E98028FE5FC235F5B889A589CB5215F2A4")); + + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); + } + }; + + internal class Holder_id_tc26_gost_3410_12_512_paramSetB + : X9ECParametersHolder + { + private Holder_id_tc26_gost_3410_12_512_paramSetB() {} + + internal static readonly X9ECParametersHolder Instance = new Holder_id_tc26_gost_3410_12_512_paramSetB(); + + protected override ECCurve CreateCurve() + { + BigInteger mod_p = FromHex("8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006F"); + BigInteger mod_q = FromHex("800000000000000000000000000000000000000000000000000000000000000149A1EC142565A545ACFDB77BD9D40CFA8B996712101BEA0EC6346C54374F25BD"); + + return ConfigureCurve(new FpCurve( + mod_p, + FromHex("8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006C"), + FromHex("687D1B459DC841457E3E06CF6F5E2517B97C7D614AF138BCBF85DC806C4B289F3E965D2DB1416D217F8B276FAD1AB69C50F78BEE1FA3106EFB8CCBC7C5140116"), + mod_q, BigInteger.One, true)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; + + X9ECPoint G = ConfigureBasepoint(curve, + BigInteger.Two, + FromHex("1A8F7EDA389B094C2C071E3647A8940F3C123B697578C213BE6DD9E6C8EC7335DCB228FD1EDF4A39152CBCAAF8C0398828041055F94CEEEC7E21340780FE41BD")); + + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); + } + }; + + internal class Holder_id_tc26_gost_3410_12_512_paramSetC + : X9ECParametersHolder + { + private Holder_id_tc26_gost_3410_12_512_paramSetC() {} + + internal static readonly X9ECParametersHolder Instance = new Holder_id_tc26_gost_3410_12_512_paramSetC(); + + protected override ECCurve CreateCurve() + { + BigInteger mod_p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDC7"); + BigInteger mod_q = FromHex("3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC98CDBA46506AB004C33A9FF5147502CC8EDA9E7A769A12694623CEF47F023ED"); + + return ConfigureCurve(new FpCurve( + mod_p, + FromHex("DC9203E514A721875485A529D2C722FB187BC8980EB866644DE41C68E143064546E861C0E2C9EDD92ADE71F46FCF50FF2AD97F951FDA9F2A2EB6546F39689BD3"), + FromHex("B4C4EE28CEBC6C2C8AC12952CF37F16AC7EFB6A9F69F4B57FFDA2E4F0DE5ADE038CBC2FFF719D2C18DE0284B8BFEF3B52B8CC7A5F5BF0A3C8D2319A5312557E1"), + mod_q, BigInteger.Four, true)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; + + X9ECPoint G = ConfigureBasepoint(curve, + FromHex("E2E31EDFC23DE7BDEBE241CE593EF5DE2295B7A9CBAEF021D385F7074CEA043AA27272A7AE602BF2A7B9033DB9ED3610C6FB85487EAE97AAC5BC7928C1950148"), + FromHex("F5CE40D95B5EB899ABBCCFF5911CB8577939804D6527378B8C108C3D2090FF9BE18E2D33E3021ED2EF32D85822423B6304F726AA854BAE07D0396E9A9ADDC40F")); + + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); + } + }; + + private static readonly Dictionary objIds = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly Dictionary curves = + new Dictionary(); + private static readonly Dictionary names = + new Dictionary(); + + private static void DefineCurve(string name, DerObjectIdentifier oid, X9ECParametersHolder holder) + { + objIds.Add(name, oid); + names.Add(oid, name); + curves.Add(oid, holder); } - public static X9ECParameters GetByOidX9(DerObjectIdentifier oid) + static ECGost3410NamedCurves() { - ECDomainParameters ec = (ECDomainParameters)parameters[oid]; - return ec == null ? null : new X9ECParameters(ec.Curve, new X9ECPoint(ec.G, false), ec.N, ec.H, ec.GetSeed()); + DefineCurve("GostR3410-2001-CryptoPro-A", + CryptoProObjectIdentifiers.GostR3410x2001CryptoProA, + Holder_gostR3410_2001_CryptoPro_A.Instance); + DefineCurve("GostR3410-2001-CryptoPro-B", + CryptoProObjectIdentifiers.GostR3410x2001CryptoProB, + Holder_gostR3410_2001_CryptoPro_B.Instance); + DefineCurve("GostR3410-2001-CryptoPro-C", + CryptoProObjectIdentifiers.GostR3410x2001CryptoProC, + Holder_gostR3410_2001_CryptoPro_C.Instance); + DefineCurve("GostR3410-2001-CryptoPro-XchA", + CryptoProObjectIdentifiers.GostR3410x2001CryptoProXchA, + Holder_gostR3410_2001_CryptoPro_A.Instance); + DefineCurve("GostR3410-2001-CryptoPro-XchB", + CryptoProObjectIdentifiers.GostR3410x2001CryptoProXchB, + Holder_gostR3410_2001_CryptoPro_XchB.Instance); + DefineCurve("Tc26-Gost-3410-12-256-paramSetA", + RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256_paramSetA, + Holder_id_tc26_gost_3410_12_256_paramSetA.Instance); + DefineCurve("Tc26-Gost-3410-12-512-paramSetA", + RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512_paramSetA, + Holder_id_tc26_gost_3410_12_512_paramSetA.Instance); + DefineCurve("Tc26-Gost-3410-12-512-paramSetB", + RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512_paramSetB, + Holder_id_tc26_gost_3410_12_512_paramSetB.Instance); + DefineCurve("Tc26-Gost-3410-12-512-paramSetC", + RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512_paramSetC, + Holder_id_tc26_gost_3410_12_512_paramSetC.Instance); } - /** - * returns an enumeration containing the name strings for curves - * contained in this structure. - */ - public static IEnumerable Names + /// Look up the for the curve with the given name. + /// The name of the curve. + public static X9ECParameters GetByName(string name) { - get { return new EnumerableProxy(names.Values); } + DerObjectIdentifier oid = GetOid(name); + return oid == null ? null : GetByOid(oid); } + /// Look up an for the curve with the given name. + /// + /// Allows accessing the curve without necessarily triggering the creation of the + /// full . + /// + /// The name of the curve. + public static X9ECParametersHolder GetByNameLazy(string name) + { + DerObjectIdentifier oid = GetOid(name); + return oid == null ? null : GetByOidLazy(oid); + } + + /// Look up the for the curve with the given + /// OID. + /// The OID for the curve. + public static X9ECParameters GetByOid(DerObjectIdentifier oid) + { + return GetByOidLazy(oid)?.Parameters; + } - public static ECDomainParameters GetByName(string name) + /// Look up an for the curve with the given + /// OID. + /// + /// Allows accessing the curve without necessarily triggering the creation of the + /// full . + /// + /// The OID for the curve. + public static X9ECParametersHolder GetByOidLazy(DerObjectIdentifier oid) { - DerObjectIdentifier oid = (DerObjectIdentifier)objIds[name]; - return oid == null ? null : (ECDomainParameters)parameters[oid]; + return CollectionUtilities.GetValueOrNull(curves, oid); } - public static X9ECParameters GetByNameX9(string name) + /// Look up the name of the curve with the given OID. + /// The OID for the curve. + public static string GetName(DerObjectIdentifier oid) { - DerObjectIdentifier oid = (DerObjectIdentifier)objIds[name]; - return oid == null ? null : GetByOidX9(oid); + return CollectionUtilities.GetValueOrNull(names, oid); } - /** - * return the named curve name represented by the given object identifier. - */ - public static string GetName( - DerObjectIdentifier oid) + /// Look up the OID of the curve with the given name. + /// The name of the curve. + public static DerObjectIdentifier GetOid(string name) { - return (string)names[oid]; + return CollectionUtilities.GetValueOrNull(objIds, name); } - public static DerObjectIdentifier GetOid( - string name) + /// Enumerate the available curve names in this registry. + public static IEnumerable Names { - return (DerObjectIdentifier)objIds[name]; + get { return CollectionUtilities.Proxy(objIds.Keys); } } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/ECGOST3410ParamSetParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/ECGOST3410ParamSetParameters.cs index d3dd515..e9f9550 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/ECGOST3410ParamSetParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/ECGOST3410ParamSetParameters.cs @@ -1,7 +1,6 @@ #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; @@ -13,27 +12,22 @@ public class ECGost3410ParamSetParameters { internal readonly DerInteger p, q, a, b, x, y; - public static ECGost3410ParamSetParameters GetInstance( - Asn1TaggedObject obj, - bool explicitly) + public static ECGost3410ParamSetParameters GetInstance(Asn1TaggedObject obj, bool explicitly) { return GetInstance(Asn1Sequence.GetInstance(obj, explicitly)); } - public static ECGost3410ParamSetParameters GetInstance( - object obj) + public static ECGost3410ParamSetParameters GetInstance(object obj) { if (obj == null || obj is ECGost3410ParamSetParameters) { return (ECGost3410ParamSetParameters) obj; } - if (obj is Asn1Sequence) - { - return new ECGost3410ParamSetParameters((Asn1Sequence) obj); - } + if (obj is Asn1Sequence seq) + return new ECGost3410ParamSetParameters(seq); - throw new ArgumentException("Invalid GOST3410Parameter: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("Invalid GOST3410Parameter: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } public ECGost3410ParamSetParameters( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/GOST28147Parameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/GOST28147Parameters.cs index fdafea0..9f32d39 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/GOST28147Parameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/GOST28147Parameters.cs @@ -1,7 +1,6 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -13,31 +12,23 @@ public class Gost28147Parameters private readonly Asn1OctetString iv; private readonly DerObjectIdentifier paramSet; - public static Gost28147Parameters GetInstance( - Asn1TaggedObject obj, - bool explicitly) + public static Gost28147Parameters GetInstance(Asn1TaggedObject obj, bool explicitly) { return GetInstance(Asn1Sequence.GetInstance(obj, explicitly)); } - public static Gost28147Parameters GetInstance( - object obj) + public static Gost28147Parameters GetInstance(object obj) { if (obj == null || obj is Gost28147Parameters) - { return (Gost28147Parameters) obj; - } - if (obj is Asn1Sequence) - { - return new Gost28147Parameters((Asn1Sequence) obj); - } + if (obj is Asn1Sequence seq) + return new Gost28147Parameters(seq); - throw new ArgumentException("Invalid GOST3410Parameter: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("Invalid GOST3410Parameter: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } - private Gost28147Parameters( - Asn1Sequence seq) + private Gost28147Parameters(Asn1Sequence seq) { if (seq.Count != 2) throw new ArgumentException("Wrong number of elements in sequence", "seq"); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/GOST3410NamedParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/GOST3410NamedParameters.cs index 064ad6d..7c67dfb 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/GOST3410NamedParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/GOST3410NamedParameters.cs @@ -1,27 +1,16 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro { - /** - * table of the available named parameters for GOST 3410-94. - */ - public sealed class Gost3410NamedParameters + /// Registry of available named parameters for GOST 3410-94. + public static class Gost3410NamedParameters { - private Gost3410NamedParameters() - { - } - - private static readonly IDictionary objIds = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private static readonly IDictionary parameters = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private static readonly Gost3410ParamSetParameters cryptoProA = new Gost3410ParamSetParameters( 1024, new BigInteger("127021248288932417465907042777176443525787653508916535812817507265705031260985098497423188333483401180925999995120988934130659205614996724254121049274349357074920312769561451689224110579311248812610229678534638401693520013288995000362260684222750813532307004517341633685004541062586971416883686778842537820383"), @@ -67,59 +56,55 @@ private Gost3410NamedParameters() new BigInteger("133531813272720673433859519948319001217942375967847486899482359599369642528734712461590403327731821410328012529253871914788598993103310567744136196364803064721377826656898686468463277710150809401182608770201615324990468332931294920912776241137878030224355746606283971659376426832674269780880061631528163475887") ); - static Gost3410NamedParameters() - { - parameters[CryptoProObjectIdentifiers.GostR3410x94CryptoProA] = cryptoProA; - parameters[CryptoProObjectIdentifiers.GostR3410x94CryptoProB] = cryptoProB; - //parameters[CryptoProObjectIdentifiers.GostR3410x94CryptoProC] = cryptoProC; - //parameters[CryptoProObjectIdentifiers.GostR3410x94CryptoProD] = cryptoProD; - parameters[CryptoProObjectIdentifiers.GostR3410x94CryptoProXchA] = cryptoProXchA; - //parameters[CryptoProObjectIdentifiers.GostR3410x94CryptoProXchB] = cryptoProXchA; - //parameters[CryptoProObjectIdentifiers.GostR3410x94CryptoProXchC] = cryptoProXchA; + private static readonly Dictionary objIds = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly Dictionary parameters = + new Dictionary(); - objIds["GostR3410-94-CryptoPro-A"] = CryptoProObjectIdentifiers.GostR3410x94CryptoProA; - objIds["GostR3410-94-CryptoPro-B"] = CryptoProObjectIdentifiers.GostR3410x94CryptoProB; - objIds["GostR3410-94-CryptoPro-XchA"] = CryptoProObjectIdentifiers.GostR3410x94CryptoProXchA; + private static void DefineParameters(string name, DerObjectIdentifier oid, + Gost3410ParamSetParameters parameterSet) + { + objIds.Add(name, oid); + parameters.Add(oid, parameterSet); } - /** - * return the GOST3410ParamSetParameters object for the given OID, null if it - * isn't present. - * - * @param oid an object identifier representing a named parameters, if present. - */ - public static Gost3410ParamSetParameters GetByOid( - DerObjectIdentifier oid) + static Gost3410NamedParameters() { - return (Gost3410ParamSetParameters) parameters[oid]; + DefineParameters("GostR3410-94-CryptoPro-A", CryptoProObjectIdentifiers.GostR3410x94CryptoProA, cryptoProA); + DefineParameters("GostR3410-94-CryptoPro-B", CryptoProObjectIdentifiers.GostR3410x94CryptoProB, cryptoProB); + DefineParameters("GostR3410-94-CryptoPro-XchA", CryptoProObjectIdentifiers.GostR3410x94CryptoProXchA, + cryptoProXchA); } - /** - * returns an enumeration containing the name strings for parameters - * contained in this structure. - */ - public static IEnumerable Names + /// Look up the for the parameter set with the given name. + /// + /// The name of the parameter set. + public static Gost3410ParamSetParameters GetByName(string name) { - get { return new EnumerableProxy(objIds.Keys); } + DerObjectIdentifier oid = GetOid(name); + return oid == null ? null : GetByOid(oid); } - public static Gost3410ParamSetParameters GetByName( - string name) + /// Look up the for the parameter set with the given + /// OID. + /// The OID for the parameter set. + public static Gost3410ParamSetParameters GetByOid(DerObjectIdentifier oid) { - DerObjectIdentifier oid = (DerObjectIdentifier) objIds[name]; - - if (oid != null) - { - return (Gost3410ParamSetParameters) parameters[oid]; - } + return CollectionUtilities.GetValueOrNull(parameters, oid); + } - return null; + /// Look up the OID of the parameter set with the given name. + /// + /// The name of the parameter set. + public static DerObjectIdentifier GetOid(string name) + { + return CollectionUtilities.GetValueOrNull(objIds, name); } - public static DerObjectIdentifier GetOid( - string name) + /// Enumerate the available parameter set names in this registry. + public static IEnumerable Names { - return (DerObjectIdentifier) objIds[name]; + get { return CollectionUtilities.Proxy(objIds.Keys); } } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/GOST3410ParamSetParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/GOST3410ParamSetParameters.cs index fe3fc82..717372d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/GOST3410ParamSetParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/GOST3410ParamSetParameters.cs @@ -1,7 +1,6 @@ #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; @@ -14,27 +13,20 @@ public class Gost3410ParamSetParameters private readonly int keySize; private readonly DerInteger p, q, a; - public static Gost3410ParamSetParameters GetInstance( - Asn1TaggedObject obj, - bool explicitly) + public static Gost3410ParamSetParameters GetInstance(Asn1TaggedObject obj, bool explicitly) { return GetInstance(Asn1Sequence.GetInstance(obj, explicitly)); } - public static Gost3410ParamSetParameters GetInstance( - object obj) + public static Gost3410ParamSetParameters GetInstance(object obj) { if (obj == null || obj is Gost3410ParamSetParameters) - { return (Gost3410ParamSetParameters) obj; - } - if (obj is Asn1Sequence) - { - return new Gost3410ParamSetParameters((Asn1Sequence) obj); - } + if (obj is Asn1Sequence seq) + return new Gost3410ParamSetParameters(seq); - throw new ArgumentException("Invalid GOST3410Parameter: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("Invalid GOST3410Parameter: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } public Gost3410ParamSetParameters( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/GOST3410PublicKeyAlgParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/GOST3410PublicKeyAlgParameters.cs index ff4c242..cd45b39 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/GOST3410PublicKeyAlgParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/cryptopro/GOST3410PublicKeyAlgParameters.cs @@ -2,8 +2,6 @@ #pragma warning disable using System; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; - namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro { public class Gost3410PublicKeyAlgParameters @@ -13,20 +11,17 @@ public class Gost3410PublicKeyAlgParameters private DerObjectIdentifier digestParamSet; private DerObjectIdentifier encryptionParamSet; - public static Gost3410PublicKeyAlgParameters GetInstance( - Asn1TaggedObject obj, - bool explicitly) + public static Gost3410PublicKeyAlgParameters GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - return GetInstance(Asn1Sequence.GetInstance(obj, explicitly)); + return GetInstance(Asn1Sequence.GetInstance(taggedObject, declaredExplicit)); } - public static Gost3410PublicKeyAlgParameters GetInstance( - object obj) + public static Gost3410PublicKeyAlgParameters GetInstance(object obj) { if (obj == null || obj is Gost3410PublicKeyAlgParameters) return (Gost3410PublicKeyAlgParameters)obj; - return new Gost3410PublicKeyAlgParameters(Asn1Sequence.GetInstance((obj))); + return new Gost3410PublicKeyAlgParameters(Asn1Sequence.GetInstance(obj)); } public Gost3410PublicKeyAlgParameters( @@ -51,9 +46,7 @@ public Gost3410PublicKeyAlgParameters( this.encryptionParamSet = encryptionParamSet; } - - public Gost3410PublicKeyAlgParameters( - Asn1Sequence seq) + private Gost3410PublicKeyAlgParameters(Asn1Sequence seq) { this.publicKeyParamSet = (DerObjectIdentifier) seq[0]; this.digestParamSet = (DerObjectIdentifier) seq[1]; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CertificateValues.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CertificateValues.cs index 33f9f32..e107df7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CertificateValues.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CertificateValues.cs @@ -1,11 +1,10 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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.Asn1.Esf { @@ -31,7 +30,7 @@ public static CertificateValues GetInstance( throw new ArgumentException( "Unknown object in 'CertificateValues' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } @@ -59,12 +58,10 @@ public CertificateValues( } public CertificateValues( - IEnumerable certificates) + IEnumerable certificates) { if (certificates == null) throw new ArgumentNullException("certificates"); - if (!CollectionUtilities.CheckElementsAreOfType(certificates, typeof(X509CertificateStructure))) - throw new ArgumentException("Must contain only 'X509CertificateStructure' objects", "certificates"); this.certificates = new DerSequence( Asn1EncodableVector.FromEnumerable(certificates)); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CommitmentTypeIndication.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CommitmentTypeIndication.cs index 7f8fa8e..ff160f1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CommitmentTypeIndication.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CommitmentTypeIndication.cs @@ -23,7 +23,7 @@ public static CommitmentTypeIndication GetInstance( throw new ArgumentException( "Unknown object in 'CommitmentTypeIndication' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CommitmentTypeQualifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CommitmentTypeQualifier.cs index 1c05410..06fe4a4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CommitmentTypeQualifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CommitmentTypeQualifier.cs @@ -86,7 +86,7 @@ public static CommitmentTypeQualifier GetInstance( throw new ArgumentException( "Unknown object in 'CommitmentTypeQualifier' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CompleteCertificateRefs.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CompleteCertificateRefs.cs index 77d2612..5bc3964 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CompleteCertificateRefs.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CompleteCertificateRefs.cs @@ -1,10 +1,9 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Esf { @@ -30,7 +29,7 @@ public static CompleteCertificateRefs GetInstance( throw new ArgumentException( "Unknown object in 'CompleteCertificateRefs' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } @@ -58,12 +57,10 @@ public CompleteCertificateRefs( } public CompleteCertificateRefs( - IEnumerable otherCertIDs) + IEnumerable otherCertIDs) { if (otherCertIDs == null) throw new ArgumentNullException("otherCertIDs"); - if (!CollectionUtilities.CheckElementsAreOfType(otherCertIDs, typeof(OtherCertID))) - throw new ArgumentException("Must contain only 'OtherCertID' objects", "otherCertIDs"); this.otherCertIDs = new DerSequence( Asn1EncodableVector.FromEnumerable(otherCertIDs)); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CompleteRevocationRefs.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CompleteRevocationRefs.cs index 2d08f21..844354c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CompleteRevocationRefs.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CompleteRevocationRefs.cs @@ -1,10 +1,9 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Esf { @@ -30,7 +29,7 @@ public static CompleteRevocationRefs GetInstance( throw new ArgumentException( "Unknown object in 'CompleteRevocationRefs' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } @@ -58,12 +57,10 @@ public CompleteRevocationRefs( } public CompleteRevocationRefs( - IEnumerable crlOcspRefs) + IEnumerable crlOcspRefs) { if (crlOcspRefs == null) throw new ArgumentNullException("crlOcspRefs"); - if (!CollectionUtilities.CheckElementsAreOfType(crlOcspRefs, typeof(CrlOcspRef))) - throw new ArgumentException("Must contain only 'CrlOcspRef' objects", "crlOcspRefs"); this.crlOcspRefs = new DerSequence( Asn1EncodableVector.FromEnumerable(crlOcspRefs)); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CrlIdentifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CrlIdentifier.cs index 61dfc96..7bca4f2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CrlIdentifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CrlIdentifier.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; - +using System.Reflection; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -22,35 +22,37 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Esf public class CrlIdentifier : Asn1Encodable { - private readonly X509Name crlIssuer; - private readonly DerUtcTime crlIssuedTime; - private readonly DerInteger crlNumber; + private readonly X509Name crlIssuer; + private readonly Asn1UtcTime crlIssuedTime; + private readonly DerInteger crlNumber; - public static CrlIdentifier GetInstance( - object obj) + public static CrlIdentifier GetInstance(object obj) { - if (obj == null || obj is CrlIdentifier) - return (CrlIdentifier) obj; + if (obj == null) + return null; + + if (obj is CrlIdentifier crlIdentifier) + return crlIdentifier; - if (obj is Asn1Sequence) - return new CrlIdentifier((Asn1Sequence) obj); + if (obj is Asn1Sequence asn1Sequence) + return new CrlIdentifier(asn1Sequence); - throw new ArgumentException( - "Unknown object in 'CrlIdentifier' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), - "obj"); + throw new ArgumentException("Unknown object in 'CrlIdentifier' factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + nameof(obj)); } - private CrlIdentifier( - Asn1Sequence seq) + private CrlIdentifier(Asn1Sequence seq) { if (seq == null) - throw new ArgumentNullException("seq"); + throw new ArgumentNullException(nameof(seq)); if (seq.Count < 2 || seq.Count > 3) - throw new ArgumentException("Bad sequence size: " + seq.Count, "seq"); + throw new ArgumentException("Bad sequence size: " + seq.Count, nameof(seq)); this.crlIssuer = X509Name.GetInstance(seq[0]); - this.crlIssuedTime = DerUtcTime.GetInstance(seq[1]); + this.crlIssuedTime = Asn1UtcTime.GetInstance(seq[1]); + + // Validate crlIssuedTime is in the appropriate year range + crlIssuedTime.ToDateTime(2049); if (seq.Count > 2) { @@ -58,38 +60,48 @@ private CrlIdentifier( } } - public CrlIdentifier( - X509Name crlIssuer, - DateTime crlIssuedTime) - : this(crlIssuer, crlIssuedTime, null) + public CrlIdentifier(X509Name crlIssuer, DateTime crlIssuedTime) + : this(crlIssuer, crlIssuedTime, null) { } - public CrlIdentifier( - X509Name crlIssuer, - DateTime crlIssuedTime, - BigInteger crlNumber) + public CrlIdentifier(X509Name crlIssuer, DateTime crlIssuedTime, BigInteger crlNumber) + : this(crlIssuer, new Asn1UtcTime(crlIssuedTime, 2049), crlNumber) { - if (crlIssuer == null) - throw new ArgumentNullException("crlIssuer"); + } - this.crlIssuer = crlIssuer; - this.crlIssuedTime = new DerUtcTime(crlIssuedTime); + public CrlIdentifier(X509Name crlIssuer, Asn1UtcTime crlIssuedTime) + : this(crlIssuer, crlIssuedTime, null) + { + } - if (crlNumber != null) - { - this.crlNumber = new DerInteger(crlNumber); - } - } + public CrlIdentifier(X509Name crlIssuer, Asn1UtcTime crlIssuedTime, BigInteger crlNumber) + { + if (crlIssuer == null) + throw new ArgumentNullException(nameof(crlIssuer)); + if (crlIssuedTime == null) + throw new ArgumentNullException(nameof(crlIssuedTime)); + + // Validate crlIssuedTime is in the appropriate year range + crlIssuedTime.ToDateTime(2049); + + this.crlIssuer = crlIssuer; + this.crlIssuedTime = crlIssuedTime; + + if (null != crlNumber) + { + this.crlNumber = new DerInteger(crlNumber); + } + } - public X509Name CrlIssuer + public X509Name CrlIssuer { get { return crlIssuer; } } public DateTime CrlIssuedTime { - get { return crlIssuedTime.ToAdjustedDateTime(); } + get { return crlIssuedTime.ToDateTime(2049); } } public BigInteger CrlNumber diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CrlListID.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CrlListID.cs index c055fc3..e680705 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CrlListID.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CrlListID.cs @@ -1,10 +1,9 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Esf { @@ -33,7 +32,7 @@ public static CrlListID GetInstance( throw new ArgumentException( "Unknown object in 'CrlListID' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } @@ -63,12 +62,10 @@ public CrlListID( } public CrlListID( - IEnumerable crls) + IEnumerable crls) { if (crls == null) throw new ArgumentNullException("crls"); - if (!CollectionUtilities.CheckElementsAreOfType(crls, typeof(CrlValidatedID))) - throw new ArgumentException("Must contain only 'CrlValidatedID' objects", "crls"); this.crls = new DerSequence( Asn1EncodableVector.FromEnumerable(crls)); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CrlOcspRef.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CrlOcspRef.cs index 32d7535..66f57f5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CrlOcspRef.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CrlOcspRef.cs @@ -34,7 +34,7 @@ public static CrlOcspRef GetInstance( throw new ArgumentException( "Unknown object in 'CrlOcspRef' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CrlValidatedID.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CrlValidatedID.cs index 270dd3a..cdff9fc 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CrlValidatedID.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/CrlValidatedID.cs @@ -31,7 +31,7 @@ public static CrlValidatedID GetInstance( throw new ArgumentException( "Unknown object in 'CrlValidatedID' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OcspIdentifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OcspIdentifier.cs index 492592b..73cfbad 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OcspIdentifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OcspIdentifier.cs @@ -22,7 +22,7 @@ public class OcspIdentifier : Asn1Encodable { private readonly ResponderID ocspResponderID; - private readonly DerGeneralizedTime producedAt; + private readonly Asn1GeneralizedTime producedAt; public static OcspIdentifier GetInstance( object obj) @@ -35,7 +35,7 @@ public static OcspIdentifier GetInstance( throw new ArgumentException( "Unknown object in 'OcspIdentifier' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } @@ -48,21 +48,30 @@ private OcspIdentifier( throw new ArgumentException("Bad sequence size: " + seq.Count, "seq"); this.ocspResponderID = ResponderID.GetInstance(seq[0].ToAsn1Object()); - this.producedAt = (DerGeneralizedTime) seq[1].ToAsn1Object(); + this.producedAt = (Asn1GeneralizedTime)seq[1].ToAsn1Object(); } - public OcspIdentifier( - ResponderID ocspResponderID, - DateTime producedAt) + public OcspIdentifier(ResponderID ocspResponderID, DateTime producedAt) { if (ocspResponderID == null) - throw new ArgumentNullException(); + throw new ArgumentNullException(nameof(ocspResponderID)); this.ocspResponderID = ocspResponderID; - this.producedAt = new DerGeneralizedTime(producedAt); + this.producedAt = new Asn1GeneralizedTime(producedAt); } - public ResponderID OcspResponderID + public OcspIdentifier(ResponderID ocspResponderID, Asn1GeneralizedTime producedAt) + { + if (ocspResponderID == null) + throw new ArgumentNullException(nameof(ocspResponderID)); + if (producedAt == null) + throw new ArgumentNullException(nameof(producedAt)); + + this.ocspResponderID = ocspResponderID; + this.producedAt = producedAt; + } + + public ResponderID OcspResponderID { get { return ocspResponderID; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OcspListID.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OcspListID.cs index 0a40004..72aece4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OcspListID.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OcspListID.cs @@ -1,10 +1,9 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Esf { @@ -32,7 +31,7 @@ public static OcspListID GetInstance( throw new ArgumentException( "Unknown object in 'OcspListID' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } @@ -62,12 +61,10 @@ public OcspListID( } public OcspListID( - IEnumerable ocspResponses) + IEnumerable ocspResponses) { if (ocspResponses == null) throw new ArgumentNullException("ocspResponses"); - if (!CollectionUtilities.CheckElementsAreOfType(ocspResponses, typeof(OcspResponsesID))) - throw new ArgumentException("Must contain only 'OcspResponsesID' objects", "ocspResponses"); this.ocspResponses = new DerSequence( Asn1EncodableVector.FromEnumerable(ocspResponses)); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OcspResponsesID.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OcspResponsesID.cs index c98af45..05fd9ae 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OcspResponsesID.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OcspResponsesID.cs @@ -32,7 +32,7 @@ public static OcspResponsesID GetInstance( throw new ArgumentException( "Unknown object in 'OcspResponsesID' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherCertID.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherCertID.cs index 89cbd49..3df13da 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherCertID.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherCertID.cs @@ -32,7 +32,7 @@ public static OtherCertID GetInstance( throw new ArgumentException( "Unknown object in 'OtherCertID' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherHashAlgAndValue.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherHashAlgAndValue.cs index 199a126..50b079e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherHashAlgAndValue.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherHashAlgAndValue.cs @@ -37,7 +37,7 @@ public static OtherHashAlgAndValue GetInstance( throw new ArgumentException( "Unknown object in 'OtherHashAlgAndValue' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherRevRefs.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherRevRefs.cs index 485bfd5..6e19b24 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherRevRefs.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherRevRefs.cs @@ -35,7 +35,7 @@ public static OtherRevRefs GetInstance( throw new ArgumentException( "Unknown object in 'OtherRevRefs' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherRevVals.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherRevVals.cs index f9688a2..1f02c7f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherRevVals.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherRevVals.cs @@ -35,7 +35,7 @@ public static OtherRevVals GetInstance( throw new ArgumentException( "Unknown object in 'OtherRevVals' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherSigningCertificate.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherSigningCertificate.cs index cfaa0c9..e7c131c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherSigningCertificate.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/OtherSigningCertificate.cs @@ -1,11 +1,10 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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.Asn1.Esf { @@ -34,7 +33,7 @@ public static OtherSigningCertificate GetInstance( throw new ArgumentException( "Unknown object in 'OtherSigningCertificate' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } @@ -76,28 +75,23 @@ public OtherSigningCertificate( } public OtherSigningCertificate( - IEnumerable certs) + IEnumerable certs) : this(certs, null) { } public OtherSigningCertificate( - IEnumerable certs, - IEnumerable policies) + IEnumerable certs, + IEnumerable policies) { if (certs == null) throw new ArgumentNullException("certs"); - if (!CollectionUtilities.CheckElementsAreOfType(certs, typeof(OtherCertID))) - throw new ArgumentException("Must contain only 'OtherCertID' objects", "certs"); this.certs = new DerSequence( Asn1EncodableVector.FromEnumerable(certs)); if (policies != null) { - if (!CollectionUtilities.CheckElementsAreOfType(policies, typeof(PolicyInformation))) - throw new ArgumentException("Must contain only 'PolicyInformation' objects", "policies"); - this.policies = new DerSequence( Asn1EncodableVector.FromEnumerable(policies)); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/RevocationValues.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/RevocationValues.cs index e3049d7..b50556a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/RevocationValues.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/RevocationValues.cs @@ -1,11 +1,10 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ocsp; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Esf { @@ -92,24 +91,18 @@ public RevocationValues( } public RevocationValues( - IEnumerable crlVals, - IEnumerable ocspVals, - OtherRevVals otherRevVals) + IEnumerable crlVals, + IEnumerable ocspVals, + OtherRevVals otherRevVals) { if (crlVals != null) { - if (!CollectionUtilities.CheckElementsAreOfType(crlVals, typeof(CertificateList))) - throw new ArgumentException("Must contain only 'CertificateList' objects", "crlVals"); - this.crlVals = new DerSequence( Asn1EncodableVector.FromEnumerable(crlVals)); } if (ocspVals != null) { - if (!CollectionUtilities.CheckElementsAreOfType(ocspVals, typeof(BasicOcspResponse))) - throw new ArgumentException("Must contain only 'BasicOcspResponse' objects", "ocspVals"); - this.ocspVals = new DerSequence( Asn1EncodableVector.FromEnumerable(ocspVals)); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SigPolicyQualifierInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SigPolicyQualifierInfo.cs index b6e7d11..d3785c9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SigPolicyQualifierInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SigPolicyQualifierInfo.cs @@ -33,7 +33,7 @@ public static SigPolicyQualifierInfo GetInstance( throw new ArgumentException( "Unknown object in 'SigPolicyQualifierInfo' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SignaturePolicyId.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SignaturePolicyId.cs index b392d59..d24690b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SignaturePolicyId.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SignaturePolicyId.cs @@ -1,10 +1,9 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Esf { @@ -39,7 +38,7 @@ public static SignaturePolicyId GetInstance( throw new ArgumentException( "Unknown object in 'SignaturePolicyId' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } @@ -87,9 +86,9 @@ public SignaturePolicyId( } public SignaturePolicyId( - DerObjectIdentifier sigPolicyIdentifier, - OtherHashAlgAndValue sigPolicyHash, - IEnumerable sigPolicyQualifiers) + DerObjectIdentifier sigPolicyIdentifier, + OtherHashAlgAndValue sigPolicyHash, + IEnumerable sigPolicyQualifiers) { if (sigPolicyIdentifier == null) throw new ArgumentNullException("sigPolicyIdentifier"); @@ -101,9 +100,6 @@ public SignaturePolicyId( if (sigPolicyQualifiers != null) { - if (!CollectionUtilities.CheckElementsAreOfType(sigPolicyQualifiers, typeof(SigPolicyQualifierInfo))) - throw new ArgumentException("Must contain only 'SigPolicyQualifierInfo' objects", "sigPolicyQualifiers"); - this.sigPolicyQualifiers = new DerSequence( Asn1EncodableVector.FromEnumerable(sigPolicyQualifiers)); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SignaturePolicyIdentifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SignaturePolicyIdentifier.cs index 84a182d..4d7d757 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SignaturePolicyIdentifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SignaturePolicyIdentifier.cs @@ -35,7 +35,7 @@ public static SignaturePolicyIdentifier GetInstance( throw new ArgumentException( "Unknown object in 'SignaturePolicyIdentifier' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SignerAttribute.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SignerAttribute.cs index 5e4370d..fe98782 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SignerAttribute.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SignerAttribute.cs @@ -24,7 +24,7 @@ public static SignerAttribute GetInstance( throw new ArgumentException( "Unknown object in 'SignerAttribute' factory: " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SignerLocation.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SignerLocation.cs index 0567449..f868d41 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SignerLocation.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/esf/SignerLocation.cs @@ -1,7 +1,6 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X500; @@ -26,27 +25,26 @@ public class SignerLocation private DirectoryString localityName; private Asn1Sequence postalAddress; - public SignerLocation( - Asn1Sequence seq) + public SignerLocation(Asn1Sequence seq) { foreach (Asn1TaggedObject obj in seq) { switch (obj.TagNo) { - case 0: - this.countryName = DirectoryString.GetInstance(obj, true); - break; - case 1: - this.localityName = DirectoryString.GetInstance(obj, true); - break; - case 2: - bool isExplicit = obj.IsExplicit(); // handle erroneous implicitly tagged sequences - this.postalAddress = Asn1Sequence.GetInstance(obj, isExplicit); - if (postalAddress != null && postalAddress.Count > 6) - throw new ArgumentException("postal address must contain less than 6 strings"); - break; - default: - throw new ArgumentException("illegal tag"); + case 0: + this.countryName = DirectoryString.GetInstance(obj, true); + break; + case 1: + this.localityName = DirectoryString.GetInstance(obj, true); + break; + case 2: + bool isExplicit = obj.IsExplicit(); // handle erroneous implicitly tagged sequences + this.postalAddress = Asn1Sequence.GetInstance(obj, isExplicit); + if (postalAddress != null && postalAddress.Count > 6) + throw new ArgumentException("postal address must contain less than 6 strings"); + break; + default: + throw new ArgumentException("illegal tag"); } } } @@ -80,13 +78,10 @@ public SignerLocation( { } - public static SignerLocation GetInstance( - object obj) + public static SignerLocation GetInstance(object obj) { if (obj == null || obj is SignerLocation) - { return (SignerLocation) obj; - } return new SignerLocation(Asn1Sequence.GetInstance(obj)); } @@ -115,18 +110,6 @@ public DirectoryString[] GetPostal() return dirStrings; } - - public DerUtf8String CountryName - { - get { return countryName == null ? null : new DerUtf8String(countryName.GetString()); } - } - - - public DerUtf8String LocalityName - { - get { return localityName == null ? null : new DerUtf8String(localityName.GetString()); } - } - public Asn1Sequence PostalAddress { get { return postalAddress; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/ContentHints.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/ContentHints.cs index 14d29d1..586bb99 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/ContentHints.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/ContentHints.cs @@ -26,7 +26,7 @@ public static ContentHints GetInstance( } throw new ArgumentException("unknown object in 'ContentHints' factory : " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(o) + "."); + + Org.BouncyCastle.Utilities.Platform.GetTypeName(o) + "."); } /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/ContentIdentifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/ContentIdentifier.cs index 1aeadae..ea4c7f7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/ContentIdentifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/ContentIdentifier.cs @@ -26,7 +26,7 @@ public static ContentIdentifier GetInstance( throw new ArgumentException( "unknown object in 'ContentIdentifier' factory : " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(o) + "."); + + Org.BouncyCastle.Utilities.Platform.GetTypeName(o) + "."); } /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/ESSCertID.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/ESSCertID.cs index d79d18a..2fadb90 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/ESSCertID.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/ESSCertID.cs @@ -28,7 +28,7 @@ public static EssCertID GetInstance( throw new ArgumentException( "unknown object in 'EssCertID' factory : " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(o) + "."); + + Org.BouncyCastle.Utilities.Platform.GetTypeName(o) + "."); } /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/SigningCertificate.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/SigningCertificate.cs index 5f01890..3fa18f1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/SigningCertificate.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/SigningCertificate.cs @@ -27,7 +27,7 @@ public static SigningCertificate GetInstance( throw new ArgumentException( "unknown object in 'SigningCertificate' factory : " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(o) + "."); + + Org.BouncyCastle.Utilities.Platform.GetTypeName(o) + "."); } /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/SigningCertificateV2.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/SigningCertificateV2.cs index 0756b52..9e53d82 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/SigningCertificateV2.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ess/SigningCertificateV2.cs @@ -24,7 +24,7 @@ public static SigningCertificateV2 GetInstance( throw new ArgumentException( "unknown object in 'SigningCertificateV2' factory : " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(o) + "."); + + Org.BouncyCastle.Utilities.Platform.GetTypeName(o) + "."); } private SigningCertificateV2( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/gm/GMNamedCurves.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/gm/GMNamedCurves.cs index 58e88ac..463a48d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/gm/GMNamedCurves.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/gm/GMNamedCurves.cs @@ -1,24 +1,20 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9; 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.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.GM { - public sealed class GMNamedCurves + /// Elliptic curve registry for GM. + public static class GMNamedCurves { - private GMNamedCurves() - { - } - private static X9ECPoint ConfigureBasepoint(ECCurve curve, string encoding) { X9ECPoint G = new X9ECPoint(curve, Hex.DecodeStrict(encoding)); @@ -36,9 +32,6 @@ private static BigInteger FromHex(string hex) return new BigInteger(1, Hex.DecodeStrict(hex)); } - /* - * sm2p256v1 - */ internal class SM2P256V1Holder : X9ECParametersHolder { @@ -46,25 +39,29 @@ private SM2P256V1Holder() {} internal static readonly X9ECParametersHolder Instance = new SM2P256V1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger p = FromHex("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF"); BigInteger a = FromHex("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC"); BigInteger b = FromHex("28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93"); - byte[] S = null; BigInteger n = FromHex("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123"); BigInteger h = BigInteger.One; - ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); + return ConfigureCurve(new FpCurve(p, a, b, n, h, true)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; + X9ECPoint G = ConfigureBasepoint(curve, "0432C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0"); - return new X9ECParameters(curve, G, n, h, S); + + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } - /* - * wapip192v1 - */ internal class WapiP192V1Holder : X9ECParametersHolder { @@ -72,34 +69,39 @@ private WapiP192V1Holder() { } internal static readonly X9ECParametersHolder Instance = new WapiP192V1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger p = FromHex("BDB6F4FE3E8B1D9E0DA8C0D46F4C318CEFE4AFE3B6B8551F"); BigInteger a = FromHex("BB8E5E8FBC115E139FE6A814FE48AAA6F0ADA1AA5DF91985"); BigInteger b = FromHex("1854BEBDC31B21B7AEFC80AB0ECD10D5B1B3308E6DBF11C1"); - byte[] S = null; BigInteger n = FromHex("BDB6F4FE3E8B1D9E0DA8C0D40FC962195DFAE76F56564677"); BigInteger h = BigInteger.One; - ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); + return ConfigureCurve(new FpCurve(p, a, b, n, h, true)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; + X9ECPoint G = ConfigureBasepoint(curve, "044AD5F7048DE709AD51236DE65E4D4B482C836DC6E410664002BB3A02D4AAADACAE24817A4CA3A1B014B5270432DB27D2"); - return new X9ECParameters(curve, G, n, h, S); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } + private static readonly Dictionary objIds = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly Dictionary curves = + new Dictionary(); + private static readonly Dictionary names = + new Dictionary(); - private static readonly IDictionary objIds = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private static readonly IDictionary curves = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private static readonly IDictionary names = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - - private static void DefineCurve( - string name, - DerObjectIdentifier oid, - X9ECParametersHolder holder) + private static void DefineCurve(string name, DerObjectIdentifier oid, X9ECParametersHolder holder) { - objIds.Add(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(name), oid); + objIds.Add(name, oid); names.Add(oid, name); curves.Add(oid, holder); } @@ -110,54 +112,64 @@ static GMNamedCurves() DefineCurve("sm2p256v1", GMObjectIdentifiers.sm2p256v1, SM2P256V1Holder.Instance); } - public static X9ECParameters GetByName( - string name) + /// Look up the for the curve with the given name. + /// The name of the curve. + public static X9ECParameters GetByName(string name) { DerObjectIdentifier oid = GetOid(name); return oid == null ? null : GetByOid(oid); } - /** - * return the X9ECParameters object for the named curve represented by - * the passed in object identifier. Null if the curve isn't present. - * - * @param oid an object identifier representing a named curve, if present. - */ - public static X9ECParameters GetByOid( - DerObjectIdentifier oid) + /// Look up an for the curve with the given name. + /// + /// Allows accessing the curve without necessarily triggering the creation of the + /// full . + /// + /// The name of the curve. + public static X9ECParametersHolder GetByNameLazy(string name) + { + DerObjectIdentifier oid = GetOid(name); + return oid == null ? null : GetByOidLazy(oid); + } + + /// Look up the for the curve with the given + /// OID. + /// The OID for the curve. + public static X9ECParameters GetByOid(DerObjectIdentifier oid) + { + return GetByOidLazy(oid)?.Parameters; + } + + /// Look up an for the curve with the given + /// OID. + /// + /// Allows accessing the curve without necessarily triggering the creation of the + /// full . + /// + /// The OID for the curve. + public static X9ECParametersHolder GetByOidLazy(DerObjectIdentifier oid) { - X9ECParametersHolder holder = (X9ECParametersHolder)curves[oid]; - return holder == null ? null : holder.Parameters; + return CollectionUtilities.GetValueOrNull(curves, oid); } - /** - * return the object identifier signified by the passed in name. Null - * if there is no object identifier associated with name. - * - * @return the object identifier associated with name, if present. - */ - public static DerObjectIdentifier GetOid( - string name) + /// Look up the name of the curve with the given OID. + /// The OID for the curve. + public static string GetName(DerObjectIdentifier oid) { - return (DerObjectIdentifier)objIds[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(name)]; + return CollectionUtilities.GetValueOrNull(names, oid); } - /** - * return the named curve name represented by the given object identifier. - */ - public static string GetName( - DerObjectIdentifier oid) + /// Look up the OID of the curve with the given name. + /// The name of the curve. + public static DerObjectIdentifier GetOid(string name) { - return (string)names[oid]; + return CollectionUtilities.GetValueOrNull(objIds, name); } - /** - * returns an enumeration containing the name strings for curves - * contained in this structure. - */ - public static IEnumerable Names + /// Enumerate the available curve names in this registry. + public static IEnumerable Names { - get { return new EnumerableProxy(names.Values); } + get { return CollectionUtilities.Proxy(objIds.Keys); } } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/icao/DataGroupHash.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/icao/DataGroupHash.cs index 571e4d0..8bff273 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/icao/DataGroupHash.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/icao/DataGroupHash.cs @@ -1,9 +1,6 @@ #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.Icao { @@ -40,8 +37,7 @@ public class DataGroupHash private readonly DerInteger dataGroupNumber; private readonly Asn1OctetString dataGroupHashValue; - public static DataGroupHash GetInstance( - object obj) + public static DataGroupHash GetInstance(object obj) { if (obj is DataGroupHash) return (DataGroupHash)obj; @@ -52,8 +48,7 @@ public static DataGroupHash GetInstance( return null; } - private DataGroupHash( - Asn1Sequence seq) + private DataGroupHash(Asn1Sequence seq) { if (seq.Count != 2) throw new ArgumentException("Wrong number of elements in sequence", "seq"); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/icao/LDSSecurityObject.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/icao/LDSSecurityObject.cs index a7cdbd5..4b5aec4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/icao/LDSSecurityObject.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/icao/LDSSecurityObject.cs @@ -1,7 +1,6 @@ #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.Math; @@ -33,8 +32,7 @@ public class LdsSecurityObject private DataGroupHash[] datagroupHash; private LdsVersionInfo versionInfo; - public static LdsSecurityObject GetInstance( - object obj) + public static LdsSecurityObject GetInstance(object obj) { if (obj is LdsSecurityObject) return (LdsSecurityObject)obj; @@ -45,13 +43,12 @@ public static LdsSecurityObject GetInstance( return null; } - private LdsSecurityObject( - Asn1Sequence seq) + private LdsSecurityObject(Asn1Sequence seq) { if (seq == null || seq.Count == 0) throw new ArgumentException("null or empty sequence passed."); - IEnumerator e = seq.GetEnumerator(); + var e = seq.GetEnumerator(); // version e.MoveNext(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/ocsp/CertHash.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/ocsp/CertHash.cs index 18a645b..96d2507 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/ocsp/CertHash.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/ocsp/CertHash.cs @@ -46,7 +46,7 @@ public static CertHash GetInstance( return new CertHash((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/ocsp/RequestedCertificate.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/ocsp/RequestedCertificate.cs index a989a46..2255684 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/ocsp/RequestedCertificate.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/ocsp/RequestedCertificate.cs @@ -73,7 +73,7 @@ public static RequestedCertificate GetInstance( return new RequestedCertificate((Asn1TaggedObject) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public static RequestedCertificate GetInstance( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/AdditionalInformationSyntax.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/AdditionalInformationSyntax.cs index 9cb74c6..7a9b7ca 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/AdditionalInformationSyntax.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/AdditionalInformationSyntax.cs @@ -29,7 +29,7 @@ public static AdditionalInformationSyntax GetInstance( if (obj is IAsn1String) return new AdditionalInformationSyntax(DirectoryString.GetInstance(obj)); - throw new ArgumentException("Unknown object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Unknown object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } private AdditionalInformationSyntax( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/AdmissionSyntax.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/AdmissionSyntax.cs index 272e089..f7e2342 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/AdmissionSyntax.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/AdmissionSyntax.cs @@ -133,7 +133,7 @@ public static AdmissionSyntax GetInstance( return new AdmissionSyntax((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/Admissions.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/Admissions.cs index e90aaaf..1e318d1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/Admissions.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/Admissions.cs @@ -1,7 +1,6 @@ #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.Utilities; @@ -32,20 +31,15 @@ public class Admissions private readonly NamingAuthority namingAuthority; private readonly Asn1Sequence professionInfos; - public static Admissions GetInstance( - object obj) + public static Admissions GetInstance(object obj) { if (obj == null || obj is Admissions) - { - return (Admissions) obj; - } + return (Admissions)obj; - if (obj is Asn1Sequence) - { - return new Admissions((Asn1Sequence) obj); - } + if (obj is Asn1Sequence seq) + return new Admissions(seq); - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** @@ -64,49 +58,48 @@ public static Admissions GetInstance( * * @param seq The ASN.1 sequence. */ - private Admissions( - Asn1Sequence seq) + private Admissions(Asn1Sequence seq) { if (seq.Count > 3) throw new ArgumentException("Bad sequence size: " + seq.Count); - IEnumerator e = seq.GetEnumerator(); + var e = seq.GetEnumerator(); e.MoveNext(); - Asn1Encodable o = (Asn1Encodable) e.Current; - if (o is Asn1TaggedObject) + Asn1Encodable o = e.Current; + if (o is Asn1TaggedObject tagged1) { - switch (((Asn1TaggedObject)o).TagNo) + switch (tagged1.TagNo) { - case 0: - admissionAuthority = GeneralName.GetInstance((Asn1TaggedObject)o, true); - break; - case 1: - namingAuthority = NamingAuthority.GetInstance((Asn1TaggedObject)o, true); - break; - default: - throw new ArgumentException("Bad tag number: " + ((Asn1TaggedObject)o).TagNo); + case 0: + admissionAuthority = GeneralName.GetInstance((Asn1TaggedObject)o, true); + break; + case 1: + namingAuthority = NamingAuthority.GetInstance((Asn1TaggedObject)o, true); + break; + default: + throw new ArgumentException("Bad tag number: " + ((Asn1TaggedObject)o).TagNo); } e.MoveNext(); - o = (Asn1Encodable) e.Current; + o = e.Current; } - if (o is Asn1TaggedObject) + if (o is Asn1TaggedObject tagged2) { - switch (((Asn1TaggedObject)o).TagNo) + switch (tagged2.TagNo) { - case 1: - namingAuthority = NamingAuthority.GetInstance((Asn1TaggedObject)o, true); - break; - default: - throw new ArgumentException("Bad tag number: " + ((Asn1TaggedObject)o).TagNo); + case 1: + namingAuthority = NamingAuthority.GetInstance((Asn1TaggedObject)o, true); + break; + default: + throw new ArgumentException("Bad tag number: " + ((Asn1TaggedObject)o).TagNo); } e.MoveNext(); - o = (Asn1Encodable) e.Current; + o = e.Current; } professionInfos = Asn1Sequence.GetInstance(o); if (e.MoveNext()) { - throw new ArgumentException("Bad object encountered: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(e.Current)); + throw new ArgumentException("Bad object encountered: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(e.Current)); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/DeclarationOfMajority.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/DeclarationOfMajority.cs index b680f33..6918caf 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/DeclarationOfMajority.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/DeclarationOfMajority.cs @@ -66,7 +66,7 @@ public DeclarationOfMajority( } public DeclarationOfMajority( - DerGeneralizedTime dateOfBirth) + Asn1GeneralizedTime dateOfBirth) { this.declaration = new DerTaggedObject(false, 2, dateOfBirth); } @@ -84,7 +84,7 @@ public static DeclarationOfMajority GetInstance( return new DeclarationOfMajority((Asn1TaggedObject) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } private DeclarationOfMajority( @@ -157,14 +157,14 @@ public virtual Asn1Sequence FullAgeAtCountry } } - public virtual DerGeneralizedTime DateOfBirth + public virtual Asn1GeneralizedTime DateOfBirth { get { switch ((Choice) declaration.TagNo) { case Choice.DateOfBirth: - return DerGeneralizedTime.GetInstance(declaration, false); + return Asn1GeneralizedTime.GetInstance(declaration, false); default: return null; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/MonetaryLimit.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/MonetaryLimit.cs index 4cdb420..a3fa719 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/MonetaryLimit.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/MonetaryLimit.cs @@ -51,7 +51,7 @@ public static MonetaryLimit GetInstance( return new MonetaryLimit(Asn1Sequence.GetInstance(obj)); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } private MonetaryLimit( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/NamingAuthority.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/NamingAuthority.cs index 21e261c..781fa72 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/NamingAuthority.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/NamingAuthority.cs @@ -1,7 +1,6 @@ #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.Utilities; @@ -39,25 +38,18 @@ public static readonly DerObjectIdentifier IdIsisMttATNamingAuthoritiesRechtWirt private readonly string namingAuthorityUrl; private readonly DirectoryString namingAuthorityText; - public static NamingAuthority GetInstance( - object obj) + public static NamingAuthority GetInstance(object obj) { if (obj == null || obj is NamingAuthority) - { return (NamingAuthority) obj; - } - if (obj is Asn1Sequence) - { - return new NamingAuthority((Asn1Sequence) obj); - } + if (obj is Asn1Sequence seq) + return new NamingAuthority(seq); - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } - public static NamingAuthority GetInstance( - Asn1TaggedObject obj, - bool isExplicit) + public static NamingAuthority GetInstance(Asn1TaggedObject obj, bool isExplicit) { return GetInstance(Asn1Sequence.GetInstance(obj, isExplicit)); } @@ -77,24 +69,23 @@ public static NamingAuthority GetInstance( * * @param seq The ASN.1 sequence. */ - private NamingAuthority( - Asn1Sequence seq) + private NamingAuthority(Asn1Sequence seq) { if (seq.Count > 3) throw new ArgumentException("Bad sequence size: " + seq.Count); - IEnumerator e = seq.GetEnumerator(); + var e = seq.GetEnumerator(); if (e.MoveNext()) { - Asn1Encodable o = (Asn1Encodable) e.Current; - if (o is DerObjectIdentifier) + Asn1Encodable o = e.Current; + if (o is DerObjectIdentifier oid) { - namingAuthorityID = (DerObjectIdentifier) o; + namingAuthorityID = oid; } - else if (o is DerIA5String) + else if (o is DerIA5String ia5) { - namingAuthorityUrl = DerIA5String.GetInstance(o).GetString(); + namingAuthorityUrl = ia5.GetString(); } else if (o is IAsn1String) { @@ -102,16 +93,16 @@ private NamingAuthority( } else { - throw new ArgumentException("Bad object encountered: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); + throw new ArgumentException("Bad object encountered: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); } } if (e.MoveNext()) { - Asn1Encodable o = (Asn1Encodable) e.Current; - if (o is DerIA5String) + Asn1Encodable o = e.Current; + if (o is DerIA5String ia5) { - namingAuthorityUrl = DerIA5String.GetInstance(o).GetString(); + namingAuthorityUrl = ia5.GetString(); } else if (o is IAsn1String) { @@ -119,20 +110,20 @@ private NamingAuthority( } else { - throw new ArgumentException("Bad object encountered: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); + throw new ArgumentException("Bad object encountered: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); } } if (e.MoveNext()) { - Asn1Encodable o = (Asn1Encodable) e.Current; + Asn1Encodable o = e.Current; if (o is IAsn1String) { namingAuthorityText = DirectoryString.GetInstance(o); } else { - throw new ArgumentException("Bad object encountered: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); + throw new ArgumentException("Bad object encountered: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/ProcurationSyntax.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/ProcurationSyntax.cs index 92ec660..bab8a76 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/ProcurationSyntax.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/ProcurationSyntax.cs @@ -1,7 +1,6 @@ #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; @@ -51,20 +50,15 @@ public class ProcurationSyntax private readonly GeneralName thirdPerson; private readonly IssuerSerial certRef; - public static ProcurationSyntax GetInstance( - object obj) + public static ProcurationSyntax GetInstance(object obj) { if (obj == null || obj is ProcurationSyntax) - { return (ProcurationSyntax) obj; - } - if (obj is Asn1Sequence) - { - return new ProcurationSyntax((Asn1Sequence) obj); - } + if (obj is Asn1Sequence seq) + return new ProcurationSyntax(seq); - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** @@ -88,38 +82,37 @@ public static ProcurationSyntax GetInstance( * * @param seq The ASN.1 sequence. */ - private ProcurationSyntax( - Asn1Sequence seq) + private ProcurationSyntax(Asn1Sequence seq) { if (seq.Count < 1 || seq.Count > 3) throw new ArgumentException("Bad sequence size: " + seq.Count); - IEnumerator e = seq.GetEnumerator(); + var e = seq.GetEnumerator(); while (e.MoveNext()) { Asn1TaggedObject o = Asn1TaggedObject.GetInstance(e.Current); switch (o.TagNo) { - case 1: - country = DerPrintableString.GetInstance(o, true).GetString(); - break; - case 2: - typeOfSubstitution = DirectoryString.GetInstance(o, true); - break; - case 3: - Asn1Object signingFor = o.GetObject(); - if (signingFor is Asn1TaggedObject) - { - thirdPerson = GeneralName.GetInstance(signingFor); - } - else - { - certRef = IssuerSerial.GetInstance(signingFor); - } - break; - default: - throw new ArgumentException("Bad tag number: " + o.TagNo); + case 1: + country = DerPrintableString.GetInstance(o, true).GetString(); + break; + case 2: + typeOfSubstitution = DirectoryString.GetInstance(o, true); + break; + case 3: + Asn1Object signingFor = o.GetObject(); + if (signingFor is Asn1TaggedObject) + { + thirdPerson = GeneralName.GetInstance(signingFor); + } + else + { + certRef = IssuerSerial.GetInstance(signingFor); + } + break; + default: + throw new ArgumentException("Bad tag number: " + o.TagNo); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/ProfessionInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/ProfessionInfo.cs index 73a159c..eb73040 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/ProfessionInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/ProfessionInfo.cs @@ -1,7 +1,6 @@ #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.Utilities; @@ -147,20 +146,15 @@ public class ProfessionInfo private readonly string registrationNumber; private readonly Asn1OctetString addProfessionInfo; - public static ProfessionInfo GetInstance( - object obj) + public static ProfessionInfo GetInstance(object obj) { if (obj == null || obj is ProfessionInfo) - { return (ProfessionInfo) obj; - } - if (obj is Asn1Sequence) - { - return new ProfessionInfo((Asn1Sequence) obj); - } + if (obj is Asn1Sequence seq) + return new ProfessionInfo(seq); - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** @@ -180,78 +174,76 @@ public static ProfessionInfo GetInstance( * * @param seq The ASN.1 sequence. */ - private ProfessionInfo( - Asn1Sequence seq) + private ProfessionInfo(Asn1Sequence seq) { if (seq.Count > 5) throw new ArgumentException("Bad sequence size: " + seq.Count); - IEnumerator e = seq.GetEnumerator(); + var e = seq.GetEnumerator(); e.MoveNext(); - Asn1Encodable o = (Asn1Encodable) e.Current; + Asn1Encodable o = e.Current; - if (o is Asn1TaggedObject) + if (o is Asn1TaggedObject ato) { - Asn1TaggedObject ato = (Asn1TaggedObject) o; if (ato.TagNo != 0) throw new ArgumentException("Bad tag number: " + ato.TagNo); namingAuthority = NamingAuthority.GetInstance(ato, true); e.MoveNext(); - o = (Asn1Encodable) e.Current; + o = e.Current; } professionItems = Asn1Sequence.GetInstance(o); if (e.MoveNext()) { - o = (Asn1Encodable) e.Current; - if (o is Asn1Sequence) + o = e.Current; + if (o is Asn1Sequence sequence) { - professionOids = Asn1Sequence.GetInstance(o); + professionOids = sequence; } - else if (o is DerPrintableString) + else if (o is DerPrintableString printable) { - registrationNumber = DerPrintableString.GetInstance(o).GetString(); + registrationNumber = printable.GetString(); } - else if (o is Asn1OctetString) + else if (o is Asn1OctetString octets) { - addProfessionInfo = Asn1OctetString.GetInstance(o); + addProfessionInfo = octets; } else { - throw new ArgumentException("Bad object encountered: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); + throw new ArgumentException("Bad object encountered: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); } } if (e.MoveNext()) { - o = (Asn1Encodable) e.Current; - if (o is DerPrintableString) + o = e.Current; + if (o is DerPrintableString printable) { - registrationNumber = DerPrintableString.GetInstance(o).GetString(); + registrationNumber = printable.GetString(); } - else if (o is DerOctetString) + else if (o is Asn1OctetString octets) { - addProfessionInfo = (DerOctetString) o; + addProfessionInfo = octets; } else { - throw new ArgumentException("Bad object encountered: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); + throw new ArgumentException("Bad object encountered: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); } } if (e.MoveNext()) { - o = (Asn1Encodable) e.Current; - if (o is DerOctetString) + o = e.Current; + if (o is Asn1OctetString octets) { - addProfessionInfo = (DerOctetString) o; + addProfessionInfo = octets; } else { - throw new ArgumentException("Bad object encountered: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); + throw new ArgumentException("Bad object encountered: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(o)); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/Restriction.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/Restriction.cs index 50d82e3..97c1d24 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/Restriction.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/isismtt/x509/Restriction.cs @@ -19,8 +19,7 @@ public class Restriction { private readonly DirectoryString restriction; - public static Restriction GetInstance( - object obj) + public static Restriction GetInstance(object obj) { if (obj is Restriction) return (Restriction) obj; @@ -28,7 +27,7 @@ public static Restriction GetInstance( if (obj is IAsn1String) return new Restriction(DirectoryString.GetInstance(obj)); - throw new ArgumentException("Unknown object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Unknown object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** @@ -42,8 +41,7 @@ public static Restriction GetInstance( * * @param restriction A IAsn1String. */ - private Restriction( - DirectoryString restriction) + private Restriction(DirectoryString restriction) { this.restriction = restriction; } @@ -53,8 +51,7 @@ private Restriction( * * @param restriction The description of the restriction. */ - public Restriction( - string restriction) + public Restriction(string restriction) { this.restriction = new DirectoryString(restriction); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/misc/MiscObjectIdentifiers.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/misc/MiscObjectIdentifiers.cs index 7fab2cd..f44782b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/misc/MiscObjectIdentifiers.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/misc/MiscObjectIdentifiers.cs @@ -42,15 +42,15 @@ public abstract class MiscObjectIdentifiers // Novell // iso/itu(2) country(16) us(840) organization(1) novell(113719) // - public static readonly string Novell = "2.16.840.1.113719"; - public static readonly DerObjectIdentifier NovellSecurityAttribs = new DerObjectIdentifier(Novell + ".1.9.4.1"); + public static readonly DerObjectIdentifier Novell = new DerObjectIdentifier("2.16.840.1.113719"); + public static readonly DerObjectIdentifier NovellSecurityAttribs = Novell.Branch("1.9.4.1"); // // Entrust // iso(1) member-body(16) us(840) nortelnetworks(113533) entrust(7) // - public static readonly string Entrust = "1.2.840.113533.7"; - public static readonly DerObjectIdentifier EntrustVersionExtension = new DerObjectIdentifier(Entrust + ".65.0"); + public static readonly DerObjectIdentifier Entrust = new DerObjectIdentifier("1.2.840.113533.7"); + public static readonly DerObjectIdentifier EntrustVersionExtension = Entrust.Branch("65.0"); public static readonly DerObjectIdentifier cast5CBC = new DerObjectIdentifier(Entrust+ ".66.10"); @@ -91,9 +91,33 @@ public abstract class MiscObjectIdentifiers public static readonly DerObjectIdentifier id_blake2s224 = blake2.Branch("2.7"); public static readonly DerObjectIdentifier id_blake2s256 = blake2.Branch("2.8"); + public static readonly DerObjectIdentifier blake3 = blake2.Branch("3"); + + public static readonly DerObjectIdentifier blake3_256 = blake3.Branch("8"); + // // Scrypt public static readonly DerObjectIdentifier id_scrypt = new DerObjectIdentifier("1.3.6.1.4.1.11591.4.11"); + + // Composite key/signature oid - prototyping + // + // id-alg-composite OBJECT IDENTIFIER ::= { + // iso(1) identified-organization(3) dod(6) internet(1) private(4) + // enterprise(1) OpenCA(18227) Algorithms(2) id-alg-composite(1) } + public static readonly DerObjectIdentifier id_alg_composite = new DerObjectIdentifier("1.3.6.1.4.1.18227.2.1"); + + // -- To be replaced by IANA + // + //id-composite-key OBJECT IDENTIFIER ::= { + // + // joint-iso-itu-t(2) country(16) us(840) organization(1) entrust(114027) + // + // Algorithm(80) Composite(4) CompositeKey(1) + public static readonly DerObjectIdentifier id_composite_key = + new DerObjectIdentifier("2.16.840.1.114027.80.4.1"); + + public static readonly DerObjectIdentifier id_oracle_pkcs12_trusted_key_usage = + new DerObjectIdentifier("2.16.840.1.113894.746875.1.1"); } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/mozilla/PublicKeyAndChallenge.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/mozilla/PublicKeyAndChallenge.cs index 42fff9f..679491d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/mozilla/PublicKeyAndChallenge.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/mozilla/PublicKeyAndChallenge.cs @@ -41,7 +41,7 @@ public static PublicKeyAndChallenge GetInstance( throw new ArgumentException( "unknown object in 'PublicKeyAndChallenge' factory : " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj) + "."); + + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj) + "."); } public PublicKeyAndChallenge( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/nist/KMACwithSHAKE256_params.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/nist/KMACwithSHAKE256_params.cs index fed72a9..6325dd6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/nist/KMACwithSHAKE256_params.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/nist/KMACwithSHAKE256_params.cs @@ -31,7 +31,7 @@ public KMacWithShake256Params(int outputLength, byte[] customizationString) this.customizationString = Arrays.Clone(customizationString); } - public static KMacWithShake256Params GetInstance(Object o) + public static KMacWithShake256Params GetInstance(object o) { if (o is KMacWithShake256Params) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/nist/NISTNamedCurves.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/nist/NISTNamedCurves.cs index 2d0c4ed..e977bd4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/nist/NISTNamedCurves.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/nist/NISTNamedCurves.cs @@ -1,33 +1,28 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Sec; 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.Asn1.Nist { - /** - * Utility class for fetching curves using their NIST names as published in FIPS-PUB 186-3 - */ - public sealed class NistNamedCurves + /// Elliptic curve registry for NIST curves. + public static class NistNamedCurves { - private NistNamedCurves() - { - } - - private static readonly IDictionary objIds = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private static readonly IDictionary names = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + private static readonly Dictionary objIds = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly Dictionary names = + new Dictionary(); - private static void DefineCurveAlias( - string name, - DerObjectIdentifier oid) + private static void DefineCurveAlias(string name, DerObjectIdentifier oid) { - objIds.Add(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(name), oid); + if (SecNamedCurves.GetByOidLazy(oid) == null) + throw new InvalidOperationException(); + + objIds.Add(name, oid); names.Add(oid, name); } @@ -52,53 +47,64 @@ static NistNamedCurves() DefineCurveAlias("P-521", SecObjectIdentifiers.SecP521r1); } - public static X9ECParameters GetByName( - string name) + /// Look up the for the curve with the given name. + /// The name of the curve. + public static X9ECParameters GetByName(string name) { DerObjectIdentifier oid = GetOid(name); return oid == null ? null : GetByOid(oid); } - /** - * return the X9ECParameters object for the named curve represented by - * the passed in object identifier. Null if the curve isn't present. - * - * @param oid an object identifier representing a named curve, if present. - */ - public static X9ECParameters GetByOid( - DerObjectIdentifier oid) + /// Look up an for the curve with the given name. + /// + /// Allows accessing the curve without necessarily triggering the creation of + /// the full . + /// + /// The name of the curve. + public static X9ECParametersHolder GetByNameLazy(string name) + { + DerObjectIdentifier oid = GetOid(name); + return oid == null ? null : GetByOidLazy(oid); + } + + /// Look up the for the curve with the given + /// OID. + /// The OID for the curve. + public static X9ECParameters GetByOid(DerObjectIdentifier oid) + { + return GetByOidLazy(oid)?.Parameters; + } + + /// Look up an for the curve with the given + /// OID. + /// + /// Allows accessing the curve without necessarily triggering the creation of + /// the full . + /// + /// The OID for the curve. + public static X9ECParametersHolder GetByOidLazy(DerObjectIdentifier oid) { - return SecNamedCurves.GetByOid(oid); + return names.ContainsKey(oid) ? SecNamedCurves.GetByOidLazy(oid) : null; } - /** - * return the object identifier signified by the passed in name. Null - * if there is no object identifier associated with name. - * - * @return the object identifier associated with name, if present. - */ - public static DerObjectIdentifier GetOid( - string name) + /// Look up the name of the curve with the given OID. + /// The OID for the curve. + public static string GetName(DerObjectIdentifier oid) { - return (DerObjectIdentifier) objIds[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(name)]; + return CollectionUtilities.GetValueOrNull(names, oid); } - /** - * return the named curve name represented by the given object identifier. - */ - public static string GetName( - DerObjectIdentifier oid) + /// Look up the OID of the curve with the given name. + /// The name of the curve. + public static DerObjectIdentifier GetOid(string name) { - return (string) names[oid]; + return CollectionUtilities.GetValueOrNull(objIds, name); } - /** - * returns an enumeration containing the name strings for curves - * contained in this structure. - */ - public static IEnumerable Names + /// Enumerate the available curve names in this registry. + public static IEnumerable Names { - get { return new EnumerableProxy(names.Values); } + get { return CollectionUtilities.Proxy(objIds.Keys); } } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/BasicOCSPResponse.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/BasicOCSPResponse.cs index 9fc13ac..687343d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/BasicOCSPResponse.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/BasicOCSPResponse.cs @@ -36,7 +36,7 @@ public static BasicOcspResponse GetInstance( return new BasicOcspResponse((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public BasicOcspResponse( @@ -64,34 +64,16 @@ private BasicOcspResponse( } } - - public ResponseData GetTbsResponseData() - { - return tbsResponseData; - } - public ResponseData TbsResponseData { get { return tbsResponseData; } } - - public AlgorithmIdentifier GetSignatureAlgorithm() - { - return signatureAlgorithm; - } - public AlgorithmIdentifier SignatureAlgorithm { get { return signatureAlgorithm; } } - - public DerBitString GetSignature() - { - return signature; - } - public DerBitString Signature { get { return signature; } @@ -102,12 +84,6 @@ public byte[] GetSignatureOctets() return signature.GetOctets(); } - - public Asn1Sequence GetCerts() - { - return certs; - } - public Asn1Sequence Certs { get { return certs; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/CertID.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/CertID.cs index 96c3035..727f6fd 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/CertID.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/CertID.cs @@ -36,7 +36,7 @@ public static CertID GetInstance( return new CertID((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public CertID( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/CertStatus.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/CertStatus.cs index 0eab05d..cc19e14 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/CertStatus.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/CertStatus.cs @@ -36,22 +36,23 @@ public CertStatus( this.value = value; } - public CertStatus( - Asn1TaggedObject choice) + public CertStatus(Asn1TaggedObject choice) { this.tagNo = choice.TagNo; switch (choice.TagNo) { - case 1: - value = RevokedInfo.GetInstance(choice, false); - break; - case 0: - case 2: - value = DerNull.Instance; - break; - default: - throw new ArgumentException("Unknown tag encountered: " + choice.TagNo); + case 0: + value = Asn1Null.GetInstance(choice, false); + break; + case 1: + value = RevokedInfo.GetInstance(choice, false); + break; + case 2: + value = Asn1Null.GetInstance(choice, false); + break; + default: + throw new ArgumentException("Unknown tag encountered: " + Asn1Utilities.GetTagText(choice)); } } @@ -68,7 +69,7 @@ public static CertStatus GetInstance( return new CertStatus((Asn1TaggedObject)obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public int TagNo diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/CrlID.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/CrlID.cs index d414198..7f182e0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/CrlID.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/CrlID.cs @@ -1,7 +1,6 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ocsp { @@ -10,11 +9,10 @@ public class CrlID { private readonly DerIA5String crlUrl; private readonly DerInteger crlNum; - private readonly DerGeneralizedTime crlTime; + private readonly Asn1GeneralizedTime crlTime; - // TODO Add GetInstance method(s) and amke this private? - public CrlID( - Asn1Sequence seq) + // TODO Add GetInstance method(s) and make this private? + public CrlID(Asn1Sequence seq) { foreach (Asn1TaggedObject o in seq) { @@ -27,7 +25,7 @@ public CrlID( crlNum = DerInteger.GetInstance(o, true); break; case 2: - crlTime = DerGeneralizedTime.GetInstance(o, true); + crlTime = Asn1GeneralizedTime.GetInstance(o, true); break; default: throw new ArgumentException("unknown tag number: " + o.TagNo); @@ -45,7 +43,7 @@ public DerInteger CrlNum get { return crlNum; } } - public DerGeneralizedTime CrlTime + public Asn1GeneralizedTime CrlTime { get { return crlTime; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/OCSPRequest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/OCSPRequest.cs index 963ff41..8cf6d78 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/OCSPRequest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/OCSPRequest.cs @@ -32,7 +32,7 @@ public static OcspRequest GetInstance( return new OcspRequest((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public OcspRequest( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/OCSPResponse.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/OCSPResponse.cs index 6c6f5e6..7812871 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/OCSPResponse.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/OCSPResponse.cs @@ -32,7 +32,7 @@ public static OcspResponse GetInstance( return new OcspResponse((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public OcspResponse( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/Request.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/Request.cs index f178b27..92fc819 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/Request.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/Request.cs @@ -34,7 +34,7 @@ public static Request GetInstance( return new Request((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public Request( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/ResponseBytes.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/ResponseBytes.cs index 03a8311..db66036 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/ResponseBytes.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/ResponseBytes.cs @@ -32,7 +32,7 @@ public static ResponseBytes GetInstance( return new ResponseBytes((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public ResponseBytes( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/ResponseData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/ResponseData.cs index 7709cba..2bb60af 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/ResponseData.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/ResponseData.cs @@ -15,7 +15,7 @@ public class ResponseData private readonly bool versionPresent; private readonly DerInteger version; private readonly ResponderID responderID; - private readonly DerGeneralizedTime producedAt; + private readonly Asn1GeneralizedTime producedAt; private readonly Asn1Sequence responses; private readonly X509Extensions responseExtensions; @@ -39,13 +39,13 @@ public static ResponseData GetInstance( return new ResponseData((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public ResponseData( DerInteger version, ResponderID responderID, - DerGeneralizedTime producedAt, + Asn1GeneralizedTime producedAt, Asn1Sequence responses, X509Extensions responseExtensions) { @@ -58,7 +58,7 @@ public ResponseData( public ResponseData( ResponderID responderID, - DerGeneralizedTime producedAt, + Asn1GeneralizedTime producedAt, Asn1Sequence responses, X509Extensions responseExtensions) : this(V1, responderID, producedAt, responses, responseExtensions) @@ -92,7 +92,7 @@ private ResponseData( } this.responderID = ResponderID.GetInstance(seq[index++]); - this.producedAt = (DerGeneralizedTime)seq[index++]; + this.producedAt = (Asn1GeneralizedTime)seq[index++]; this.responses = (Asn1Sequence)seq[index++]; if (seq.Count > index) @@ -112,7 +112,7 @@ public ResponderID ResponderID get { return responderID; } } - public DerGeneralizedTime ProducedAt + public Asn1GeneralizedTime ProducedAt { get { return producedAt; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/RevokedInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/RevokedInfo.cs index f2a79e5..718b75e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/RevokedInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/RevokedInfo.cs @@ -10,7 +10,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ocsp public class RevokedInfo : Asn1Encodable { - private readonly DerGeneralizedTime revocationTime; + private readonly Asn1GeneralizedTime revocationTime; private readonly CrlReason revocationReason; public static RevokedInfo GetInstance( @@ -33,17 +33,17 @@ public static RevokedInfo GetInstance( return new RevokedInfo((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public RevokedInfo( - DerGeneralizedTime revocationTime) + Asn1GeneralizedTime revocationTime) : this(revocationTime, null) { } public RevokedInfo( - DerGeneralizedTime revocationTime, + Asn1GeneralizedTime revocationTime, CrlReason revocationReason) { if (revocationTime == null) @@ -56,7 +56,7 @@ public RevokedInfo( private RevokedInfo( Asn1Sequence seq) { - this.revocationTime = (DerGeneralizedTime) seq[0]; + this.revocationTime = (Asn1GeneralizedTime)seq[0]; if (seq.Count > 1) { @@ -65,7 +65,7 @@ private RevokedInfo( } } - public DerGeneralizedTime RevocationTime + public Asn1GeneralizedTime RevocationTime { get { return revocationTime; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/ServiceLocator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/ServiceLocator.cs index e6b2a4f..09bb707 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/ServiceLocator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/ServiceLocator.cs @@ -33,7 +33,7 @@ public static ServiceLocator GetInstance( return new ServiceLocator((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public ServiceLocator( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/Signature.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/Signature.cs index 53b26b4..5d15d61 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/Signature.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/Signature.cs @@ -34,7 +34,7 @@ public static Signature GetInstance( return new Signature((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public Signature( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/SingleResponse.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/SingleResponse.cs index fda108c..8430679 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/SingleResponse.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/SingleResponse.cs @@ -12,15 +12,15 @@ public class SingleResponse { private readonly CertID certID; private readonly CertStatus certStatus; - private readonly DerGeneralizedTime thisUpdate; - private readonly DerGeneralizedTime nextUpdate; + private readonly Asn1GeneralizedTime thisUpdate; + private readonly Asn1GeneralizedTime nextUpdate; private readonly X509Extensions singleExtensions; public SingleResponse( CertID certID, CertStatus certStatus, - DerGeneralizedTime thisUpdate, - DerGeneralizedTime nextUpdate, + Asn1GeneralizedTime thisUpdate, + Asn1GeneralizedTime nextUpdate, X509Extensions singleExtensions) { this.certID = certID; @@ -35,11 +35,11 @@ public SingleResponse( { this.certID = CertID.GetInstance(seq[0]); this.certStatus = CertStatus.GetInstance(seq[1]); - this.thisUpdate = (DerGeneralizedTime)seq[2]; + this.thisUpdate = (Asn1GeneralizedTime)seq[2]; if (seq.Count > 4) { - this.nextUpdate = DerGeneralizedTime.GetInstance( + this.nextUpdate = Asn1GeneralizedTime.GetInstance( (Asn1TaggedObject) seq[3], true); this.singleExtensions = X509Extensions.GetInstance( (Asn1TaggedObject) seq[4], true); @@ -50,7 +50,7 @@ public SingleResponse( if (o.TagNo == 0) { - this.nextUpdate = DerGeneralizedTime.GetInstance(o, true); + this.nextUpdate = Asn1GeneralizedTime.GetInstance(o, true); } else { @@ -79,7 +79,7 @@ public static SingleResponse GetInstance( return new SingleResponse((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public CertID CertId @@ -92,12 +92,12 @@ public CertStatus CertStatus get { return certStatus; } } - public DerGeneralizedTime ThisUpdate + public Asn1GeneralizedTime ThisUpdate { get { return thisUpdate; } } - public DerGeneralizedTime NextUpdate + public Asn1GeneralizedTime NextUpdate { get { return nextUpdate; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/TBSRequest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/TBSRequest.cs index a9877ae..2206a81 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/TBSRequest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ocsp/TBSRequest.cs @@ -39,7 +39,7 @@ public static TbsRequest GetInstance( return new TbsRequest((Asn1Sequence)obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public TbsRequest( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/oiw/ElGamalParameter.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/oiw/ElGamalParameter.cs index 3987138..186d1ab 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/oiw/ElGamalParameter.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/oiw/ElGamalParameter.cs @@ -1,9 +1,7 @@ #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.Math; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/Attribute.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/Attribute.cs index 6885fef..c5efb2e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/Attribute.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/Attribute.cs @@ -33,7 +33,7 @@ public static AttributePkcs GetInstance( return new AttributePkcs(seq); } - throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } private AttributePkcs( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/CertificationRequest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/CertificationRequest.cs index 32b7699..52b35a6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/CertificationRequest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/CertificationRequest.cs @@ -26,13 +26,11 @@ public class CertificationRequest public static CertificationRequest GetInstance( object obj) { - if (obj is CertificationRequest) + if (obj == null) + return null; + if (obj is CertificationRequest) return (CertificationRequest)obj; - - if (obj != null) - return new CertificationRequest((Asn1Sequence)obj); - - return null; + return new CertificationRequest(Asn1Sequence.GetInstance(obj)); } protected CertificationRequest() @@ -49,9 +47,7 @@ public CertificationRequest( this.sigBits = signature; } - - public CertificationRequest( - Asn1Sequence seq) + internal CertificationRequest(Asn1Sequence seq) { if (seq.Count != 3) throw new ArgumentException("Wrong number of elements in sequence", "seq"); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/ContentInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/ContentInfo.cs index e958b3f..f2e31ac 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/ContentInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/ContentInfo.cs @@ -1,9 +1,6 @@ #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.Pkcs { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/DHParameter.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/DHParameter.cs index c0a06fa..72d535c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/DHParameter.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/DHParameter.cs @@ -1,9 +1,5 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; -using System; -using System.Collections; - using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs @@ -30,7 +26,7 @@ public DHParameter( public DHParameter( Asn1Sequence seq) { - IEnumerator e = seq.GetEnumerator(); + var e = seq.GetEnumerator(); e.MoveNext(); p = (DerInteger)e.Current; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/EncryptedData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/EncryptedData.cs index dc91439..52f079e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/EncryptedData.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/EncryptedData.cs @@ -45,7 +45,7 @@ public static EncryptedData GetInstance( return new EncryptedData((Asn1Sequence) obj); } - throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } private EncryptedData( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/EncryptedPrivateKeyInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/EncryptedPrivateKeyInfo.cs index cf08d46..c811775 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/EncryptedPrivateKeyInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/EncryptedPrivateKeyInfo.cs @@ -1,7 +1,6 @@ #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.Utilities; @@ -14,8 +13,7 @@ public class EncryptedPrivateKeyInfo private readonly AlgorithmIdentifier algId; private readonly Asn1OctetString data; - private EncryptedPrivateKeyInfo( - Asn1Sequence seq) + private EncryptedPrivateKeyInfo(Asn1Sequence seq) { if (seq.Count != 2) throw new ArgumentException("Wrong number of elements in sequence", "seq"); @@ -40,12 +38,10 @@ public static EncryptedPrivateKeyInfo GetInstance( return (EncryptedPrivateKeyInfo) obj; } - if (obj is Asn1Sequence) - { - return new EncryptedPrivateKeyInfo((Asn1Sequence) obj); - } + if (obj is Asn1Sequence seq) + return new EncryptedPrivateKeyInfo(seq); - throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public AlgorithmIdentifier EncryptionAlgorithm diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/EncryptionScheme.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/EncryptionScheme.cs index 1350d4f..0d7ff9a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/EncryptionScheme.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/EncryptionScheme.cs @@ -41,7 +41,7 @@ internal EncryptionScheme( return new EncryptionScheme((Asn1Sequence)obj); } - throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public Asn1Object Asn1Object diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/IssuerAndSerialNumber.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/IssuerAndSerialNumber.cs index 859e457..7f5e86a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/IssuerAndSerialNumber.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/IssuerAndSerialNumber.cs @@ -27,7 +27,7 @@ public static IssuerAndSerialNumber GetInstance( return new IssuerAndSerialNumber((Asn1Sequence) obj); } - throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } private IssuerAndSerialNumber( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/MacData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/MacData.cs index 5e72c4f..501a3bc 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/MacData.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/MacData.cs @@ -28,7 +28,7 @@ public static MacData GetInstance( return new MacData((Asn1Sequence) obj); } - throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } private MacData( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PBEParameter.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PBEParameter.cs index 1814c79..801ddee 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PBEParameter.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PBEParameter.cs @@ -1,7 +1,6 @@ #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; @@ -26,7 +25,7 @@ public static PbeParameter GetInstance(object obj) return new PbeParameter((Asn1Sequence) obj); } - throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } private PbeParameter(Asn1Sequence seq) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PBES2Parameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PBES2Parameters.cs index 82c8443..f43a7fe 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PBES2Parameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PBES2Parameters.cs @@ -26,9 +26,7 @@ public PbeS2Parameters(KeyDerivationFunc keyDevFunc, EncryptionScheme encScheme) this.scheme = encScheme; } - - public PbeS2Parameters( - Asn1Sequence seq) + private PbeS2Parameters(Asn1Sequence seq) { if (seq.Count != 2) throw new ArgumentException("Wrong number of elements in sequence", "seq"); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PBKDF2Params.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PBKDF2Params.cs index a561d34..581933c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PBKDF2Params.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PBKDF2Params.cs @@ -26,7 +26,7 @@ public static Pbkdf2Params GetInstance( 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"); + throw new ArgumentException("Unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public Pbkdf2Params( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PKCS12PBEParams.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PKCS12PBEParams.cs index 6a0201a..aea459f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PKCS12PBEParams.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PKCS12PBEParams.cs @@ -44,7 +44,7 @@ public static Pkcs12PbeParams GetInstance( return new Pkcs12PbeParams((Asn1Sequence) obj); } - throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public BigInteger Iterations diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PKCSObjectIdentifiers.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PKCSObjectIdentifiers.cs index 0255622..84d5550 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PKCSObjectIdentifiers.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PKCSObjectIdentifiers.cs @@ -131,9 +131,6 @@ public abstract class PkcsObjectIdentifiers public static readonly DerObjectIdentifier Pkcs9AtFriendlyName = new DerObjectIdentifier(Pkcs9 + ".20"); public static readonly DerObjectIdentifier Pkcs9AtLocalKeyID = new DerObjectIdentifier(Pkcs9 + ".21"); - - 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"); @@ -143,11 +140,12 @@ public abstract class PkcsObjectIdentifiers 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 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 IdAlgZlibCompress = IdAlg.Branch("8"); + public static readonly DerObjectIdentifier IdAlgPwriKek = IdAlg.Branch("9"); + public static readonly DerObjectIdentifier IdAlgSsdh = IdAlg.Branch("10"); /* *
@@ -172,6 +170,14 @@ public abstract class PkcsObjectIdentifiers
          */
         public static readonly DerObjectIdentifier IdAlgAeadChaCha20Poly1305 = IdAlg.Branch("18");
 
+        
+        /**
+     * id-alg-hss-lms-hashsig OBJECT IDENTIFIER ::= { iso(1)
+     *     member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
+     *    smime(16) alg(3) 17 }
+     */
+        public static readonly DerObjectIdentifier IdAlgHssLmsHashsig = IdAlg.Branch("17");
+
         //
         // SMIME capability sub oids.
         //
@@ -263,15 +269,6 @@ public abstract class PkcsObjectIdentifiers
         /** PKCS#9: 1.2.840.113549.1.9.16.2.40   RFC7030*/
         public static readonly DerObjectIdentifier IdAACommunityIdentifiers = IdAAOid.Branch("40");
 
-
-		public static readonly DerObjectIdentifier IdAASigPolicyID = IdAAEtsSigPolicyID;
-
-		public static readonly DerObjectIdentifier IdAACommitmentType = IdAAEtsCommitmentType;
-
-		public static readonly DerObjectIdentifier IdAASignerLocation = IdAAEtsSignerLocation;
-
-		public static readonly DerObjectIdentifier IdAAOtherSigCert = IdAAEtsOtherSigCert;
-
 		//
 		// id-spq OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840)
 		// rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) id-spq(5)}
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PrivateKeyInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PrivateKeyInfo.cs
index 61d8db1..81af967 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PrivateKeyInfo.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/PrivateKeyInfo.cs	
@@ -1,8 +1,6 @@
 #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.Math;
@@ -110,7 +108,7 @@ public PrivateKeyInfo(
 
         private PrivateKeyInfo(Asn1Sequence seq)
         {
-            IEnumerator e = seq.GetEnumerator();
+            var e = seq.GetEnumerator();
 
             this.version = DerInteger.GetInstance(CollectionUtilities.RequireNext(e));
 
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/RC2CBCParameter.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/RC2CBCParameter.cs
index d586d9c..690986e 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/RC2CBCParameter.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/RC2CBCParameter.cs	
@@ -21,7 +21,7 @@ public static RC2CbcParameter GetInstance(
                 return new RC2CbcParameter((Asn1Sequence) obj);
             }
 
-			throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+			throw new ArgumentException("Unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
 		}
 
 		public RC2CbcParameter(
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/RSAESOAEPparams.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/RSAESOAEPparams.cs
index 9e2064b..6f379f8 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/RSAESOAEPparams.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/RSAESOAEPparams.cs	
@@ -31,7 +31,7 @@ public static RsaesOaepParameters GetInstance(
 				return new RsaesOaepParameters((Asn1Sequence)obj);
 			}
 
-			throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+			throw new ArgumentException("Unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
 		}
 
 		/**
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/RSAPrivateKeyStructure.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/RSAPrivateKeyStructure.cs
index 3d6f0f3..8c8f841 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/RSAPrivateKeyStructure.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/RSAPrivateKeyStructure.cs	
@@ -1,9 +1,7 @@
 #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.Math;
 
 namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs
@@ -54,9 +52,7 @@ public RsaPrivateKeyStructure(
             this.coefficient = coefficient;
         }
 
-
-        public RsaPrivateKeyStructure(
-            Asn1Sequence seq)
+        private RsaPrivateKeyStructure(Asn1Sequence seq)
         {
             BigInteger version = ((DerInteger)seq[0]).Value;
             if (version.IntValue != 0)
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/RSASSAPSSparams.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/RSASSAPSSparams.cs
index 5d4d8f8..7d1cd3a 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/RSASSAPSSparams.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/RSASSAPSSparams.cs	
@@ -34,7 +34,7 @@ public static RsassaPssParameters GetInstance(
 				return new RsassaPssParameters((Asn1Sequence)obj);
 			}
 
-			throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+			throw new ArgumentException("Unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
 		}
 
 		/**
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/SignedData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/SignedData.cs
index 1d4fca7..364f9a6 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/SignedData.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/SignedData.cs	
@@ -1,9 +1,6 @@
 #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.Pkcs
 {
@@ -49,7 +46,7 @@ public SignedData(
         private SignedData(
             Asn1Sequence seq)
         {
-            IEnumerator e = seq.GetEnumerator();
+            var e = seq.GetEnumerator();
 
             e.MoveNext();
             version = (DerInteger) e.Current;
@@ -62,26 +59,24 @@ private SignedData(
 
             while (e.MoveNext())
             {
-                Asn1Object o = (Asn1Object) e.Current;
+                Asn1Object o = e.Current.ToAsn1Object();
 
                 //
                 // an interesting feature of SignedData is that there appear to be varying implementations...
                 // for the moment we ignore anything which doesn't fit.
                 //
-                if (o is Asn1TaggedObject)
+                if (o is Asn1TaggedObject tagged)
                 {
-                    Asn1TaggedObject tagged = (Asn1TaggedObject)o;
-
                     switch (tagged.TagNo)
                     {
-                        case 0:
-                            certificates = Asn1Set.GetInstance(tagged, false);
-                            break;
-                        case 1:
-                            crls = Asn1Set.GetInstance(tagged, false);
-                            break;
-                        default:
-                            throw new ArgumentException("unknown tag value " + tagged.TagNo);
+                    case 0:
+                        certificates = Asn1Set.GetInstance(tagged, false);
+                        break;
+                    case 1:
+                        crls = Asn1Set.GetInstance(tagged, false);
+                        break;
+                    default:
+                        throw new ArgumentException("unknown tag value " + tagged.TagNo);
                     }
                 }
                 else
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/SignerInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/SignerInfo.cs
index 1ac852a..41bc6c0 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/SignerInfo.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/pkcs/SignerInfo.cs	
@@ -1,7 +1,6 @@
 #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.Utilities;
@@ -35,7 +34,7 @@ public static SignerInfo GetInstance(
                 return new SignerInfo((Asn1Sequence) obj);
             }
 
-			throw new ArgumentException("Unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+			throw new ArgumentException("Unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
 		}
 
 		public SignerInfo(
@@ -59,7 +58,7 @@ public SignerInfo(
 		public SignerInfo(
             Asn1Sequence seq)
         {
-            IEnumerator e = seq.GetEnumerator();
+            var e = seq.GetEnumerator();
 
 			e.MoveNext();
             version = (DerInteger) e.Current;
@@ -71,11 +70,11 @@ public SignerInfo(
             digAlgorithm = AlgorithmIdentifier.GetInstance(e.Current);
 
 			e.MoveNext();
-            object obj = e.Current;
+            var obj = e.Current;
 
-			if (obj is Asn1TaggedObject)
+			if (obj is Asn1TaggedObject tagged)
             {
-                authenticatedAttributes = Asn1Set.GetInstance((Asn1TaggedObject) obj, false);
+                authenticatedAttributes = Asn1Set.GetInstance(tagged, false);
 
 				e.MoveNext();
                 digEncryptionAlgorithm = AlgorithmIdentifier.GetInstance(e.Current);
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/sec/ECPrivateKeyStructure.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/sec/ECPrivateKeyStructure.cs
index a41fadc..4b82ca2 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/sec/ECPrivateKeyStructure.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/sec/ECPrivateKeyStructure.cs	
@@ -2,7 +2,6 @@
 #pragma warning disable
 using System;
 
-using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
 using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
 using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
 
@@ -14,37 +13,20 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Sec
     public class ECPrivateKeyStructure
         : Asn1Encodable
     {
-        private readonly Asn1Sequence seq;
+        private readonly Asn1Sequence m_seq;
 
         public static ECPrivateKeyStructure GetInstance(object obj)
         {
             if (obj == null)
                 return null;
-            if (obj is ECPrivateKeyStructure)
-                return (ECPrivateKeyStructure)obj;
+            if (obj is ECPrivateKeyStructure ecPrivateKeyStructure)
+                return ecPrivateKeyStructure;
             return new ECPrivateKeyStructure(Asn1Sequence.GetInstance(obj));
         }
 
-
-        public ECPrivateKeyStructure(
-            Asn1Sequence seq)
+        private ECPrivateKeyStructure(Asn1Sequence seq)
         {
-            if (seq == null)
-                throw new ArgumentNullException("seq");
-
-            this.seq = seq;
-        }
-
-
-        public ECPrivateKeyStructure(
-            BigInteger key)
-        {
-            if (key == null)
-                throw new ArgumentNullException("key");
-
-            this.seq = new DerSequence(
-                new DerInteger(1),
-                new DerOctetString(key.ToByteArrayUnsigned()));
+            m_seq = seq ?? throw new ArgumentNullException(nameof(seq));
         }
 
         public ECPrivateKeyStructure(
@@ -54,40 +36,6 @@ public ECPrivateKeyStructure(
         {
         }
 
-
-        public ECPrivateKeyStructure(
-            BigInteger		key,
-            Asn1Encodable	parameters)
-            : this(key, null, parameters)
-        {
-        }
-
-
-        public ECPrivateKeyStructure(
-            BigInteger		key,
-            DerBitString	publicKey,
-            Asn1Encodable	parameters)
-        {
-            if (key == null)
-                throw new ArgumentNullException("key");
-
-            Asn1EncodableVector v = new Asn1EncodableVector(
-                new DerInteger(1),
-                new DerOctetString(key.ToByteArrayUnsigned()));
-
-            if (parameters != null)
-            {
-                v.Add(new DerTaggedObject(true, 0, parameters));
-            }
-
-            if (publicKey != null)
-            {
-                v.Add(new DerTaggedObject(true, 1, publicKey));
-            }
-
-            this.seq = new DerSequence(v);
-        }
-
         public ECPrivateKeyStructure(
             int             orderBitLength,
             BigInteger      key,
@@ -103,9 +51,9 @@ public ECPrivateKeyStructure(
             Asn1Encodable   parameters)
         {
             if (key == null)
-                throw new ArgumentNullException("key");
+                throw new ArgumentNullException(nameof(key));
             if (orderBitLength < key.BitLength)
-                throw new ArgumentException("must be >= key bitlength", "orderBitLength");
+                throw new ArgumentException("must be >= key bitlength", nameof(orderBitLength));
 
             byte[] bytes = BigIntegers.AsUnsignedByteArray((orderBitLength + 7) / 8, key);
 
@@ -113,48 +61,42 @@ public ECPrivateKeyStructure(
                 new DerInteger(1),
                 new DerOctetString(bytes));
 
-            if (parameters != null)
-            {
-                v.Add(new DerTaggedObject(true, 0, parameters));
-            }
-
-            if (publicKey != null)
-            {
-                v.Add(new DerTaggedObject(true, 1, publicKey));
-            }
+            v.AddOptionalTagged(true, 0, parameters);
+            v.AddOptionalTagged(true, 1, publicKey);
 
-            this.seq = new DerSequence(v);
+            m_seq = new DerSequence(v);
         }
 
         public virtual BigInteger GetKey()
         {
-            Asn1OctetString octs = (Asn1OctetString) seq[1];
+            Asn1OctetString octs = (Asn1OctetString)m_seq[1];
 
             return new BigInteger(1, octs.GetOctets());
         }
 
         public virtual DerBitString GetPublicKey()
         {
-            return (DerBitString) GetObjectInTag(1);
+            return (DerBitString)GetObjectInTag(1, Asn1Tags.BitString);
         }
 
         public virtual Asn1Object GetParameters()
         {
-            return GetObjectInTag(0);
+            return GetObjectInTag(0, -1);
         }
 
-        private Asn1Object GetObjectInTag(int tagNo)
+        private Asn1Object GetObjectInTag(int tagNo, int baseTagNo)
         {
-            foreach (Asn1Encodable ae in seq)
+            foreach (Asn1Encodable ae in m_seq)
             {
                 Asn1Object obj = ae.ToAsn1Object();
 
-                if (obj is Asn1TaggedObject)
+                if (obj is Asn1TaggedObject tag)
                 {
-                    Asn1TaggedObject tag = (Asn1TaggedObject) obj;
-                    if (tag.TagNo == tagNo)
+                    if (tag.HasContextTag(tagNo))
                     {
-                        return tag.GetObject();
+                        return baseTagNo < 0
+                            ? tag.GetExplicitBaseObject().ToAsn1Object()
+                            : tag.GetBaseUniversal(true, baseTagNo);
                     }
                 }
             }
@@ -171,7 +113,7 @@ private Asn1Object GetObjectInTag(int tagNo)
          */
         public override Asn1Object ToAsn1Object()
         {
-            return seq;
+            return m_seq;
         }
     }
 }
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/sec/SECNamedCurves.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/sec/SECNamedCurves.cs
index 3432822..e0e17cd 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/sec/SECNamedCurves.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/sec/SECNamedCurves.cs	
@@ -1,26 +1,21 @@
 #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
 #pragma warning disable
 using System;
-using System.Collections;
+using System.Collections.Generic;
 
-using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1;
 using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
 using BestHTTP.SecureProtocol.Org.BouncyCastle.Math;
 using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC;
 using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Endo;
 using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier;
-using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
 using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
 using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
 
 namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Sec
 {
-    public sealed class SecNamedCurves
+    /// Elliptic curve registry for the SEC standard.
+    public static class SecNamedCurves
     {
-        private SecNamedCurves()
-        {
-        }
-
         private static X9ECPoint ConfigureBasepoint(ECCurve curve, string encoding)
         {
             X9ECPoint G = new X9ECPoint(curve, Hex.DecodeStrict(encoding));
@@ -43,9 +38,6 @@ private static BigInteger FromHex(string hex)
             return new BigInteger(1, Hex.DecodeStrict(hex));
         }
 
-        /*
-         * secp112r1
-         */
         internal class Secp112r1Holder
             : X9ECParametersHolder
         {
@@ -53,28 +45,30 @@ private Secp112r1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new Secp112r1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 // p = (2^128 - 3) / 76439
                 BigInteger p = FromHex("DB7C2ABF62E35E668076BEAD208B");
                 BigInteger a = FromHex("DB7C2ABF62E35E668076BEAD2088");
                 BigInteger b = FromHex("659EF8BA043916EEDE8911702B22");
-                byte[] S = Hex.DecodeStrict("00F50B028E4D696E676875615175290472783FB1");
                 BigInteger n = FromHex("DB7C2ABF62E35E7628DFAC6561C5");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
+                return ConfigureCurve(new FpCurve(p, a, b, n, h, true));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("00F50B028E4D696E676875615175290472783FB1");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "0409487239995A5EE76B55F9C2F098A89CE5AF8724C0A23E0E0FF77500"); 
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * secp112r2
-         */
         internal class Secp112r2Holder
             : X9ECParametersHolder
         {
@@ -82,28 +76,30 @@ private Secp112r2Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new Secp112r2Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 // p = (2^128 - 3) / 76439
                 BigInteger p = FromHex("DB7C2ABF62E35E668076BEAD208B");
                 BigInteger a = FromHex("6127C24C05F38A0AAAF65C0EF02C");
                 BigInteger b = FromHex("51DEF1815DB5ED74FCC34C85D709");
-                byte[] S = Hex.DecodeStrict("002757A1114D696E6768756151755316C05E0BD4");
                 BigInteger n = FromHex("36DF0AAFD8B8D7597CA10520D04B");
                 BigInteger h = BigInteger.ValueOf(4);
 
-                ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
+                return ConfigureCurve(new FpCurve(p, a, b, n, h, true));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("002757A1114D696E6768756151755316C05E0BD4");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "044BA30AB5E892B4E1649DD0928643ADCD46F5882E3747DEF36E956E97");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * secp128r1
-         */
         internal class Secp128r1Holder
             : X9ECParametersHolder
         {
@@ -111,28 +107,30 @@ private Secp128r1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new Secp128r1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 // p = 2^128 - 2^97 - 1
                 BigInteger p = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF");
                 BigInteger a = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC");
                 BigInteger b = FromHex("E87579C11079F43DD824993C2CEE5ED3");
-                byte[] S = Hex.DecodeStrict("000E0D4D696E6768756151750CC03A4473D03679");
                 BigInteger n = FromHex("FFFFFFFE0000000075A30D1B9038A115");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
+                return ConfigureCurve(new FpCurve(p, a, b, n, h, true));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("000E0D4D696E6768756151750CC03A4473D03679");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "04161FF7528B899B2D0C28607CA52C5B86CF5AC8395BAFEB13C02DA292DDED7A83");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * secp128r2
-         */
         internal class Secp128r2Holder
             : X9ECParametersHolder
         {
@@ -140,28 +138,30 @@ private Secp128r2Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new Secp128r2Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 // p = 2^128 - 2^97 - 1
                 BigInteger p = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF");
                 BigInteger a = FromHex("D6031998D1B3BBFEBF59CC9BBFF9AEE1");
                 BigInteger b = FromHex("5EEEFCA380D02919DC2C6558BB6D8A5D");
-                byte[] S = Hex.DecodeStrict("004D696E67687561517512D8F03431FCE63B88F4");
                 BigInteger n = FromHex("3FFFFFFF7FFFFFFFBE0024720613B5A3");
                 BigInteger h = BigInteger.ValueOf(4);
 
-                ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
+                return ConfigureCurve(new FpCurve(p, a, b, n, h, true));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("004D696E67687561517512D8F03431FCE63B88F4");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "047B6AA5D85E572983E6FB32A7CDEBC14027B6916A894D3AEE7106FE805FC34B44");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * secp160k1
-         */
         internal class Secp160k1Holder
             : X9ECParametersHolder
         {
@@ -169,13 +169,12 @@ private Secp160k1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new Secp160k1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1
                 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73");
                 BigInteger a = BigInteger.Zero;
                 BigInteger b = BigInteger.ValueOf(7);
-                byte[] S = null;
                 BigInteger n = FromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3");
                 BigInteger h = BigInteger.One;
 
@@ -193,18 +192,21 @@ protected override X9ECParameters CreateParameters()
                         new BigInteger("96341f1138933bc2f503fd44", 16),
                         176));
 
-                ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv);
+                return ConfigureCurveGlv(new FpCurve(p, a, b, n, h, true), glv);
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = null;
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "043B4C382CE37AA192A4019E763036F4F5DD4D7EBB938CF935318FDCED6BC28286531733C3F03C4FEE");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * secp160r1
-         */
         internal class Secp160r1Holder
             : X9ECParametersHolder
         {
@@ -212,28 +214,30 @@ private Secp160r1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new Secp160r1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 // p = 2^160 - 2^31 - 1
                 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF");
                 BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC");
                 BigInteger b = FromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45");
-                byte[] S = Hex.DecodeStrict("1053CDE42C14D696E67687561517533BF3F83345");
                 BigInteger n = FromHex("0100000000000000000001F4C8F927AED3CA752257");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
+                return ConfigureCurve(new FpCurve(p, a, b, n, h, true));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("1053CDE42C14D696E67687561517533BF3F83345");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "044A96B5688EF573284664698968C38BB913CBFC8223A628553168947D59DCC912042351377AC5FB32");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * secp160r2
-         */
         internal class Secp160r2Holder
             : X9ECParametersHolder
         {
@@ -241,28 +245,30 @@ private Secp160r2Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new Secp160r2Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1
                 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73");
                 BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC70");
                 BigInteger b = FromHex("B4E134D3FB59EB8BAB57274904664D5AF50388BA");
-                byte[] S = Hex.DecodeStrict("B99B99B099B323E02709A4D696E6768756151751");
                 BigInteger n = FromHex("0100000000000000000000351EE786A818F3A1A16B");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
+                return ConfigureCurve(new FpCurve(p, a, b, n, h, true));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("B99B99B099B323E02709A4D696E6768756151751");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "0452DCB034293A117E1F4FF11B30F7199D3144CE6DFEAFFEF2E331F296E071FA0DF9982CFEA7D43F2E");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * secp192k1
-         */
         internal class Secp192k1Holder
             : X9ECParametersHolder
         {
@@ -270,13 +276,12 @@ private Secp192k1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new Secp192k1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1
                 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37");
                 BigInteger a = BigInteger.Zero;
                 BigInteger b = BigInteger.ValueOf(3);
-                byte[] S = null;
                 BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D");
                 BigInteger h = BigInteger.One;
 
@@ -294,18 +299,21 @@ protected override X9ECParameters CreateParameters()
                         new BigInteger("b3fb3400dec5c4adceb8655d4c94", 16),
                         208));
 
-                ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv);
+                return ConfigureCurveGlv(new FpCurve(p, a, b, n, h, true), glv);
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = null;
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "04DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * secp192r1
-         */
         internal class Secp192r1Holder
             : X9ECParametersHolder
         {
@@ -313,28 +321,30 @@ private Secp192r1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new Secp192r1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 // p = 2^192 - 2^64 - 1
                 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF");
                 BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC");
                 BigInteger b = FromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1");
-                byte[] S = Hex.DecodeStrict("3045AE6FC8422F64ED579528D38120EAE12196D5");
                 BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
+                return ConfigureCurve(new FpCurve(p, a, b, n, h, true));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("3045AE6FC8422F64ED579528D38120EAE12196D5");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "04188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF101207192B95FFC8DA78631011ED6B24CDD573F977A11E794811");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * secp224k1
-         */
         internal class Secp224k1Holder
             : X9ECParametersHolder
         {
@@ -342,13 +352,12 @@ private Secp224k1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new Secp224k1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 // p = 2^224 - 2^32 - 2^12 - 2^11 - 2^9 - 2^7 - 2^4 - 2 - 1
                 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFE56D");
                 BigInteger a = BigInteger.Zero;
                 BigInteger b = BigInteger.ValueOf(5);
-                byte[] S = null;
                 BigInteger n = FromHex("010000000000000000000000000001DCE8D2EC6184CAF0A971769FB1F7");
                 BigInteger h = BigInteger.One;
 
@@ -366,18 +375,21 @@ protected override X9ECParameters CreateParameters()
                         new BigInteger("b8adf1378a6eb73409fa6c9c637ba7f5", 16),
                         240));
 
-                ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv);
+                return ConfigureCurveGlv(new FpCurve(p, a, b, n, h, true), glv);
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = null;
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "04A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * secp224r1
-         */
         internal class Secp224r1Holder
             : X9ECParametersHolder
         {
@@ -385,28 +397,30 @@ private Secp224r1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new Secp224r1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 // p = 2^224 - 2^96 + 1
                 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001");
                 BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE");
                 BigInteger b = FromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4");
-                byte[] S = Hex.DecodeStrict("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5");
                 BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
+                return ConfigureCurve(new FpCurve(p, a, b, n, h, true));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "04B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * secp256k1
-         */
         internal class Secp256k1Holder
             : X9ECParametersHolder
         {
@@ -414,13 +428,12 @@ private Secp256k1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new Secp256k1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 // p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1
                 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F");
                 BigInteger a = BigInteger.Zero;
                 BigInteger b = BigInteger.ValueOf(7);
-                byte[] S = null;
                 BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");
                 BigInteger h = BigInteger.One;
 
@@ -438,18 +451,21 @@ protected override X9ECParameters CreateParameters()
                         new BigInteger("e4437ed6010e88286f547fa90abfe4c42212", 16),
                         272));
 
-                ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv);
+                return ConfigureCurveGlv(new FpCurve(p, a, b, n, h, true), glv);
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = null;
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "0479BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * secp256r1
-         */
         internal class Secp256r1Holder
             : X9ECParametersHolder
         {
@@ -457,28 +473,30 @@ private Secp256r1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new Secp256r1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1
                 BigInteger p = FromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF");
                 BigInteger a = FromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC");
                 BigInteger b = FromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B");
-                byte[] S = Hex.DecodeStrict("C49D360886E704936A6678E1139D26B7819F7E90");
                 BigInteger n = FromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
+                return ConfigureCurve(new FpCurve(p, a, b, n, h, true));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("C49D360886E704936A6678E1139D26B7819F7E90");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "046B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C2964FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * secp384r1
-         */
         internal class Secp384r1Holder
             : X9ECParametersHolder
         {
@@ -486,29 +504,31 @@ private Secp384r1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new Secp384r1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 // p = 2^384 - 2^128 - 2^96 + 2^32 - 1
                 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF");
                 BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC");
                 BigInteger b = FromHex("B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF");
-                byte[] S = Hex.DecodeStrict("A335926AA319A27A1D00896A6773A4827ACDAC73");
                 BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
+                return ConfigureCurve(new FpCurve(p, a, b, n, h, true));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("A335926AA319A27A1D00896A6773A4827ACDAC73");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve, "04"
                     + "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7"
                     + "3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * secp521r1
-         */
         internal class Secp521r1Holder
             : X9ECParametersHolder
         {
@@ -516,29 +536,31 @@ private Secp521r1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new Secp521r1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 // p = 2^521 - 1
                 BigInteger p = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");
                 BigInteger a = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC");
                 BigInteger b = FromHex("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00");
-                byte[] S = Hex.DecodeStrict("D09E8800291CB85396CC6717393284AAA0DA64BA");
                 BigInteger n = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h));
+                return ConfigureCurve(new FpCurve(p, a, b, n, h, true));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("D09E8800291CB85396CC6717393284AAA0DA64BA");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve, "04"
                     + "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66"
                     + "011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * sect113r1
-         */
         internal class Sect113r1Holder
             : X9ECParametersHolder
         {
@@ -549,26 +571,28 @@ private Sect113r1Holder() {}
             private const int m = 113;
             private const int k = 9;
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger a = FromHex("003088250CA6E7C7FE649CE85820F7");
                 BigInteger b = FromHex("00E8BEE4D3E2260744188BE0E9C723");
-                byte[] S = Hex.DecodeStrict("10E723AB14D696E6768756151756FEBF8FCB49A9");
                 BigInteger n = FromHex("0100000000000000D9CCEC8A39E56F");
                 BigInteger h = BigInteger.ValueOf(2);
 
-                ECCurve curve = new F2mCurve(m, k, a, b, n, h);
+                return ConfigureCurve(new F2mCurve(m, k, a, b, n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("10E723AB14D696E6768756151756FEBF8FCB49A9");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "04009D73616F35F4AB1407D73562C10F00A52830277958EE84D1315ED31886");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * sect113r2
-         */
         internal class Sect113r2Holder
             : X9ECParametersHolder
         {
@@ -579,26 +603,28 @@ private Sect113r2Holder() {}
             private const int m = 113;
             private const int k = 9;
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger a = FromHex("00689918DBEC7E5A0DD6DFC0AA55C7");
                 BigInteger b = FromHex("0095E9A9EC9B297BD4BF36E059184F");
-                byte[] S = Hex.DecodeStrict("10C0FB15760860DEF1EEF4D696E676875615175D");
                 BigInteger n = FromHex("010000000000000108789B2496AF93");
                 BigInteger h = BigInteger.ValueOf(2);
 
-                ECCurve curve = new F2mCurve(m, k, a, b, n, h);
+                return ConfigureCurve(new F2mCurve(m, k, a, b, n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("10C0FB15760860DEF1EEF4D696E676875615175D");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "0401A57A6A7B26CA5EF52FCDB816479700B3ADC94ED1FE674C06E695BABA1D");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * sect131r1
-         */
         internal class Sect131r1Holder
             : X9ECParametersHolder
         {
@@ -611,26 +637,28 @@ private Sect131r1Holder() {}
             private const int k2 = 3;
             private const int k3 = 8;
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger a = FromHex("07A11B09A76B562144418FF3FF8C2570B8");
                 BigInteger b = FromHex("0217C05610884B63B9C6C7291678F9D341");
-                byte[] S = Hex.DecodeStrict("4D696E676875615175985BD3ADBADA21B43A97E2");
                 BigInteger n = FromHex("0400000000000000023123953A9464B54D");
                 BigInteger h = BigInteger.ValueOf(2);
 
-                ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
+                return ConfigureCurve(new F2mCurve(m, k1, k2, k3, a, b, n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("4D696E676875615175985BD3ADBADA21B43A97E2");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "040081BAF91FDF9833C40F9C181343638399078C6E7EA38C001F73C8134B1B4EF9E150");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * sect131r2
-         */
         internal class Sect131r2Holder
             : X9ECParametersHolder
         {
@@ -643,26 +671,28 @@ private Sect131r2Holder() {}
             private const int k2 = 3;
             private const int k3 = 8;
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger a = FromHex("03E5A88919D7CAFCBF415F07C2176573B2");
                 BigInteger b = FromHex("04B8266A46C55657AC734CE38F018F2192");
-                byte[] S = Hex.DecodeStrict("985BD3ADBAD4D696E676875615175A21B43A97E3");
                 BigInteger n = FromHex("0400000000000000016954A233049BA98F");
                 BigInteger h = BigInteger.ValueOf(2);
 
-                ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
+                return ConfigureCurve(new F2mCurve(m, k1, k2, k3, a, b, n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("985BD3ADBAD4D696E676875615175A21B43A97E3");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "040356DCD8F2F95031AD652D23951BB366A80648F06D867940A5366D9E265DE9EB240F");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * sect163k1
-         */
         internal class Sect163k1Holder
             : X9ECParametersHolder
         {
@@ -675,26 +705,28 @@ private Sect163k1Holder() {}
             private const int k2 = 6;
             private const int k3 = 7;
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger a = BigInteger.One;
                 BigInteger b = BigInteger.One;
-                byte[] S = null;
                 BigInteger n = FromHex("04000000000000000000020108A2E0CC0D99F8A5EF");
                 BigInteger h = BigInteger.ValueOf(2);
 
-                ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
+                return ConfigureCurve(new F2mCurve(m, k1, k2, k3, a, b, n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = null;
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "0402FE13C0537BBC11ACAA07D793DE4E6D5E5C94EEE80289070FB05D38FF58321F2E800536D538CCDAA3D9");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * sect163r1
-         */
         internal class Sect163r1Holder
             : X9ECParametersHolder
         {
@@ -707,26 +739,28 @@ private Sect163r1Holder() {}
             private const int k2 = 6;
             private const int k3 = 7;
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger a = FromHex("07B6882CAAEFA84F9554FF8428BD88E246D2782AE2");
                 BigInteger b = FromHex("0713612DCDDCB40AAB946BDA29CA91F73AF958AFD9");
-                byte[] S = Hex.DecodeStrict("24B7B137C8A14D696E6768756151756FD0DA2E5C");
                 BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFF48AAB689C29CA710279B");
                 BigInteger h = BigInteger.ValueOf(2);
 
-                ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
+                return ConfigureCurve(new F2mCurve(m, k1, k2, k3, a, b, n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("24B7B137C8A14D696E6768756151756FD0DA2E5C");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "040369979697AB43897789566789567F787A7876A65400435EDB42EFAFB2989D51FEFCE3C80988F41FF883");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * sect163r2
-         */
         internal class Sect163r2Holder
             : X9ECParametersHolder
         {
@@ -739,26 +773,28 @@ private Sect163r2Holder() {}
             private const int k2 = 6;
             private const int k3 = 7;
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger a = BigInteger.One;
                 BigInteger b = FromHex("020A601907B8C953CA1481EB10512F78744A3205FD");
-                byte[] S = Hex.DecodeStrict("85E25BFE5C86226CDB12016F7553F9D0E693A268");
                 BigInteger n = FromHex("040000000000000000000292FE77E70C12A4234C33");
                 BigInteger h = BigInteger.ValueOf(2);
 
-                ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
+                return ConfigureCurve(new F2mCurve(m, k1, k2, k3, a, b, n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("85E25BFE5C86226CDB12016F7553F9D0E693A268");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "0403F0EBA16286A2D57EA0991168D4994637E8343E3600D51FBC6C71A0094FA2CDD545B11C5C0C797324F1");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * sect193r1
-         */
         internal class Sect193r1Holder
             : X9ECParametersHolder
         {
@@ -769,26 +805,28 @@ private Sect193r1Holder() {}
             private const int m = 193;
             private const int k = 15;
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger a = FromHex("0017858FEB7A98975169E171F77B4087DE098AC8A911DF7B01");
                 BigInteger b = FromHex("00FDFB49BFE6C3A89FACADAA7A1E5BBC7CC1C2E5D831478814");
-                byte[] S = Hex.DecodeStrict("103FAEC74D696E676875615175777FC5B191EF30");
                 BigInteger n = FromHex("01000000000000000000000000C7F34A778F443ACC920EBA49");
                 BigInteger h = BigInteger.ValueOf(2);
 
-                ECCurve curve = new F2mCurve(m, k, a, b, n, h);
+                return ConfigureCurve(new F2mCurve(m, k, a, b, n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("103FAEC74D696E676875615175777FC5B191EF30");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "0401F481BC5F0FF84A74AD6CDF6FDEF4BF6179625372D8C0C5E10025E399F2903712CCF3EA9E3A1AD17FB0B3201B6AF7CE1B05");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * sect193r2
-         */
         internal class Sect193r2Holder
             : X9ECParametersHolder
         {
@@ -799,26 +837,28 @@ private Sect193r2Holder() {}
             private const int m = 193;
             private const int k = 15;
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger a = FromHex("0163F35A5137C2CE3EA6ED8667190B0BC43ECD69977702709B");
                 BigInteger b = FromHex("00C9BB9E8927D4D64C377E2AB2856A5B16E3EFB7F61D4316AE");
-                byte[] S = Hex.DecodeStrict("10B7B4D696E676875615175137C8A16FD0DA2211");
                 BigInteger n = FromHex("010000000000000000000000015AAB561B005413CCD4EE99D5");
                 BigInteger h = BigInteger.ValueOf(2);
 
-                ECCurve curve = new F2mCurve(m, k, a, b, n, h);
+                return ConfigureCurve(new F2mCurve(m, k, a, b, n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("10B7B4D696E676875615175137C8A16FD0DA2211");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "0400D9B67D192E0367C803F39E1A7E82CA14A651350AAE617E8F01CE94335607C304AC29E7DEFBD9CA01F596F927224CDECF6C");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * sect233k1
-         */
         internal class Sect233k1Holder
             : X9ECParametersHolder
         {
@@ -829,26 +869,28 @@ private Sect233k1Holder() {}
             private const int m = 233;
             private const int k = 74;
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger a = BigInteger.Zero;
                 BigInteger b = BigInteger.One;
-                byte[] S = null;
                 BigInteger n = FromHex("8000000000000000000000000000069D5BB915BCD46EFB1AD5F173ABDF");
                 BigInteger h = BigInteger.ValueOf(4);
 
-                ECCurve curve = new F2mCurve(m, k, a, b, n, h);
+                return ConfigureCurve(new F2mCurve(m, k, a, b, n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = null;
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "04017232BA853A7E731AF129F22FF4149563A419C26BF50A4C9D6EEFAD612601DB537DECE819B7F70F555A67C427A8CD9BF18AEB9B56E0C11056FAE6A3");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * sect233r1
-         */
         internal class Sect233r1Holder
             : X9ECParametersHolder
         {
@@ -859,26 +901,28 @@ private Sect233r1Holder() {}
             private const int m = 233;
             private const int k = 74;
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger a = BigInteger.One;
                 BigInteger b = FromHex("0066647EDE6C332C7F8C0923BB58213B333B20E9CE4281FE115F7D8F90AD");
-                byte[] S = Hex.DecodeStrict("74D59FF07F6B413D0EA14B344B20A2DB049B50C3");
                 BigInteger n = FromHex("01000000000000000000000000000013E974E72F8A6922031D2603CFE0D7");
                 BigInteger h = BigInteger.ValueOf(2);
 
-                ECCurve curve = new F2mCurve(m, k, a, b, n, h);
+                return ConfigureCurve(new F2mCurve(m, k, a, b, n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("74D59FF07F6B413D0EA14B344B20A2DB049B50C3");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "0400FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * sect239k1
-         */
         internal class Sect239k1Holder
             : X9ECParametersHolder
         {
@@ -889,26 +933,28 @@ private Sect239k1Holder() {}
             private const int m = 239;
             private const int k = 158;
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger a = BigInteger.Zero;
                 BigInteger b = BigInteger.One;
-                byte[] S = null;
                 BigInteger n = FromHex("2000000000000000000000000000005A79FEC67CB6E91F1C1DA800E478A5");
                 BigInteger h = BigInteger.ValueOf(4);
 
-                ECCurve curve = new F2mCurve(m, k, a, b, n, h);
+                return ConfigureCurve(new F2mCurve(m, k, a, b, n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = null;
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "0429A0B6A887A983E9730988A68727A8B2D126C44CC2CC7B2A6555193035DC76310804F12E549BDB011C103089E73510ACB275FC312A5DC6B76553F0CA");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * sect283k1
-         */
         internal class Sect283k1Holder
             : X9ECParametersHolder
         {
@@ -921,27 +967,29 @@ private Sect283k1Holder() {}
             private const int k2 = 7;
             private const int k3 = 12;
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger a = BigInteger.Zero;
                 BigInteger b = BigInteger.One;
-                byte[] S = null;
                 BigInteger n = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE9AE2ED07577265DFF7F94451E061E163C61");
                 BigInteger h = BigInteger.ValueOf(4);
 
-                ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
+                return ConfigureCurve(new F2mCurve(m, k1, k2, k3, a, b, n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = null;
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve, "04"
                     + "0503213F78CA44883F1A3B8162F188E553CD265F23C1567A16876913B0C2AC2458492836"
                     + "01CCDA380F1C9E318D90F95D07E5426FE87E45C0E8184698E45962364E34116177DD2259");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * sect283r1
-         */
         internal class Sect283r1Holder
             : X9ECParametersHolder
         {
@@ -954,27 +1002,29 @@ private Sect283r1Holder() {}
             private const int k2 = 7;
             private const int k3 = 12;
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger a = BigInteger.One;
                 BigInteger b = FromHex("027B680AC8B8596DA5A4AF8A19A0303FCA97FD7645309FA2A581485AF6263E313B79A2F5");
-                byte[] S = Hex.DecodeStrict("77E2B07370EB0F832A6DD5B62DFC88CD06BB84BE");
                 BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEF90399660FC938A90165B042A7CEFADB307");
                 BigInteger h = BigInteger.ValueOf(2);
 
-                ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
+                return ConfigureCurve(new F2mCurve(m, k1, k2, k3, a, b, n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("77E2B07370EB0F832A6DD5B62DFC88CD06BB84BE");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve, "04"
                     + "05F939258DB7DD90E1934F8C70B0DFEC2EED25B8557EAC9C80E2E198F8CDBECD86B12053"
                     + "03676854FE24141CB98FE6D4B20D02B4516FF702350EDDB0826779C813F0DF45BE8112F4");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * sect409k1
-         */
         internal class Sect409k1Holder
             : X9ECParametersHolder
         {
@@ -985,27 +1035,29 @@ private Sect409k1Holder() {}
             private const int m = 409;
             private const int k = 87;
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger a = BigInteger.Zero;
                 BigInteger b = BigInteger.One;
-                byte[] S = null;
                 BigInteger n = FromHex("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE5F83B2D4EA20400EC4557D5ED3E3E7CA5B4B5C83B8E01E5FCF");
                 BigInteger h = BigInteger.ValueOf(4);
 
-                ECCurve curve = new F2mCurve(m, k, a, b, n, h);
+                return ConfigureCurve(new F2mCurve(m, k, a, b, n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = null;
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve, "04"
                     + "0060F05F658F49C1AD3AB1890F7184210EFD0987E307C84C27ACCFB8F9F67CC2C460189EB5AAAA62EE222EB1B35540CFE9023746"
                     + "01E369050B7C4E42ACBA1DACBF04299C3460782F918EA427E6325165E9EA10E3DA5F6C42E9C55215AA9CA27A5863EC48D8E0286B");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * sect409r1
-         */
         internal class Sect409r1Holder
             : X9ECParametersHolder
         {
@@ -1016,27 +1068,29 @@ private Sect409r1Holder() {}
             private const int m = 409;
             private const int k = 87;
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger a = BigInteger.One;
                 BigInteger b = FromHex("0021A5C2C8EE9FEB5C4B9A753B7B476B7FD6422EF1F3DD674761FA99D6AC27C8A9A197B272822F6CD57A55AA4F50AE317B13545F");
-                byte[] S = Hex.DecodeStrict("4099B5A457F9D69F79213D094C4BCD4D4262210B");
                 BigInteger n = FromHex("010000000000000000000000000000000000000000000000000001E2AAD6A612F33307BE5FA47C3C9E052F838164CD37D9A21173");
                 BigInteger h = BigInteger.ValueOf(2);
 
-                ECCurve curve = new F2mCurve(m, k, a, b, n, h);
+                return ConfigureCurve(new F2mCurve(m, k, a, b, n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("4099B5A457F9D69F79213D094C4BCD4D4262210B");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve, "04"
                     + "015D4860D088DDB3496B0C6064756260441CDE4AF1771D4DB01FFE5B34E59703DC255A868A1180515603AEAB60794E54BB7996A7"
                     + "0061B1CFAB6BE5F32BBFA78324ED106A7636B9C5A7BD198D0158AA4F5488D08F38514F1FDF4B4F40D2181B3681C364BA0273C706");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * sect571k1
-         */
         internal class Sect571k1Holder
             : X9ECParametersHolder
         {
@@ -1049,27 +1103,29 @@ private Sect571k1Holder() {}
             private const int k2 = 5;
             private const int k3 = 10;
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger a = BigInteger.Zero;
                 BigInteger b = BigInteger.One;
-                byte[] S = null;
                 BigInteger n = FromHex("020000000000000000000000000000000000000000000000000000000000000000000000131850E1F19A63E4B391A8DB917F4138B630D84BE5D639381E91DEB45CFE778F637C1001");
                 BigInteger h = BigInteger.ValueOf(4);
 
-                ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
+                return ConfigureCurve(new F2mCurve(m, k1, k2, k3, a, b, n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = null;
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve, "04"
                     + "026EB7A859923FBC82189631F8103FE4AC9CA2970012D5D46024804801841CA44370958493B205E647DA304DB4CEB08CBBD1BA39494776FB988B47174DCA88C7E2945283A01C8972"
                     + "0349DC807F4FBF374F4AEADE3BCA95314DD58CEC9F307A54FFC61EFC006D8A2C9D4979C0AC44AEA74FBEBBB9F772AEDCB620B01A7BA7AF1B320430C8591984F601CD4C143EF1C7A3");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
-        /*
-         * sect571r1
-         */
         internal class Sect571r1Holder
             : X9ECParametersHolder
         {
@@ -1082,35 +1138,39 @@ private Sect571r1Holder() {}
             private const int k2 = 5;
             private const int k3 = 10;
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger a = BigInteger.One;
                 BigInteger b = FromHex("02F40E7E2221F295DE297117B7F3D62F5C6A97FFCB8CEFF1CD6BA8CE4A9A18AD84FFABBD8EFA59332BE7AD6756A66E294AFD185A78FF12AA520E4DE739BACA0C7FFEFF7F2955727A");
-                byte[] S = Hex.DecodeStrict("2AA058F73A0E33AB486B0F610410C53A7F132310");
                 BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE661CE18FF55987308059B186823851EC7DD9CA1161DE93D5174D66E8382E9BB2FE84E47");
                 BigInteger h = BigInteger.ValueOf(2);
 
-                ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h);
+                return ConfigureCurve(new F2mCurve(m, k1, k2, k3, a, b, n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                byte[] S = Hex.DecodeStrict("2AA058F73A0E33AB486B0F610410C53A7F132310");
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve, "04"
                     + "0303001D34B856296C16C0D40D3CD7750A93D1D2955FA80AA5F40FC8DB7B2ABDBDE53950F4C0D293CDD711A35B67FB1499AE60038614F1394ABFA3B4C850D927E1E7769C8EEC2D19"
                     + "037BF27342DA639B6DCCFFFEB73D69D78C6C27A6009CBBCA1980F8533921E8A684423E43BAB08A576291AF8F461BB2A8B3531D2F0485C19B16E2F1516E23DD3C1A4827AF1B8AC15B");
 
-                return new X9ECParameters(curve, G, n, h, S);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S);
             }
         }
 
+        private static readonly Dictionary objIds =
+            new Dictionary(StringComparer.OrdinalIgnoreCase);
+        private static readonly Dictionary curves =
+            new Dictionary();
+        private static readonly Dictionary names =
+            new Dictionary();
 
-        private static readonly IDictionary objIds = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
-        private static readonly IDictionary curves = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
-        private static readonly IDictionary names = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
-
-        private static void DefineCurve(
-            string					name,
-            DerObjectIdentifier		oid,
-            X9ECParametersHolder	holder)
+        private static void DefineCurve(string name, DerObjectIdentifier oid, X9ECParametersHolder holder)
         {
-            objIds.Add(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(name), oid);
+            objIds.Add(name, oid);
             names.Add(oid, name);
             curves.Add(oid, holder);
         }
@@ -1153,54 +1213,64 @@ static SecNamedCurves()
             DefineCurve("sect571r1", SecObjectIdentifiers.SecT571r1, Sect571r1Holder.Instance);
         }
 
-        public static X9ECParameters GetByName(
-            string name)
+        /// Look up the  for the curve with the given name.
+        /// The name of the curve.
+        public static X9ECParameters GetByName(string name)
         {
             DerObjectIdentifier oid = GetOid(name);
             return oid == null ? null : GetByOid(oid);
         }
 
-        /**
-         * return the X9ECParameters object for the named curve represented by
-         * the passed in object identifier. Null if the curve isn't present.
-         *
-         * @param oid an object identifier representing a named curve, if present.
-         */
-        public static X9ECParameters GetByOid(
-            DerObjectIdentifier oid)
+        /// Look up an  for the curve with the given name.
+        /// 
+        /// Allows accessing the curve without necessarily triggering the creation of the
+        /// full .
+        /// 
+        /// The name of the curve.
+        public static X9ECParametersHolder GetByNameLazy(string name)
+        {
+            DerObjectIdentifier oid = GetOid(name);
+            return oid == null ? null : GetByOidLazy(oid);
+        }
+
+        /// Look up the  for the curve with the given
+        /// OID.
+        /// The OID for the curve.
+        public static X9ECParameters GetByOid(DerObjectIdentifier oid)
+        {
+            return GetByOidLazy(oid)?.Parameters;
+        }
+
+        /// Look up an  for the curve with the given
+        /// OID.
+        /// 
+        /// Allows accessing the curve without necessarily triggering the creation of the
+        /// full .
+        /// 
+        /// The OID for the curve.
+        public static X9ECParametersHolder GetByOidLazy(DerObjectIdentifier oid)
         {
-            X9ECParametersHolder holder = (X9ECParametersHolder)curves[oid];
-            return holder == null ? null : holder.Parameters;
+            return CollectionUtilities.GetValueOrNull(curves, oid);
         }
 
-        /**
-         * return the object identifier signified by the passed in name. Null
-         * if there is no object identifier associated with name.
-         *
-         * @return the object identifier associated with name, if present.
-         */
-        public static DerObjectIdentifier GetOid(
-            string name)
+        /// Look up the name of the curve with the given OID.
+        /// The OID for the curve.
+        public static string GetName(DerObjectIdentifier oid)
         {
-            return (DerObjectIdentifier)objIds[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(name)];
+            return CollectionUtilities.GetValueOrNull(names, oid);
         }
 
-        /**
-         * return the named curve name represented by the given object identifier.
-         */
-        public static string GetName(
-            DerObjectIdentifier oid)
+        /// Look up the OID of the curve with the given name.
+        /// The name of the curve.
+        public static DerObjectIdentifier GetOid(string name)
         {
-            return (string)names[oid];
+            return CollectionUtilities.GetValueOrNull(objIds, name);
         }
 
-        /**
-         * returns an enumeration containing the name strings for curves
-         * contained in this structure.
-         */
-        public static IEnumerable Names
+        /// Enumerate the available curve names in this registry.
+        public static IEnumerable Names
         {
-            get { return new EnumerableProxy(names.Values); }
+            get { return CollectionUtilities.Proxy(objIds.Keys); }
         }
     }
 }
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/smime/SMIMECapabilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/smime/SMIMECapabilities.cs
index b7f6f41..a67cbdc 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/smime/SMIMECapabilities.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/smime/SMIMECapabilities.cs	
@@ -1,9 +1,8 @@
 #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
 #pragma warning disable
 using System;
-using System.Collections;
+using System.Collections.Generic;
 
-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;
@@ -64,7 +63,7 @@ public static SmimeCapabilities GetInstance(
                     (Asn1Sequence)(((AttributeX509) obj).AttrValues[0]));
             }
 
-            throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
+            throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj");
         }
 
 		public SmimeCapabilities(
@@ -73,51 +72,27 @@ public SmimeCapabilities(
             capabilities = seq;
         }
 
-#if !(SILVERLIGHT || PORTABLE || NETFX_CORE)
-
-        public ArrayList GetCapabilities(
-            DerObjectIdentifier capability)
-        {
-            ArrayList list = new ArrayList();
-            DoGetCapabilitiesForOid(capability, list);
-			return list;
-        }
-#endif
-
         /**
          * returns an ArrayList with 0 or more objects of all the capabilities
          * matching the passed in capability Oid. If the Oid passed is null the
          * entire set is returned.
          */
-        public IList GetCapabilitiesForOid(
-            DerObjectIdentifier capability)
+        public IList GetCapabilitiesForOid(DerObjectIdentifier capability)
         {
-            IList list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList();
+            var list = new List();
             DoGetCapabilitiesForOid(capability, list);
 			return list;
         }
 
-        private void DoGetCapabilitiesForOid(DerObjectIdentifier capability, IList list)
+        private void DoGetCapabilitiesForOid(DerObjectIdentifier capability, IList list)
         {
-			if (capability == null)
-            {
-				foreach (object o in capabilities)
-				{
-                    SmimeCapability cap = SmimeCapability.GetInstance(o);
-
-					list.Add(cap);
-                }
-            }
-            else
+            foreach (object o in capabilities)
             {
-				foreach (object o in capabilities)
-				{
-                    SmimeCapability cap = SmimeCapability.GetInstance(o);
+                SmimeCapability cap = SmimeCapability.GetInstance(o);
 
-					if (capability.Equals(cap.CapabilityID))
-                    {
-                        list.Add(cap);
-                    }
+                if (capability == null || capability.Equals(cap.CapabilityID))
+                {
+                    list.Add(cap);
                 }
             }
         }
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/teletrust/TeleTrusTNamedCurves.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/teletrust/TeleTrusTNamedCurves.cs
index 5c6d126..ca94aa0 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/teletrust/TeleTrusTNamedCurves.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/teletrust/TeleTrusTNamedCurves.cs	
@@ -1,22 +1,20 @@
 #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
 #pragma warning disable
-using System.Collections;
+using System;
+using System.Collections.Generic;
 
 using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9;
 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.Utilities;
 using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections;
 using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders;
 
 namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.TeleTrust
 {
-    /**
-    * elliptic curves defined in "ECC Brainpool Standard Curves and Curve Generation"
-    * http://www.ecc-brainpool.org/download/draft_pkix_additional_ecc_dp.txt
-    */
-    public class TeleTrusTNamedCurves
+    /// Elliptic curve registry for curves defined in "ECC Brainpool Standard Curves and Curve Generation"
+    /// http://www.ecc-brainpool.org/download/draft_pkix_additional_ecc_dp.txt .
+    public static class TeleTrusTNamedCurves
     {
         private static X9ECPoint ConfigureBasepoint(ECCurve curve, string encoding)
         {
@@ -42,21 +40,26 @@ private BrainpoolP160r1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new BrainpoolP160r1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger n = FromHex("E95E4A5F737059DC60DF5991D45029409E60FC09");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(
+                return ConfigureCurve(new FpCurve(
                     FromHex("E95E4A5F737059DC60DFC7AD95B3D8139515620F"), // q
                     FromHex("340E7BE2A280EB74E2BE61BADA745D97E8F7C300"), // a
                     FromHex("1E589A8595423412134FAA2DBDEC95C8D8675E58"), // b
                     n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "04BED5AF16EA3F6A4F62938C4631EB5AF7BDBCDBC31667CB477A1A8EC338F94741669C976316DA6321");
 
-                return new X9ECParameters(curve, G, n, h);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor);
             }
         }
 
@@ -67,22 +70,27 @@ private BrainpoolP160t1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new BrainpoolP160t1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger n = FromHex("E95E4A5F737059DC60DF5991D45029409E60FC09");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(
+                return ConfigureCurve(new FpCurve(
                     //FromHex("24DBFF5DEC9B986BBFE5295A29BFBAE45E0F5D0B"), // Z
                     FromHex("E95E4A5F737059DC60DFC7AD95B3D8139515620F"), // q
                     FromHex("E95E4A5F737059DC60DFC7AD95B3D8139515620C"), // a
                     FromHex("7A556B6DAE535B7B51ED2C4D7DAA7A0B5C55F380"), // b
                     n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "04B199B13B9B34EFC1397E64BAEB05ACC265FF2378ADD6718B7C7C1961F0991B842443772152C9E0AD");
 
-                return new X9ECParameters(curve, G, n, h);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor);
             }
         }
 
@@ -93,21 +101,26 @@ private BrainpoolP192r1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new BrainpoolP192r1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger n = FromHex("C302F41D932A36CDA7A3462F9E9E916B5BE8F1029AC4ACC1");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(
+                return ConfigureCurve(new FpCurve(
                     FromHex("C302F41D932A36CDA7A3463093D18DB78FCE476DE1A86297"), // q
                     FromHex("6A91174076B1E0E19C39C031FE8685C1CAE040E5C69A28EF"), // a
                     FromHex("469A28EF7C28CCA3DC721D044F4496BCCA7EF4146FBF25C9"), // b
                     n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "04C0A0647EAAB6A48753B033C56CB0F0900A2F5C4853375FD614B690866ABD5BB88B5F4828C1490002E6773FA2FA299B8F");
 
-                return new X9ECParameters(curve, G, n, h);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor);
             }
         }
 
@@ -118,22 +131,27 @@ private BrainpoolP192t1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new BrainpoolP192t1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger n = FromHex("C302F41D932A36CDA7A3462F9E9E916B5BE8F1029AC4ACC1");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(
+                return ConfigureCurve(new FpCurve(
                     //FromHex("1B6F5CC8DB4DC7AF19458A9CB80DC2295E5EB9C3732104CB") // Z
                     FromHex("C302F41D932A36CDA7A3463093D18DB78FCE476DE1A86297"), // q
                     FromHex("C302F41D932A36CDA7A3463093D18DB78FCE476DE1A86294"), // a
                     FromHex("13D56FFAEC78681E68F9DEB43B35BEC2FB68542E27897B79"), // b
                     n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "043AE9E58C82F63C30282E1FE7BBF43FA72C446AF6F4618129097E2C5667C2223A902AB5CA449D0084B7E5B3DE7CCC01C9");
 
-                return new X9ECParameters(curve, G, n, h);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor);
             }
         }
 
@@ -144,21 +162,26 @@ private BrainpoolP224r1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new BrainpoolP224r1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger n = FromHex("D7C134AA264366862A18302575D0FB98D116BC4B6DDEBCA3A5A7939F");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(
+                return ConfigureCurve(new FpCurve(
                     FromHex("D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FF"), // q
                     FromHex("68A5E62CA9CE6C1C299803A6C1530B514E182AD8B0042A59CAD29F43"), // a
                     FromHex("2580F63CCFE44138870713B1A92369E33E2135D266DBB372386C400B"), // b
                     n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "040D9029AD2C7E5CF4340823B2A87DC68C9E4CE3174C1E6EFDEE12C07D58AA56F772C0726F24C6B89E4ECDAC24354B9E99CAA3F6D3761402CD");
 
-                return new X9ECParameters(curve, G, n, h);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor);
             }
         }
 
@@ -169,22 +192,27 @@ private BrainpoolP224t1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new BrainpoolP224t1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger n = FromHex("D7C134AA264366862A18302575D0FB98D116BC4B6DDEBCA3A5A7939F");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(
+                return ConfigureCurve(new FpCurve(
                     //FromHex("2DF271E14427A346910CF7A2E6CFA7B3F484E5C2CCE1C8B730E28B3F") // Z
                     FromHex("D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FF"), // q
                     FromHex("D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FC"), // a
                     FromHex("4B337D934104CD7BEF271BF60CED1ED20DA14C08B3BB64F18A60888D"), // b
                     n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "046AB1E344CE25FF3896424E7FFE14762ECB49F8928AC0C76029B4D5800374E9F5143E568CD23F3F4D7C0D4B1E41C8CC0D1C6ABD5F1A46DB4C");
 
-                return new X9ECParameters(curve, G, n, h);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor);
             }
         }
 
@@ -195,21 +223,26 @@ private BrainpoolP256r1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new BrainpoolP256r1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger n = FromHex("A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(
+                return ConfigureCurve(new FpCurve(
                     FromHex("A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377"), // q
                     FromHex("7D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9"), // a
                     FromHex("26DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B6"), // b
                     n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "048BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997");
 
-                return new X9ECParameters(curve, G, n, h);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor);
             }
         }
 
@@ -220,22 +253,27 @@ private BrainpoolP256t1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new BrainpoolP256t1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger n = FromHex("A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(
+                return ConfigureCurve(new FpCurve(
                     //FromHex("3E2D4BD9597B58639AE7AA669CAB9837CF5CF20A2C852D10F655668DFC150EF0") // Z
                     FromHex("A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377"), // q
                     FromHex("A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5374"), // a
                     FromHex("662C61C430D84EA4FE66A7733D0B76B7BF93EBC4AF2F49256AE58101FEE92B04"), // b
                     n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "04A3E8EB3CC1CFE7B7732213B23A656149AFA142C47AAFBC2B79A191562E1305F42D996C823439C56D7F7B22E14644417E69BCB6DE39D027001DABE8F35B25C9BE");
 
-                return new X9ECParameters(curve, G, n, h);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor);
             }
         }
 
@@ -246,21 +284,26 @@ private BrainpoolP320r1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new BrainpoolP320r1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger n = FromHex("D35E472036BC4FB7E13C785ED201E065F98FCFA5B68F12A32D482EC7EE8658E98691555B44C59311");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(
+                return ConfigureCurve(new FpCurve(
                     FromHex("D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC28FCD412B1F1B32E27"), // q
                     FromHex("3EE30B568FBAB0F883CCEBD46D3F3BB8A2A73513F5EB79DA66190EB085FFA9F492F375A97D860EB4"), // a
                     FromHex("520883949DFDBC42D3AD198640688A6FE13F41349554B49ACC31DCCD884539816F5EB4AC8FB1F1A6"), // b
                     n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "0443BD7E9AFB53D8B85289BCC48EE5BFE6F20137D10A087EB6E7871E2A10A599C710AF8D0D39E2061114FDD05545EC1CC8AB4093247F77275E0743FFED117182EAA9C77877AAAC6AC7D35245D1692E8EE1");
 
-                return new X9ECParameters(curve, G, n, h);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor);
             }
         }
 
@@ -271,22 +314,27 @@ private BrainpoolP320t1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new BrainpoolP320t1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger n = FromHex("D35E472036BC4FB7E13C785ED201E065F98FCFA5B68F12A32D482EC7EE8658E98691555B44C59311");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(
+                return ConfigureCurve(new FpCurve(
                     //FromHex("15F75CAF668077F7E85B42EB01F0A81FF56ECD6191D55CB82B7D861458A18FEFC3E5AB7496F3C7B1") // Z
                     FromHex("D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC28FCD412B1F1B32E27"), // q
                     FromHex("D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC28FCD412B1F1B32E24"), // a
                     FromHex("A7F561E038EB1ED560B3D147DB782013064C19F27ED27C6780AAF77FB8A547CEB5B4FEF422340353"), // b
                     n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "04925BE9FB01AFC6FB4D3E7D4990010F813408AB106C4F09CB7EE07868CC136FFF3357F624A21BED5263BA3A7A27483EBF6671DBEF7ABB30EBEE084E58A0B077AD42A5A0989D1EE71B1B9BC0455FB0D2C3");
 
-                return new X9ECParameters(curve, G, n, h);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor);
             }
         }
 
@@ -297,21 +345,26 @@ private BrainpoolP384r1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new BrainpoolP384r1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger n = FromHex("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(
+                return ConfigureCurve(new FpCurve(
                     FromHex("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53"), // q
                     FromHex("7BC382C63D8C150C3C72080ACE05AFA0C2BEA28E4FB22787139165EFBA91F90F8AA5814A503AD4EB04A8C7DD22CE2826"), // a
                     FromHex("04A8C7DD22CE28268B39B55416F0447C2FB77DE107DCD2A62E880EA53EEB62D57CB4390295DBC9943AB78696FA504C11"), // b
                     n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "041D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10E8E826E03436D646AAEF87B2E247D4AF1E8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129280E4646217791811142820341263C5315");
 
-                return new X9ECParameters(curve, G, n, h);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor);
             }
         }
 
@@ -322,22 +375,27 @@ private BrainpoolP384t1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new BrainpoolP384t1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger n = FromHex("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(
+                return ConfigureCurve(new FpCurve(
                     //FromHex("41DFE8DD399331F7166A66076734A89CD0D2BCDB7D068E44E1F378F41ECBAE97D2D63DBC87BCCDDCCC5DA39E8589291C") // Z
                     FromHex("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53"), // q
                     FromHex("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC50"), // a
                     FromHex("7F519EADA7BDA81BD826DBA647910F8C4B9346ED8CCDC64E4B1ABD11756DCE1D2074AA263B88805CED70355A33B471EE"), // b
                     n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "0418DE98B02DB9A306F2AFCD7235F72A819B80AB12EBD653172476FECD462AABFFC4FF191B946A5F54D8D0AA2F418808CC25AB056962D30651A114AFD2755AD336747F93475B7A1FCA3B88F2B6A208CCFE469408584DC2B2912675BF5B9E582928");
 
-                return new X9ECParameters(curve, G, n, h);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor);
             }
         }
 
@@ -348,21 +406,26 @@ private BrainpoolP512r1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new BrainpoolP512r1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger n = FromHex("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(
+                return ConfigureCurve(new FpCurve(
                     FromHex("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3"), // q
                     FromHex("7830A3318B603B89E2327145AC234CC594CBDD8D3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CA"), // a
                     FromHex("3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CADC083E67984050B75EBAE5DD2809BD638016F723"), // b
                     n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "0481AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D0098EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F8227DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F8111B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892");
 
-                return new X9ECParameters(curve, G, n, h);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor);
             }
         }
 
@@ -373,36 +436,40 @@ private BrainpoolP512t1Holder() {}
 
             internal static readonly X9ECParametersHolder Instance = new BrainpoolP512t1Holder();
 
-            protected override X9ECParameters CreateParameters()
+            protected override ECCurve CreateCurve()
             {
                 BigInteger n = FromHex("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069");
                 BigInteger h = BigInteger.One;
 
-                ECCurve curve = ConfigureCurve(new FpCurve(
+                return ConfigureCurve(new FpCurve(
                     //FromHex("12EE58E6764838B69782136F0F2D3BA06E27695716054092E60A80BEDB212B64E585D90BCE13761F85C3F1D2A64E3BE8FEA2220F01EBA5EEB0F35DBD29D922AB") // Z
                     FromHex("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3"), // q
                     FromHex("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F0"), // a
                     FromHex("7CBBBCF9441CFAB76E1890E46884EAE321F70C0BCB4981527897504BEC3E36A62BCDFA2304976540F6450085F2DAE145C22553B465763689180EA2571867423E"), // b
                     n, h));
+            }
+
+            protected override X9ECParameters CreateParameters()
+            {
+                ECCurve curve = Curve;
 
                 X9ECPoint G = ConfigureBasepoint(curve,
                     "04640ECE5C12788717B9C1BA06CBC2A6FEBA85842458C56DDE9DB1758D39C0313D82BA51735CDB3EA499AA77A7D6943A64F7A3F25FE26F06B51BAA2696FA9035DA5B534BD595F5AF0FA2C892376C84ACE1BB4E3019B71634C01131159CAE03CEE9D9932184BEEF216BD71DF2DADF86A627306ECFF96DBB8BACE198B61E00F8B332");
 
-                return new X9ECParameters(curve, G, n, h);
+                return new X9ECParameters(curve, G, curve.Order, curve.Cofactor);
             }
         }
 
+        private static readonly Dictionary objIds =
+            new Dictionary(StringComparer.OrdinalIgnoreCase);
+        private static readonly Dictionary curves =
+            new Dictionary();
+        private static readonly Dictionary names =
+            new Dictionary();
 
-        private static readonly IDictionary objIds = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
-        private static readonly IDictionary curves = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
-        private static readonly IDictionary names = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable();
-
-        private static void DefineCurve(
-            string					name,
-            DerObjectIdentifier		oid,
-            X9ECParametersHolder	holder)
+        private static void DefineCurve(string name, DerObjectIdentifier oid, X9ECParametersHolder holder)
         {
-            objIds.Add(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(name), oid);
+            objIds.Add(name, oid);
             names.Add(oid, name);
             curves.Add(oid, holder);
         }
@@ -425,61 +492,64 @@ static TeleTrusTNamedCurves()
             DefineCurve("brainpoolP512t1", TeleTrusTObjectIdentifiers.BrainpoolP512T1, BrainpoolP512t1Holder.Instance);
         }
 
-        public static X9ECParameters GetByName(
-            string name)
+        /// Look up the  for the curve with the given name.
+        /// The name of the curve.
+        public static X9ECParameters GetByName(string name)
         {
             DerObjectIdentifier oid = GetOid(name);
             return oid == null ? null : GetByOid(oid);
         }
 
-        /**
-        * return the X9ECParameters object for the named curve represented by
-        * the passed in object identifier. Null if the curve isn't present.
-        *
-        * @param oid an object identifier representing a named curve, if present.
-        */
-        public static X9ECParameters GetByOid(
-            DerObjectIdentifier oid)
+        /// Look up an  for the curve with the given name.
+        /// 
+        /// Allows accessing the curve without necessarily triggering the creation of the
+        /// full .
+        /// 
+        /// The name of the curve.
+        public static X9ECParametersHolder GetByNameLazy(string name)
+        {
+            DerObjectIdentifier oid = GetOid(name);
+            return oid == null ? null : GetByOidLazy(oid);
+        }
+
+        /// Look up the  for the curve with the given
+        /// OID.
+        /// The OID for the curve.
+        public static X9ECParameters GetByOid(DerObjectIdentifier oid)
         {
-            X9ECParametersHolder holder = (X9ECParametersHolder)curves[oid];
-            return holder == null ? null : holder.Parameters;
+            return GetByOidLazy(oid)?.Parameters;
         }
 
-        /**
-        * return the object identifier signified by the passed in name. Null
-        * if there is no object identifier associated with name.
-        *
-        * @return the object identifier associated with name, if present.
-        */
-        public static DerObjectIdentifier GetOid(
-            string name)
+        /// Look up an  for the curve with the given
+        /// OID.
+        /// 
+        /// Allows accessing the curve without necessarily triggering the creation of the
+        /// full .
+        /// 
+        /// The OID for the curve.
+        public static X9ECParametersHolder GetByOidLazy(DerObjectIdentifier oid)
         {
-            return (DerObjectIdentifier)objIds[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(name)];
+            return CollectionUtilities.GetValueOrNull(curves, oid);
         }
 
-        /**
-        * return the named curve name represented by the given object identifier.
-        */
-        public static string GetName(
-            DerObjectIdentifier oid)
+        /// Look up the name of the curve with the given OID.
+        /// The OID for the curve.
+        public static string GetName(DerObjectIdentifier oid)
         {
-            return (string)names[oid];
+            return CollectionUtilities.GetValueOrNull(names, oid);
         }
 
-        /**
-         * returns an enumeration containing the name strings for curves
-         * contained in this structure.
-         */
-        public static IEnumerable Names
+        /// Look up the OID of the curve with the given name.
+        /// The name of the curve.
+        public static DerObjectIdentifier GetOid(string name)
         {
-            get { return new EnumerableProxy(names.Values); }
+            return CollectionUtilities.GetValueOrNull(objIds, name);
         }
 
-        public static DerObjectIdentifier GetOid(
-            short	curvesize,
-            bool	twisted)
+        /// Enumerate the available curve names in this registry.
+        public static IEnumerable Names
         {
-            return GetOid("brainpoolP" + curvesize + (twisted ? "t" : "r") + "1");
+            get { return CollectionUtilities.Proxy(objIds.Keys); }
         }
     }
 }
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/tsp/TSTInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/tsp/TSTInfo.cs
index 7f7b895..45c24b6 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/tsp/TSTInfo.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/tsp/TSTInfo.cs	
@@ -1,11 +1,8 @@
 #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
 {
@@ -16,7 +13,7 @@ public class TstInfo
 		private readonly DerObjectIdentifier	tsaPolicyId;
 		private readonly MessageImprint			messageImprint;
 		private readonly DerInteger				serialNumber;
-		private readonly DerGeneralizedTime		genTime;
+		private readonly Asn1GeneralizedTime	genTime;
 		private readonly Accuracy				accuracy;
 		private readonly DerBoolean				ordering;
 		private readonly DerInteger				nonce;
@@ -32,10 +29,9 @@ public static TstInfo GetInstance(object obj)
             return new TstInfo(Asn1Sequence.GetInstance(obj));
 		}
 
-		private TstInfo(
-			Asn1Sequence seq)
+		private TstInfo(Asn1Sequence seq)
 		{
-			IEnumerator e = seq.GetEnumerator();
+			var e = seq.GetEnumerator();
 
 			// version
 			e.MoveNext();
@@ -55,7 +51,7 @@ private TstInfo(
 
 			// genTime
 			e.MoveNext();
-			genTime = DerGeneralizedTime.GetInstance(e.Current);
+			genTime = Asn1GeneralizedTime.GetInstance(e.Current);
 
 			// default for ordering
 			ordering = DerBoolean.False;
@@ -102,7 +98,7 @@ public TstInfo(
 			DerObjectIdentifier	tsaPolicyId,
 			MessageImprint		messageImprint,
 			DerInteger			serialNumber,
-			DerGeneralizedTime	genTime,
+            Asn1GeneralizedTime genTime,
 			Accuracy			accuracy,
 			DerBoolean			ordering,
 			DerInteger			nonce,
@@ -146,7 +142,7 @@ public Accuracy Accuracy
 			get { return accuracy; }
 		}
 
-		public DerGeneralizedTime GenTime
+		public Asn1GeneralizedTime GenTime
 		{
 			get { return genTime; }
 		}
diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ua/UAObjectIdentifiers.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ua/UAObjectIdentifiers.cs
index 8c6b082..044402d 100644
--- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ua/UAObjectIdentifiers.cs	
+++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/ua/UAObjectIdentifiers.cs	
@@ -4,11 +4,11 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.UA
 {
     /**
      * Ukrainian object identifiers
-     * 

+ *

* {iso(1) member-body(2) Ukraine(804) root(2) security(1) cryptography(1) pki(1)} - *

+ *

* { ... pki-alg(1) pki-alg-sym(3) Dstu4145WithGost34311(1) PB(1)} - *

+ *

* DSTU4145 in polynomial basis has 2 oids, one for little-endian representation and one for big-endian */ public abstract class UAObjectIdentifiers diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/util/Asn1Dump.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/util/Asn1Dump.cs index 4167789..8df74b1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/util/Asn1Dump.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/util/Asn1Dump.cs @@ -4,19 +4,12 @@ using System.IO; using System.Text; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Utilities { - public sealed class Asn1Dump + public static class Asn1Dump { - private static readonly string NewLine = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine; - - private Asn1Dump() - { - } - private const string Tab = " "; private const int SampleSize = 32; @@ -25,243 +18,252 @@ private Asn1Dump() * * @param obj the Asn1Object to be dumped out. */ - private static void AsString( - string indent, - bool verbose, - Asn1Object obj, - StringBuilder buf) + private static void AsString(string indent, bool verbose, Asn1Object obj, StringBuilder buf) { if (obj is Asn1Null) { buf.Append(indent); - buf.Append("NULL"); - buf.Append(NewLine); + buf.AppendLine("NULL"); } - else if (obj is Asn1Sequence) + else if (obj is Asn1Sequence asn1Sequence) { buf.Append(indent); - if (obj is BerSequence) + + if (asn1Sequence is BerSequence) { - buf.Append("BER Sequence"); + buf.AppendLine("BER Sequence"); } - else if (obj is DerSequence) + else if (!(asn1Sequence is DLSequence)) { - buf.Append("DER Sequence"); + buf.AppendLine("DER Sequence"); } else { - buf.Append("Sequence"); + buf.AppendLine("Sequence"); } - buf.Append(NewLine); - Asn1Sequence sequence = (Asn1Sequence)obj; string elementsIndent = indent + Tab; - for (int i = 0, count = sequence.Count; i < count; ++i) + for (int i = 0, count = asn1Sequence.Count; i < count; ++i) { - AsString(elementsIndent, verbose, sequence[i].ToAsn1Object(), buf); + AsString(elementsIndent, verbose, asn1Sequence[i].ToAsn1Object(), buf); } } - else if (obj is Asn1Set) + else if (obj is Asn1Set asn1Set) { buf.Append(indent); - if (obj is BerSet) + + if (asn1Set is BerSet) { - buf.Append("BER Set"); + buf.AppendLine("BER Set"); + } + else if (!(asn1Set is DLSet)) + { + buf.AppendLine("DER Set"); + } + else + { + buf.AppendLine("Set"); } - else if (obj is DerSet) - { - buf.Append("DER Set"); - } - else - { - buf.Append("Set"); - } - buf.Append(NewLine); - Asn1Set set = (Asn1Set)obj; string elementsIndent = indent + Tab; - for (int i = 0, count = set.Count; i < count; ++i) + for (int i = 0, count = asn1Set.Count; i < count; ++i) { - AsString(elementsIndent, verbose, set[i].ToAsn1Object(), buf); + AsString(elementsIndent, verbose, asn1Set[i].ToAsn1Object(), buf); } } - else if (obj is Asn1TaggedObject) + else if (obj is Asn1TaggedObject taggedObject) { - string tab = indent + Tab; buf.Append(indent); - if (obj is BerTaggedObject) + + if (taggedObject is BerTaggedObject) + { + buf.Append("BER Tagged "); + } + else if (!(taggedObject is DLTaggedObject)) { - buf.Append("BER Tagged ["); + buf.Append("DER Tagged "); } else { - buf.Append("Tagged ["); + buf.Append("Tagged "); } - Asn1TaggedObject o = (Asn1TaggedObject)obj; + buf.Append(Asn1Utilities.GetTagText(taggedObject)); - buf.Append(o.TagNo.ToString()); - buf.Append(']'); - - if (!o.IsExplicit()) + if (!taggedObject.IsExplicit()) { buf.Append(" IMPLICIT "); } - buf.Append(NewLine); + buf.AppendLine(); - if (o.IsEmpty()) - { - buf.Append(tab); - buf.Append("EMPTY"); - buf.Append(NewLine); - } - else - { - AsString(tab, verbose, o.GetObject(), buf); - } - } - else if (obj is DerObjectIdentifier) - { - buf.Append(indent + "ObjectIdentifier(" + ((DerObjectIdentifier)obj).Id + ")" + NewLine); - } - else if (obj is DerBoolean) - { - buf.Append(indent + "Boolean(" + ((DerBoolean)obj).IsTrue + ")" + NewLine); + string baseIndent = indent + Tab; + + AsString(baseIndent, verbose, taggedObject.GetBaseObject().ToAsn1Object(), buf); } - else if (obj is DerInteger) + else if (obj is DerObjectIdentifier oid) { - buf.Append(indent + "Integer(" + ((DerInteger)obj).Value + ")" + NewLine); + buf.Append(indent); + buf.AppendLine("ObjectIdentifier(" + oid.Id + ")"); } - else if (obj is BerOctetString) + else if (obj is Asn1RelativeOid relativeOid) { - byte[] octets = ((Asn1OctetString)obj).GetOctets(); - string extra = verbose ? dumpBinaryDataAsString(indent, octets) : Hex.ToHexString(octets); - buf.Append(indent + "BER Octet String" + "[" + octets.Length + "] " + extra + NewLine); + buf.Append(indent); + buf.AppendLine("RelativeOID(" + relativeOid.Id + ")"); } - else if (obj is DerOctetString) + else if (obj is DerBoolean derBoolean) { - byte[] octets = ((Asn1OctetString)obj).GetOctets(); - string extra = verbose ? dumpBinaryDataAsString(indent, octets) : Hex.ToHexString(octets); - buf.Append(indent + "DER Octet String" + "[" + octets.Length + "] " + extra + NewLine); + buf.Append(indent); + buf.AppendLine("Boolean(" + derBoolean.IsTrue + ")"); } - else if (obj is DerBitString) + else if (obj is DerInteger derInteger) { - DerBitString bt = (DerBitString)obj; - byte[] bytes = bt.GetBytes(); - string extra = verbose ? dumpBinaryDataAsString(indent, bytes) : ""; - buf.Append(indent + "DER Bit String" + "[" + bytes.Length + ", " + bt.PadBits + "] " + extra + NewLine); + buf.Append(indent); + buf.AppendLine("Integer(" + derInteger.Value + ")"); } - else if (obj is DerIA5String) + else if (obj is Asn1OctetString oct) { - buf.Append(indent + "IA5String(" + ((DerIA5String)obj).GetString() + ") " + NewLine); + byte[] octets = oct.GetOctets(); + + buf.Append(indent); + + if (obj is BerOctetString) + { + buf.AppendLine("BER Octet String[" + octets.Length + "]"); + } + else + { + buf.AppendLine("DER Octet String[" + octets.Length + "]"); + } + + if (verbose) + { + DumpBinaryDataAsString(buf, indent, octets); + } } - else if (obj is DerUtf8String) + else if (obj is DerBitString bitString) { - buf.Append(indent + "UTF8String(" + ((DerUtf8String)obj).GetString() + ") " + NewLine); + byte[] bytes = bitString.GetBytes(); + int padBits = bitString.PadBits; + + buf.Append(indent); + + if (bitString is BerBitString) + { + buf.AppendLine("BER Bit String[" + bytes.Length + ", " + padBits + "]"); + } + else if (bitString is DLBitString) + { + buf.AppendLine("DL Bit String[" + bytes.Length + ", " + padBits + "]"); + } + else + { + buf.AppendLine("DER Bit String[" + bytes.Length + ", " + padBits + "]"); + } + + if (verbose) + { + DumpBinaryDataAsString(buf, indent, bytes); + } } - else if (obj is DerPrintableString) + else if (obj is DerIA5String ia5String) { - buf.Append(indent + "PrintableString(" + ((DerPrintableString)obj).GetString() + ") " + NewLine); + buf.Append(indent); + buf.AppendLine("IA5String(" + ia5String.GetString() + ")"); } - else if (obj is DerVisibleString) + else if (obj is DerUtf8String utf8String) { - buf.Append(indent + "VisibleString(" + ((DerVisibleString)obj).GetString() + ") " + NewLine); + buf.Append(indent); + buf.AppendLine("UTF8String(" + utf8String.GetString() + ")"); } - else if (obj is DerBmpString) + else if (obj is DerPrintableString printableString) { - buf.Append(indent + "BMPString(" + ((DerBmpString)obj).GetString() + ") " + NewLine); + buf.Append(indent); + buf.AppendLine("PrintableString(" + printableString.GetString() + ")"); } - else if (obj is DerT61String) + else if (obj is DerVisibleString visibleString) { - buf.Append(indent + "T61String(" + ((DerT61String)obj).GetString() + ") " + NewLine); + buf.Append(indent); + buf.AppendLine("VisibleString(" + visibleString.GetString() + ")"); } - else if (obj is DerGraphicString) + else if (obj is DerBmpString bmpString) { - buf.Append(indent + "GraphicString(" + ((DerGraphicString)obj).GetString() + ") " + NewLine); + buf.Append(indent); + buf.AppendLine("BMPString(" + bmpString.GetString() + ")"); } - else if (obj is DerVideotexString) + else if (obj is DerT61String t61String) { - buf.Append(indent + "VideotexString(" + ((DerVideotexString)obj).GetString() + ") " + NewLine); + buf.Append(indent); + buf.AppendLine("T61String(" + t61String.GetString() + ")"); } - else if (obj is DerUtcTime) + else if (obj is DerGraphicString graphicString) { - buf.Append(indent + "UTCTime(" + ((DerUtcTime)obj).TimeString + ") " + NewLine); + buf.Append(indent); + buf.AppendLine("GraphicString(" + graphicString.GetString() + ")"); } - else if (obj is DerGeneralizedTime) + else if (obj is DerVideotexString videotexString) { - buf.Append(indent + "GeneralizedTime(" + ((DerGeneralizedTime)obj).GetTime() + ") " + NewLine); + buf.Append(indent); + buf.AppendLine("VideotexString(" + videotexString.GetString() + ")"); } - else if (obj is BerApplicationSpecific) + else if (obj is Asn1UtcTime utcTime) { - buf.Append(outputApplicationSpecific("BER", indent, verbose, (BerApplicationSpecific)obj)); + buf.Append(indent); + buf.AppendLine("UTCTime(" + utcTime.TimeString + ")"); } - else if (obj is DerApplicationSpecific) + else if (obj is Asn1GeneralizedTime generalizedTime) { - buf.Append(outputApplicationSpecific("DER", indent, verbose, (DerApplicationSpecific)obj)); + buf.Append(indent); + buf.AppendLine("GeneralizedTime(" + generalizedTime.TimeString + ")"); } - else if (obj is DerEnumerated) + else if (obj is DerEnumerated en) { - DerEnumerated en = (DerEnumerated)obj; - buf.Append(indent + "DER Enumerated(" + en.Value + ")" + NewLine); + buf.Append(indent); + buf.AppendLine("DER Enumerated(" + en.Value + ")"); } - else if (obj is DerExternal) + else if (obj is DerExternal ext) { - DerExternal ext = (DerExternal)obj; - buf.Append(indent + "External " + NewLine); + buf.Append(indent); + buf.AppendLine("External "); string tab = indent + Tab; if (ext.DirectReference != null) { - buf.Append(tab + "Direct Reference: " + ext.DirectReference.Id + NewLine); + buf.Append(tab); + buf.AppendLine("Direct Reference: " + ext.DirectReference.Id); } if (ext.IndirectReference != null) { - buf.Append(tab + "Indirect Reference: " + ext.IndirectReference.ToString() + NewLine); + buf.Append(tab); + buf.AppendLine("Indirect Reference: " + ext.IndirectReference.ToString()); } if (ext.DataValueDescriptor != null) { AsString(tab, verbose, ext.DataValueDescriptor, buf); } - buf.Append(tab + "Encoding: " + ext.Encoding + NewLine); + buf.Append(tab); + buf.AppendLine("Encoding: " + ext.Encoding); AsString(tab, verbose, ext.ExternalContent, buf); } else { - buf.Append(indent + obj.ToString() + NewLine); + buf.Append(indent); + buf.Append(obj); + buf.AppendLine(); } } - private static string outputApplicationSpecific( - string type, - string indent, - bool verbose, - DerApplicationSpecific app) + ///

Parse ASN.1 objects from input , and write them to the output. + public static void Dump(Stream input, TextWriter output) { - StringBuilder buf = new StringBuilder(); - - if (app.IsConstructed()) + Asn1InputStream asn1InputStream = new Asn1InputStream(input); + Asn1Object asn1Object; + while ((asn1Object = asn1InputStream.ReadObject()) != null) { - try - { - Asn1Sequence s = Asn1Sequence.GetInstance(app.GetObject(Asn1Tags.Sequence)); - buf.Append(indent + type + " ApplicationSpecific[" + app.ApplicationTag + "]" + NewLine); - foreach (Asn1Encodable ae in s) - { - AsString(indent + Tab, verbose, ae.ToAsn1Object(), buf); - } - } - catch (IOException e) - { - buf.Append(e); - } - return buf.ToString(); + output.Write(DumpAsString(asn1Object)); } - - return indent + type + " ApplicationSpecific[" + app.ApplicationTag + "] (" - + Hex.ToHexString(app.GetContents()) + ")" + NewLine; } /** @@ -270,8 +272,7 @@ private static string outputApplicationSpecific( * @param obj the Asn1Encodable to be dumped out. * @return the resulting string. */ - public static string DumpAsString( - Asn1Encodable obj) + public static string DumpAsString(Asn1Encodable obj) { return DumpAsString(obj, false); } @@ -283,55 +284,39 @@ public static string DumpAsString( * @param verbose if true, dump out the contents of octet and bit strings. * @return the resulting string. */ - public static string DumpAsString( - Asn1Encodable obj, - bool verbose) + public static string DumpAsString(Asn1Encodable obj, bool verbose) { StringBuilder buf = new StringBuilder(); AsString("", verbose, obj.ToAsn1Object(), buf); return buf.ToString(); } - private static string dumpBinaryDataAsString(string indent, byte[] bytes) + private static void DumpBinaryDataAsString(StringBuilder buf, string indent, byte[] bytes) { - indent += Tab; + if (bytes.Length < 1) + return; - StringBuilder buf = new StringBuilder(NewLine); + indent += Tab; for (int i = 0; i < bytes.Length; i += SampleSize) { - if (bytes.Length - i > SampleSize) - { - buf.Append(indent); - buf.Append(Hex.ToHexString(bytes, i, SampleSize)); - buf.Append(Tab); - buf.Append(calculateAscString(bytes, i, SampleSize)); - buf.Append(NewLine); - } - else + int remaining = bytes.Length - i; + int chunk = System.Math.Min(remaining, SampleSize); + + buf.Append(indent); + buf.Append(Hex.ToHexString(bytes, i, chunk)); + for (int j = chunk; j < SampleSize; ++j) { - buf.Append(indent); - buf.Append(Hex.ToHexString(bytes, i, bytes.Length - i)); - for (int j = bytes.Length - i; j != SampleSize; j++) - { - buf.Append(" "); - } - buf.Append(Tab); - buf.Append(calculateAscString(bytes, i, bytes.Length - i)); - buf.Append(NewLine); + buf.Append(" "); } + buf.Append(Tab); + AppendAscString(buf, bytes, i, chunk); + buf.AppendLine(); } - - return buf.ToString(); } - private static string calculateAscString( - byte[] bytes, - int off, - int len) + private static void AppendAscString(StringBuilder buf, byte[] bytes, int off, int len) { - StringBuilder buf = new StringBuilder(); - for (int i = off; i != off + len; i++) { char c = (char)bytes[i]; @@ -340,8 +325,6 @@ private static string calculateAscString( buf.Append(c); } } - - return buf.ToString(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/util/FilterStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/util/FilterStream.cs index 8b6aa38..0454b34 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/util/FilterStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/util/FilterStream.cs @@ -1,87 +1,3 @@ #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.Utilities -{ - - 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/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/util/FilterStream.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/util/FilterStream.cs.meta index 7871a25..4c3c298 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/util/FilterStream.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/util/FilterStream.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: ecc1ac8ab2a920c418f97b8619491c2a +guid: 2bdac595e49fdea498ef77f610df00fa MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x500/DirectoryString.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x500/DirectoryString.cs index 6535a93..f336f5c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x500/DirectoryString.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x500/DirectoryString.cs @@ -28,7 +28,7 @@ public static DirectoryString GetInstance(object obj) } } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public static DirectoryString GetInstance( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x500/style/IetfUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x500/style/IetfUtilities.cs index 3b0cd11..e6bc456 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x500/style/IetfUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x500/style/IetfUtilities.cs @@ -1,7 +1,6 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; using System.IO; using System.Text; @@ -96,15 +95,15 @@ public static string ValueToString(Asn1Encodable value) public static string Canonicalize(string s) { - string value = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToLowerInvariant(s); + string value = s.ToLowerInvariant(); if (value.Length > 0 && value[0] == '#') { Asn1Object obj = DecodeObject(value); - if (obj is IAsn1String) + if (obj is IAsn1String str) { - value = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToLowerInvariant(((IAsn1String)obj).GetString()); + value = str.GetString().ToLowerInvariant(); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AccessDescription.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AccessDescription.cs index ccdd01a..3ac4ef7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AccessDescription.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AccessDescription.cs @@ -32,7 +32,7 @@ public static AccessDescription GetInstance( if (obj is Asn1Sequence) return new AccessDescription((Asn1Sequence) obj); - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } private AccessDescription( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AlgorithmIdentifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AlgorithmIdentifier.cs index 8dd3e77..7be4643 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AlgorithmIdentifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AlgorithmIdentifier.cs @@ -33,13 +33,6 @@ public AlgorithmIdentifier( this.algorithm = algorithm; } - - public AlgorithmIdentifier( - string algorithm) - { - this.algorithm = new DerObjectIdentifier(algorithm); - } - public AlgorithmIdentifier( DerObjectIdentifier algorithm, Asn1Encodable parameters) @@ -66,12 +59,6 @@ public virtual DerObjectIdentifier Algorithm get { return algorithm; } } - - public virtual DerObjectIdentifier ObjectID - { - get { return algorithm; } - } - /// /// Return the parameters structure in the Parameters entry of this identifier. /// diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AttCertIssuer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AttCertIssuer.cs index 60a068f..6973bde 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AttCertIssuer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AttCertIssuer.cs @@ -36,7 +36,7 @@ public static AttCertIssuer GetInstance( return new AttCertIssuer(GeneralNames.GetInstance(obj)); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public static AttCertIssuer GetInstance( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AttCertValidityPeriod.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AttCertValidityPeriod.cs index a54321e..2550488 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AttCertValidityPeriod.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AttCertValidityPeriod.cs @@ -9,8 +9,8 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509 public class AttCertValidityPeriod : Asn1Encodable { - private readonly DerGeneralizedTime notBeforeTime; - private readonly DerGeneralizedTime notAfterTime; + private readonly Asn1GeneralizedTime notBeforeTime; + private readonly Asn1GeneralizedTime notAfterTime; public static AttCertValidityPeriod GetInstance( object obj) @@ -25,7 +25,7 @@ public static AttCertValidityPeriod GetInstance( return new AttCertValidityPeriod((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public static AttCertValidityPeriod GetInstance( @@ -41,24 +41,24 @@ private AttCertValidityPeriod( if (seq.Count != 2) throw new ArgumentException("Bad sequence size: " + seq.Count); - notBeforeTime = DerGeneralizedTime.GetInstance(seq[0]); - notAfterTime = DerGeneralizedTime.GetInstance(seq[1]); + notBeforeTime = Asn1GeneralizedTime.GetInstance(seq[0]); + notAfterTime = Asn1GeneralizedTime.GetInstance(seq[1]); } public AttCertValidityPeriod( - DerGeneralizedTime notBeforeTime, - DerGeneralizedTime notAfterTime) + Asn1GeneralizedTime notBeforeTime, + Asn1GeneralizedTime notAfterTime) { this.notBeforeTime = notBeforeTime; this.notAfterTime = notAfterTime; } - public DerGeneralizedTime NotBeforeTime + public Asn1GeneralizedTime NotBeforeTime { get { return notBeforeTime; } } - public DerGeneralizedTime NotAfterTime + public Asn1GeneralizedTime NotAfterTime { get { return notAfterTime; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Attribute.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Attribute.cs index e175a49..578bcd8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Attribute.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Attribute.cs @@ -31,7 +31,7 @@ public static AttributeX509 GetInstance( return new AttributeX509((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } private AttributeX509( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AttributeCertificateInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AttributeCertificateInfo.cs index 85b185f..8390d86 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AttributeCertificateInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AttributeCertificateInfo.cs @@ -39,7 +39,7 @@ public static AttributeCertificateInfo GetInstance( return new AttributeCertificateInfo((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } private AttributeCertificateInfo( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AttributeTable.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AttributeTable.cs index bb21878..5d7f921 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AttributeTable.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AttributeTable.cs @@ -1,75 +1,52 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System; -using System.Collections; +using System.Collections.Generic; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509 { public class AttributeTable { - private readonly IDictionary attributes; + private readonly IDictionary m_attributes; - public AttributeTable( - IDictionary attrs) + public AttributeTable(IDictionary attrs) { - this.attributes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(attrs); + m_attributes = new Dictionary(attrs); } -#if !(SILVERLIGHT || PORTABLE || NETFX_CORE) - [Obsolete] - public AttributeTable( - Hashtable attrs) + public AttributeTable(Asn1EncodableVector v) { - this.attributes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(attrs); - } -#endif + m_attributes = new Dictionary(v.Count); - public AttributeTable( - Asn1EncodableVector v) - { - this.attributes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(v.Count); - - for (int i = 0; i != v.Count; i++) + for (int i = 0; i != v.Count; i++) { AttributeX509 a = AttributeX509.GetInstance(v[i]); - attributes.Add(a.AttrType, a); + m_attributes.Add(a.AttrType, a); } } - public AttributeTable( - Asn1Set s) + public AttributeTable(Asn1Set s) { - this.attributes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(s.Count); + m_attributes = new Dictionary(s.Count); - for (int i = 0; i != s.Count; i++) + for (int i = 0; i != s.Count; i++) { AttributeX509 a = AttributeX509.GetInstance(s[i]); - attributes.Add(a.AttrType, a); + m_attributes.Add(a.AttrType, a); } } - public AttributeX509 Get( - DerObjectIdentifier oid) + public AttributeX509 Get(DerObjectIdentifier oid) { - return (AttributeX509) attributes[oid]; + return CollectionUtilities.GetValueOrNull(m_attributes, oid); } -#if !(SILVERLIGHT || PORTABLE || NETFX_CORE) - - public Hashtable ToHashtable() - { - return new Hashtable(attributes); - } -#endif - - public IDictionary ToDictionary() + public IDictionary ToDictionary() { - return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(attributes); + return new Dictionary(m_attributes); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AuthorityInformationAccess.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AuthorityInformationAccess.cs index 7e01c9c..9a9a0e3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AuthorityInformationAccess.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AuthorityInformationAccess.cs @@ -1,10 +1,8 @@ #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.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509 @@ -98,18 +96,13 @@ public override string ToString() //return "AuthorityInformationAccess: Oid(" + this.descriptions[0].AccessMethod.Id + ")"; StringBuilder buf = new StringBuilder(); - string sep = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine; - - buf.Append("AuthorityInformationAccess:"); - buf.Append(sep); - + buf.AppendLine("AuthorityInformationAccess:"); foreach (AccessDescription description in descriptions) { - buf.Append(" "); - buf.Append(description); - buf.Append(sep); + buf.Append(" ") + .Append(description) + .AppendLine(); } - return buf.ToString(); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AuthorityKeyIdentifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AuthorityKeyIdentifier.cs index 3b632e5..9be2163 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AuthorityKeyIdentifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/AuthorityKeyIdentifier.cs @@ -1,12 +1,10 @@ #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.Math; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/CRLDistPoint.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/CRLDistPoint.cs index e2d8688..b8b2e7a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/CRLDistPoint.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/CRLDistPoint.cs @@ -74,16 +74,12 @@ public override Asn1Object ToAsn1Object() public override string ToString() { StringBuilder buf = new StringBuilder(); - string sep = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine; - - buf.Append("CRLDistPoint:"); - buf.Append(sep); - DistributionPoint[] dp = GetDistributionPoints(); - for (int i = 0; i != dp.Length; i++) + buf.AppendLine("CRLDistPoint:"); + foreach (DistributionPoint dp in GetDistributionPoints()) { - buf.Append(" "); - buf.Append(dp[i]); - buf.Append(sep); + buf.Append(" ") + .Append(dp) + .AppendLine(); } return buf.ToString(); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/CertificateList.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/CertificateList.cs index 6d4b814..e2f6509 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/CertificateList.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/CertificateList.cs @@ -1,9 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; - -using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; +using System.Collections.Generic; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509 { @@ -67,7 +65,7 @@ public CrlEntry[] GetRevokedCertificates() return tbsCertList.GetRevokedCertificates(); } - public IEnumerable GetRevokedCertificateEnumeration() + public IEnumerable GetRevokedCertificateEnumeration() { return tbsCertList.GetRevokedCertificateEnumeration(); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/CertificatePair.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/CertificatePair.cs index 1f50468..66cb3f8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/CertificatePair.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/CertificatePair.cs @@ -57,7 +57,7 @@ public static CertificatePair GetInstance( return new CertificatePair((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DSAParameter.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DSAParameter.cs index 42cfcf9..ca9d721 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DSAParameter.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DSAParameter.cs @@ -1,7 +1,6 @@ #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; @@ -33,7 +32,7 @@ public static DsaParameter GetInstance( return new DsaParameter((Asn1Sequence) obj); } - throw new ArgumentException("Invalid DsaParameter: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("Invalid DsaParameter: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } public DsaParameter( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DigestInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DigestInfo.cs index 5fa8601..92c70d1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DigestInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DigestInfo.cs @@ -1,7 +1,6 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -41,7 +40,7 @@ public static DigestInfo GetInstance( return new DigestInfo((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public DigestInfo( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DisplayText.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DisplayText.cs index f5cebd2..7dabc51 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DisplayText.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DisplayText.cs @@ -155,7 +155,7 @@ public static DisplayText GetInstance( return (DisplayText) obj; } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public override Asn1Object ToAsn1Object() diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DistributionPoint.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DistributionPoint.cs index c6b2769..48ece19 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DistributionPoint.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DistributionPoint.cs @@ -44,7 +44,7 @@ public static DistributionPoint GetInstance( return new DistributionPoint((Asn1Sequence) obj); } - throw new ArgumentException("Invalid DistributionPoint: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("Invalid DistributionPoint: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } private DistributionPoint( @@ -108,43 +108,34 @@ public override Asn1Object ToAsn1Object() public override string ToString() { - string sep = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine; StringBuilder buf = new StringBuilder(); - buf.Append("DistributionPoint: ["); - buf.Append(sep); + buf.AppendLine("DistributionPoint: ["); if (distributionPoint != null) { - appendObject(buf, sep, "distributionPoint", distributionPoint.ToString()); + AppendObject(buf, "distributionPoint", distributionPoint.ToString()); } if (reasons != null) { - appendObject(buf, sep, "reasons", reasons.ToString()); + AppendObject(buf, "reasons", reasons.ToString()); } if (cRLIssuer != null) { - appendObject(buf, sep, "cRLIssuer", cRLIssuer.ToString()); + AppendObject(buf, "cRLIssuer", cRLIssuer.ToString()); } - buf.Append("]"); - buf.Append(sep); + buf.AppendLine("]"); return buf.ToString(); } - private void appendObject( - StringBuilder buf, - string sep, - string name, - string val) + private void AppendObject(StringBuilder buf, string name, string val) { string indent = " "; - buf.Append(indent); buf.Append(name); - buf.Append(":"); - buf.Append(sep); + buf.AppendLine(":"); buf.Append(indent); buf.Append(indent); buf.Append(val); - buf.Append(sep); + buf.AppendLine(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DistributionPointName.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DistributionPointName.cs index b100750..32e8d6c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DistributionPointName.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/DistributionPointName.cs @@ -45,7 +45,7 @@ public static DistributionPointName GetInstance( return new DistributionPointName((Asn1TaggedObject) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public DistributionPointName( @@ -94,41 +94,32 @@ public override Asn1Object ToAsn1Object() public override string ToString() { - string sep = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine; StringBuilder buf = new StringBuilder(); - buf.Append("DistributionPointName: ["); - buf.Append(sep); + buf.AppendLine("DistributionPointName: ["); if (type == FullName) { - appendObject(buf, sep, "fullName", name.ToString()); + AppendObject(buf, "fullName", name.ToString()); } else { - appendObject(buf, sep, "nameRelativeToCRLIssuer", name.ToString()); + AppendObject(buf, "nameRelativeToCRLIssuer", name.ToString()); } - buf.Append("]"); - buf.Append(sep); + buf.AppendLine("]"); return buf.ToString(); } - private void appendObject( - StringBuilder buf, - string sep, - string name, - string val) + private void AppendObject(StringBuilder buf, string name, string val) { string indent = " "; - buf.Append(indent); buf.Append(name); - buf.Append(":"); - buf.Append(sep); + buf.AppendLine(":"); buf.Append(indent); buf.Append(indent); buf.Append(val); - buf.Append(sep); - } - } + buf.AppendLine(); + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/ExtendedKeyUsage.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/ExtendedKeyUsage.cs index da302e3..bde2923 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/ExtendedKeyUsage.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/ExtendedKeyUsage.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -40,11 +40,10 @@ public static ExtendedKeyUsage FromExtensions(X509Extensions extensions) return GetInstance(X509Extensions.GetExtensionParsedValue(extensions, X509Extensions.ExtendedKeyUsage)); } - internal readonly IDictionary usageTable = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + internal readonly ISet m_usageTable = new HashSet(); internal readonly Asn1Sequence seq; - private ExtendedKeyUsage( - Asn1Sequence seq) + private ExtendedKeyUsage(Asn1Sequence seq) { this.seq = seq; @@ -52,32 +51,21 @@ private ExtendedKeyUsage( { DerObjectIdentifier oid = DerObjectIdentifier.GetInstance(element); - this.usageTable[oid] = oid; + m_usageTable.Add(oid); } } - public ExtendedKeyUsage( - params KeyPurposeID[] usages) + public ExtendedKeyUsage(params KeyPurposeID[] usages) { this.seq = new DerSequence(usages); foreach (KeyPurposeID usage in usages) { - this.usageTable[usage] = usage; + m_usageTable.Add(usage); } } -#if !(SILVERLIGHT || PORTABLE || NETFX_CORE) - [Obsolete] - public ExtendedKeyUsage( - ArrayList usages) - : this((IEnumerable)usages) - { - } -#endif - - public ExtendedKeyUsage( - IEnumerable usages) + public ExtendedKeyUsage(IEnumerable usages) { Asn1EncodableVector v = new Asn1EncodableVector(); @@ -86,39 +74,30 @@ public ExtendedKeyUsage( DerObjectIdentifier oid = DerObjectIdentifier.GetInstance(usage); v.Add(oid); - this.usageTable[oid] = oid; + m_usageTable.Add(oid); } this.seq = new DerSequence(v); } - public bool HasKeyPurposeId( - KeyPurposeID keyPurposeId) + public bool HasKeyPurposeId(KeyPurposeID keyPurposeId) { - return usageTable.Contains(keyPurposeId); + return m_usageTable.Contains(keyPurposeId); } -#if !(SILVERLIGHT || PORTABLE || NETFX_CORE) - - public ArrayList GetUsages() - { - return new ArrayList(usageTable.Values); - } -#endif - /** * Returns all extended key usages. * The returned ArrayList contains DerObjectIdentifier instances. * @return An ArrayList with all key purposes. */ - public IList GetAllUsages() + public IList GetAllUsages() { - return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(usageTable.Values); + return new List(m_usageTable); } public int Count { - get { return usageTable.Count; } + get { return m_usageTable.Count; } } public override Asn1Object ToAsn1Object() diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/GeneralName.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/GeneralName.cs index 47376a7..7999ae8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/GeneralName.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/GeneralName.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; @@ -206,7 +206,7 @@ public static GeneralName GetInstance( } } - throw new ArgumentException("unknown object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public static GeneralName GetInstance( @@ -321,7 +321,7 @@ private byte[] toGeneralNameEncoding( private void parseIPv4Mask(string mask, byte[] addr, int offset) { - int maskVal = Int32.Parse(mask); + int maskVal = int.Parse(mask); for (int i = 0; i != maskVal; i++) { @@ -333,14 +333,14 @@ private void parseIPv4(string ip, byte[] addr, int offset) { foreach (string token in ip.Split('.', '/')) { - addr[offset++] = (byte)Int32.Parse(token); + addr[offset++] = (byte)int.Parse(token); } } private int[] parseMask(string mask) { int[] res = new int[8]; - int maskVal = Int32.Parse(mask); + int maskVal = int.Parse(mask); for (int i = 0; i != maskVal; i++) { @@ -360,16 +360,17 @@ private void copyInts(int[] parsedIp, byte[] addr, int offSet) private int[] parseIPv6(string ip) { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(ip, "::")) + if (Org.BouncyCastle.Utilities.Platform.StartsWith(ip, "::")) { ip = ip.Substring(1); } - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(ip, "::")) + else if (Org.BouncyCastle.Utilities.Platform.EndsWith(ip, "::")) { ip = ip.Substring(0, ip.Length - 1); } - IEnumerator sEnum = ip.Split(':').GetEnumerator(); + IEnumerable split = ip.Split(':'); + var sEnum = split.GetEnumerator(); int index = 0; int[] val = new int[8]; @@ -378,7 +379,7 @@ private int[] parseIPv6(string ip) while (sEnum.MoveNext()) { - string e = (string) sEnum.Current; + string e = sEnum.Current; if (e.Length == 0) { @@ -389,14 +390,14 @@ private int[] parseIPv6(string ip) { if (e.IndexOf('.') < 0) { - val[index++] = Int32.Parse(e, NumberStyles.AllowHexSpecifier); + val[index++] = int.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]); + val[index++] = (int.Parse(tokens[0]) << 8) | int.Parse(tokens[1]); + val[index++] = (int.Parse(tokens[2]) << 8) | int.Parse(tokens[3]); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/GeneralNames.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/GeneralNames.cs index 6c55512..326cbbc 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/GeneralNames.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/GeneralNames.cs @@ -80,18 +80,13 @@ public override Asn1Object ToAsn1Object() public override string ToString() { StringBuilder buf = new StringBuilder(); - string sep = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine; - - buf.Append("GeneralNames:"); - buf.Append(sep); - + buf.AppendLine("GeneralNames:"); foreach (GeneralName name in names) { - buf.Append(" "); - buf.Append(name); - buf.Append(sep); + buf.Append(" ") + .Append(name) + .AppendLine(); } - return buf.ToString(); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Holder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Holder.cs index 3f6e160..c6d7a14 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Holder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Holder.cs @@ -62,7 +62,7 @@ public static Holder GetInstance( return new Holder((Asn1TaggedObject) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/IetfAttrSyntax.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/IetfAttrSyntax.cs index bd4a318..3feebc4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/IetfAttrSyntax.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/IetfAttrSyntax.cs @@ -1,9 +1,6 @@ #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 { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/IssuerSerial.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/IssuerSerial.cs index 5d05ec1..549c25b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/IssuerSerial.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/IssuerSerial.cs @@ -26,7 +26,7 @@ public static IssuerSerial GetInstance( return new IssuerSerial((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public static IssuerSerial GetInstance( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/IssuingDistributionPoint.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/IssuingDistributionPoint.cs index 7acae10..7f58f7e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/IssuingDistributionPoint.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/IssuingDistributionPoint.cs @@ -50,7 +50,7 @@ public static IssuingDistributionPoint GetInstance( return new IssuingDistributionPoint((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** @@ -194,56 +194,46 @@ public override Asn1Object ToAsn1Object() public override string ToString() { - string sep = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine; StringBuilder buf = new StringBuilder(); - - buf.Append("IssuingDistributionPoint: ["); - buf.Append(sep); + buf.AppendLine("IssuingDistributionPoint: ["); if (_distributionPoint != null) { - appendObject(buf, sep, "distributionPoint", _distributionPoint.ToString()); + AppendObject(buf, "distributionPoint", _distributionPoint.ToString()); } if (_onlyContainsUserCerts) { - appendObject(buf, sep, "onlyContainsUserCerts", _onlyContainsUserCerts.ToString()); + AppendObject(buf, "onlyContainsUserCerts", _onlyContainsUserCerts.ToString()); } if (_onlyContainsCACerts) { - appendObject(buf, sep, "onlyContainsCACerts", _onlyContainsCACerts.ToString()); + AppendObject(buf, "onlyContainsCACerts", _onlyContainsCACerts.ToString()); } if (_onlySomeReasons != null) { - appendObject(buf, sep, "onlySomeReasons", _onlySomeReasons.ToString()); + AppendObject(buf, "onlySomeReasons", _onlySomeReasons.ToString()); } if (_onlyContainsAttributeCerts) { - appendObject(buf, sep, "onlyContainsAttributeCerts", _onlyContainsAttributeCerts.ToString()); + AppendObject(buf, "onlyContainsAttributeCerts", _onlyContainsAttributeCerts.ToString()); } if (_indirectCRL) { - appendObject(buf, sep, "indirectCRL", _indirectCRL.ToString()); + AppendObject(buf, "indirectCRL", _indirectCRL.ToString()); } - buf.Append("]"); - buf.Append(sep); + buf.AppendLine("]"); return buf.ToString(); } - private void appendObject( - StringBuilder buf, - string sep, - string name, - string val) + private void AppendObject(StringBuilder buf, string name, string val) { string indent = " "; - buf.Append(indent); buf.Append(name); - buf.Append(":"); - buf.Append(sep); + buf.AppendLine(":"); buf.Append(indent); buf.Append(indent); buf.Append(val); - buf.Append(sep); + buf.AppendLine(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/KeyPurposeId.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/KeyPurposeId.cs index 977d22b..0389fa2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/KeyPurposeId.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/KeyPurposeId.cs @@ -1,5 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable +using System; + namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509 { /** @@ -11,31 +13,87 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509 public sealed class KeyPurposeID : DerObjectIdentifier { - private const string IdKP = "1.3.6.1.5.5.7.3"; + private const string id_kp = "1.3.6.1.5.5.7.3"; - private KeyPurposeID( - string id) + private KeyPurposeID(string id) : base(id) { } public static readonly KeyPurposeID AnyExtendedKeyUsage = new KeyPurposeID(X509Extensions.ExtendedKeyUsage.Id + ".0"); - public static readonly KeyPurposeID IdKPServerAuth = new KeyPurposeID(IdKP + ".1"); - public static readonly KeyPurposeID IdKPClientAuth = new KeyPurposeID(IdKP + ".2"); - public static readonly KeyPurposeID IdKPCodeSigning = new KeyPurposeID(IdKP + ".3"); - public static readonly KeyPurposeID IdKPEmailProtection = new KeyPurposeID(IdKP + ".4"); - public static readonly KeyPurposeID IdKPIpsecEndSystem = new KeyPurposeID(IdKP + ".5"); - public static readonly KeyPurposeID IdKPIpsecTunnel = new KeyPurposeID(IdKP + ".6"); - public static readonly KeyPurposeID IdKPIpsecUser = new KeyPurposeID(IdKP + ".7"); - public static readonly KeyPurposeID IdKPTimeStamping = new KeyPurposeID(IdKP + ".8"); - public static readonly KeyPurposeID IdKPOcspSigning = new KeyPurposeID(IdKP + ".9"); - - // + + public static readonly KeyPurposeID id_kp_serverAuth = new KeyPurposeID(id_kp + ".1"); + public static readonly KeyPurposeID id_kp_clientAuth = new KeyPurposeID(id_kp + ".2"); + public static readonly KeyPurposeID id_kp_codeSigning = new KeyPurposeID(id_kp + ".3"); + public static readonly KeyPurposeID id_kp_emailProtection = new KeyPurposeID(id_kp + ".4"); + public static readonly KeyPurposeID id_kp_ipsecEndSystem = new KeyPurposeID(id_kp + ".5"); + public static readonly KeyPurposeID id_kp_ipsecTunnel = new KeyPurposeID(id_kp + ".6"); + public static readonly KeyPurposeID id_kp_ipsecUser = new KeyPurposeID(id_kp + ".7"); + public static readonly KeyPurposeID id_kp_timeStamping = new KeyPurposeID(id_kp + ".8"); + public static readonly KeyPurposeID id_kp_OCSPSigning = new KeyPurposeID(id_kp + ".9"); + public static readonly KeyPurposeID id_kp_dvcs = new KeyPurposeID(id_kp + ".10"); + public static readonly KeyPurposeID id_kp_sbgpCertAAServerAuth = new KeyPurposeID(id_kp + ".11"); + public static readonly KeyPurposeID id_kp_scvp_responder = new KeyPurposeID(id_kp + ".12"); + public static readonly KeyPurposeID id_kp_eapOverPPP = new KeyPurposeID(id_kp + ".13"); + public static readonly KeyPurposeID id_kp_eapOverLAN = new KeyPurposeID(id_kp + ".14"); + public static readonly KeyPurposeID id_kp_scvpServer = new KeyPurposeID(id_kp + ".15"); + public static readonly KeyPurposeID id_kp_scvpClient = new KeyPurposeID(id_kp + ".16"); + public static readonly KeyPurposeID id_kp_ipsecIKE = new KeyPurposeID(id_kp + ".17"); + public static readonly KeyPurposeID id_kp_capwapAC = new KeyPurposeID(id_kp + ".18"); + public static readonly KeyPurposeID id_kp_capwapWTP = new KeyPurposeID(id_kp + ".19"); + + public static readonly KeyPurposeID id_kp_cmcCA = new KeyPurposeID(id_kp + ".27"); + public static readonly KeyPurposeID id_kp_cmcRA = new KeyPurposeID(id_kp + ".28"); + public static readonly KeyPurposeID id_kp_cmKGA = new KeyPurposeID(id_kp + ".32"); + + // // microsoft key purpose ids // - public static readonly KeyPurposeID IdKPSmartCardLogon = new KeyPurposeID("1.3.6.1.4.1.311.20.2.2"); + public static readonly KeyPurposeID id_kp_smartcardlogon = new KeyPurposeID("1.3.6.1.4.1.311.20.2.2"); + + public static readonly KeyPurposeID id_kp_macAddress = new KeyPurposeID("1.3.6.1.1.1.1.22"); + + /// Microsoft Server Gated Crypto (msSGC). + /// see https://www.alvestrand.no/objectid/1.3.6.1.4.1.311.10.3.3.html + public static readonly KeyPurposeID id_kp_msSGC = new KeyPurposeID("1.3.6.1.4.1.311.10.3.3"); + + private const string id_pkinit = "1.3.6.1.5.2.3"; + + public static readonly KeyPurposeID scSysNodeNumber = new KeyPurposeID(id_pkinit + ".0"); + public static readonly KeyPurposeID id_pkinit_authData = new KeyPurposeID(id_pkinit + ".1"); + public static readonly KeyPurposeID id_pkinit_DHKeyData = new KeyPurposeID(id_pkinit + ".2"); + public static readonly KeyPurposeID id_pkinit_rkeyData = new KeyPurposeID(id_pkinit + ".3"); + public static readonly KeyPurposeID keyPurposeClientAuth = new KeyPurposeID(id_pkinit + ".4"); + public static readonly KeyPurposeID keyPurposeKdc = new KeyPurposeID(id_pkinit + ".5"); + + /// Netscape Server Gated Crypto (nsSGC). + /// see https://www.alvestrand.no/objectid/2.16.840.1.113730.4.1.html + public static readonly KeyPurposeID id_kp_nsSGC = new KeyPurposeID("2.16.840.1.113730.4.1"); + + + public static readonly KeyPurposeID IdKPServerAuth = id_kp_serverAuth; + + public static readonly KeyPurposeID IdKPClientAuth = id_kp_clientAuth; + + public static readonly KeyPurposeID IdKPCodeSigning = id_kp_codeSigning; + + public static readonly KeyPurposeID IdKPEmailProtection = id_kp_emailProtection; + + public static readonly KeyPurposeID IdKPIpsecEndSystem = id_kp_ipsecEndSystem; + + public static readonly KeyPurposeID IdKPIpsecTunnel = id_kp_ipsecTunnel; + + public static readonly KeyPurposeID IdKPIpsecUser = id_kp_ipsecUser; + + public static readonly KeyPurposeID IdKPTimeStamping = id_kp_timeStamping; + + public static readonly KeyPurposeID IdKPOcspSigning = id_kp_OCSPSigning; + + + public static readonly KeyPurposeID IdKPSmartCardLogon = id_kp_smartcardlogon; + - public static readonly KeyPurposeID IdKPMacAddress = new KeyPurposeID("1.3.6.1.1.1.1.22"); + public static readonly KeyPurposeID IdKPMacAddress = id_kp_macAddress; } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/NameConstraints.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/NameConstraints.cs index 99efdcb..e0c2a74 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/NameConstraints.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/NameConstraints.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -25,7 +25,7 @@ public static NameConstraints GetInstance( return new NameConstraints((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public NameConstraints( @@ -45,15 +45,6 @@ public NameConstraints( } } -#if !(SILVERLIGHT || PORTABLE || NETFX_CORE) - public NameConstraints( - ArrayList permitted, - ArrayList excluded) - : this((IList)permitted, (IList)excluded) - { - } -#endif - /** * Constructor from a given details. * @@ -63,8 +54,8 @@ public NameConstraints( * @param excluded Excluded subtrees */ public NameConstraints( - IList permitted, - IList excluded) + IList permitted, + IList excluded) { if (permitted != null) { @@ -77,13 +68,12 @@ public NameConstraints( } } - private DerSequence CreateSequence( - IList subtrees) + private DerSequence CreateSequence(IList subtrees) { GeneralSubtree[] gsts = new GeneralSubtree[subtrees.Count]; for (int i = 0; i < subtrees.Count; ++i) { - gsts[i] = (GeneralSubtree)subtrees[i]; + gsts[i] = subtrees[i]; } return new DerSequence(gsts); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/NoticeReference.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/NoticeReference.cs index 38023d0..904bc5b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/NoticeReference.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/NoticeReference.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; @@ -28,7 +28,7 @@ public class NoticeReference private readonly DisplayText organization; private readonly Asn1Sequence noticeNumbers; - private static Asn1EncodableVector ConvertVector(IList numbers) + private static Asn1EncodableVector ConvertVector(IList numbers) { Asn1EncodableVector av = new Asn1EncodableVector(); @@ -60,7 +60,7 @@ private static Asn1EncodableVector ConvertVector(IList numbers) * @param organization a String value * @param numbers a Vector value */ - public NoticeReference(string organization, IList numbers) + public NoticeReference(string organization, IList numbers) : this(organization, ConvertVector(numbers)) { } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/ObjectDigestInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/ObjectDigestInfo.cs index e3ee0ba..8b3042f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/ObjectDigestInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/ObjectDigestInfo.cs @@ -62,7 +62,7 @@ public static ObjectDigestInfo GetInstance( return new ObjectDigestInfo((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public static ObjectDigestInfo GetInstance( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/PolicyMappings.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/PolicyMappings.cs index 85250f7..02e00eb 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/PolicyMappings.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/PolicyMappings.cs @@ -1,6 +1,6 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System.Collections; +using System.Collections.Generic; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509 { @@ -31,14 +31,6 @@ public PolicyMappings( this.seq = seq; } -#if !(SILVERLIGHT || PORTABLE || NETFX_CORE) - public PolicyMappings( - Hashtable mappings) - : this((IDictionary)mappings) - { - } -#endif - /** * Creates a new PolicyMappings instance. * @@ -46,14 +38,14 @@ public PolicyMappings( * string oids * to other string oids. */ - public PolicyMappings( - IDictionary mappings) + public PolicyMappings(IDictionary mappings) { Asn1EncodableVector v = new Asn1EncodableVector(); - foreach (string idp in mappings.Keys) + foreach (var entry in mappings) { - string sdp = (string) mappings[idp]; + string idp = entry.Key; + string sdp = entry.Value; v.Add( new DerSequence( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/PrivateKeyUsagePeriod.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/PrivateKeyUsagePeriod.cs index dac39ea..7b245a0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/PrivateKeyUsagePeriod.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/PrivateKeyUsagePeriod.cs @@ -35,10 +35,10 @@ public static PrivateKeyUsagePeriod GetInstance( return GetInstance(X509Extension.ConvertValueToObject((X509Extension) obj)); } - throw new ArgumentException("unknown object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } - private DerGeneralizedTime _notBefore, _notAfter; + private Asn1GeneralizedTime _notBefore, _notAfter; private PrivateKeyUsagePeriod( Asn1Sequence seq) @@ -47,21 +47,21 @@ private PrivateKeyUsagePeriod( { if (tObj.TagNo == 0) { - _notBefore = DerGeneralizedTime.GetInstance(tObj, false); + _notBefore = Asn1GeneralizedTime.GetInstance(tObj, false); } else if (tObj.TagNo == 1) { - _notAfter = DerGeneralizedTime.GetInstance(tObj, false); + _notAfter = Asn1GeneralizedTime.GetInstance(tObj, false); } } } - public DerGeneralizedTime NotBefore + public Asn1GeneralizedTime NotBefore { get { return _notBefore; } } - public DerGeneralizedTime NotAfter + public Asn1GeneralizedTime NotAfter { get { return _notAfter; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/RSAPublicKeyStructure.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/RSAPublicKeyStructure.cs index 6b450c4..2ec0a79 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/RSAPublicKeyStructure.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/RSAPublicKeyStructure.cs @@ -1,9 +1,7 @@ #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.Math; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -35,7 +33,7 @@ public static RsaPublicKeyStructure GetInstance( return new RsaPublicKeyStructure((Asn1Sequence) obj); } - throw new ArgumentException("Invalid RsaPublicKeyStructure: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new ArgumentException("Invalid RsaPublicKeyStructure: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } public RsaPublicKeyStructure( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/SubjectDirectoryAttributes.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/SubjectDirectoryAttributes.cs index 5c6a31b..a294df4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/SubjectDirectoryAttributes.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/SubjectDirectoryAttributes.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; @@ -30,7 +30,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509 public class SubjectDirectoryAttributes : Asn1Encodable { - private readonly IList attributes; + private readonly IList m_attributes; public static SubjectDirectoryAttributes GetInstance( object obj) @@ -45,7 +45,7 @@ public static SubjectDirectoryAttributes GetInstance( return new SubjectDirectoryAttributes((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** @@ -72,23 +72,15 @@ public static SubjectDirectoryAttributes GetInstance( private SubjectDirectoryAttributes( Asn1Sequence seq) { - this.attributes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + m_attributes = new List(); + foreach (object o in seq) { Asn1Sequence s = Asn1Sequence.GetInstance(o); - attributes.Add(AttributeX509.GetInstance(s)); + m_attributes.Add(AttributeX509.GetInstance(s)); } } -#if !(SILVERLIGHT || PORTABLE || NETFX_CORE) - [Obsolete] - public SubjectDirectoryAttributes( - ArrayList attributes) - : this((IList)attributes) - { - } -#endif - /** * Constructor from an ArrayList of attributes. * @@ -97,11 +89,10 @@ public SubjectDirectoryAttributes( * @param attributes The attributes. * */ - public SubjectDirectoryAttributes( - IList attributes) + public SubjectDirectoryAttributes(IList attributes) { - this.attributes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(attributes); - } + m_attributes = new List(attributes); + } /** * Produce an object suitable for an Asn1OutputStream. @@ -125,10 +116,10 @@ public SubjectDirectoryAttributes( */ public override Asn1Object ToAsn1Object() { - AttributeX509[] v = new AttributeX509[attributes.Count]; - for (int i = 0; i < attributes.Count; ++i) + AttributeX509[] v = new AttributeX509[m_attributes.Count]; + for (int i = 0; i < m_attributes.Count; ++i) { - v[i] = (AttributeX509)attributes[i]; + v[i] = m_attributes[i]; } return new DerSequence(v); } @@ -136,9 +127,9 @@ public override Asn1Object ToAsn1Object() /** * @return Returns the attributes. */ - public IEnumerable Attributes + public IEnumerable Attributes { - get { return new EnumerableProxy(attributes); } + get { return CollectionUtilities.Proxy(m_attributes); } } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/SubjectPublicKeyInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/SubjectPublicKeyInfo.cs index 67d24a3..4c935b9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/SubjectPublicKeyInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/SubjectPublicKeyInfo.cs @@ -1,7 +1,6 @@ #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.Asn1.X509 @@ -80,19 +79,6 @@ public Asn1Object ParsePublicKey() return Asn1Object.FromByteArray(keyData.GetOctets()); } - /** - * for when the public key is an encoded object - if the bitstring - * can't be decoded this routine raises an IOException. - * - * @exception IOException - if the bit string doesn't represent a Der - * encoded object. - */ - - public Asn1Object GetPublicKey() - { - return Asn1Object.FromByteArray(keyData.GetOctets()); - } - /** * for when the public key is raw bits... */ diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/TBSCertList.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/TBSCertList.cs index 909555f..afc4918 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/TBSCertList.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/TBSCertList.cs @@ -1,10 +1,9 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509 { @@ -16,13 +15,10 @@ public class CrlEntry internal Time revocationDate; internal X509Extensions crlEntryExtensions; - public CrlEntry( - Asn1Sequence seq) + public CrlEntry(Asn1Sequence seq) { if (seq.Count < 2 || seq.Count > 3) - { throw new ArgumentException("Bad sequence size: " + seq.Count); - } this.seq = seq; @@ -84,32 +80,39 @@ public class TbsCertificateList : Asn1Encodable { private class RevokedCertificatesEnumeration - : IEnumerable + : IEnumerable { - private readonly IEnumerable en; + private readonly IEnumerable en; - internal RevokedCertificatesEnumeration( - IEnumerable en) + internal RevokedCertificatesEnumeration(IEnumerable en) { this.en = en; } - public IEnumerator GetEnumerator() + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public IEnumerator GetEnumerator() { return new RevokedCertificatesEnumerator(en.GetEnumerator()); } private class RevokedCertificatesEnumerator - : IEnumerator + : IEnumerator { - private readonly IEnumerator e; + private readonly IEnumerator e; - internal RevokedCertificatesEnumerator( - IEnumerator e) + internal RevokedCertificatesEnumerator(IEnumerator e) { this.e = e; } + public virtual void Dispose() + { + } + public bool MoveNext() { return e.MoveNext(); @@ -120,7 +123,12 @@ public void Reset() e.Reset(); } - public object Current + object System.Collections.IEnumerator.Current + { + get { return Current; } + } + + public CrlEntry Current { get { return new CrlEntry(Asn1Sequence.GetInstance(e.Current)); } } @@ -158,7 +166,7 @@ public static TbsCertificateList GetInstance( return new TbsCertificateList((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } internal TbsCertificateList( @@ -187,8 +195,8 @@ internal TbsCertificateList( thisUpdate = Time.GetInstance(seq[seqPos++]); if (seqPos < seq.Count - && (seq[seqPos] is DerUtcTime - || seq[seqPos] is DerGeneralizedTime + && (seq[seqPos] is Asn1UtcTime + || seq[seqPos] is Asn1GeneralizedTime || seq[seqPos] is Time)) { nextUpdate = Time.GetInstance(seq[seqPos++]); @@ -254,12 +262,10 @@ public CrlEntry[] GetRevokedCertificates() return entries; } - public IEnumerable GetRevokedCertificateEnumeration() + public IEnumerable GetRevokedCertificateEnumeration() { if (revokedCertificates == null) - { - return EmptyEnumerable.Instance; - } + return new List(0); return new RevokedCertificatesEnumeration(revokedCertificates); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/TBSCertificateStructure.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/TBSCertificateStructure.cs index 2a38737..66fd8a2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/TBSCertificateStructure.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/TBSCertificateStructure.cs @@ -215,7 +215,7 @@ public X509Extensions Extensions public override Asn1Object ToAsn1Object() { string property = Org.BouncyCastle.Utilities.Platform.GetEnvironmentVariable("BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Allow_Non-DER_TBSCert"); - if (null == property || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase("true", property)) + if (null == property || Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase("true", property)) return seq; Asn1EncodableVector v = new Asn1EncodableVector(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Target.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Target.cs index b3e84cf..9c3f53a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Target.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Target.cs @@ -57,7 +57,7 @@ public static Target GetInstance( return new Target((Asn1TaggedObject) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/TargetInformation.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/TargetInformation.cs index 3edd2c4..46deb5d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/TargetInformation.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/TargetInformation.cs @@ -42,7 +42,7 @@ public static TargetInformation GetInstance( return new TargetInformation((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Targets.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Targets.cs index 3c4f903..24f88ef 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Targets.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Targets.cs @@ -56,7 +56,7 @@ public static Targets GetInstance( return new Targets((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Time.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Time.cs index da84df1..d27a4d8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Time.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/Time.cs @@ -10,24 +10,41 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509 public class Time : Asn1Encodable, IAsn1Choice { - private readonly Asn1Object time; + public static Time GetInstance(object obj) + { + if (obj == null) + return null; + if (obj is Time time) + return time; + if (obj is Asn1UtcTime utcTime) + return new Time(utcTime); + if (obj is Asn1GeneralizedTime generalizedTime) + return new Time(generalizedTime); + + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), nameof(obj)); + } - public static Time GetInstance( - Asn1TaggedObject obj, - bool explicitly) + public static Time GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - return GetInstance(obj.GetObject()); + return GetInstance(taggedObject.GetObject()); } - public Time( - Asn1Object time) + private readonly Asn1Object m_timeObject; + + public Time(Asn1GeneralizedTime generalizedTime) { - if (time == null) - throw new ArgumentNullException("time"); - if (!(time is DerUtcTime) && !(time is DerGeneralizedTime)) - throw new ArgumentException("unknown object passed to Time"); + this.m_timeObject = generalizedTime ?? throw new ArgumentNullException(nameof(generalizedTime)); + } - this.time = time; + public Time(Asn1UtcTime utcTime) + { + if (utcTime == null) + throw new ArgumentNullException(nameof(utcTime)); + + // Validate utcTime is in the appropriate year range + utcTime.ToDateTime(2049); + + this.m_timeObject = utcTime; } /** @@ -35,48 +52,18 @@ public Time( * and 2049 a UTCTime object is Generated, otherwise a GeneralizedTime * is used. */ - public Time( - DateTime date) + public Time(DateTime date) { -#if PORTABLE || NETFX_CORE - string d = date.ToUniversalTime().ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture) + "Z"; -#else - string d = date.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture) + "Z"; -#endif + DateTime utc = date.ToUniversalTime(); - int year = int.Parse(d.Substring(0, 4)); - - if (year < 1950 || year > 2049) + if (utc.Year < 1950 || utc.Year > 2049) { - time = new DerGeneralizedTime(d); + m_timeObject = new DerGeneralizedTime(utc); } else { - time = new DerUtcTime(d.Substring(2)); - } - } - - public static Time GetInstance( - object obj) - { - if (obj == null || obj is Time) - return (Time)obj; - if (obj is DerUtcTime) - return new Time((DerUtcTime)obj); - if (obj is DerGeneralizedTime) - return new Time((DerGeneralizedTime)obj); - - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); - } - - public string GetTime() - { - if (time is DerUtcTime) - { - return ((DerUtcTime) time).AdjustedTimeString; + m_timeObject = new DerUtcTime(utc, 2049); } - - return ((DerGeneralizedTime) time).GetTime(); } /// @@ -87,14 +74,10 @@ public DateTime ToDateTime() { try { - if (time is DerUtcTime) - { - return ((DerUtcTime)time).ToAdjustedDateTime(); - } - else - { - return ((DerGeneralizedTime)time).ToDateTime(); - } + if (m_timeObject is Asn1UtcTime utcTime) + return utcTime.ToDateTime(2049); + + return ((Asn1GeneralizedTime)m_timeObject).ToDateTime(); } catch (FormatException e) { @@ -113,12 +96,18 @@ public DateTime ToDateTime() */ public override Asn1Object ToAsn1Object() { - return time; + return m_timeObject; } public override string ToString() { - return GetTime(); + if (m_timeObject is Asn1UtcTime utcTime) + return utcTime.ToDateTime(2049).ToString(@"yyyyMMddHHmmssK", DateTimeFormatInfo.InvariantInfo); + + if (m_timeObject is Asn1GeneralizedTime generalizedTime) + return generalizedTime.ToDateTime().ToString(@"yyyyMMddHHmmss.FFFFFFFK", DateTimeFormatInfo.InvariantInfo); + + throw new InvalidOperationException(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/UserNotice.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/UserNotice.cs index 091f258..281601e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/UserNotice.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/UserNotice.cs @@ -51,18 +51,7 @@ public UserNotice( { } - /** - * 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 UserNotice( - Asn1Sequence seq) + private UserNotice(Asn1Sequence seq) { if (seq.Count == 2) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/V1TBSCertificateGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/V1TBSCertificateGenerator.cs index 20565c9..138a412 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/V1TBSCertificateGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/V1TBSCertificateGenerator.cs @@ -58,7 +58,7 @@ public void SetStartDate( } public void SetStartDate( - DerUtcTime startDate) + Asn1UtcTime startDate) { this.startDate = new Time(startDate); } @@ -70,7 +70,7 @@ public void SetEndDate( } public void SetEndDate( - DerUtcTime endDate) + Asn1UtcTime endDate) { this.endDate = new Time(endDate); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/V2AttributeCertificateInfoGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/V2AttributeCertificateInfoGenerator.cs index bd1afd0..f561369 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/V2AttributeCertificateInfoGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/V2AttributeCertificateInfoGenerator.cs @@ -28,11 +28,13 @@ public class V2AttributeCertificateInfoGenerator internal AttCertIssuer issuer; internal AlgorithmIdentifier signature; internal DerInteger serialNumber; -// internal AttCertValidityPeriod attrCertValidityPeriod; internal Asn1EncodableVector attributes; internal DerBitString issuerUniqueID; internal X509Extensions extensions; - internal DerGeneralizedTime startDate, endDate; + + // Note: validity period start/end dates stored directly + //internal AttCertValidityPeriod attrCertValidityPeriod; + internal Asn1GeneralizedTime startDate, endDate; public V2AttributeCertificateInfoGenerator() { @@ -80,13 +82,13 @@ public void SetIssuer( } public void SetStartDate( - DerGeneralizedTime startDate) + Asn1GeneralizedTime startDate) { this.startDate = startDate; } public void SetEndDate( - DerGeneralizedTime endDate) + Asn1GeneralizedTime endDate) { this.endDate = endDate; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/V2TBSCertListGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/V2TBSCertListGenerator.cs index 70cdd36..b489785 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/V2TBSCertListGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/V2TBSCertListGenerator.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -38,7 +38,7 @@ public class V2TbsCertListGenerator private X509Name issuer; private Time thisUpdate, nextUpdate; private X509Extensions extensions; - private IList crlEntries; + private List crlEntries; public V2TbsCertListGenerator() { @@ -57,13 +57,13 @@ public void SetIssuer( } public void SetThisUpdate( - DerUtcTime thisUpdate) + Asn1UtcTime thisUpdate) { this.thisUpdate = new Time(thisUpdate); } public void SetNextUpdate( - DerUtcTime nextUpdate) + Asn1UtcTime nextUpdate) { this.nextUpdate = (nextUpdate != null) ? new Time(nextUpdate) @@ -82,18 +82,17 @@ public void SetNextUpdate( this.nextUpdate = nextUpdate; } - public void AddCrlEntry( - Asn1Sequence crlEntry) + public void AddCrlEntry(Asn1Sequence crlEntry) { if (crlEntries == null) { - crlEntries = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + crlEntries = new List(); } crlEntries.Add(crlEntry); } - public void AddCrlEntry(DerInteger userCertificate, DerUtcTime revocationDate, int reason) + public void AddCrlEntry(DerInteger userCertificate, Asn1UtcTime revocationDate, int reason) { AddCrlEntry(userCertificate, new Time(revocationDate), reason); } @@ -104,10 +103,10 @@ public void AddCrlEntry(DerInteger userCertificate, Time revocationDate, int rea } public void AddCrlEntry(DerInteger userCertificate, Time revocationDate, int reason, - DerGeneralizedTime invalidityDate) + Asn1GeneralizedTime invalidityDate) { - IList extOids = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); - IList extValues = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var extOids = new List(); + var extValues = new List(); if (reason != 0) { @@ -149,8 +148,7 @@ public void AddCrlEntry(DerInteger userCertificate, Time revocationDate, int rea public void AddCrlEntry(DerInteger userCertificate, Time revocationDate, X509Extensions extensions) { - Asn1EncodableVector v = new Asn1EncodableVector( - userCertificate, revocationDate); + Asn1EncodableVector v = new Asn1EncodableVector(userCertificate, revocationDate); if (extensions != null) { @@ -184,12 +182,7 @@ public TbsCertificateList GenerateTbsCertList() // Add CRLEntries if they exist if (crlEntries != null) { - Asn1Sequence[] certs = new Asn1Sequence[crlEntries.Count]; - for (int i = 0; i < crlEntries.Count; ++i) - { - certs[i] = (Asn1Sequence)crlEntries[i]; - } - v.Add(new DerSequence(certs)); + v.Add(new DerSequence(crlEntries.ToArray())); } if (extensions != null) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/V3TBSCertificateGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/V3TBSCertificateGenerator.cs index 0ef0a85..1b6a18e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/V3TBSCertificateGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/V3TBSCertificateGenerator.cs @@ -60,7 +60,7 @@ public void SetIssuer( } public void SetStartDate( - DerUtcTime startDate) + Asn1UtcTime startDate) { this.startDate = new Time(startDate); } @@ -72,7 +72,7 @@ public void SetStartDate( } public void SetEndDate( - DerUtcTime endDate) + Asn1UtcTime endDate) { this.endDate = new Time(endDate); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/X509DefaultEntryConverter.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/X509DefaultEntryConverter.cs index b842699..279ad4c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/X509DefaultEntryConverter.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/X509DefaultEntryConverter.cs @@ -48,7 +48,7 @@ public override Asn1Object GetConvertedValue( if (oid.Equals(X509Name.DateOfBirth)) // accept time string as well as # (for compatibility) { - return new DerGeneralizedTime(value); + return new Asn1GeneralizedTime(value); } if (oid.Equals(X509Name.C) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/X509Extensions.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/X509Extensions.cs index 09157f2..cd4cca1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/X509Extensions.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/X509Extensions.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; @@ -171,8 +171,9 @@ public class X509Extensions */ public static readonly DerObjectIdentifier ExpiredCertsOnCrl = new DerObjectIdentifier("2.5.29.60"); - private readonly IDictionary extensions = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private readonly IList ordering; + private readonly Dictionary m_extensions = + new Dictionary(); + private readonly List m_ordering; public static X509Extension GetExtension(X509Extensions extensions, DerObjectIdentifier oid) { @@ -184,11 +185,9 @@ public static Asn1Encodable GetExtensionParsedValue(X509Extensions extensions, D return null == extensions ? null : extensions.GetExtensionParsedValue(oid); } - public static X509Extensions GetInstance( - Asn1TaggedObject obj, - bool explicitly) + public static X509Extensions GetInstance(Asn1TaggedObject taggedObject, bool declaredExplicit) { - return GetInstance(Asn1Sequence.GetInstance(obj, explicitly)); + return GetInstance(Asn1Sequence.GetInstance(taggedObject, declaredExplicit)); } public static X509Extensions GetInstance( @@ -209,7 +208,7 @@ public static X509Extensions GetInstance( return GetInstance(((Asn1TaggedObject) obj).GetObject()); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** @@ -217,10 +216,9 @@ public static X509Extensions GetInstance( * * the extensions are a list of constructed sequences, either with (Oid, OctetString) or (Oid, Boolean, OctetString) */ - private X509Extensions( - Asn1Sequence seq) + private X509Extensions(Asn1Sequence seq) { - this.ordering = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + m_ordering = new List(); foreach (Asn1Encodable ae in seq) { @@ -236,11 +234,11 @@ private X509Extensions( Asn1OctetString octets = Asn1OctetString.GetInstance(s[s.Count - 1].ToAsn1Object()); - if (extensions.Contains(oid)) + if (m_extensions.ContainsKey(oid)) throw new ArgumentException("repeated extension found: " + oid); - extensions.Add(oid, new X509Extension(isCritical, octets)); - ordering.Add(oid); + m_extensions.Add(oid, new X509Extension(isCritical, octets)); + m_ordering.Add(oid); } } @@ -249,8 +247,7 @@ private X509Extensions( *

* it's is assumed the table contains Oid/string pairs.

*/ - public X509Extensions( - IDictionary extensions) + public X509Extensions(IDictionary extensions) : this(null, extensions) { } @@ -260,22 +257,21 @@ public X509Extensions( *

* It's is assumed the table contains Oid/string pairs.

*/ - public X509Extensions( - IList ordering, - IDictionary extensions) + public X509Extensions(IList ordering, + IDictionary extensions) { if (ordering == null) { - this.ordering = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(extensions.Keys); + m_ordering = new List(extensions.Keys); } else { - this.ordering = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(ordering); + m_ordering = new List(ordering); } - foreach (DerObjectIdentifier oid in this.ordering) + foreach (DerObjectIdentifier oid in m_ordering) { - this.extensions.Add(oid, (X509Extension)extensions[oid]); + m_extensions.Add(oid, extensions[oid]); } } @@ -285,90 +281,23 @@ public X509Extensions( * @param objectIDs an ArrayList of the object identifiers. * @param values an ArrayList of the extension values. */ - public X509Extensions( - IList oids, - IList values) + public X509Extensions(IList oids, IList values) { - this.ordering = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(oids); + m_ordering = new List(oids); int count = 0; - foreach (DerObjectIdentifier oid in this.ordering) + foreach (DerObjectIdentifier oid in m_ordering) { - this.extensions.Add(oid, (X509Extension)values[count++]); + m_extensions.Add(oid, values[count++]); } } -#if !(SILVERLIGHT || PORTABLE || NETFX_CORE) - /** - * constructor from a table of extensions. - *

- * it's is assumed the table contains Oid/string pairs.

- */ - [Obsolete] - public X509Extensions( - Hashtable extensions) - : this(null, extensions) - { - } - - /** - * Constructor from a table of extensions with ordering. - *

- * It's is assumed the table contains Oid/string pairs.

- */ - [Obsolete] - public X509Extensions( - ArrayList ordering, - Hashtable extensions) - { - if (ordering == null) - { - this.ordering = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(extensions.Keys); - } - else - { - this.ordering = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(ordering); - } - - foreach (DerObjectIdentifier oid in this.ordering) - { - this.extensions.Add(oid, (X509Extension) extensions[oid]); - } - } - - /** - * Constructor from two vectors - * - * @param objectIDs an ArrayList of the object identifiers. - * @param values an ArrayList of the extension values. - */ - [Obsolete] - public X509Extensions( - ArrayList oids, - ArrayList values) - { - this.ordering = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(oids); - - int count = 0; - foreach (DerObjectIdentifier oid in this.ordering) - { - this.extensions.Add(oid, (X509Extension) values[count++]); - } - } -#endif - - - public IEnumerator Oids() - { - return ExtensionOids.GetEnumerator(); - } - /** * return an Enumeration of the extension field's object ids. */ - public IEnumerable ExtensionOids + public IEnumerable ExtensionOids { - get { return new EnumerableProxy(ordering); } + get { return CollectionUtilities.Proxy(m_ordering); } } /** @@ -377,10 +306,9 @@ public IEnumerable ExtensionOids * * @return the extension if it's present, null otherwise. */ - public X509Extension GetExtension( - DerObjectIdentifier oid) + public X509Extension GetExtension(DerObjectIdentifier oid) { - return (X509Extension)extensions[oid]; + return CollectionUtilities.GetValueOrNull(m_extensions, oid); } /** @@ -391,9 +319,7 @@ public X509Extension GetExtension( */ public Asn1Encodable GetExtensionParsedValue(DerObjectIdentifier oid) { - X509Extension ext = GetExtension(oid); - - return ext == null ? null : ext.GetParsedValue(); + return GetExtension(oid)?.GetParsedValue(); } /** @@ -408,44 +334,41 @@ public Asn1Encodable GetExtensionParsedValue(DerObjectIdentifier oid) */ public override Asn1Object ToAsn1Object() { - Asn1EncodableVector vec = new Asn1EncodableVector(); + Asn1EncodableVector v = new Asn1EncodableVector(m_ordering.Count); - foreach (DerObjectIdentifier oid in ordering) + foreach (DerObjectIdentifier oid in m_ordering) { - X509Extension ext = (X509Extension) extensions[oid]; - Asn1EncodableVector v = new Asn1EncodableVector(oid); - - if (ext.IsCritical) + X509Extension ext = m_extensions[oid]; + if (ext.IsCritical) { - v.Add(DerBoolean.True); + v.Add(new DerSequence(oid, DerBoolean.True, ext.Value)); + } + else + { + v.Add(new DerSequence(oid, ext.Value)); } - - v.Add(ext.Value); - - vec.Add(new DerSequence(v)); } - return new DerSequence(vec); + return new DerSequence(v); } - public bool Equivalent( - X509Extensions other) + public bool Equivalent(X509Extensions other) { - if (extensions.Count != other.extensions.Count) + if (m_extensions.Count != other.m_extensions.Count) return false; - foreach (DerObjectIdentifier oid in extensions.Keys) - { - if (!extensions[oid].Equals(other.extensions[oid])) - return false; - } + foreach (var entry in m_extensions) + { + if (!entry.Value.Equals(other.GetExtension(entry.Key))) + return false; + } return true; } public DerObjectIdentifier[] GetExtensionOids() { - return ToOidArray(ordering); + return m_ordering.ToArray(); } public DerObjectIdentifier[] GetNonCriticalExtensionOids() @@ -460,25 +383,17 @@ public DerObjectIdentifier[] GetCriticalExtensionOids() private DerObjectIdentifier[] GetExtensionOids(bool isCritical) { - IList oids = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var oids = new List(); - foreach (DerObjectIdentifier oid in this.ordering) + foreach (DerObjectIdentifier oid in m_ordering) { - X509Extension ext = (X509Extension)extensions[oid]; - if (ext.IsCritical == isCritical) + if (m_extensions[oid].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; + return oids.ToArray(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/X509ExtensionsGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/X509ExtensionsGenerator.cs index 5cdca84..8e4d9d9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/X509ExtensionsGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/X509ExtensionsGenerator.cs @@ -1,36 +1,30 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; - -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; +using System.Collections.Generic; 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(); - - private static readonly IDictionary dupsAllowed = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + private Dictionary m_extensions = + new Dictionary(); + private List m_ordering = new List(); - static X509ExtensionsGenerator() + private static readonly ISet m_dupsAllowed = new HashSet() { - dupsAllowed.Add(X509Extensions.SubjectAlternativeName, true); - dupsAllowed.Add(X509Extensions.IssuerAlternativeName, true); - dupsAllowed.Add(X509Extensions.SubjectDirectoryAttributes, true); - dupsAllowed.Add(X509Extensions.CertificateIssuer, true); - - } - - + X509Extensions.SubjectAlternativeName, + X509Extensions.IssuerAlternativeName, + X509Extensions.SubjectDirectoryAttributes, + X509Extensions.CertificateIssuer + }; /// Reset the generator public void Reset() { - extensions = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - extOrdering = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + m_extensions = new Dictionary(); + m_ordering = new List(); } /// @@ -40,10 +34,7 @@ public void Reset() /// 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) + public void AddExtension(DerObjectIdentifier oid, bool critical, Asn1Encodable extValue) { byte[] encoded; try @@ -65,38 +56,30 @@ public void AddExtension( /// OID for the extension. /// True if critical, false otherwise. /// The byte array to be wrapped. - public void AddExtension( - DerObjectIdentifier oid, - bool critical, - byte[] extValue) + public void AddExtension(DerObjectIdentifier oid, bool critical, byte[] extValue) { - if (extensions.Contains(oid)) + if (m_extensions.TryGetValue(oid, out X509Extension existingExtension)) { - if (dupsAllowed.Contains(oid)) - { - X509Extension existingExtension = (X509Extension)extensions[oid]; - - Asn1Sequence seq1 = Asn1Sequence.GetInstance(DerOctetString.GetInstance(existingExtension.Value).GetOctets()); - Asn1EncodableVector items = Asn1EncodableVector.FromEnumerable(seq1); - Asn1Sequence seq2 = Asn1Sequence.GetInstance(extValue); - - foreach (Asn1Encodable enc in seq2) - { - items.Add(enc); - } + if (!m_dupsAllowed.Contains(oid)) + throw new ArgumentException("extension " + oid + " already added"); - extensions[oid] = new X509Extension(existingExtension.IsCritical, new DerOctetString(new DerSequence(items).GetEncoded())); + Asn1Sequence seq1 = Asn1Sequence.GetInstance( + Asn1OctetString.GetInstance(existingExtension.Value).GetOctets()); + Asn1EncodableVector items = Asn1EncodableVector.FromEnumerable(seq1); + Asn1Sequence seq2 = Asn1Sequence.GetInstance(extValue); - } - else + foreach (Asn1Encodable enc in seq2) { - throw new ArgumentException("extension " + oid + " already added"); + items.Add(enc); } + + m_extensions[oid] = new X509Extension(existingExtension.IsCritical, + new DerOctetString(new DerSequence(items).GetEncoded())); } else { - extOrdering.Add(oid); - extensions.Add(oid, new X509Extension(critical, new DerOctetString(extValue))); + m_ordering.Add(oid); + m_extensions.Add(oid, new X509Extension(critical, new DerOctetString(extValue))); } } @@ -115,25 +98,23 @@ public void AddExtensions(X509Extensions extensions) /// True if empty, false otherwise public bool IsEmpty { - get { return extOrdering.Count < 1; } + get { return m_ordering.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); + return new X509Extensions(m_ordering, m_extensions); } internal void AddExtension(DerObjectIdentifier oid, X509Extension x509Extension) { - if (extensions.Contains(oid)) - { + if (m_extensions.ContainsKey(oid)) throw new ArgumentException("extension " + oid + " already added"); - } - extOrdering.Add(oid); - extensions.Add(oid, x509Extension); + m_ordering.Add(oid); + m_extensions.Add(oid, x509Extension); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/X509Name.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/X509Name.cs index 7ec211f..575b211 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/X509Name.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/X509Name.cs @@ -1,16 +1,13 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using System.Text; -#if SILVERLIGHT || PORTABLE || NETFX_CORE -using System.Collections.Generic; -#endif - +using BestHTTP.PlatformSupport.Text; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509 @@ -201,153 +198,140 @@ public class X509Name * 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; } + get { lock (defaultReverse) return defaultReverse[0]; } + set { lock (defaultReverse) 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(); + private static readonly IDictionary DefaultSymbolsInternal = + new Dictionary(); + public static readonly IDictionary DefaultSymbols = + CollectionUtilities.ReadOnly(DefaultSymbolsInternal); /** * look up table translating OID values into their common symbols following the convention in RFC 2253 */ - public static readonly Hashtable RFC2253Symbols = new Hashtable(); + private static readonly IDictionary RFC2253SymbolsInternal = + new Dictionary(); + public static readonly IDictionary RFC2253Symbols = + CollectionUtilities.ReadOnly(RFC2253SymbolsInternal); /** * look up table translating OID values into their common symbols following the convention in RFC 1779 * */ - public static readonly Hashtable RFC1779Symbols = new Hashtable(); + private static readonly IDictionary RFC1779SymbolsInternal = + new Dictionary(); + public static readonly IDictionary RFC1779Symbols = + CollectionUtilities.ReadOnly(RFC1779SymbolsInternal); /** * look up table translating common symbols into their OIDS. */ - public static readonly Hashtable DefaultLookup = new Hashtable(); -#endif + private static readonly IDictionary DefaultLookupInternal = + new Dictionary(StringComparer.OrdinalIgnoreCase); + public static readonly IDictionary DefaultLookup = + CollectionUtilities.ReadOnly(DefaultLookupInternal); 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); + DefaultSymbolsInternal.Add(C, "C"); + DefaultSymbolsInternal.Add(O, "O"); + DefaultSymbolsInternal.Add(T, "T"); + DefaultSymbolsInternal.Add(OU, "OU"); + DefaultSymbolsInternal.Add(CN, "CN"); + DefaultSymbolsInternal.Add(L, "L"); + DefaultSymbolsInternal.Add(ST, "ST"); + DefaultSymbolsInternal.Add(SerialNumber, "SERIALNUMBER"); + DefaultSymbolsInternal.Add(EmailAddress, "E"); + DefaultSymbolsInternal.Add(DC, "DC"); + DefaultSymbolsInternal.Add(UID, "UID"); + DefaultSymbolsInternal.Add(Street, "STREET"); + DefaultSymbolsInternal.Add(Surname, "SURNAME"); + DefaultSymbolsInternal.Add(GivenName, "GIVENNAME"); + DefaultSymbolsInternal.Add(Initials, "INITIALS"); + DefaultSymbolsInternal.Add(Generation, "GENERATION"); + DefaultSymbolsInternal.Add(UnstructuredAddress, "unstructuredAddress"); + DefaultSymbolsInternal.Add(UnstructuredName, "unstructuredName"); + DefaultSymbolsInternal.Add(UniqueIdentifier, "UniqueIdentifier"); + DefaultSymbolsInternal.Add(DnQualifier, "DN"); + DefaultSymbolsInternal.Add(Pseudonym, "Pseudonym"); + DefaultSymbolsInternal.Add(PostalAddress, "PostalAddress"); + DefaultSymbolsInternal.Add(NameAtBirth, "NameAtBirth"); + DefaultSymbolsInternal.Add(CountryOfCitizenship, "CountryOfCitizenship"); + DefaultSymbolsInternal.Add(CountryOfResidence, "CountryOfResidence"); + DefaultSymbolsInternal.Add(Gender, "Gender"); + DefaultSymbolsInternal.Add(PlaceOfBirth, "PlaceOfBirth"); + DefaultSymbolsInternal.Add(DateOfBirth, "DateOfBirth"); + DefaultSymbolsInternal.Add(PostalCode, "PostalCode"); + DefaultSymbolsInternal.Add(BusinessCategory, "BusinessCategory"); + DefaultSymbolsInternal.Add(TelephoneNumber, "TelephoneNumber"); + + RFC2253SymbolsInternal.Add(C, "C"); + RFC2253SymbolsInternal.Add(O, "O"); + RFC2253SymbolsInternal.Add(OU, "OU"); + RFC2253SymbolsInternal.Add(CN, "CN"); + RFC2253SymbolsInternal.Add(L, "L"); + RFC2253SymbolsInternal.Add(ST, "ST"); + RFC2253SymbolsInternal.Add(Street, "STREET"); + RFC2253SymbolsInternal.Add(DC, "DC"); + RFC2253SymbolsInternal.Add(UID, "UID"); + + RFC1779SymbolsInternal.Add(C, "C"); + RFC1779SymbolsInternal.Add(O, "O"); + RFC1779SymbolsInternal.Add(OU, "OU"); + RFC1779SymbolsInternal.Add(CN, "CN"); + RFC1779SymbolsInternal.Add(L, "L"); + RFC1779SymbolsInternal.Add(ST, "ST"); + RFC1779SymbolsInternal.Add(Street, "STREET"); + + DefaultLookupInternal.Add("c", C); + DefaultLookupInternal.Add("o", O); + DefaultLookupInternal.Add("t", T); + DefaultLookupInternal.Add("ou", OU); + DefaultLookupInternal.Add("cn", CN); + DefaultLookupInternal.Add("l", L); + DefaultLookupInternal.Add("st", ST); + DefaultLookupInternal.Add("serialnumber", SerialNumber); + DefaultLookupInternal.Add("street", Street); + DefaultLookupInternal.Add("emailaddress", E); + DefaultLookupInternal.Add("dc", DC); + DefaultLookupInternal.Add("e", E); + DefaultLookupInternal.Add("uid", UID); + DefaultLookupInternal.Add("surname", Surname); + DefaultLookupInternal.Add("givenname", GivenName); + DefaultLookupInternal.Add("initials", Initials); + DefaultLookupInternal.Add("generation", Generation); + DefaultLookupInternal.Add("unstructuredaddress", UnstructuredAddress); + DefaultLookupInternal.Add("unstructuredname", UnstructuredName); + DefaultLookupInternal.Add("uniqueidentifier", UniqueIdentifier); + DefaultLookupInternal.Add("dn", DnQualifier); + DefaultLookupInternal.Add("pseudonym", Pseudonym); + DefaultLookupInternal.Add("postaladdress", PostalAddress); + DefaultLookupInternal.Add("nameofbirth", NameAtBirth); + DefaultLookupInternal.Add("countryofcitizenship", CountryOfCitizenship); + DefaultLookupInternal.Add("countryofresidence", CountryOfResidence); + DefaultLookupInternal.Add("gender", Gender); + DefaultLookupInternal.Add("placeofbirth", PlaceOfBirth); + DefaultLookupInternal.Add("dateofbirth", DateOfBirth); + DefaultLookupInternal.Add("postalcode", PostalCode); + DefaultLookupInternal.Add("businesscategory", BusinessCategory); + DefaultLookupInternal.Add("telephonenumber", TelephoneNumber); } - private readonly IList ordering = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + private readonly List ordering = new List(); 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; + private IList values = new List(); + private IList added = new List(); + private Asn1Sequence seq; /** * Return a X509Name based on the passed in tagged object. @@ -382,8 +366,7 @@ protected X509Name() * * the principal will be a list of constructed sets, each containing an (OID, string) pair. */ - protected X509Name( - Asn1Sequence seq) + protected X509Name(Asn1Sequence seq) { this.seq = seq; @@ -404,7 +387,11 @@ protected X509Name( if (derValue is IAsn1String && !(derValue is DerUniversalString)) { string v = ((IAsn1String)derValue).GetString(); - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(v, "#")) +#if NET_STANDARD_2_1 + if (v.StartsWith('#')) +#else + if (v.StartsWith("#")) +#endif { v = "\\" + v; } @@ -430,8 +417,8 @@ protected X509Name( * in the order they are meant to be encoded or printed in ToString.

*/ public X509Name( - IList ordering, - IDictionary attributes) + IList ordering, + IDictionary attributes) : this(ordering, attributes, new X509DefaultEntryConverter()) { } @@ -448,19 +435,22 @@ public X509Name( * ASN.1 counterparts.

*/ public X509Name( - IList ordering, - IDictionary attributes, + IList ordering, + IDictionary attributes, X509NameEntryConverter converter) { this.converter = converter; foreach (DerObjectIdentifier oid in ordering) { - object attribute = attributes[oid]; - if (attribute == null) - { + if (!attributes.TryGetValue(oid, out var attribute)) throw new ArgumentException("No attribute for object id - " + oid + " - passed to distinguished name"); - } + + //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); @@ -471,9 +461,7 @@ public X509Name( /** * Takes two vectors one of the oids and the other of the values. */ - public X509Name( - IList oids, - IList values) + public X509Name(IList oids, IList values) : this(oids, values, new X509DefaultEntryConverter()) { } @@ -484,17 +472,12 @@ public X509Name( * The passed in converter will be used to convert the strings into their * ASN.1 counterparts.

*/ - public X509Name( - IList oids, - IList values, - X509NameEntryConverter converter) + 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++) { @@ -508,9 +491,8 @@ public X509Name( * 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) + public X509Name(string dirName) + : this(DefaultReverse, DefaultLookup, dirName) { } @@ -520,9 +502,7 @@ public X509Name( * string value being converted to its associated ASN.1 type using the passed * in converter. */ - public X509Name( - string dirName, - X509NameEntryConverter converter) + public X509Name(string dirName, X509NameEntryConverter converter) : this(DefaultReverse, DefaultLookup, dirName, converter) { } @@ -533,10 +513,8 @@ public X509Name( * 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) + public X509Name(bool reverse, string dirName) + : this(reverse, DefaultLookup, dirName) { } @@ -547,10 +525,7 @@ public X509Name( * 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) + public X509Name(bool reverse, string dirName, X509NameEntryConverter converter) : this(reverse, DefaultLookup, dirName, converter) { } @@ -568,34 +543,23 @@ public X509Name( * @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()) + public X509Name(bool reverse, IDictionary lookup, string dirName) + : this(reverse, lookup, dirName, new X509DefaultEntryConverter()) { } - private DerObjectIdentifier DecodeOid( - string name, - IDictionary lookUp) + 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') - { + if (name.StartsWith("OID.", StringComparison.OrdinalIgnoreCase)) + return new DerObjectIdentifier(name.Substring("OID.".Length)); + + 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"); - } + if (lookup.TryGetValue(name, out var oid)) + return oid; - return oid; + throw new ArgumentException("Unknown object id - " + name + " - passed to distinguished name"); } /** @@ -611,11 +575,8 @@ private DerObjectIdentifier DecodeOid( * @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) + public X509Name(bool reverse, IDictionary lookup, string dirName, + X509NameEntryConverter converter) { this.converter = converter; X509NameTokenizer nTok = new X509NameTokenizer(dirName); @@ -626,13 +587,11 @@ public X509Name( 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); + DerObjectIdentifier oid = DecodeOid(name, lookup); if (value.IndexOf('+') > 0) { @@ -650,7 +609,7 @@ public X509Name( string nm = sv.Substring(0, ndx); string vl = sv.Substring(ndx + 1); - this.ordering.Add(DecodeOid(nm, lookUp)); + this.ordering.Add(DecodeOid(nm, lookup)); this.values.Add(vl); this.added.Add(true); } @@ -668,9 +627,9 @@ public X509Name( // 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(); + var o = new List(); + var v = new List(); + var a = new List(); int count = 1; for (int i = 0; i < this.ordering.Count; i++) @@ -696,16 +655,16 @@ public X509Name( /** * return an IList of the oids in the name, in the order they were found. */ - public IList GetOidList() + public IList GetOidList() { - return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(ordering); + return new List(ordering); } /** * return an IList of the values found in the name, in the order they * were found. */ - public IList GetValueList() + public IList GetValueList() { return GetValueList(null); } @@ -714,16 +673,15 @@ public IList GetValueList() * 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) + public IList GetValueList(DerObjectIdentifier oid) { - IList v = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var v = new List(); 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, "\\#")) + if (val.StartsWith("\\#", StringComparison.OrdinalIgnoreCase)) { val = val.Substring(1); } @@ -805,7 +763,7 @@ public bool Equivalent( string val = (string) values[i]; string oVal = (string) other.values[i]; - if (!equivalentStrings(val, oVal)) + if (!EquivalentStrings(val, oVal)) return false; } @@ -866,7 +824,7 @@ public bool Equivalent( { string oValue = (string)other.values[j]; - if (equivalentStrings(value, oValue)) + if (EquivalentStrings(value, oValue)) { indexes[j] = true; found = true; @@ -884,47 +842,44 @@ public bool Equivalent( return true; } - private static bool equivalentStrings( - string s1, - string s2) + private static bool EquivalentStrings(string s1, string s2) { - string v1 = canonicalize(s1); - string v2 = canonicalize(s2); + string v1 = Canonicalize(s1); + string v2 = Canonicalize(s2); if (!v1.Equals(v2)) { - v1 = stripInternalSpaces(v1); - v2 = stripInternalSpaces(v2); + v1 = StripInternalSpaces(v1); + v2 = StripInternalSpaces(v2); if (!v1.Equals(v2)) - { return false; - } } return true; } - private static string canonicalize( - string s) + private static string Canonicalize(string s) { - string v = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToLowerInvariant(s).Trim(); + string v = s.ToLowerInvariant().Trim(); - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(v, "#")) +#if NET_STANDARD_2_1 + if (v.StartsWith('#')) +#else + if (v.StartsWith("#")) +#endif { - Asn1Object obj = decodeObject(v); - - if (obj is IAsn1String) + Asn1Object obj = DecodeObject(v); + if (obj is IAsn1String str) { - v = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToLowerInvariant(((IAsn1String)obj).GetString()).Trim(); + v = str.GetString().ToLowerInvariant().Trim(); } } return v; } - private static Asn1Object decodeObject( - string v) + private static Asn1Object DecodeObject(string v) { try { @@ -936,8 +891,7 @@ private static Asn1Object decodeObject( } } - private static string stripInternalSpaces( - string str) + private static string StripInternalSpaces(string str) { StringBuilder res = new StringBuilder(); @@ -961,15 +915,10 @@ private static string stripInternalSpaces( return res.ToString(); } - private void AppendValue( - StringBuilder buf, - IDictionary oidSymbols, - DerObjectIdentifier oid, - string val) + private void AppendValue(StringBuilder buf, IDictionary oidSymbols, + DerObjectIdentifier oid, string val) { - string sym = (string)oidSymbols[oid]; - - if (sym != null) + if (oidSymbols.TryGetValue(oid, out var sym)) { buf.Append(sym); } @@ -986,7 +935,7 @@ private void AppendValue( int end = buf.Length; - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(val, "\\#")) + if (val.StartsWith("\\#", StringComparison.OrdinalIgnoreCase)) { index += 2; } @@ -1022,33 +971,23 @@ private void AppendValue( * @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) + public string ToString(bool reverse, IDictionary oidSymbols) { -#if SILVERLIGHT || PORTABLE || NETFX_CORE - List components = new List(); -#else - ArrayList components = new ArrayList(); -#endif + var components = new List(); StringBuilder ava = null; for (int i = 0; i < ordering.Count; i++) { - if ((bool) added[i]) + if (added[i]) { ava.Append('+'); - AppendValue(ava, oidSymbols, - (DerObjectIdentifier)ordering[i], - (string)values[i]); + AppendValue(ava, oidSymbols, ordering[i], values[i]); } else { - ava = new StringBuilder(); - AppendValue(ava, oidSymbols, - (DerObjectIdentifier)ordering[i], - (string)values[i]); + ava = StringBuilderPool.Get(0); //new StringBuilder(); + AppendValue(ava, oidSymbols, ordering[i], values[i]); components.Add(ava); } } @@ -1058,26 +997,26 @@ public string ToString( components.Reverse(); } - StringBuilder buf = new StringBuilder(); + StringBuilder buf = StringBuilderPool.Get(components.Count); //new StringBuilder(); if (components.Count > 0) { - buf.Append(components[0].ToString()); + buf.Append(StringBuilderPool.ReleaseAndGrab(components[0])); for (int i = 1; i < components.Count; ++i) { buf.Append(','); - buf.Append(components[i].ToString()); + buf.Append(StringBuilderPool.ReleaseAndGrab(components[i])); } } - return buf.ToString(); + return StringBuilderPool.ReleaseAndGrab(buf); } string cachedStrRepresentation = null; public override string ToString() { - return cachedStrRepresentation ?? (cachedStrRepresentation = ToString(DefaultReverse, (IDictionary)DefaultSymbols)); + return cachedStrRepresentation ?? (cachedStrRepresentation = ToString(DefaultReverse, DefaultSymbols)); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/BiometricData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/BiometricData.cs index 5fb0dd9..de6bd1b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/BiometricData.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/BiometricData.cs @@ -37,7 +37,7 @@ public static BiometricData GetInstance( return new BiometricData(Asn1Sequence.GetInstance(obj)); } - throw new ArgumentException("unknown object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } private BiometricData( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/Iso4217CurrencyCode.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/Iso4217CurrencyCode.cs index 66e0dfc..87e732e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/Iso4217CurrencyCode.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/Iso4217CurrencyCode.cs @@ -47,7 +47,7 @@ public static Iso4217CurrencyCode GetInstance( return new Iso4217CurrencyCode(alphabetic.GetString()); } - throw new ArgumentException("unknown object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public Iso4217CurrencyCode( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/MonetaryValue.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/MonetaryValue.cs index 9ce3b11..18cffe2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/MonetaryValue.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/MonetaryValue.cs @@ -1,7 +1,6 @@ #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; @@ -38,7 +37,7 @@ public static MonetaryValue GetInstance( return new MonetaryValue(Asn1Sequence.GetInstance(obj)); } - throw new ArgumentException("unknown object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } private MonetaryValue( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/QCStatement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/QCStatement.cs index 306b99c..30081c3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/QCStatement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/QCStatement.cs @@ -33,7 +33,7 @@ public static QCStatement GetInstance( return new QCStatement(Asn1Sequence.GetInstance(obj)); } - throw new ArgumentException("unknown object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } private QCStatement( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/SemanticsInformation.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/SemanticsInformation.cs index a3998a6..75ee42b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/SemanticsInformation.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/SemanticsInformation.cs @@ -1,9 +1,7 @@ #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.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509.Qualified @@ -41,36 +39,33 @@ public static SemanticsInformation GetInstance( return new SemanticsInformation(Asn1Sequence.GetInstance(obj)); } - throw new ArgumentException("unknown object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } - public SemanticsInformation( - Asn1Sequence seq) + public SemanticsInformation(Asn1Sequence seq) { if (seq.Count < 1) - { throw new ArgumentException("no objects in SemanticsInformation"); - } - IEnumerator e = seq.GetEnumerator(); + var e = seq.GetEnumerator(); e.MoveNext(); - object obj = e.Current; - if (obj is DerObjectIdentifier) + var obj = e.Current; + if (obj is DerObjectIdentifier oid) { - semanticsIdentifier = DerObjectIdentifier.GetInstance(obj); + semanticsIdentifier = oid; if (e.MoveNext()) { - obj = e.Current; + obj = e.Current; } else { - obj = null; + obj = null; } } - if (obj != null) + if (obj != null) { - Asn1Sequence generalNameSeq = Asn1Sequence.GetInstance(obj ); + Asn1Sequence generalNameSeq = Asn1Sequence.GetInstance(obj); nameRegistrationAuthorities = new GeneralName[generalNameSeq.Count]; for (int i= 0; i < generalNameSeq.Count; i++) { @@ -99,7 +94,10 @@ public SemanticsInformation( this.nameRegistrationAuthorities = generalNames; } - public DerObjectIdentifier SemanticsIdentifier { get { return semanticsIdentifier; } } + public DerObjectIdentifier SemanticsIdentifier + { + get { return semanticsIdentifier; } + } public GeneralName[] GetNameRegistrationAuthorities() { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/TypeOfBiometricData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/TypeOfBiometricData.cs index d9f4c76..5099d90 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/TypeOfBiometricData.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/qualified/TypeOfBiometricData.cs @@ -48,7 +48,7 @@ public static TypeOfBiometricData GetInstance( return new TypeOfBiometricData(BiometricDataOid); } - throw new ArgumentException("unknown object in GetInstance: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in GetInstance: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public TypeOfBiometricData( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/sigi/NameOrPseudonym.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/sigi/NameOrPseudonym.cs index f8e46f9..1096640 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/sigi/NameOrPseudonym.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/sigi/NameOrPseudonym.cs @@ -1,7 +1,6 @@ #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.Utilities; @@ -49,7 +48,7 @@ public static NameOrPseudonym GetInstance( return new NameOrPseudonym((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** @@ -98,7 +97,7 @@ private NameOrPseudonym( throw new ArgumentException("Bad sequence size: " + seq.Count); if (!(seq[0] is IAsn1String)) - throw new ArgumentException("Bad object encountered: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(seq[0])); + throw new ArgumentException("Bad object encountered: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(seq[0])); surname = DirectoryString.GetInstance(seq[0]); givenName = Asn1Sequence.GetInstance(seq[1]); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/sigi/PersonalData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/sigi/PersonalData.cs index 9403fad..b117195 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/sigi/PersonalData.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x509/sigi/PersonalData.cs @@ -1,7 +1,6 @@ #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.Math; @@ -32,7 +31,7 @@ public class PersonalData { private readonly NameOrPseudonym nameOrPseudonym; private readonly BigInteger nameDistinguisher; - private readonly DerGeneralizedTime dateOfBirth; + private readonly Asn1GeneralizedTime dateOfBirth; private readonly DirectoryString placeOfBirth; private readonly string gender; private readonly DirectoryString postalAddress; @@ -50,7 +49,7 @@ public static PersonalData GetInstance( return new PersonalData((Asn1Sequence) obj); } - throw new ArgumentException("unknown object in factory: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("unknown object in factory: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } /** @@ -71,13 +70,12 @@ public static PersonalData GetInstance( * * @param seq The ASN.1 sequence. */ - private PersonalData( - Asn1Sequence seq) + private PersonalData(Asn1Sequence seq) { if (seq.Count < 1) throw new ArgumentException("Bad sequence size: " + seq.Count); - IEnumerator e = seq.GetEnumerator(); + var e = seq.GetEnumerator(); e.MoveNext(); nameOrPseudonym = NameOrPseudonym.GetInstance(e.Current); @@ -88,23 +86,23 @@ private PersonalData( int tag = o.TagNo; switch (tag) { - case 0: - nameDistinguisher = DerInteger.GetInstance(o, false).Value; - break; - case 1: - dateOfBirth = DerGeneralizedTime.GetInstance(o, false); - break; - case 2: - placeOfBirth = DirectoryString.GetInstance(o, true); - break; - case 3: - gender = DerPrintableString.GetInstance(o, false).GetString(); - break; - case 4: - postalAddress = DirectoryString.GetInstance(o, true); - break; - default: - throw new ArgumentException("Bad tag number: " + o.TagNo); + case 0: + nameDistinguisher = DerInteger.GetInstance(o, false).Value; + break; + case 1: + dateOfBirth = Asn1GeneralizedTime.GetInstance(o, false); + break; + case 2: + placeOfBirth = DirectoryString.GetInstance(o, true); + break; + case 3: + gender = DerPrintableString.GetInstance(o, false).GetString(); + break; + case 4: + postalAddress = DirectoryString.GetInstance(o, true); + break; + default: + throw new ArgumentException("Bad tag number: " + o.TagNo); } } } @@ -122,7 +120,7 @@ private PersonalData( public PersonalData( NameOrPseudonym nameOrPseudonym, BigInteger nameDistinguisher, - DerGeneralizedTime dateOfBirth, + Asn1GeneralizedTime dateOfBirth, DirectoryString placeOfBirth, string gender, DirectoryString postalAddress) @@ -145,7 +143,7 @@ public BigInteger NameDistinguisher get { return nameDistinguisher; } } - public DerGeneralizedTime DateOfBirth + public Asn1GeneralizedTime DateOfBirth { get { return dateOfBirth; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/DHDomainParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/DHDomainParameters.cs index 732a6dd..6b4c1a0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/DHDomainParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/DHDomainParameters.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -26,7 +26,7 @@ public static DHDomainParameters GetInstance(object obj) if (obj is Asn1Sequence) return new DHDomainParameters((Asn1Sequence)obj); - throw new ArgumentException("Invalid DHDomainParameters: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Invalid DHDomainParameters: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public DHDomainParameters(DerInteger p, DerInteger g, DerInteger q, DerInteger j, @@ -51,7 +51,7 @@ private DHDomainParameters(Asn1Sequence seq) if (seq.Count < 3 || seq.Count > 5) throw new ArgumentException("Bad sequence size: " + seq.Count, "seq"); - IEnumerator e = seq.GetEnumerator(); + var e = seq.GetEnumerator(); this.p = DerInteger.GetInstance(GetNext(e)); this.g = DerInteger.GetInstance(GetNext(e)); this.q = DerInteger.GetInstance(GetNext(e)); @@ -70,7 +70,7 @@ private DHDomainParameters(Asn1Sequence seq) } } - private static Asn1Encodable GetNext(IEnumerator e) + private static Asn1Encodable GetNext(IEnumerator e) { return e.MoveNext() ? (Asn1Encodable)e.Current : null; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/DHPublicKey.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/DHPublicKey.cs index 3009c80..852baa1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/DHPublicKey.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/DHPublicKey.cs @@ -24,7 +24,7 @@ public static DHPublicKey GetInstance(object obj) if (obj is DerInteger) return new DHPublicKey((DerInteger)obj); - throw new ArgumentException("Invalid DHPublicKey: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Invalid DHPublicKey: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public DHPublicKey(DerInteger y) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/DHValidationParms.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/DHValidationParms.cs index aa897ea..a787f39 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/DHValidationParms.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/DHValidationParms.cs @@ -25,7 +25,7 @@ public static DHValidationParms GetInstance(object obj) if (obj is Asn1Sequence) return new DHValidationParms((Asn1Sequence)obj); - throw new ArgumentException("Invalid DHValidationParms: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); + throw new ArgumentException("Invalid DHValidationParms: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj), "obj"); } public DHValidationParms(DerBitString seed, DerInteger pgenCounter) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/ECNamedCurveTable.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/ECNamedCurveTable.cs index 90a4e8b..9a33f70 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/ECNamedCurveTable.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/ECNamedCurveTable.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Anssi; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro; @@ -9,23 +9,14 @@ 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.Utilities; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9 { - /** - * A general class that reads all X9.62 style EC curve tables. - */ + /// A unified elliptic curve registry of the various standard-specific registries. public class ECNamedCurveTable { - /** - * return a X9ECParameters object representing the passed in named - * curve. The routine returns null if the curve is not present. - * - * @param name the name of the curve requested - * @return an X9ECParameters object or null if the curve is not available. - */ + /// Look up the for the curve with the given name. + /// The name of the curve. public static X9ECParameters GetByName(string name) { X9ECParameters ecP = X962NamedCurves.GetByName(name); @@ -47,7 +38,7 @@ public static X9ECParameters GetByName(string name) } if (ecP == null) { - ecP = ECGost3410NamedCurves.GetByNameX9(name); + ecP = ECGost3410NamedCurves.GetByName(name); } if (ecP == null) { @@ -56,6 +47,112 @@ public static X9ECParameters GetByName(string name) return ecP; } + /// Look up an for the curve with the given name. + /// + /// Allows accessing the curve without necessarily triggering the creation of + /// the full . + /// + /// The name of the curve. + public static X9ECParametersHolder GetByNameLazy(string name) + { + X9ECParametersHolder holder = X962NamedCurves.GetByNameLazy(name); + if (null == holder) + { + holder = SecNamedCurves.GetByNameLazy(name); + } + if (null == holder) + { + holder = NistNamedCurves.GetByNameLazy(name); + } + if (null == holder) + { + holder = TeleTrusTNamedCurves.GetByNameLazy(name); + } + if (null == holder) + { + holder = AnssiNamedCurves.GetByNameLazy(name); + } + if (null == holder) + { + holder = ECGost3410NamedCurves.GetByNameLazy(name); + } + if (null == holder) + { + holder = GMNamedCurves.GetByNameLazy(name); + } + return holder; + } + + /// Look up the for the curve with the given + /// OID. + /// The OID for the curve. + public static X9ECParameters GetByOid(DerObjectIdentifier oid) + { + X9ECParameters ecP = X962NamedCurves.GetByOid(oid); + if (ecP == null) + { + ecP = SecNamedCurves.GetByOid(oid); + } + + // NOTE: All the NIST curves are currently from SEC, so no point in redundant OID lookup + + if (ecP == null) + { + ecP = TeleTrusTNamedCurves.GetByOid(oid); + } + if (ecP == null) + { + ecP = AnssiNamedCurves.GetByOid(oid); + } + if (ecP == null) + { + ecP = ECGost3410NamedCurves.GetByOid(oid); + } + if (ecP == null) + { + ecP = GMNamedCurves.GetByOid(oid); + } + return ecP; + } + + /// Look up an for the curve with the given + /// OID. + /// + /// Allows accessing the curve without necessarily triggering the creation of + /// the full . + /// + /// The OID for the curve. + public static X9ECParametersHolder GetByOidLazy(DerObjectIdentifier oid) + { + X9ECParametersHolder holder = X962NamedCurves.GetByOidLazy(oid); + if (null == holder) + { + holder = SecNamedCurves.GetByOidLazy(oid); + } + + // NOTE: All the NIST curves are currently from SEC, so no point in redundant OID lookup + + if (null == holder) + { + holder = TeleTrusTNamedCurves.GetByOidLazy(oid); + } + if (null == holder) + { + holder = AnssiNamedCurves.GetByOidLazy(oid); + } + if (null == holder) + { + holder = ECGost3410NamedCurves.GetByOidLazy(oid); + } + if (null == holder) + { + holder = GMNamedCurves.GetByOidLazy(oid); + } + return holder; + } + + /// Look up the name of the curve with the given OID. + /// The OID for the curve. public static string GetName(DerObjectIdentifier oid) { string name = X962NamedCurves.GetName(oid); @@ -86,12 +183,8 @@ public static string GetName(DerObjectIdentifier oid) return name; } - /** - * return the object identifier signified by the passed in name. Null - * if there is no object identifier associated with name. - * - * @return the object identifier associated with name, if present. - */ + /// Look up the OID of the curve with the given name. + /// The name of the curve. public static DerObjectIdentifier GetOid(string name) { DerObjectIdentifier oid = X962NamedCurves.GetOid(name); @@ -122,60 +215,20 @@ public static DerObjectIdentifier GetOid(string name) return oid; } - /** - * return a X9ECParameters object representing the passed in named - * curve. - * - * @param oid the object id of the curve requested - * @return an X9ECParameters object or null if the curve is not available. - */ - public static X9ECParameters GetByOid(DerObjectIdentifier oid) - { - X9ECParameters ecP = X962NamedCurves.GetByOid(oid); - if (ecP == null) - { - ecP = SecNamedCurves.GetByOid(oid); - } - - // NOTE: All the NIST curves are currently from SEC, so no point in redundant OID lookup - - if (ecP == null) - { - ecP = TeleTrusTNamedCurves.GetByOid(oid); - } - if (ecP == null) - { - ecP = AnssiNamedCurves.GetByOid(oid); - } - if (ecP == null) - { - ecP = ECGost3410NamedCurves.GetByOidX9(oid); - } - if (ecP == null) - { - ecP = GMNamedCurves.GetByOid(oid); - } - return ecP; - } - - /** - * return an enumeration of the names of the available curves. - * - * @return an enumeration of the names of the available curves. - */ - public static IEnumerable Names + /// Enumerate the available curve names in all the registries. + public static IEnumerable Names { get { - IList v = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); - CollectionUtilities.AddRange(v, X962NamedCurves.Names); - CollectionUtilities.AddRange(v, SecNamedCurves.Names); - CollectionUtilities.AddRange(v, NistNamedCurves.Names); - CollectionUtilities.AddRange(v, TeleTrusTNamedCurves.Names); - CollectionUtilities.AddRange(v, AnssiNamedCurves.Names); - CollectionUtilities.AddRange(v, ECGost3410NamedCurves.Names); - CollectionUtilities.AddRange(v, GMNamedCurves.Names); - return v; + var result = new List(); + result.AddRange(X962NamedCurves.Names); + result.AddRange(SecNamedCurves.Names); + result.AddRange(NistNamedCurves.Names); + result.AddRange(TeleTrusTNamedCurves.Names); + result.AddRange(AnssiNamedCurves.Names); + result.AddRange(ECGost3410NamedCurves.Names); + result.AddRange(GMNamedCurves.Names); + return result; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/KeySpecificInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/KeySpecificInfo.cs index 2b47a58..e732e19 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/KeySpecificInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/KeySpecificInfo.cs @@ -1,7 +1,5 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System.Collections; - namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9 { /** @@ -22,10 +20,9 @@ public KeySpecificInfo( this.counter = counter; } - public KeySpecificInfo( - Asn1Sequence seq) + public KeySpecificInfo(Asn1Sequence seq) { - IEnumerator e = seq.GetEnumerator(); + var e = seq.GetEnumerator(); e.MoveNext(); algorithm = (DerObjectIdentifier)e.Current; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/OtherInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/OtherInfo.cs index fafb6b5..54ab5be 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/OtherInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/OtherInfo.cs @@ -1,7 +1,5 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System.Collections; - namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9 { /** @@ -25,25 +23,24 @@ public OtherInfo( this.suppPubInfo = suppPubInfo; } - public OtherInfo( - Asn1Sequence seq) + public OtherInfo(Asn1Sequence seq) { - IEnumerator e = seq.GetEnumerator(); + var e = seq.GetEnumerator(); e.MoveNext(); - keyInfo = new KeySpecificInfo((Asn1Sequence) e.Current); + keyInfo = new KeySpecificInfo((Asn1Sequence)e.Current); while (e.MoveNext()) { - DerTaggedObject o = (DerTaggedObject) e.Current; + Asn1TaggedObject o = (Asn1TaggedObject)e.Current; if (o.TagNo == 0) { - partyAInfo = (Asn1OctetString) o.GetObject(); + partyAInfo = (Asn1OctetString)o.GetObject(); } else if ((int) o.TagNo == 2) { - suppPubInfo = (Asn1OctetString) o.GetObject(); + suppPubInfo = (Asn1OctetString)o.GetObject(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X962NamedCurves.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X962NamedCurves.cs index 11087ee..1e6f15c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X962NamedCurves.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X962NamedCurves.cs @@ -1,26 +1,19 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9 { - /** - * table of the current named curves defined in X.962 EC-DSA. - */ - public sealed class X962NamedCurves + /// Elliptic curve registry for the curves defined in X.962 EC-DSA. + public static class X962NamedCurves { - private X962NamedCurves() - { - } - private static X9ECPoint ConfigureBasepoint(ECCurve curve, string encoding) { X9ECPoint G = new X9ECPoint(curve, Hex.DecodeStrict(encoding)); @@ -45,21 +38,27 @@ private Prime192v1Holder() {} internal static readonly X9ECParametersHolder Instance = new Prime192v1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("ffffffffffffffffffffffff99def836146bc9b1b4d22831"); BigInteger h = BigInteger.One; - ECCurve curve = ConfigureCurve(new FpCurve( + return ConfigureCurve(new FpCurve( FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"), FromHex("fffffffffffffffffffffffffffffffefffffffffffffffc"), FromHex("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1"), - n, h)); + n, h, true)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = Hex.DecodeStrict("3045AE6FC8422f64ED579528D38120EAE12196D5"); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012"); - return new X9ECParameters(curve, G, n, h, Hex.DecodeStrict("3045AE6FC8422f64ED579528D38120EAE12196D5")); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -70,21 +69,27 @@ private Prime192v2Holder() {} internal static readonly X9ECParametersHolder Instance = new Prime192v2Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("fffffffffffffffffffffffe5fb1a724dc80418648d8dd31"); BigInteger h = BigInteger.One; - ECCurve curve = ConfigureCurve(new FpCurve( + return ConfigureCurve(new FpCurve( FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"), FromHex("fffffffffffffffffffffffffffffffefffffffffffffffc"), FromHex("cc22d6dfb95c6b25e49c0d6364a4e5980c393aa21668d953"), - n, h)); + n, h, true)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = Hex.DecodeStrict("31a92ee2029fd10d901b113e990710f0d21ac6b6"); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "03eea2bae7e1497842f2de7769cfe9c989c072ad696f48034a"); - return new X9ECParameters(curve, G, n, h, Hex.DecodeStrict("31a92ee2029fd10d901b113e990710f0d21ac6b6")); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -95,21 +100,27 @@ private Prime192v3Holder() {} internal static readonly X9ECParametersHolder Instance = new Prime192v3Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("ffffffffffffffffffffffff7a62d031c83f4294f640ec13"); BigInteger h = BigInteger.One; - ECCurve curve = ConfigureCurve(new FpCurve( + return ConfigureCurve(new FpCurve( FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"), FromHex("fffffffffffffffffffffffffffffffefffffffffffffffc"), FromHex("22123dc2395a05caa7423daeccc94760a7d462256bd56916"), - n, h)); + n, h, true)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = Hex.DecodeStrict("c469684435deb378c4b65ca9591e2a5763059a2e"); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "027d29778100c65a1da1783716588dce2b8b4aee8e228f1896"); - return new X9ECParameters(curve, G, n, h, Hex.DecodeStrict("c469684435deb378c4b65ca9591e2a5763059a2e")); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -120,21 +131,27 @@ private Prime239v1Holder() {} internal static readonly X9ECParametersHolder Instance = new Prime239v1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("7fffffffffffffffffffffff7fffff9e5e9a9f5d9071fbd1522688909d0b"); BigInteger h = BigInteger.One; - ECCurve curve = ConfigureCurve(new FpCurve( + return ConfigureCurve(new FpCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), FromHex("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc"), FromHex("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a"), - n, h)); + n, h, true)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = Hex.DecodeStrict("e43bb460f0b80cc0c0b075798e948060f8321b7d"); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf"); - return new X9ECParameters(curve, G, n, h, Hex.DecodeStrict("e43bb460f0b80cc0c0b075798e948060f8321b7d")); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -145,21 +162,27 @@ private Prime239v2Holder() {} internal static readonly X9ECParametersHolder Instance = new Prime239v2Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("7fffffffffffffffffffffff800000cfa7e8594377d414c03821bc582063"); BigInteger h = BigInteger.One; - ECCurve curve = ConfigureCurve(new FpCurve( + return ConfigureCurve(new FpCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), FromHex("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc"), FromHex("617fab6832576cbbfed50d99f0249c3fee58b94ba0038c7ae84c8c832f2c"), - n, h)); + n, h, true)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = Hex.DecodeStrict("e8b4011604095303ca3b8099982be09fcb9ae616"); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "0238af09d98727705120c921bb5e9e26296a3cdcf2f35757a0eafd87b830e7"); - return new X9ECParameters(curve, G, n, h, Hex.DecodeStrict("e8b4011604095303ca3b8099982be09fcb9ae616")); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -170,21 +193,27 @@ private Prime239v3Holder() {} internal static readonly X9ECParametersHolder Instance = new Prime239v3Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("7fffffffffffffffffffffff7fffff975deb41b3a6057c3c432146526551"); BigInteger h = BigInteger.One; - ECCurve curve = ConfigureCurve(new FpCurve( + return ConfigureCurve(new FpCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), FromHex("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc"), FromHex("255705fa2a306654b1f4cb03d6a750a30c250102d4988717d9ba15ab6d3e"), - n, h)); + n, h, true)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = Hex.DecodeStrict("7d7374168ffe3471b60a857686a19475d3bfa2ff"); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "036768ae8e18bb92cfcf005c949aa2c6d94853d0e660bbf854b1c9505fe95a"); - return new X9ECParameters(curve, G, n, h, Hex.DecodeStrict("7d7374168ffe3471b60a857686a19475d3bfa2ff")); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -195,27 +224,30 @@ private Prime256v1Holder() {} internal static readonly X9ECParametersHolder Instance = new Prime256v1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"); BigInteger h = BigInteger.One; - ECCurve curve = ConfigureCurve(new FpCurve( + return ConfigureCurve(new FpCurve( new BigInteger("115792089210356248762697446949407573530086143415290314195533631308867097853951"), FromHex("ffffffff00000001000000000000000000000000fffffffffffffffffffffffc"), FromHex("5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"), - n, h)); + n, h, true)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = Hex.DecodeStrict("c49d360886e704936a6678e1139d26b7819f7e90"); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "036b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"); - return new X9ECParameters(curve, G, n, h, Hex.DecodeStrict("c49d360886e704936a6678e1139d26b7819f7e90")); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } - /* - * F2m Curves - */ internal class C2pnb163v1Holder : X9ECParametersHolder { @@ -223,22 +255,28 @@ private C2pnb163v1Holder() {} internal static readonly X9ECParametersHolder Instance = new C2pnb163v1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("0400000000000000000001E60FC8821CC74DAEAFC1"); BigInteger h = BigInteger.Two; - ECCurve curve = ConfigureCurve(new F2mCurve( + return ConfigureCurve(new F2mCurve( 163, 1, 2, 8, FromHex("072546B5435234A422E0789675F432C89435DE5242"), FromHex("00C9517D06D5240D3CFF38C74B20B6CD4D6F9DD4D9"), n, h)); + } + protected override X9ECParameters CreateParameters() + { + byte[] S = Hex.DecodeStrict("D2C0FB15760860DEF1EEF4D696E6768756151754"); + ECCurve curve = Curve; + X9ECPoint G = ConfigureBasepoint(curve, "0307AF69989546103D79329FCC3D74880F33BBE803CB"); - return new X9ECParameters(curve, G, n, h, Hex.DecodeStrict("D2C0FB15760860DEF1EEF4D696E6768756151754")); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -249,22 +287,28 @@ private C2pnb163v2Holder() {} internal static readonly X9ECParametersHolder Instance = new C2pnb163v2Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFDF64DE1151ADBB78F10A7"); BigInteger h = BigInteger.Two; - ECCurve curve = ConfigureCurve(new F2mCurve( + return ConfigureCurve(new F2mCurve( 163, 1, 2, 8, FromHex("0108B39E77C4B108BED981ED0E890E117C511CF072"), FromHex("0667ACEB38AF4E488C407433FFAE4F1C811638DF20"), n, h)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "030024266E4EB5106D0A964D92C4860E2671DB9B6CC5"); - return new X9ECParameters(curve, G, n, h); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -275,22 +319,28 @@ private C2pnb163v3Holder() {} internal static readonly X9ECParametersHolder Instance = new C2pnb163v3Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFE1AEE140F110AFF961309"); BigInteger h = BigInteger.Two; - ECCurve curve = ConfigureCurve(new F2mCurve( + return ConfigureCurve(new F2mCurve( 163, 1, 2, 8, FromHex("07A526C63D3E25A256A007699F5447E32AE456B50E"), FromHex("03F7061798EB99E238FD6F1BF95B48FEEB4854252B"), n, h)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "0202F9F87B7C574D0BDECF8A22E6524775F98CDEBDCB"); - return new X9ECParameters(curve, G, n, h); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -301,22 +351,28 @@ private C2pnb176w1Holder() {} internal static readonly X9ECParametersHolder Instance = new C2pnb176w1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("010092537397ECA4F6145799D62B0A19CE06FE26AD"); BigInteger h = BigInteger.ValueOf(0xFF6E); - ECCurve curve = ConfigureCurve(new F2mCurve( + return ConfigureCurve(new F2mCurve( 176, 1, 2, 43, FromHex("E4E6DB2995065C407D9D39B8D0967B96704BA8E9C90B"), FromHex("5DDA470ABE6414DE8EC133AE28E9BBD7FCEC0AE0FFF2"), n, h)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "038D16C2866798B600F9F08BB4A8E860F3298CE04A5798"); - return new X9ECParameters(curve, G, n, h); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -327,22 +383,28 @@ private C2tnb191v1Holder() {} internal static readonly X9ECParametersHolder Instance = new C2tnb191v1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("40000000000000000000000004A20E90C39067C893BBB9A5"); BigInteger h = BigInteger.Two; - ECCurve curve = ConfigureCurve(new F2mCurve( + return ConfigureCurve(new F2mCurve( 191, 9, FromHex("2866537B676752636A68F56554E12640276B649EF7526267"), FromHex("2E45EF571F00786F67B0081B9495A3D95462F5DE0AA185EC"), n, h)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = Hex.DecodeStrict("4E13CA542744D696E67687561517552F279A8C84"); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "0236B3DAF8A23206F9C4F299D7B21A9C369137F2C84AE1AA0D"); - return new X9ECParameters(curve, G, n, h, Hex.DecodeStrict("4E13CA542744D696E67687561517552F279A8C84")); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -353,22 +415,28 @@ private C2tnb191v2Holder() {} internal static readonly X9ECParametersHolder Instance = new C2tnb191v2Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("20000000000000000000000050508CB89F652824E06B8173"); BigInteger h = BigInteger.ValueOf(4); - ECCurve curve = ConfigureCurve(new F2mCurve( + return ConfigureCurve(new F2mCurve( 191, 9, FromHex("401028774D7777C7B7666D1366EA432071274F89FF01E718"), FromHex("0620048D28BCBD03B6249C99182B7C8CD19700C362C46A01"), n, h)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "023809B2B7CC1B28CC5A87926AAD83FD28789E81E2C9E3BF10"); - return new X9ECParameters(curve, G, n, h); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -379,22 +447,28 @@ private C2tnb191v3Holder() {} internal static readonly X9ECParametersHolder Instance = new C2tnb191v3Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("155555555555555555555555610C0B196812BFB6288A3EA3"); BigInteger h = BigInteger.ValueOf(6); - ECCurve curve = ConfigureCurve(new F2mCurve( + return ConfigureCurve(new F2mCurve( 191, 9, FromHex("6C01074756099122221056911C77D77E77A777E7E7E77FCB"), FromHex("71FE1AF926CF847989EFEF8DB459F66394D90F32AD3F15E8"), n, h)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "03375D4CE24FDE434489DE8746E71786015009E66E38A926DD"); - return new X9ECParameters(curve, G, n, h); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -405,22 +479,28 @@ private C2pnb208w1Holder() {} internal static readonly X9ECParametersHolder Instance = new C2pnb208w1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("0101BAF95C9723C57B6C21DA2EFF2D5ED588BDD5717E212F9D"); BigInteger h = BigInteger.ValueOf(0xFE48); - ECCurve curve = ConfigureCurve(new F2mCurve( + return ConfigureCurve(new F2mCurve( 208, 1, 2, 83, BigInteger.Zero, FromHex("C8619ED45A62E6212E1160349E2BFA844439FAFC2A3FD1638F9E"), n, h)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "0289FDFBE4ABE193DF9559ECF07AC0CE78554E2784EB8C1ED1A57A"); - return new X9ECParameters(curve, G, n, h); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -431,22 +511,28 @@ private C2tnb239v1Holder() {} internal static readonly X9ECParametersHolder Instance = new C2tnb239v1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("2000000000000000000000000000000F4D42FFE1492A4993F1CAD666E447"); BigInteger h = BigInteger.ValueOf(4); - ECCurve curve = ConfigureCurve(new F2mCurve( + return ConfigureCurve(new F2mCurve( 239, 36, FromHex("32010857077C5431123A46B808906756F543423E8D27877578125778AC76"), FromHex("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16"), n, h)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "0257927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D"); - return new X9ECParameters(curve, G, n, h); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -457,22 +543,28 @@ private C2tnb239v2Holder() {} internal static readonly X9ECParametersHolder Instance = new C2tnb239v2Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("1555555555555555555555555555553C6F2885259C31E3FCDF154624522D"); BigInteger h = BigInteger.ValueOf(6); - ECCurve curve = ConfigureCurve(new F2mCurve( + return ConfigureCurve(new F2mCurve( 239, 36, FromHex("4230017757A767FAE42398569B746325D45313AF0766266479B75654E65F"), FromHex("5037EA654196CFF0CD82B2C14A2FCF2E3FF8775285B545722F03EACDB74B"), n, h)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "0228F9D04E900069C8DC47A08534FE76D2B900B7D7EF31F5709F200C4CA205"); - return new X9ECParameters(curve, G, n, h); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -483,22 +575,28 @@ private C2tnb239v3Holder() {} internal static readonly X9ECParametersHolder Instance = new C2tnb239v3Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("0CCCCCCCCCCCCCCCCCCCCCCCCCCCCCAC4912D2D9DF903EF9888B8A0E4CFF"); BigInteger h = BigInteger.ValueOf(10); - ECCurve curve = ConfigureCurve(new F2mCurve( + return ConfigureCurve(new F2mCurve( 239, 36, FromHex("01238774666A67766D6676F778E676B66999176666E687666D8766C66A9F"), FromHex("6A941977BA9F6A435199ACFC51067ED587F519C5ECB541B8E44111DE1D40"), n, h)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "0370F6E9D04D289C4E89913CE3530BFDE903977D42B146D539BF1BDE4E9C92"); - return new X9ECParameters(curve, G, n, h); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -509,22 +607,28 @@ private C2pnb272w1Holder() {} internal static readonly X9ECParametersHolder Instance = new C2pnb272w1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("0100FAF51354E0E39E4892DF6E319C72C8161603FA45AA7B998A167B8F1E629521"); BigInteger h = BigInteger.ValueOf(0xFF06); - ECCurve curve = ConfigureCurve(new F2mCurve( + return ConfigureCurve(new F2mCurve( 272, 1, 3, 56, FromHex("91A091F03B5FBA4AB2CCF49C4EDD220FB028712D42BE752B2C40094DBACDB586FB20"), FromHex("7167EFC92BB2E3CE7C8AAAFF34E12A9C557003D7C73A6FAF003F99F6CC8482E540F7"), n, h)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "026108BABB2CEEBCF787058A056CBE0CFE622D7723A289E08A07AE13EF0D10D171DD8D"); - return new X9ECParameters(curve, G, n, h); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -535,22 +639,28 @@ private C2pnb304w1Holder() {} internal static readonly X9ECParametersHolder Instance = new C2pnb304w1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("0101D556572AABAC800101D556572AABAC8001022D5C91DD173F8FB561DA6899164443051D"); BigInteger h = BigInteger.ValueOf(0xFE2E); - ECCurve curve = ConfigureCurve(new F2mCurve( + return ConfigureCurve(new F2mCurve( 304, 1, 2, 11, FromHex("FD0D693149A118F651E6DCE6802085377E5F882D1B510B44160074C1288078365A0396C8E681"), FromHex("BDDB97E555A50A908E43B01C798EA5DAA6788F1EA2794EFCF57166B8C14039601E55827340BE"), n, h)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "02197B07845E9BE2D96ADB0F5F3C7F2CFFBD7A3EB8B6FEC35C7FD67F26DDF6285A644F740A2614"); - return new X9ECParameters(curve, G, n, h); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -561,22 +671,28 @@ private C2tnb359v1Holder() {} internal static readonly X9ECParametersHolder Instance = new C2tnb359v1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("01AF286BCA1AF286BCA1AF286BCA1AF286BCA1AF286BC9FB8F6B85C556892C20A7EB964FE7719E74F490758D3B"); BigInteger h = BigInteger.ValueOf(0x4C); - ECCurve curve = ConfigureCurve(new F2mCurve( + return ConfigureCurve(new F2mCurve( 359, 68, FromHex("5667676A654B20754F356EA92017D946567C46675556F19556A04616B567D223A5E05656FB549016A96656A557"), FromHex("2472E2D0197C49363F1FE7F5B6DB075D52B6947D135D8CA445805D39BC345626089687742B6329E70680231988"), n, h)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "033C258EF3047767E7EDE0F1FDAA79DAEE3841366A132E163ACED4ED2401DF9C6BDCDE98E8E707C07A2239B1B097"); - return new X9ECParameters(curve, G, n, h); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -587,22 +703,28 @@ private C2pnb368w1Holder() {} internal static readonly X9ECParametersHolder Instance = new C2pnb368w1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("010090512DA9AF72B08349D98A5DD4C7B0532ECA51CE03E2D10F3B7AC579BD87E909AE40A6F131E9CFCE5BD967"); BigInteger h = BigInteger.ValueOf(0xFF70); - ECCurve curve = ConfigureCurve(new F2mCurve( + return ConfigureCurve(new F2mCurve( 368, 1, 2, 85, FromHex("E0D2EE25095206F5E2A4F9ED229F1F256E79A0E2B455970D8D0D865BD94778C576D62F0AB7519CCD2A1A906AE30D"), FromHex("FC1217D4320A90452C760A58EDCD30C8DD069B3C34453837A34ED50CB54917E1C2112D84D164F444F8F74786046A"), n, h)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "021085E2755381DCCCE3C1557AFA10C2F0C0C2825646C5B34A394CBCFA8BC16B22E7E789E927BE216F02E1FB136A5F"); - return new X9ECParameters(curve, G, n, h); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } @@ -613,36 +735,41 @@ private C2tnb431r1Holder() {} internal static readonly X9ECParametersHolder Instance = new C2tnb431r1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { BigInteger n = FromHex("0340340340340340340340340340340340340340340340340340340323C313FAB50589703B5EC68D3587FEC60D161CC149C1AD4A91"); BigInteger h = BigInteger.ValueOf(0x2760); - ECCurve curve = ConfigureCurve(new F2mCurve( + return ConfigureCurve(new F2mCurve( 431, 120, FromHex("1A827EF00DD6FC0E234CAF046C6A5D8A85395B236CC4AD2CF32A0CADBDC9DDF620B0EB9906D0957F6C6FEACD615468DF104DE296CD8F"), FromHex("10D9B4A3D9047D8B154359ABFB1B7F5485B04CEB868237DDC9DEDA982A679A5A919B626D4E50A8DD731B107A9962381FB5D807BF2618"), n, h)); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "02120FC05D3C67A99DE161D2F4092622FECA701BE4F50F4758714E8A87BBF2A658EF8C21E7C5EFE965361F6C2999C0C247B0DBD70CE6B7"); - return new X9ECParameters(curve, G, n, h); + return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } + private static readonly Dictionary objIds = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly Dictionary curves = + new Dictionary(); + private static readonly Dictionary names = + new Dictionary(); - private static readonly IDictionary objIds = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private static readonly IDictionary curves = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private static readonly IDictionary names = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - - private static void DefineCurve( - string name, - DerObjectIdentifier oid, - X9ECParametersHolder holder) + private static void DefineCurve(string name, DerObjectIdentifier oid, X9ECParametersHolder holder) { - objIds.Add(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(name), oid); + objIds.Add(name, oid); names.Add(oid, name); curves.Add(oid, holder); } @@ -674,54 +801,64 @@ static X962NamedCurves() DefineCurve("c2tnb431r1", X9ObjectIdentifiers.C2Tnb431r1, C2tnb431r1Holder.Instance); } - public static X9ECParameters GetByName( - string name) + /// Look up the for the curve with the given name. + /// The name of the curve. + public static X9ECParameters GetByName(string name) { DerObjectIdentifier oid = GetOid(name); return oid == null ? null : GetByOid(oid); } - /** - * return the X9ECParameters object for the named curve represented by - * the passed in object identifier. Null if the curve isn't present. - * - * @param oid an object identifier representing a named curve, if present. - */ - public static X9ECParameters GetByOid( - DerObjectIdentifier oid) + /// Look up an for the curve with the given name. + /// + /// Allows accessing the curve without necessarily triggering the creation of the + /// full . + /// + /// The name of the curve. + public static X9ECParametersHolder GetByNameLazy(string name) + { + DerObjectIdentifier oid = GetOid(name); + return oid == null ? null : GetByOidLazy(oid); + } + + /// Look up the for the curve with the given + /// OID. + /// The OID for the curve. + public static X9ECParameters GetByOid(DerObjectIdentifier oid) + { + return GetByOidLazy(oid)?.Parameters; + } + + /// Look up an for the curve with the given + /// OID. + /// + /// Allows accessing the curve without necessarily triggering the creation of the + /// full . + /// + /// The OID for the curve. + public static X9ECParametersHolder GetByOidLazy(DerObjectIdentifier oid) { - X9ECParametersHolder holder = (X9ECParametersHolder)curves[oid]; - return holder == null ? null : holder.Parameters; + return CollectionUtilities.GetValueOrNull(curves, oid); } - /** - * return the object identifier signified by the passed in name. Null - * if there is no object identifier associated with name. - * - * @return the object identifier associated with name, if present. - */ - public static DerObjectIdentifier GetOid( - string name) + /// Look up the name of the curve with the given OID. + /// The OID for the curve. + public static string GetName(DerObjectIdentifier oid) { - return (DerObjectIdentifier)objIds[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(name)]; + return CollectionUtilities.GetValueOrNull(names, oid); } - /** - * return the named curve name represented by the given object identifier. - */ - public static string GetName( - DerObjectIdentifier oid) + /// Look up the OID of the curve with the given name. + /// The name of the curve. + public static DerObjectIdentifier GetOid(string name) { - return (string)names[oid]; + return CollectionUtilities.GetValueOrNull(objIds, name); } - /** - * returns an enumeration containing the name strings for curves - * contained in this structure. - */ - public static IEnumerable Names + /// Enumerate the available curve names in this registry. + public static IEnumerable Names { - get { return new EnumerableProxy(names.Values); } + get { return CollectionUtilities.Proxy(objIds.Keys); } } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X962Parameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X962Parameters.cs index d2652bc..782af7c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X962Parameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X962Parameters.cs @@ -57,9 +57,7 @@ public X962Parameters( this._params = obj; } - - public X962Parameters( - Asn1Object obj) + private X962Parameters(Asn1Object obj) { this._params = obj; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9Curve.cs index ff9f21c..78f4384 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9Curve.cs @@ -49,14 +49,6 @@ public X9Curve( } } - - public X9Curve( - X9FieldID fieldID, - Asn1Sequence seq) - : this(fieldID, null, null, seq) - { - } - public X9Curve( X9FieldID fieldID, BigInteger order, diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9ECParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9ECParameters.cs index 21c40a9..77a74b0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9ECParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9ECParameters.cs @@ -22,7 +22,7 @@ public class X9ECParameters private BigInteger h; private byte[] seed; - public static X9ECParameters GetInstance(Object obj) + public static X9ECParameters GetInstance(object obj) { if (obj is X9ECParameters) return (X9ECParameters)obj; @@ -69,9 +69,9 @@ public X9ECParameters( } public X9ECParameters( - ECCurve curve, - ECPoint g, - BigInteger n) + ECCurve curve, + X9ECPoint g, + BigInteger n) : this(curve, g, n, null, null) { } @@ -85,25 +85,6 @@ public X9ECParameters( { } - public X9ECParameters( - ECCurve curve, - ECPoint g, - BigInteger n, - BigInteger h) - : this(curve, g, n, h, null) - { - } - - public X9ECParameters( - ECCurve curve, - ECPoint g, - BigInteger n, - BigInteger h, - byte[] seed) - : this(curve, new X9ECPoint(g), n, h, seed) - { - } - public X9ECParameters( ECCurve curve, X9ECPoint g, diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9ECParametersHolder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9ECParametersHolder.cs index 5dba6b5..09eccd8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9ECParametersHolder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9ECParametersHolder.cs @@ -1,28 +1,52 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable +using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC; + namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9 { public abstract class X9ECParametersHolder { - private X9ECParameters parameters; + private ECCurve m_curve; + private X9ECParameters m_parameters; + + public ECCurve Curve + { + get + { + lock (this) + { + if (m_curve == null) + { + m_curve = CreateCurve(); + } - public X9ECParameters Parameters + return m_curve; + } + } + } + + public X9ECParameters Parameters { get { lock (this) { - if (parameters == null) + if (m_parameters == null) { - parameters = CreateParameters(); + m_parameters = CreateParameters(); } - return parameters; + return m_parameters; } } } - protected abstract X9ECParameters CreateParameters(); + protected virtual ECCurve CreateCurve() + { + return CreateParameters().Curve; + } + + protected abstract X9ECParameters CreateParameters(); } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9ECPoint.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9ECPoint.cs index 7ccb21c..b33eba2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9ECPoint.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9ECPoint.cs @@ -17,11 +17,6 @@ public class X9ECPoint private ECCurve c; private ECPoint p; - public X9ECPoint(ECPoint p) - : this(p, false) - { - } - public X9ECPoint(ECPoint p, bool compressed) { this.p = p.Normalize(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9FieldElement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9FieldElement.cs index 7a11e73..84d8e90 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9FieldElement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9FieldElement.cs @@ -21,25 +21,6 @@ public X9FieldElement( this.f = f; } - - public X9FieldElement( - BigInteger p, - Asn1OctetString s) - : this(new FpFieldElement(p, new BigInteger(1, s.GetOctets()))) - { - } - - - 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; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9ObjectIdentifiers.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9ObjectIdentifiers.cs index deb98fd..3a4aa54 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9ObjectIdentifiers.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/asn1/x9/X9ObjectIdentifiers.cs @@ -13,9 +13,7 @@ public abstract class X9ObjectIdentifiers // us(840) ansi-x962(10045) } // - internal const string AnsiX962 = "1.2.840.10045"; - - public static readonly DerObjectIdentifier ansi_X9_62 = new DerObjectIdentifier(AnsiX962); + public static readonly DerObjectIdentifier ansi_X9_62 = new DerObjectIdentifier("1.2.840.10045"); public static readonly DerObjectIdentifier IdFieldType = ansi_X9_62.Branch("1"); @@ -26,14 +24,10 @@ public abstract class X9ObjectIdentifiers public static readonly DerObjectIdentifier TPBasis = CharacteristicTwoField.Branch("3.2"); public static readonly DerObjectIdentifier PPBasis = CharacteristicTwoField.Branch("3.3"); - - public const string IdECSigType = AnsiX962 + ".4"; public static readonly DerObjectIdentifier id_ecSigType = ansi_X9_62.Branch("4"); public static readonly DerObjectIdentifier ECDsaWithSha1 = id_ecSigType.Branch("1"); - - public const string IdPublicKeyType = AnsiX962 + ".2"; public static readonly DerObjectIdentifier id_publicKeyType = ansi_X9_62.Branch("2"); public static readonly DerObjectIdentifier IdECPublicKey = id_publicKeyType.Branch("1"); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ArmoredInputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ArmoredInputStream.cs index 364d25a..10dba57 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ArmoredInputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ArmoredInputStream.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using System.Text; @@ -116,7 +116,7 @@ private static int Decode(int in0, int in1, int in2, int in3, int[] result) bool newLineFound = false; bool clearText = false; bool restart = false; - IList headerList = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + IList headerList = new List(); int lastC = 0; bool isEndOfStream; @@ -160,7 +160,7 @@ private bool ParseHeaders() int last = 0; bool headerFound = false; - headerList = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + headerList = new List(); // // if restart we already have a header @@ -313,6 +313,46 @@ private int ReadIgnoreSpace() return c; } + public override int Read(byte[] buffer, int offset, int count) + { + Streams.ValidateBufferArguments(buffer, offset, count); + + /* + * TODO Currently can't return partial data when exception thrown (breaking test case), so we don't inherit + * the base class implementation. Probably the reason is that throws don't mark this instance as 'failed'. + */ + int pos = 0; + while (pos < count) + { + int b = ReadByte(); + if (b < 0) + break; + + buffer[offset + pos++] = (byte)b; + } + return pos; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int Read(Span buffer) + { + /* + * TODO Currently can't return partial data when exception thrown (breaking test case), so we don't inherit + * the base class implementation. Probably the reason is that throws don't mark this instance as 'failed'. + */ + int pos = 0; + while (pos < buffer.Length) + { + int b = ReadByte(); + if (b < 0) + break; + + buffer[pos++] = (byte)b; + } + return pos; + } +#endif + public override int ReadByte() { if (start) @@ -465,68 +505,14 @@ public override int ReadByte() return c; } - /** - * Reads up to len bytes of data from the input stream into - * an array of bytes. An attempt is made to read as many as - * len bytes, but a smaller number may be read. - * The number of bytes actually read is returned as an integer. - * - * The first byte read is stored into element b[off], the - * next one into b[off+1], and so on. The number of bytes read - * is, at most, equal to len. - * - * NOTE: We need to override the custom behavior of Java's {@link InputStream#read(byte[], int, int)}, - * as the upstream method silently swallows {@link IOException IOExceptions}. - * This would cause CRC checksum errors to go unnoticed. - * - * @see Related BC bug report - * @param b byte array - * @param off offset at which we start writing data to the array - * @param len number of bytes we write into the array - * @return total number of bytes read into the buffer - * - * @throws IOException if an exception happens AT ANY POINT - */ - public override int Read(byte[] b, int off, int len) - { - CheckIndexSize(b.Length, off, len); - - int pos = 0; - while (pos < len) - { - int c = ReadByte(); - if (c < 0) - break; - - b[off + pos++] = (byte)c; - } - return pos; - } - - private void CheckIndexSize(int size, int off, int len) - { - if (off < 0 || len < 0) - throw new IndexOutOfRangeException("Offset and length cannot be negative."); - if (off > size - len) - throw new IndexOutOfRangeException("Invalid offset and length."); - } - -#if PORTABLE || NETFX_CORE protected override void Dispose(bool disposing) { if (disposing) { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(input); + input.Dispose(); } base.Dispose(disposing); } -#else - public override void Close() - { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(input); - base.Close(); - } -#endif /** * Change how the stream should react if it encounters missing CRC checksum. diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ArmoredOutputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ArmoredOutputStream.cs index c9de885..f0fa0bc 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ArmoredOutputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ArmoredOutputStream.cs @@ -1,17 +1,13 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; -using System.Text; - -#if PORTABLE || NETFX_CORE -using System.Linq; -#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Bcpg @@ -99,32 +95,40 @@ private static void Encode( private string type; - private static readonly string nl = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine; + private static readonly string NewLine = Environment.NewLine; private static readonly string headerStart = "-----BEGIN PGP "; private static readonly string headerTail = "-----"; private static readonly string footerStart = "-----END PGP "; private static readonly string footerTail = "-----"; - private static readonly string Version = "BCPG C# v" + HTTPManager.UserAgent; + private static string CreateVersion() + { + var assembly = Assembly.GetExecutingAssembly(); + var title = assembly.GetCustomAttribute().Title; + var version = assembly.GetCustomAttribute().InformationalVersion; + return title + " v" + version; + } + + private static readonly string Version = CreateVersion(); - private readonly IDictionary headers; + private readonly IDictionary> m_headers; public ArmoredOutputStream(Stream outStream) { this.outStream = outStream; - this.headers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(1); + this.m_headers = new Dictionary>(1); SetHeader(HeaderVersion, Version); } - public ArmoredOutputStream(Stream outStream, IDictionary headers) + public ArmoredOutputStream(Stream outStream, IDictionary headers) : this(outStream) { - foreach (string header in headers.Keys) + foreach (var header in headers) { - IList headerList = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(1); - headerList.Add(headers[header]); + var headerList = new List(1); + headerList.Add(header.Value); - this.headers[header] = headerList; + m_headers[header.Key] = headerList; } } @@ -138,22 +142,21 @@ public void SetHeader(string name, string val) { if (val == null) { - this.headers.Remove(name); + this.m_headers.Remove(name); + return; + } + + if (m_headers.TryGetValue(name, out var valueList)) + { + valueList.Clear(); } else { - IList valueList = (IList)headers[name]; - if (valueList == null) - { - valueList = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(1); - this.headers[name] = valueList; - } - else - { - valueList.Clear(); - } - valueList.Add(val); + valueList = new List(1); + m_headers[name] = valueList; } + + valueList.Add(val); } /** @@ -168,12 +171,12 @@ public void AddHeader(string name, string val) if (val == null || name == null) return; - IList valueList = (IList)headers[name]; - if (valueList == null) + if (!m_headers.TryGetValue(name, out var valueList)) { - valueList = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(1); - this.headers[name] = valueList; + valueList = new List(1); + m_headers[name] = valueList; } + valueList.Add(val); } @@ -182,13 +185,13 @@ public void AddHeader(string name, string val) */ public void ResetHeaders() { - IList versions = (IList)headers[HeaderVersion]; + var versions = CollectionUtilities.GetValueOrNull(m_headers, HeaderVersion); - headers.Clear(); + m_headers.Clear(); if (versions != null) { - headers[HeaderVersion] = versions; + m_headers[HeaderVersion] = versions; } } @@ -228,8 +231,8 @@ public void BeginClearText( throw new IOException("unknown hash algorithm tag in beginClearText: " + hashAlgorithm); } - DoWrite("-----BEGIN PGP SIGNED MESSAGE-----" + nl); - DoWrite("Hash: " + hash + nl + nl); + DoWrite("-----BEGIN PGP SIGNED MESSAGE-----" + NewLine); + DoWrite("Hash: " + hash + NewLine + NewLine); clearText = true; newLine = true; @@ -241,45 +244,44 @@ public void EndClearText() clearText = false; } - public override void WriteByte( - byte b) + public override void WriteByte(byte value) { if (clearText) { - outStream.WriteByte(b); + outStream.WriteByte(value); if (newLine) { - if (!(b == '\n' && lastb == '\r')) + if (!(value == '\n' && lastb == '\r')) { newLine = false; } - if (b == '-') + if (value == '-') { outStream.WriteByte((byte)' '); outStream.WriteByte((byte)'-'); // dash escape } } - if (b == '\r' || (b == '\n' && lastb != '\r')) + if (value == '\r' || (value == '\n' && lastb != '\r')) { newLine = true; } - lastb = b; + lastb = value; return; } if (start) { - bool newPacket = (b & 0x40) != 0; + bool newPacket = (value & 0x40) != 0; int tag; if (newPacket) { - tag = b & 0x3f; + tag = value & 0x3f; } else { - tag = (b & 0x3f) >> 2; + tag = (value & 0x3f) >> 2; } switch ((PacketTag)tag) @@ -298,30 +300,26 @@ public override void WriteByte( break; } - DoWrite(headerStart + type + headerTail + nl); + DoWrite(headerStart + type + headerTail + NewLine); + if (m_headers.TryGetValue(HeaderVersion, out var versionHeaders)) { - IList versionHeaders = (IList)headers[HeaderVersion]; - if (versionHeaders != null) - { - WriteHeaderEntry(HeaderVersion, versionHeaders[0].ToString()); - } + WriteHeaderEntry(HeaderVersion, versionHeaders[0]); } - foreach (DictionaryEntry de in headers) + foreach (var de in m_headers) { - string k = (string)de.Key; + string k = de.Key; if (k != HeaderVersion) { - IList values = (IList)de.Value; - foreach (string v in values) + foreach (string v in de.Value) { WriteHeaderEntry(k, v); } } } - DoWrite(nl); + DoWrite(NewLine); start = false; } @@ -332,47 +330,32 @@ public override void WriteByte( bufPtr = 0; if ((++chunkCount & 0xf) == 0) { - DoWrite(nl); + DoWrite(NewLine); } } - crc.Update(b); - buf[bufPtr++] = b & 0xff; + crc.Update(value); + buf[bufPtr++] = value & 0xff; } /** * Note: Close() does not close the underlying stream. So it is possible to write * multiple objects using armoring to a single stream. */ -#if PORTABLE || NETFX_CORE protected override void Dispose(bool disposing) { if (disposing) { - if (type == null) - return; - - DoClose(); + if (type != null) + { + DoClose(); - type = null; - start = true; + type = null; + start = true; + } } base.Dispose(disposing); } -#else - public override void Close() - { - if (type == null) - return; - - DoClose(); - - type = null; - start = true; - - base.Close(); - } -#endif private void DoClose() { @@ -381,7 +364,7 @@ private void DoClose() Encode(outStream, buf, bufPtr); } - DoWrite(nl + '='); + DoWrite(NewLine + '='); int crcV = crc.Value; @@ -391,11 +374,11 @@ private void DoClose() Encode(outStream, buf, 3); - DoWrite(nl); + DoWrite(NewLine); DoWrite(footerStart); DoWrite(type); DoWrite(footerTail); - DoWrite(nl); + DoWrite(NewLine); outStream.Flush(); } @@ -404,7 +387,7 @@ private void WriteHeaderEntry( string name, string v) { - DoWrite(name + ": " + v + nl); + DoWrite(name + ": " + v + NewLine); } private void DoWrite( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/BcpgInputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/BcpgInputStream.cs index 2ea4665..0bdef70 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/BcpgInputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/BcpgInputStream.cs @@ -3,7 +3,6 @@ using System; using System.IO; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO; @@ -45,53 +44,61 @@ public override int ReadByte() return m_in.ReadByte(); } - public override int Read( - byte[] buffer, - int offset, - int count) + public override int Read(byte[] buffer, int offset, int count) { - // Strangely, when count == 0, we should still attempt to read a byte -// if (count == 0) -// return 0; - if (!next) return m_in.Read(buffer, offset, count); - // We have next byte waiting, so return it + Streams.ValidateBufferArguments(buffer, offset, count); if (nextB < 0) - return 0; // EndOfStream + return 0; - if (buffer == null) - throw new ArgumentNullException("buffer"); + buffer[offset] = (byte)nextB; + next = false; + return 1; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int Read(Span buffer) + { + if (!next) + return m_in.Read(buffer); - buffer[offset] = (byte) nextB; - next = false; + if (nextB < 0) + return 0; - return 1; + buffer[0] = (byte)nextB; + next = false; + return 1; } +#endif - public byte[] ReadAll() + public byte[] ReadAll() { return Streams.ReadAll(this); } - public void ReadFully( - byte[] buffer, - int off, - int len) + public void ReadFully(byte[] buffer, int offset, int count) { - if (Streams.ReadFully(this, buffer, off, len) < len) + if (Streams.ReadFully(this, buffer, offset, count) < count) throw new EndOfStreamException(); } - public void ReadFully( - byte[] buffer) + public void ReadFully(byte[] buffer) { ReadFully(buffer, 0, buffer.Length); } - /// Returns the next packet tag in the stream. +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void ReadFully(Span buffer) + { + if (Streams.ReadFully(this, buffer) < buffer.Length) + throw new EndOfStreamException(); + } +#endif + + /// Returns the next packet tag in the stream. public PacketTag NextPacketTag() { if (!next) @@ -198,11 +205,7 @@ public Packet ReadPacket() else { PartialInputStream pis = new PartialInputStream(this, partial, bodyLen); -#if NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE - Stream buf = pis; -#else Stream buf = new BufferedStream(pis); -#endif objStream = new BcpgInputStream(buf); } @@ -265,22 +268,14 @@ public PacketTag SkipMarkerPackets() return tag; } -#if PORTABLE || NETFX_CORE protected override void Dispose(bool disposing) { if (disposing) { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(m_in); + m_in.Dispose(); } base.Dispose(disposing); } -#else - public override void Close() - { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(m_in); - base.Close(); - } -#endif /// /// A stream that overlays our input stream, allowing the user to only read a segment of it. @@ -325,6 +320,8 @@ public override int ReadByte() public override int Read(byte[] buffer, int offset, int count) { + Streams.ValidateBufferArguments(buffer, offset, count); + do { if (dataLength != 0) @@ -332,9 +329,8 @@ public override int Read(byte[] buffer, int offset, int count) int readLen = (dataLength > count || dataLength < 0) ? count : dataLength; int len = m_in.Read(buffer, offset, readLen); if (len < 1) - { throw new EndOfStreamException("Premature end of stream in PartialInputStream"); - } + dataLength -= len; return len; } @@ -344,6 +340,29 @@ public override int Read(byte[] buffer, int offset, int count) return 0; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int Read(Span buffer) + { + do + { + if (dataLength != 0) + { + int count = buffer.Length; + int readLen = (dataLength > count || dataLength < 0) ? count : dataLength; + int len = m_in.Read(buffer[..readLen]); + if (len < 1) + throw new EndOfStreamException("Premature end of stream in PartialInputStream"); + + dataLength -= len; + return len; + } + } + while (partial && ReadPartialDataLength() >= 0); + + return 0; + } +#endif + private int ReadPartialDataLength() { int l = m_in.ReadByte(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/BcpgOutputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/BcpgOutputStream.cs index adc73ea..20b3bd6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/BcpgOutputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/BcpgOutputStream.cs @@ -166,7 +166,7 @@ private void WriteHeader( if (partialBuffer != null) { - PartialFlush(true); + PartialFlushLast(); partialBuffer = null; } @@ -217,96 +217,143 @@ private void WriteHeader( } } - private void PartialFlush( - bool isLast) + private void PartialFlush() { - if (isLast) + outStr.WriteByte((byte)(0xE0 | partialPower)); + outStr.Write(partialBuffer, 0, partialBufferLength); + partialOffset = 0; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void PartialFlush(ref ReadOnlySpan buffer) + { + outStr.WriteByte((byte)(0xE0 | partialPower)); + outStr.Write(buffer[..partialBufferLength]); + buffer = buffer[partialBufferLength..]; + } +#endif + + private void PartialFlushLast() + { + WriteNewPacketLength(partialOffset); + outStr.Write(partialBuffer, 0, partialOffset); + partialOffset = 0; + } + + private void PartialWrite(byte[] buffer, int offset, int count) + { + Streams.ValidateBufferArguments(buffer, offset, count); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + PartialWrite(buffer.AsSpan(offset, count)); +#else + if (partialOffset == partialBufferLength) { - WriteNewPacketLength(partialOffset); - outStr.Write(partialBuffer, 0, partialOffset); + PartialFlush(); } - else + + if (count <= (partialBufferLength - partialOffset)) { - outStr.WriteByte((byte)(0xE0 | partialPower)); - outStr.Write(partialBuffer, 0, partialBufferLength); + Array.Copy(buffer, offset, partialBuffer, partialOffset, count); + partialOffset += count; + return; } - partialOffset = 0; + int diff = partialBufferLength - partialOffset; + Array.Copy(buffer, offset, partialBuffer, partialOffset, diff); + offset += diff; + count -= diff; + PartialFlush(); + while (count > partialBufferLength) + { + Array.Copy(buffer, offset, partialBuffer, 0, partialBufferLength); + offset += partialBufferLength; + count -= partialBufferLength; + PartialFlush(); + } + Array.Copy(buffer, offset, partialBuffer, 0, count); + partialOffset = count; +#endif } - private void WritePartial( - byte b) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void PartialWrite(ReadOnlySpan buffer) { if (partialOffset == partialBufferLength) { - PartialFlush(false); + PartialFlush(); + } + + if (buffer.Length <= (partialBufferLength - partialOffset)) + { + buffer.CopyTo(partialBuffer.AsSpan(partialOffset)); + partialOffset += buffer.Length; + return; } - partialBuffer[partialOffset++] = b; + int diff = partialBufferLength - partialOffset; + buffer[..diff].CopyTo(partialBuffer.AsSpan(partialOffset)); + buffer = buffer[diff..]; + PartialFlush(); + while (buffer.Length > partialBufferLength) + { + PartialFlush(ref buffer); + } + buffer.CopyTo(partialBuffer); + partialOffset = buffer.Length; } +#endif - private void WritePartial( - byte[] buffer, - int off, - int len) + private void PartialWriteByte(byte value) { if (partialOffset == partialBufferLength) { - PartialFlush(false); + PartialFlush(); } - if (len <= (partialBufferLength - partialOffset)) + partialBuffer[partialOffset++] = value; + } + + public override void Write(byte[] buffer, int offset, int count) + { + if (partialBuffer != null) { - Array.Copy(buffer, off, partialBuffer, partialOffset, len); - partialOffset += len; + PartialWrite(buffer, offset, count); } else { - int diff = partialBufferLength - partialOffset; - Array.Copy(buffer, off, partialBuffer, partialOffset, diff); - off += diff; - len -= diff; - PartialFlush(false); - while (len > partialBufferLength) - { - Array.Copy(buffer, off, partialBuffer, 0, partialBufferLength); - off += partialBufferLength; - len -= partialBufferLength; - PartialFlush(false); - } - Array.Copy(buffer, off, partialBuffer, 0, len); - partialOffset += len; + outStr.Write(buffer, offset, count); } } - public override void WriteByte( - byte value) + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) { if (partialBuffer != null) { - WritePartial(value); + PartialWrite(buffer); } else { - outStr.WriteByte(value); + outStr.Write(buffer); } } - public override void Write( - byte[] buffer, - int offset, - int count) +#endif + + public override void WriteByte(byte value) { if (partialBuffer != null) { - WritePartial(buffer, offset, count); + PartialWriteByte(value); } else { - outStr.Write(buffer, offset, count); + outStr.WriteByte(value); } } - // Additional helper methods to write primitive types - internal virtual void WriteShort( + // Additional helper methods to write primitive types + internal virtual void WriteShort( short n) { this.Write( @@ -377,32 +424,22 @@ public void Finish() { if (partialBuffer != null) { - PartialFlush(true); + PartialFlushLast(); Array.Clear(partialBuffer, 0, partialBuffer.Length); partialBuffer = null; } } -#if PORTABLE || NETFX_CORE protected override void Dispose(bool disposing) { if (disposing) { this.Finish(); outStr.Flush(); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(outStr); + outStr.Dispose(); } base.Dispose(disposing); } -#else - public override void Close() - { - this.Finish(); - outStr.Flush(); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(outStr); - base.Close(); - } -#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/Crc24.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/Crc24.cs index 4df03e4..d13861a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/Crc24.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/Crc24.cs @@ -29,12 +29,6 @@ public void Update( } } - - public int GetValue() - { - return crc; - } - public int Value { get { return crc; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ECDHPublicBCPGKey.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ECDHPublicBCPGKey.cs index 32e8fe2..4665ba1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ECDHPublicBCPGKey.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ECDHPublicBCPGKey.cs @@ -3,6 +3,7 @@ using System; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Bcpg @@ -16,15 +17,18 @@ public class ECDHPublicBcpgKey private SymmetricKeyAlgorithmTag symAlgorithmId; /// The stream to read the packet from. - public ECDHPublicBcpgKey( - BcpgInputStream bcpgIn) + public ECDHPublicBcpgKey(BcpgInputStream bcpgIn) : base(bcpgIn) { int length = bcpgIn.ReadByte(); - byte[] kdfParameters = new byte[length]; - if (kdfParameters.Length != 3) - throw new InvalidOperationException("kdf parameters size of 3 expected."); + if (length != 3) + throw new InvalidOperationException("KDF parameters size of 3 expected."); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span kdfParameters = stackalloc byte[3]; +#else + byte[] kdfParameters = new byte[3]; +#endif bcpgIn.ReadFully(kdfParameters); reserved = kdfParameters[0]; @@ -50,6 +54,21 @@ public ECDHPublicBcpgKey( VerifySymmetricKeyAlgorithm(); } + public ECDHPublicBcpgKey( + DerObjectIdentifier oid, + BigInteger point, + HashAlgorithmTag hashAlgorithm, + SymmetricKeyAlgorithmTag symmetricKeyAlgorithm) + : base(oid, point) + { + reserved = 1; + hashFunctionId = hashAlgorithm; + symAlgorithmId = symmetricKeyAlgorithm; + + VerifyHashAlgorithm(); + VerifySymmetricKeyAlgorithm(); + } + public virtual byte Reserved { get { return reserved; } @@ -77,7 +96,7 @@ public override void Encode( private void VerifyHashAlgorithm() { - switch ((HashAlgorithmTag)hashFunctionId) + switch (hashFunctionId) { case HashAlgorithmTag.Sha256: case HashAlgorithmTag.Sha384: @@ -90,7 +109,7 @@ private void VerifyHashAlgorithm() private void VerifySymmetricKeyAlgorithm() { - switch ((SymmetricKeyAlgorithmTag)symAlgorithmId) + switch (symAlgorithmId) { case SymmetricKeyAlgorithmTag.Aes128: case SymmetricKeyAlgorithmTag.Aes192: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ECPublicBCPGKey.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ECPublicBCPGKey.cs index df4db3d..326fc89 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ECPublicBCPGKey.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ECPublicBCPGKey.cs @@ -28,7 +28,7 @@ protected ECPublicBcpgKey( DerObjectIdentifier oid, ECPoint point) { - this.point = new BigInteger(1, point.GetEncoded(false)); + this.point = MPInteger.ToMpiBigInteger(point); this.oid = oid; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ECSecretBCPGKey.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ECSecretBCPGKey.cs index 7c02611..54ed1ab 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ECSecretBCPGKey.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/ECSecretBCPGKey.cs @@ -2,7 +2,6 @@ #pragma warning disable using System; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Bcpg @@ -11,18 +10,18 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Bcpg public class ECSecretBcpgKey : BcpgObject, IBcpgKey { - internal MPInteger x; + internal readonly MPInteger m_x; public ECSecretBcpgKey( BcpgInputStream bcpgIn) { - this.x = new MPInteger(bcpgIn); + m_x = new MPInteger(bcpgIn); } public ECSecretBcpgKey( BigInteger x) { - this.x = new MPInteger(x); + m_x = new MPInteger(x); } /// The format, as a string, always "PGP". @@ -47,12 +46,12 @@ public override byte[] GetEncoded() public override void Encode( BcpgOutputStream bcpgOut) { - bcpgOut.WriteObject(x); + bcpgOut.WriteObject(m_x); } public virtual BigInteger X { - get { return x.Value; } + get { return m_x.Value; } } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/EdDsaPublicBcpgKey.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/EdDsaPublicBcpgKey.cs new file mode 100644 index 0000000..89e0a42 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/EdDsaPublicBcpgKey.cs @@ -0,0 +1,29 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Bcpg +{ + public sealed class EdDsaPublicBcpgKey + : ECPublicBcpgKey + { + internal EdDsaPublicBcpgKey(BcpgInputStream bcpgIn) + : base(bcpgIn) + { + } + + public EdDsaPublicBcpgKey(DerObjectIdentifier oid, ECPoint point) + : base(oid, point) + { + } + + public EdDsaPublicBcpgKey(DerObjectIdentifier oid, BigInteger encodedPoint) + : base(oid, encodedPoint) + { + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/EdDsaPublicBcpgKey.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/EdDsaPublicBcpgKey.cs.meta new file mode 100644 index 0000000..0977360 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/EdDsaPublicBcpgKey.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 886e996d31601394ba4c3f2d691c6d68 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/EdSecretBcpgKey.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/EdSecretBcpgKey.cs new file mode 100644 index 0000000..e8e102b --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/EdSecretBcpgKey.cs @@ -0,0 +1,47 @@ +#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.Bcpg +{ + public sealed class EdSecretBcpgKey + : BcpgObject, IBcpgKey + { + internal readonly MPInteger m_x; + + public EdSecretBcpgKey(BcpgInputStream bcpgIn) + { + m_x = new MPInteger(bcpgIn); + } + + public EdSecretBcpgKey(BigInteger x) + { + m_x = new MPInteger(x); + } + + public string Format => "PGP"; + + public override byte[] GetEncoded() + { + try + { + return base.GetEncoded(); + } + catch (Exception) + { + return null; + } + } + + public override void Encode(BcpgOutputStream bcpgOut) + { + bcpgOut.WriteObject(m_x); + } + + public BigInteger X => m_x.Value; + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/EdSecretBcpgKey.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/EdSecretBcpgKey.cs.meta new file mode 100644 index 0000000..e9eb583 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/EdSecretBcpgKey.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f1b967203f5d100409763ad04d4f89e3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/MPInteger.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/MPInteger.cs index 0ab860f..5a33ed1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/MPInteger.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/MPInteger.cs @@ -1,62 +1,69 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Bcpg { /// A multiple precision integer - public class MPInteger + public sealed class MPInteger : BcpgObject { - private readonly BigInteger val; + private readonly BigInteger m_val; - public MPInteger( - BcpgInputStream bcpgIn) + public MPInteger(BcpgInputStream bcpgIn) { if (bcpgIn == null) - throw new ArgumentNullException("bcpgIn"); + throw new ArgumentNullException(nameof(bcpgIn)); - int length = (bcpgIn.ReadByte() << 8) | bcpgIn.ReadByte(); - byte[] bytes = new byte[(length + 7) / 8]; + int lengthInBits = (bcpgIn.ReadByte() << 8) | bcpgIn.ReadByte(); + int lengthInBytes = (lengthInBits + 7) / 8; - bcpgIn.ReadFully(bytes); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span bytes = lengthInBytes <= 512 + ? stackalloc byte[lengthInBytes] + : new byte[lengthInBytes]; +#else + byte[] bytes = new byte[lengthInBytes]; +#endif - this.val = new BigInteger(1, bytes); + bcpgIn.ReadFully(bytes); + m_val = new BigInteger(1, bytes); } - public MPInteger( - BigInteger val) + public MPInteger(BigInteger val) { if (val == null) - throw new ArgumentNullException("val"); + throw new ArgumentNullException(nameof(val)); if (val.SignValue < 0) - throw new ArgumentException("Values must be positive", "val"); + throw new ArgumentException("Values must be positive", nameof(val)); - this.val = val; + m_val = val; } - public BigInteger Value + public BigInteger Value => m_val; + + public override void Encode(BcpgOutputStream bcpgOut) { - get { return val; } + bcpgOut.WriteShort((short)m_val.BitLength); + bcpgOut.Write(m_val.ToByteArrayUnsigned()); } - public override void Encode( - BcpgOutputStream bcpgOut) + internal static BigInteger ToMpiBigInteger(ECPoint point) { - bcpgOut.WriteShort((short) val.BitLength); - bcpgOut.Write(val.ToByteArrayUnsigned()); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int encodedLength = point.GetEncodedLength(false); + Span encoding = encodedLength <= 512 + ? stackalloc byte[encodedLength] + : new byte[encodedLength]; + point.EncodeTo(false, encoding); +#else + byte[] encoding = point.GetEncoded(false); +#endif + return new BigInteger(1, encoding); } - - internal static void Encode( - BcpgOutputStream bcpgOut, - BigInteger val) - { - bcpgOut.WriteShort((short) val.BitLength); - bcpgOut.Write(val.ToByteArrayUnsigned()); - } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/OnePassSignaturePacket.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/OnePassSignaturePacket.cs index 853ba8f..03dfa4f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/OnePassSignaturePacket.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/OnePassSignaturePacket.cs @@ -73,21 +73,15 @@ public long KeyId get { return keyId; } } - public override void Encode( - BcpgOutputStream bcpgOut) + public override void Encode(BcpgOutputStream bcpgOut) { MemoryStream bOut = new MemoryStream(); - BcpgOutputStream pOut = new BcpgOutputStream(bOut); - - pOut.Write( - (byte) version, - (byte) sigType, - (byte) hashAlgorithm, - (byte) keyAlgorithm); - - pOut.WriteLong(keyId); - - pOut.WriteByte((byte) nested); + using (var pOut = new BcpgOutputStream(bOut)) + { + pOut.Write((byte)version, (byte)sigType, (byte)hashAlgorithm, (byte)keyAlgorithm); + pOut.WriteLong(keyId); + pOut.WriteByte((byte)nested); + } bcpgOut.WritePacket(PacketTag.OnePassSignature, bOut.ToArray(), true); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/PublicKeyAlgorithmTags.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/PublicKeyAlgorithmTags.cs index fc7b307..07d96f8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/PublicKeyAlgorithmTags.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/PublicKeyAlgorithmTags.cs @@ -12,8 +12,6 @@ public enum PublicKeyAlgorithmTag RsaSign = 3, // RSA Sign-Only ElGamalEncrypt = 16, // Elgamal (Encrypt-Only), see [ELGAMAL] Dsa = 17, // DSA (Digital Signature Standard) - - EC = 18, // Reserved for Elliptic Curve ECDH = 18, // Reserved for Elliptic Curve (actual algorithm name) ECDsa = 19, // Reserved for ECDSA ElGamalGeneral = 20, // Elgamal (Encrypt or Sign) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/PublicKeyEncSessionPacket.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/PublicKeyEncSessionPacket.cs index d488508..e58c158 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/PublicKeyEncSessionPacket.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/PublicKeyEncSessionPacket.cs @@ -92,26 +92,22 @@ public byte[][] GetEncSessionKey() return data; } - public override void Encode( - BcpgOutputStream bcpgOut) + public override void Encode(BcpgOutputStream bcpgOut) { MemoryStream bOut = new MemoryStream(); - BcpgOutputStream pOut = new BcpgOutputStream(bOut); - - pOut.WriteByte((byte) version); - - pOut.WriteLong(keyId); - - pOut.WriteByte((byte)algorithm); - - for (int i = 0; i < data.Length; ++i) - { - pOut.Write(data[i]); - } - - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(pOut); + using (var pOut = new BcpgOutputStream(bOut)) + { + pOut.WriteByte((byte)version); + pOut.WriteLong(keyId); + pOut.WriteByte((byte)algorithm); + + for (int i = 0; i < data.Length; ++i) + { + pOut.Write(data[i]); + } + } - bcpgOut.WritePacket(PacketTag.PublicKeyEncryptedSession , bOut.ToArray(), true); + bcpgOut.WritePacket(PacketTag.PublicKeyEncryptedSession, bOut.ToArray(), true); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/PublicKeyPacket.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/PublicKeyPacket.cs index b53a90b..18c731a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/PublicKeyPacket.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/PublicKeyPacket.cs @@ -30,30 +30,33 @@ internal PublicKeyPacket( validDays = (bcpgIn.ReadByte() << 8) | bcpgIn.ReadByte(); } - algorithm = (PublicKeyAlgorithmTag) bcpgIn.ReadByte(); + algorithm = (PublicKeyAlgorithmTag)bcpgIn.ReadByte(); - switch ((PublicKeyAlgorithmTag) algorithm) + switch (algorithm) { - case PublicKeyAlgorithmTag.RsaEncrypt: - case PublicKeyAlgorithmTag.RsaGeneral: - case PublicKeyAlgorithmTag.RsaSign: - key = new RsaPublicBcpgKey(bcpgIn); - break; - case PublicKeyAlgorithmTag.Dsa: - key = new DsaPublicBcpgKey(bcpgIn); - break; - case PublicKeyAlgorithmTag.ElGamalEncrypt: - case PublicKeyAlgorithmTag.ElGamalGeneral: - key = new ElGamalPublicBcpgKey(bcpgIn); - break; - case PublicKeyAlgorithmTag.ECDH: - key = new ECDHPublicBcpgKey(bcpgIn); - break; - case PublicKeyAlgorithmTag.ECDsa: - key = new ECDsaPublicBcpgKey(bcpgIn); - break; - default: - throw new IOException("unknown PGP public key algorithm encountered"); + case PublicKeyAlgorithmTag.RsaEncrypt: + case PublicKeyAlgorithmTag.RsaGeneral: + case PublicKeyAlgorithmTag.RsaSign: + key = new RsaPublicBcpgKey(bcpgIn); + break; + case PublicKeyAlgorithmTag.Dsa: + key = new DsaPublicBcpgKey(bcpgIn); + break; + case PublicKeyAlgorithmTag.ElGamalEncrypt: + case PublicKeyAlgorithmTag.ElGamalGeneral: + key = new ElGamalPublicBcpgKey(bcpgIn); + break; + case PublicKeyAlgorithmTag.ECDH: + key = new ECDHPublicBcpgKey(bcpgIn); + break; + case PublicKeyAlgorithmTag.ECDsa: + key = new ECDsaPublicBcpgKey(bcpgIn); + break; + case PublicKeyAlgorithmTag.EdDsa: + key = new EdDsaPublicBcpgKey(bcpgIn); + break; + default: + throw new IOException("unknown PGP public key algorithm encountered"); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/S2k.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/S2k.cs index 018620f..9099a94 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/S2k.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/S2k.cs @@ -103,12 +103,6 @@ public virtual byte[] GetIV() return Arrays.Clone(iv); } - - public long GetIterationCount() - { - return IterationCount; - } - /// The iteration count public virtual long IterationCount { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/SignaturePacket.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/SignaturePacket.cs index 91c2946..48dfc96 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/SignaturePacket.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/SignaturePacket.cs @@ -1,11 +1,10 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Bcpg.Sig; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO; @@ -13,7 +12,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Bcpg { /// Generic signature packet. public class SignaturePacket - : ContainedPacket //, PublicKeyAlgorithmTag + : ContainedPacket { private int version; private int signatureType; @@ -70,29 +69,26 @@ internal SignaturePacket( SignatureSubpacketsParser sIn = new SignatureSubpacketsParser( new MemoryStream(hashed, false)); - IList v = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var v = new List(); + SignatureSubpacket sub; while ((sub = sIn.ReadPacket()) != null) { v.Add(sub); } - hashedData = new SignatureSubpacket[v.Count]; + hashedData = v.ToArray(); - for (int i = 0; i != hashedData.Length; i++) + foreach (var p in hashedData) { - SignatureSubpacket p = (SignatureSubpacket)v[i]; - if (p is IssuerKeyId) + if (p is IssuerKeyId issuerKeyId) { - keyId = ((IssuerKeyId)p).KeyId; + keyId = issuerKeyId.KeyId; } - else if (p is SignatureCreationTime) + else if (p is SignatureCreationTime sigCreationTime) { - creationTime = DateTimeUtilities.DateTimeToUnixMs( - ((SignatureCreationTime)p).GetTime()); + creationTime = DateTimeUtilities.DateTimeToUnixMs(sigCreationTime.GetTime()); } - - hashedData[i] = p; } int unhashedLength = (bcpgIn.ReadByte() << 8) | bcpgIn.ReadByte(); @@ -109,17 +105,14 @@ internal SignaturePacket( v.Add(sub); } - unhashedData = new SignatureSubpacket[v.Count]; + unhashedData = v.ToArray(); - for (int i = 0; i != unhashedData.Length; i++) + foreach (var p in unhashedData) { - SignatureSubpacket p = (SignatureSubpacket)v[i]; - if (p is IssuerKeyId) + if (p is IssuerKeyId issuerKeyId) { - keyId = ((IssuerKeyId)p).KeyId; + keyId = issuerKeyId.KeyId; } - - unhashedData[i] = p; } } else @@ -137,41 +130,38 @@ internal SignaturePacket( case PublicKeyAlgorithmTag.RsaGeneral: case PublicKeyAlgorithmTag.RsaSign: MPInteger v = new MPInteger(bcpgIn); - signature = new MPInteger[]{ v }; + signature = new MPInteger[1]{ v }; break; case PublicKeyAlgorithmTag.Dsa: MPInteger r = new MPInteger(bcpgIn); MPInteger s = new MPInteger(bcpgIn); - signature = new MPInteger[]{ r, s }; + signature = new MPInteger[2]{ r, s }; break; case PublicKeyAlgorithmTag.ElGamalEncrypt: // yep, this really does happen sometimes. case PublicKeyAlgorithmTag.ElGamalGeneral: MPInteger p = new MPInteger(bcpgIn); MPInteger g = new MPInteger(bcpgIn); MPInteger y = new MPInteger(bcpgIn); - signature = new MPInteger[]{ p, g, y }; + signature = new MPInteger[3]{ p, g, y }; break; case PublicKeyAlgorithmTag.ECDsa: + case PublicKeyAlgorithmTag.EdDsa: MPInteger ecR = new MPInteger(bcpgIn); MPInteger ecS = new MPInteger(bcpgIn); - signature = new MPInteger[]{ ecR, ecS }; + signature = new MPInteger[2]{ ecR, ecS }; break; default: - if (keyAlgorithm >= PublicKeyAlgorithmTag.Experimental_1 && keyAlgorithm <= PublicKeyAlgorithmTag.Experimental_11) - { - signature = null; - MemoryStream bOut = new MemoryStream(); - int ch; - while ((ch = bcpgIn.ReadByte()) >= 0) - { - bOut.WriteByte((byte) ch); - } - signatureEncoding = bOut.ToArray(); - } - else + if (keyAlgorithm < PublicKeyAlgorithmTag.Experimental_1 || keyAlgorithm > PublicKeyAlgorithmTag.Experimental_11) + throw new IOException("unknown signature key algorithm: " + keyAlgorithm); + + signature = null; + MemoryStream bOut = new MemoryStream(); + int ch; + while ((ch = bcpgIn.ReadByte()) >= 0) { - throw new IOException("unknown signature key algorithm: " + keyAlgorithm); + bOut.WriteByte((byte) ch); } + signatureEncoding = bOut.ToArray(); break; } } @@ -246,7 +236,7 @@ public SignaturePacket( if (hashedData != null) { - setCreationTime(); + SetCreationTime(); } } @@ -277,56 +267,53 @@ public long KeyId */ public byte[] GetSignatureTrailer() { - byte[] trailer = null; - if (version == 3) { - trailer = new byte[5]; - - long time = creationTime / 1000L; + long time = creationTime / 1000L; + byte[] trailer = new byte[5]; trailer[0] = (byte)signatureType; trailer[1] = (byte)(time >> 24); trailer[2] = (byte)(time >> 16); - trailer[3] = (byte)(time >> 8); - trailer[4] = (byte)(time); + trailer[3] = (byte)(time >> 8); + trailer[4] = (byte)(time ); + return trailer; } - else - { - MemoryStream sOut = new MemoryStream(); - - sOut.WriteByte((byte)this.Version); - sOut.WriteByte((byte)this.SignatureType); - sOut.WriteByte((byte)this.KeyAlgorithm); - sOut.WriteByte((byte)this.HashAlgorithm); - MemoryStream hOut = new MemoryStream(); - SignatureSubpacket[] hashed = this.GetHashedSubPackets(); + MemoryStream sOut = new MemoryStream(); - for (int i = 0; i != hashed.Length; i++) - { - hashed[i].Encode(hOut); - } + sOut.WriteByte((byte)Version); + sOut.WriteByte((byte)SignatureType); + sOut.WriteByte((byte)KeyAlgorithm); + sOut.WriteByte((byte)HashAlgorithm); - byte[] data = hOut.ToArray(); + // Mark position an reserve two bytes for length + long lengthPosition = sOut.Position; + sOut.WriteByte(0x00); + sOut.WriteByte(0x00); - sOut.WriteByte((byte)(data.Length >> 8)); - sOut.WriteByte((byte)data.Length); - sOut.Write(data, 0, data.Length); + SignatureSubpacket[] hashed = GetHashedSubPackets(); + for (int i = 0; i != hashed.Length; i++) + { + hashed[i].Encode(sOut); + } - byte[] hData = sOut.ToArray(); + ushort dataLength = Convert.ToUInt16(sOut.Position - lengthPosition - 2); + uint hDataLength = Convert.ToUInt32(sOut.Position); - sOut.WriteByte((byte)this.Version); - sOut.WriteByte((byte)0xff); - sOut.WriteByte((byte)(hData.Length>> 24)); - sOut.WriteByte((byte)(hData.Length >> 16)); - sOut.WriteByte((byte)(hData.Length >> 8)); - sOut.WriteByte((byte)(hData.Length)); + sOut.WriteByte((byte)Version); + sOut.WriteByte(0xff); + sOut.WriteByte((byte)(hDataLength >> 24)); + sOut.WriteByte((byte)(hDataLength >> 16)); + sOut.WriteByte((byte)(hDataLength >> 8)); + sOut.WriteByte((byte)(hDataLength )); - trailer = sOut.ToArray(); - } + // Reset position and fill in length + sOut.Position = lengthPosition; + sOut.WriteByte((byte)(dataLength >> 8)); + sOut.WriteByte((byte)(dataLength )); - return trailer; + return sOut.ToArray(); } public PublicKeyAlgorithmTag KeyAlgorithm @@ -393,55 +380,44 @@ public long CreationTime get { return creationTime; } } - public override void Encode( - BcpgOutputStream bcpgOut) + public override void Encode(BcpgOutputStream bcpgOut) { MemoryStream bOut = new MemoryStream(); - BcpgOutputStream pOut = new BcpgOutputStream(bOut); - - pOut.WriteByte((byte) version); - - if (version == 3 || version == 2) + using (var pOut = new BcpgOutputStream(bOut)) { - pOut.Write( - 5, // the length of the next block - (byte) signatureType); - - pOut.WriteInt((int)(creationTime / 1000L)); + pOut.WriteByte((byte)version); - pOut.WriteLong(keyId); - - pOut.Write( - (byte) keyAlgorithm, - (byte) hashAlgorithm); - } - else if (version == 4) - { - pOut.Write( - (byte) signatureType, - (byte) keyAlgorithm, - (byte) hashAlgorithm); + if (version == 3 || version == 2) + { + byte nextBlockLength = 5; + pOut.Write(nextBlockLength, (byte)signatureType); + pOut.WriteInt((int)(creationTime / 1000L)); + pOut.WriteLong(keyId); + pOut.Write((byte)keyAlgorithm, (byte)hashAlgorithm); + } + else if (version == 4) + { + pOut.Write((byte)signatureType, (byte)keyAlgorithm, (byte)hashAlgorithm); + EncodeLengthAndData(pOut, GetEncodedSubpackets(hashedData)); + EncodeLengthAndData(pOut, GetEncodedSubpackets(unhashedData)); + } + else + { + throw new IOException("unknown version: " + version); + } - EncodeLengthAndData(pOut, GetEncodedSubpackets(hashedData)); + pOut.Write(fingerprint); - EncodeLengthAndData(pOut, GetEncodedSubpackets(unhashedData)); - } - else - { - throw new IOException("unknown version: " + version); + if (signature != null) + { + pOut.WriteObjects(signature); + } + else + { + pOut.Write(signatureEncoding); + } } - pOut.Write(fingerprint); - - if (signature != null) - { - pOut.WriteObjects(signature); - } - else - { - pOut.Write(signatureEncoding); - } - bcpgOut.WritePacket(PacketTag.Signature, bOut.ToArray(), true); } @@ -466,18 +442,18 @@ private static byte[] GetEncodedSubpackets( return sOut.ToArray(); } - private void setCreationTime() + private void SetCreationTime() { foreach (SignatureSubpacket p in hashedData) { - if (p is SignatureCreationTime) + if (p is SignatureCreationTime signatureCreationTime) { - creationTime = DateTimeUtilities.DateTimeToUnixMs( - ((SignatureCreationTime)p).GetTime()); + creationTime = DateTimeUtilities.DateTimeToUnixMs(signatureCreationTime.GetTime()); break; } } } + public static SignaturePacket FromByteArray(byte[] data) { BcpgInputStream input = BcpgInputStream.Wrap(new MemoryStream(data)); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/SignatureSubpacketsReader.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/SignatureSubpacketsReader.cs index 3870683..6cb09bf 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/SignatureSubpacketsReader.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/SignatureSubpacketsReader.cs @@ -92,33 +92,37 @@ public SignatureSubpacket ReadPacket() switch (type) { - case SignatureSubpacketTag.CreationTime: - return new SignatureCreationTime(isCritical, isLongLength, data); - case SignatureSubpacketTag.KeyExpireTime: - return new KeyExpirationTime(isCritical, isLongLength, data); - case SignatureSubpacketTag.ExpireTime: - return new SignatureExpirationTime(isCritical, isLongLength, data); - case SignatureSubpacketTag.Revocable: - return new Revocable(isCritical, isLongLength, data); - case SignatureSubpacketTag.Exportable: - return new Exportable(isCritical, isLongLength, data); - case SignatureSubpacketTag.IssuerKeyId: - return new IssuerKeyId(isCritical, isLongLength, data); - case SignatureSubpacketTag.TrustSig: - return new TrustSignature(isCritical, isLongLength, data); - case SignatureSubpacketTag.PreferredCompressionAlgorithms: - case SignatureSubpacketTag.PreferredHashAlgorithms: - case SignatureSubpacketTag.PreferredSymmetricAlgorithms: - return new PreferredAlgorithms(type, isCritical, isLongLength, data); - case SignatureSubpacketTag.KeyFlags: - return new KeyFlags(isCritical, isLongLength, data); - case SignatureSubpacketTag.PrimaryUserId: - return new PrimaryUserId(isCritical, isLongLength, data); - case SignatureSubpacketTag.SignerUserId: - return new SignerUserId(isCritical, isLongLength, data); - case SignatureSubpacketTag.NotationData: - return new NotationData(isCritical, isLongLength, data); - } + case SignatureSubpacketTag.CreationTime: + return new SignatureCreationTime(isCritical, isLongLength, data); + case SignatureSubpacketTag.KeyExpireTime: + return new KeyExpirationTime(isCritical, isLongLength, data); + case SignatureSubpacketTag.ExpireTime: + return new SignatureExpirationTime(isCritical, isLongLength, data); + case SignatureSubpacketTag.Revocable: + return new Revocable(isCritical, isLongLength, data); + case SignatureSubpacketTag.Exportable: + return new Exportable(isCritical, isLongLength, data); + case SignatureSubpacketTag.IssuerKeyId: + return new IssuerKeyId(isCritical, isLongLength, data); + case SignatureSubpacketTag.TrustSig: + return new TrustSignature(isCritical, isLongLength, data); + case SignatureSubpacketTag.PreferredCompressionAlgorithms: + case SignatureSubpacketTag.PreferredHashAlgorithms: + case SignatureSubpacketTag.PreferredSymmetricAlgorithms: + return new PreferredAlgorithms(type, isCritical, isLongLength, data); + case SignatureSubpacketTag.KeyFlags: + return new KeyFlags(isCritical, isLongLength, data); + case SignatureSubpacketTag.PrimaryUserId: + return new PrimaryUserId(isCritical, isLongLength, data); + case SignatureSubpacketTag.SignerUserId: + return new SignerUserId(isCritical, isLongLength, data); + case SignatureSubpacketTag.NotationData: + return new NotationData(isCritical, isLongLength, data); + case SignatureSubpacketTag.RevocationReason: + return new RevocationReason(isCritical, isLongLength, data); + case SignatureSubpacketTag.RevocationKey: + return new RevocationKey(isCritical, isLongLength, data); + } return new SignatureSubpacket(type, isCritical, isLongLength, data); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/SymmetricKeyEncSessionPacket.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/SymmetricKeyEncSessionPacket.cs index 26d81e3..23507a8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/SymmetricKeyEncSessionPacket.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/SymmetricKeyEncSessionPacket.cs @@ -70,21 +70,18 @@ public int Version get { return version; } } - public override void Encode( - BcpgOutputStream bcpgOut) + public override void Encode(BcpgOutputStream bcpgOut) { MemoryStream bOut = new MemoryStream(); - BcpgOutputStream pOut = new BcpgOutputStream(bOut); + using (var pOut = new BcpgOutputStream(bOut)) + { + pOut.Write((byte)version, (byte)encAlgorithm); + pOut.WriteObject(s2k); - pOut.Write( - (byte) version, - (byte) encAlgorithm); - - pOut.WriteObject(s2k); - - if (secKeyData != null && secKeyData.Length > 0) - { - pOut.Write(secKeyData); + if (secKeyData != null && secKeyData.Length > 0) + { + pOut.Write(secKeyData); + } } bcpgOut.WritePacket(PacketTag.SymmetricKeyEncryptedSessionKey, bOut.ToArray(), true); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/UnsupportedPacketVersionException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/UnsupportedPacketVersionException.cs index dabd02a..385deb1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/UnsupportedPacketVersionException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/UnsupportedPacketVersionException.cs @@ -1,16 +1,33 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Bcpg { + [Serializable] public class UnsupportedPacketVersionException : Exception { - public UnsupportedPacketVersionException(string msg) - : base(msg) - { - } + public UnsupportedPacketVersionException() + : base() + { + } + + public UnsupportedPacketVersionException(string message) + : base(message) + { + } + + public UnsupportedPacketVersionException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected UnsupportedPacketVersionException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/UserAttributePacket.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/UserAttributePacket.cs index b98334a..5517578 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/UserAttributePacket.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/UserAttributePacket.cs @@ -1,11 +1,8 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System; -using System.Collections; +using System.Collections.Generic; using System.IO; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; - namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Bcpg { /** @@ -22,18 +19,13 @@ public UserAttributePacket( UserAttributeSubpacketsParser sIn = new UserAttributeSubpacketsParser(bcpgIn); UserAttributeSubpacket sub; - IList v = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var v = new List(); while ((sub = sIn.ReadPacket()) != null) { v.Add(sub); } - subpackets = new UserAttributeSubpacket[v.Count]; - - for (int i = 0; i != subpackets.Length; i++) - { - subpackets[i] = (UserAttributeSubpacket)v[i]; - } + subpackets = v.ToArray(); } public UserAttributePacket( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/Exportable.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/Exportable.cs index 25d7252..e617f35 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/Exportable.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/Exportable.cs @@ -12,17 +12,7 @@ public class Exportable { private static byte[] BooleanToByteArray(bool val) { - byte[] data = new byte[1]; - - if (val) - { - data[0] = 1; - return data; - } - else - { - return data; - } + return new byte[1]{ Convert.ToByte(val) }; } public Exportable( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/Features.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/Features.cs index 3c445c5..eea3ef2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/Features.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/Features.cs @@ -21,31 +21,25 @@ public class Features fingerprint format */ public static readonly byte FEATURE_VERSION_5_PUBLIC_KEY = 0x04; - private static byte[] featureToByteArray(byte feature) + private static byte[] FeatureToByteArray(byte feature) { - byte[] data = new byte[1]; - data[0] = feature; - return data; + return new byte[1]{ feature }; } public Features( bool critical, bool isLongLength, - byte[] data): base(SignatureSubpacketTag.Features, critical, isLongLength, data) + byte[] data) + : base(SignatureSubpacketTag.Features, critical, isLongLength, data) { - } - - public Features(bool critical, byte features): this(critical, false, featureToByteArray(features)) + public Features(bool critical, byte features): this(critical, false, FeatureToByteArray(features)) { - } - - public Features(bool critical, int features): this(critical, false, featureToByteArray((byte)features)) + public Features(bool critical, int features): this(critical, false, FeatureToByteArray((byte)features)) { - } /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/IssuerKeyId.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/IssuerKeyId.cs index d5181dd..981e526 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/IssuerKeyId.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/IssuerKeyId.cs @@ -1,8 +1,6 @@ #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.Bcpg.Sig { @@ -12,21 +10,9 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Bcpg.Sig public class IssuerKeyId : SignatureSubpacket { - protected static byte[] KeyIdToBytes( - long keyId) + protected static byte[] KeyIdToBytes(long keyId) { - byte[] data = new byte[8]; - - data[0] = (byte)(keyId >> 56); - data[1] = (byte)(keyId >> 48); - data[2] = (byte)(keyId >> 40); - data[3] = (byte)(keyId >> 32); - data[4] = (byte)(keyId >> 24); - data[5] = (byte)(keyId >> 16); - data[6] = (byte)(keyId >> 8); - data[7] = (byte)keyId; - - return data; + return Pack.UInt64_To_BE((ulong)keyId); } public IssuerKeyId( @@ -44,22 +30,7 @@ public IssuerKeyId( { } - public long KeyId - { - get - { - long keyId = ((long)(data[0] & 0xff) << 56) - | ((long)(data[1] & 0xff) << 48) - | ((long)(data[2] & 0xff) << 40) - | ((long)(data[3] & 0xff) << 32) - | ((long)(data[4] & 0xff) << 24) - | ((long)(data[5] & 0xff) << 16) - | ((long)(data[6] & 0xff) << 8) - | ((long)data[7] & 0xff); - - return keyId; - } - } + public long KeyId => (long)Pack.BE_To_UInt64(data); } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/KeyExpirationTime.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/KeyExpirationTime.cs index dee992c..bbc115e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/KeyExpirationTime.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/KeyExpirationTime.cs @@ -1,6 +1,6 @@ #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.Bcpg.Sig { @@ -10,17 +10,9 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Bcpg.Sig public class KeyExpirationTime : SignatureSubpacket { - protected static byte[] TimeToBytes( - long t) + protected static byte[] TimeToBytes(long t) { - byte[] data = new byte[4]; - - data[0] = (byte)(t >> 24); - data[1] = (byte)(t >> 16); - data[2] = (byte)(t >> 8); - data[3] = (byte)t; - - return data; + return Pack.UInt32_To_BE((uint)t); } public KeyExpirationTime( @@ -43,16 +35,7 @@ public KeyExpirationTime( * * @return second count for key validity. */ - public long Time - { - get - { - long time = ((long)(data[0] & 0xff) << 24) | ((long)(data[1] & 0xff) << 16) - | ((long)(data[2] & 0xff) << 8) | ((long)data[3] & 0xff); - - return time; - } - } + public long Time => (long)Pack.BE_To_UInt32(data); } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/NotationData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/NotationData.cs index d6df673..0604d62 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/NotationData.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/NotationData.cs @@ -81,7 +81,7 @@ private static byte[] CreateData( public bool IsHumanReadable { - get { return data[0] == (byte)0x80; } + get { return data[0] == 0x80; } } public string GetNotationName() diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/PrimaryUserId.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/PrimaryUserId.cs index 8bd63ca..fed076d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/PrimaryUserId.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/PrimaryUserId.cs @@ -10,20 +10,9 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Bcpg.Sig public class PrimaryUserId : SignatureSubpacket { - private static byte[] BooleanToByteArray( - bool val) + private static byte[] BooleanToByteArray(bool val) { - byte[] data = new byte[1]; - - if (val) - { - data[0] = 1; - return data; - } - else - { - return data; - } + return new byte[1]{ Convert.ToByte(val) }; } public PrimaryUserId( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/Revocable.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/Revocable.cs index 9b0b992..7914cb6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/Revocable.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/Revocable.cs @@ -10,20 +10,9 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Bcpg.Sig public class Revocable : SignatureSubpacket { - private static byte[] BooleanToByteArray( - bool value) + private static byte[] BooleanToByteArray(bool value) { - byte[] data = new byte[1]; - - if (value) - { - data[0] = 1; - return data; - } - else - { - return data; - } + return new byte[1]{ Convert.ToByte(value) }; } public Revocable( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/RevocationReason.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/RevocationReason.cs index 6f0d5ef..72aa4ae 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/RevocationReason.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/RevocationReason.cs @@ -48,9 +48,7 @@ public virtual string GetRevocationDescription() { byte[] data = GetData(); if (data.Length == 1) - { return string.Empty; - } byte[] description = new byte[data.Length - 1]; Array.Copy(data, 1, description, 0, description.Length); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/SignatureCreationTime.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/SignatureCreationTime.cs index 0ca5639..b3a62eb 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/SignatureCreationTime.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/SignatureCreationTime.cs @@ -2,6 +2,7 @@ #pragma warning disable using System; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Bcpg.Sig @@ -12,41 +13,25 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Bcpg.Sig public class SignatureCreationTime : SignatureSubpacket { - protected static byte[] TimeToBytes( - DateTime time) + protected static byte[] TimeToBytes(DateTime time) { long t = DateTimeUtilities.DateTimeToUnixMs(time) / 1000L; - byte[] data = new byte[4]; - data[0] = (byte)(t >> 24); - data[1] = (byte)(t >> 16); - data[2] = (byte)(t >> 8); - data[3] = (byte)t; - return data; + return Pack.UInt32_To_BE((uint)t); } - public SignatureCreationTime( - bool critical, - bool isLongLength, - byte[] data) + public SignatureCreationTime(bool critical, bool isLongLength, byte[] data) : base(SignatureSubpacketTag.CreationTime, critical, isLongLength, data) { } - public SignatureCreationTime( - bool critical, - DateTime date) + public SignatureCreationTime(bool critical, DateTime date) : base(SignatureSubpacketTag.CreationTime, critical, false, TimeToBytes(date)) { } public DateTime GetTime() { - long time = (long)( - ((uint)data[0] << 24) - | ((uint)data[1] << 16) - | ((uint)data[2] << 8) - | ((uint)data[3]) - ); + uint time = Pack.BE_To_UInt32(data, 0); return DateTimeUtilities.UnixMsToDateTime(time * 1000L); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/SignatureExpirationTime.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/SignatureExpirationTime.cs index 32c6cbd..b7fc8ad 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/SignatureExpirationTime.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/SignatureExpirationTime.cs @@ -1,6 +1,6 @@ #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.Bcpg.Sig { @@ -10,28 +10,17 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Bcpg.Sig public class SignatureExpirationTime : SignatureSubpacket { - protected static byte[] TimeToBytes( - long t) + protected static byte[] TimeToBytes(long t) { - byte[] data = new byte[4]; - data[0] = (byte)(t >> 24); - data[1] = (byte)(t >> 16); - data[2] = (byte)(t >> 8); - data[3] = (byte)t; - return data; + return Pack.UInt32_To_BE((uint)t); } - public SignatureExpirationTime( - bool critical, - bool isLongLength, - byte[] data) + public SignatureExpirationTime(bool critical, bool isLongLength, byte[] data) : base(SignatureSubpacketTag.ExpireTime, critical, isLongLength, data) { } - public SignatureExpirationTime( - bool critical, - long seconds) + public SignatureExpirationTime(bool critical, long seconds) : base(SignatureSubpacketTag.ExpireTime, critical, false, TimeToBytes(seconds)) { } @@ -39,16 +28,7 @@ public SignatureExpirationTime( /** * return time in seconds before signature expires after creation time. */ - public long Time - { - get - { - long time = ((long)(data[0] & 0xff) << 24) | ((long)(data[1] & 0xff) << 16) - | ((long)(data[2] & 0xff) << 8) | ((long)data[3] & 0xff); - - return time; - } - } + public long Time => Pack.BE_To_UInt32(data, 0); } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/SignerUserId.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/SignerUserId.cs index e9008b7..45c68c1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/SignerUserId.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/bcpg/sig/SignerUserId.cs @@ -1,9 +1,5 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System; - - - namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Bcpg.Sig { /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/CertificateConfirmationContent.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/CertificateConfirmationContent.cs index f04ca47..61b12f0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/CertificateConfirmationContent.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/CertificateConfirmationContent.cs @@ -9,33 +9,33 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cmp { public class CertificateConfirmationContent { - private readonly DefaultDigestAlgorithmIdentifierFinder digestAlgFinder; - private readonly CertConfirmContent content; + private readonly DefaultDigestAlgorithmIdentifierFinder m_digestAlgFinder; + private readonly CertConfirmContent m_content; public CertificateConfirmationContent(CertConfirmContent content) { - this.content = content; + this.m_content = content; } public CertificateConfirmationContent(CertConfirmContent content, DefaultDigestAlgorithmIdentifierFinder digestAlgFinder) { - this.content = content; - this.digestAlgFinder = digestAlgFinder; + this.m_content = content; + this.m_digestAlgFinder = digestAlgFinder; } public CertConfirmContent ToAsn1Structure() { - return content; + return m_content; } public CertificateStatus[] GetStatusMessages() { - CertStatus[] statusArray = content.ToCertStatusArray(); + CertStatus[] statusArray = m_content.ToCertStatusArray(); CertificateStatus[] ret = new CertificateStatus[statusArray.Length]; for (int i = 0; i != ret.Length; i++) { - ret[i] = new CertificateStatus(digestAlgFinder, statusArray[i]); + ret[i] = new CertificateStatus(m_digestAlgFinder, statusArray[i]); } return ret; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/CertificateConfirmationContentBuilder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/CertificateConfirmationContentBuilder.cs index dc154ea..706adff 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/CertificateConfirmationContentBuilder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/CertificateConfirmationContentBuilder.cs @@ -1,27 +1,25 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cmp; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509; using BestHTTP.SecureProtocol.Org.BouncyCastle.Cms; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO; 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.Cmp { - public class CertificateConfirmationContentBuilder + public sealed class CertificateConfirmationContentBuilder { - private static readonly DefaultSignatureAlgorithmIdentifierFinder sigAlgFinder = new DefaultSignatureAlgorithmIdentifierFinder(); + private static readonly DefaultSignatureAlgorithmIdentifierFinder SigAlgFinder = + new DefaultSignatureAlgorithmIdentifierFinder(); - private readonly DefaultDigestAlgorithmIdentifierFinder digestAlgFinder; - private readonly IList acceptedCerts = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); - private readonly IList acceptedReqIds = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + private readonly DefaultDigestAlgorithmIdentifierFinder m_digestAlgFinder; + private readonly IList m_acceptedCerts = new List(); + private readonly IList m_acceptedReqIDs = new List(); public CertificateConfirmationContentBuilder() : this(new DefaultDigestAlgorithmIdentifierFinder()) @@ -30,39 +28,40 @@ public CertificateConfirmationContentBuilder() public CertificateConfirmationContentBuilder(DefaultDigestAlgorithmIdentifierFinder digestAlgFinder) { - this.digestAlgFinder = digestAlgFinder; + this.m_digestAlgFinder = digestAlgFinder; } public CertificateConfirmationContentBuilder AddAcceptedCertificate(X509Certificate certHolder, BigInteger certReqId) { - acceptedCerts.Add(certHolder); - acceptedReqIds.Add(certReqId); + m_acceptedCerts.Add(certHolder); + m_acceptedReqIDs.Add(certReqId); return this; } public CertificateConfirmationContent Build() { Asn1EncodableVector v = new Asn1EncodableVector(); - for (int i = 0; i != acceptedCerts.Count; i++) + for (int i = 0; i != m_acceptedCerts.Count; i++) { - X509Certificate cert = (X509Certificate)acceptedCerts[i]; - BigInteger reqId = (BigInteger)acceptedReqIds[i]; + X509Certificate cert = m_acceptedCerts[i]; + BigInteger reqID = m_acceptedReqIDs[i]; + AlgorithmIdentifier algorithmIdentifier = SigAlgFinder.Find(cert.SigAlgName); + if (null == algorithmIdentifier) + throw new CmpException("cannot find algorithm identifier for signature name"); - AlgorithmIdentifier algorithmIdentifier = sigAlgFinder.Find(cert.SigAlgName); - - AlgorithmIdentifier digAlg = digestAlgFinder.find(algorithmIdentifier); + AlgorithmIdentifier digAlg = m_digestAlgFinder.Find(algorithmIdentifier); if (null == digAlg) throw new CmpException("cannot find algorithm for digest from signature"); byte[] digest = DigestUtilities.CalculateDigest(digAlg.Algorithm, cert.GetEncoded()); - v.Add(new CertStatus(digest, reqId)); + v.Add(new CertStatus(digest, reqID)); } return new CertificateConfirmationContent(CertConfirmContent.GetInstance(new DerSequence(v)), - digestAlgFinder); + m_digestAlgFinder); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/CertificateStatus.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/CertificateStatus.cs index 4bf4066..921f407 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/CertificateStatus.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/CertificateStatus.cs @@ -26,19 +26,13 @@ public CertificateStatus(DefaultDigestAlgorithmIdentifierFinder digestAlgFinder, this.certStatus = certStatus; } - public PkiStatusInfo PkiStatusInfo - { - get { return certStatus.StatusInfo; } - } + public virtual PkiStatusInfo StatusInfo => certStatus.StatusInfo; - public BigInteger CertRequestId - { - get { return certStatus.CertReqID.Value; } - } + public virtual BigInteger CertRequestID => certStatus.CertReqID.Value; - public bool IsVerified(X509Certificate cert) + public virtual bool IsVerified(X509Certificate cert) { - AlgorithmIdentifier digAlg = digestAlgFinder.find(sigAlgFinder.Find(cert.SigAlgName)); + AlgorithmIdentifier digAlg = digestAlgFinder.Find(sigAlgFinder.Find(cert.SigAlgName)); if (null == digAlg) throw new CmpException("cannot find algorithm for digest from signature " + cert.SigAlgName); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/CmpException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/CmpException.cs index 816a37f..e31b76d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/CmpException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/CmpException.cs @@ -1,13 +1,16 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cmp { + [Serializable] public class CmpException : Exception { public CmpException() + : base() { } @@ -20,6 +23,11 @@ public CmpException(string message, Exception innerException) : base(message, innerException) { } + + protected CmpException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/GeneralPkiMessage.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/GeneralPkiMessage.cs index fa10db9..71062fe 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/GeneralPkiMessage.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/GeneralPkiMessage.cs @@ -1,7 +1,5 @@ #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.Cmp; @@ -9,7 +7,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cmp { public class GeneralPkiMessage { - private readonly PkiMessage pkiMessage; + private readonly PkiMessage m_pkiMessage; private static PkiMessage ParseBytes(byte[] encoding) { @@ -22,7 +20,7 @@ private static PkiMessage ParseBytes(byte[] encoding) /// PKI message. public GeneralPkiMessage(PkiMessage pkiMessage) { - this.pkiMessage = pkiMessage; + this.m_pkiMessage = pkiMessage; } /// @@ -34,29 +32,17 @@ public GeneralPkiMessage(byte[] encoding) { } - public PkiHeader Header - { - get { return pkiMessage.Header; } - } + public virtual PkiHeader Header => m_pkiMessage.Header; - public PkiBody Body - { - get { return pkiMessage.Body; } - } + public virtual PkiBody Body => m_pkiMessage.Body; /// /// Return true if this message has protection bits on it. A return value of true /// indicates the message can be used to construct a ProtectedPKIMessage. /// - public bool HasProtection - { - get { return pkiMessage.Protection != null; } - } + public virtual bool HasProtection => m_pkiMessage.Protection != null; - public PkiMessage ToAsn1Structure() - { - return pkiMessage; - } + public virtual PkiMessage ToAsn1Structure() => m_pkiMessage; } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/ProtectedPkiMessage.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/ProtectedPkiMessage.cs index 6b79d88..96a8091 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/ProtectedPkiMessage.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/ProtectedPkiMessage.cs @@ -17,7 +17,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cmp /// public class ProtectedPkiMessage { - private readonly PkiMessage pkiMessage; + private readonly PkiMessage m_pkiMessage; /// /// Wrap a general message. @@ -27,11 +27,12 @@ public class ProtectedPkiMessage public ProtectedPkiMessage(GeneralPkiMessage pkiMessage) { if (!pkiMessage.HasProtection) - throw new ArgumentException("pki message not protected"); + throw new ArgumentException("GeneralPkiMessage not protected"); - this.pkiMessage = pkiMessage.ToAsn1Structure(); + this.m_pkiMessage = pkiMessage.ToAsn1Structure(); } + // TODO[cmp] Make internal? (Has test that uses it) /// /// Wrap a PKI message. /// @@ -40,63 +41,49 @@ public ProtectedPkiMessage(GeneralPkiMessage pkiMessage) public ProtectedPkiMessage(PkiMessage pkiMessage) { if (null == pkiMessage.Header.ProtectionAlg) - throw new ArgumentException("pki message not protected"); + throw new ArgumentException("PkiMessage not protected"); - this.pkiMessage = pkiMessage; + this.m_pkiMessage = pkiMessage; } - /// - /// Message header - /// - public PkiHeader Header - { - get { return pkiMessage.Header; } - } + /// Message header + public virtual PkiHeader Header => m_pkiMessage.Header; - /// - /// Message Body - /// - public PkiBody Body - { - get { return pkiMessage.Body; } - } + /// Message body + public virtual PkiBody Body => m_pkiMessage.Body; /// /// Return the underlying ASN.1 structure contained in this object. /// - /// PKI Message structure - public PkiMessage ToAsn1Message() - { - return pkiMessage; - } + /// PkiMessage structure + public virtual PkiMessage ToAsn1Message() => m_pkiMessage; /// /// Determine whether the message is protected by a password based MAC. Use verify(PKMACBuilder, char[]) /// to verify the message if this method returns true. /// /// true if protection MAC PBE based, false otherwise. - public bool HasPasswordBasedMacProtected + public virtual bool HasPasswordBasedMacProtected { - get { return Header.ProtectionAlg.Algorithm.Equals(CmpObjectIdentifiers.passwordBasedMac); } + get { return CmpObjectIdentifiers.passwordBasedMac.Equals(Header.ProtectionAlg.Algorithm); } } /// /// Return the extra certificates associated with this message. /// /// an array of extra certificates, zero length if none present. - public X509Certificate[] GetCertificates() + public virtual X509Certificate[] GetCertificates() { - CmpCertificate[] certs = pkiMessage.GetExtraCerts(); + CmpCertificate[] certs = m_pkiMessage.GetExtraCerts(); if (null == certs) return new X509Certificate[0]; - X509Certificate[] res = new X509Certificate[certs.Length]; + X509Certificate[] result = new X509Certificate[certs.Length]; for (int t = 0; t < certs.Length; t++) { - res[t] = new X509Certificate(X509CertificateStructure.GetInstance(certs[t].GetEncoded())); + result[t] = new X509Certificate(certs[t].X509v3PKCert); } - - return res; + return result; } /// @@ -104,27 +91,13 @@ public X509Certificate[] GetCertificates() /// /// a factory of signature verifiers. /// true if the provider is able to create a verifier that validates the signature, false otherwise. - public bool Verify(IVerifierFactory verifierFactory) + public virtual bool Verify(IVerifierFactory verifierFactory) { - IStreamCalculator streamCalculator = verifierFactory.CreateCalculator(); + IStreamCalculator streamCalculator = verifierFactory.CreateCalculator(); - IVerifier result = (IVerifier)Process(streamCalculator); + IVerifier result = Process(streamCalculator); - return result.IsVerified(pkiMessage.Protection.GetBytes()); - } - - private object Process(IStreamCalculator streamCalculator) - { - Asn1EncodableVector avec = new Asn1EncodableVector(); - avec.Add(pkiMessage.Header); - avec.Add(pkiMessage.Body); - byte[] enc = new DerSequence(avec).GetDerEncoded(); - - streamCalculator.Stream.Write(enc, 0, enc.Length); - streamCalculator.Stream.Flush(); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(streamCalculator.Stream); - - return streamCalculator.GetResult(); + return result.IsVerified(m_pkiMessage.Protection.GetBytes()); } /// @@ -134,18 +107,33 @@ private object Process(IStreamCalculator streamCalculator) /// the MAC password /// true if the passed in password and MAC builder verify the message, false otherwise. /// if algorithm not MAC based, or an exception is thrown verifying the MAC. - public bool Verify(PKMacBuilder pkMacBuilder, char[] password) + public virtual bool Verify(PKMacBuilder pkMacBuilder, char[] password) { - if (!CmpObjectIdentifiers.passwordBasedMac.Equals(pkiMessage.Header.ProtectionAlg.Algorithm)) + if (!CmpObjectIdentifiers.passwordBasedMac.Equals(m_pkiMessage.Header.ProtectionAlg.Algorithm)) throw new InvalidOperationException("protection algorithm is not mac based"); - PbmParameter parameter = PbmParameter.GetInstance(pkiMessage.Header.ProtectionAlg.Parameters); + PbmParameter parameter = PbmParameter.GetInstance(m_pkiMessage.Header.ProtectionAlg.Parameters); pkMacBuilder.SetParameters(parameter); - IBlockResult result = (IBlockResult)Process(pkMacBuilder.Build(password).CreateCalculator()); + IBlockResult result = Process(pkMacBuilder.Build(password).CreateCalculator()); + + return Arrays.ConstantTimeAreEqual(result.Collect(), m_pkiMessage.Protection.GetBytes()); + } + + private TResult Process(IStreamCalculator streamCalculator) + { + Asn1EncodableVector avec = new Asn1EncodableVector(); + avec.Add(m_pkiMessage.Header); + avec.Add(m_pkiMessage.Body); + byte[] enc = new DerSequence(avec).GetDerEncoded(); - return Arrays.ConstantTimeAreEqual(result.Collect(), this.pkiMessage.Protection.GetBytes()); + using (var stream = streamCalculator.Stream) + { + stream.Write(enc, 0, enc.Length); + } + + return streamCalculator.GetResult(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/ProtectedPkiMessageBuilder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/ProtectedPkiMessageBuilder.cs index 2d67fb6..db86f1e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/ProtectedPkiMessageBuilder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/ProtectedPkiMessageBuilder.cs @@ -1,24 +1,23 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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.X509; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.X509; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cmp { - public class ProtectedPkiMessageBuilder + public sealed class ProtectedPkiMessageBuilder { - private PkiHeaderBuilder hdrBuilBuilder; + private readonly PkiHeaderBuilder m_hdrBuilder; private PkiBody body; - private IList generalInfos = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); - private IList extraCerts = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + private readonly List generalInfos = new List(); + private readonly List extraCerts = new List(); public ProtectedPkiMessageBuilder(GeneralName sender, GeneralName recipient) : this(PkiHeader.CMP_2000, sender, recipient) @@ -27,18 +26,18 @@ public ProtectedPkiMessageBuilder(GeneralName sender, GeneralName recipient) public ProtectedPkiMessageBuilder(int pvno, GeneralName sender, GeneralName recipient) { - hdrBuilBuilder = new PkiHeaderBuilder(pvno, sender, recipient); + m_hdrBuilder = new PkiHeaderBuilder(pvno, sender, recipient); } public ProtectedPkiMessageBuilder SetTransactionId(byte[] tid) { - hdrBuilBuilder.SetTransactionID(tid); + m_hdrBuilder.SetTransactionID(tid); return this; } public ProtectedPkiMessageBuilder SetFreeText(PkiFreeText freeText) { - hdrBuilBuilder.SetFreeText(freeText); + m_hdrBuilder.SetFreeText(freeText); return this; } @@ -48,33 +47,39 @@ public ProtectedPkiMessageBuilder AddGeneralInfo(InfoTypeAndValue genInfo) return this; } - public ProtectedPkiMessageBuilder SetMessageTime(DerGeneralizedTime generalizedTime) + public ProtectedPkiMessageBuilder SetMessageTime(DateTime time) { - hdrBuilBuilder.SetMessageTime(generalizedTime); + m_hdrBuilder.SetMessageTime(new Asn1GeneralizedTime(time)); + return this; + } + + public ProtectedPkiMessageBuilder SetMessageTime(Asn1GeneralizedTime generalizedTime) + { + m_hdrBuilder.SetMessageTime(generalizedTime); return this; } public ProtectedPkiMessageBuilder SetRecipKID(byte[] id) { - hdrBuilBuilder.SetRecipKID(id); + m_hdrBuilder.SetRecipKID(id); return this; } public ProtectedPkiMessageBuilder SetRecipNonce(byte[] nonce) { - hdrBuilBuilder.SetRecipNonce(nonce); + m_hdrBuilder.SetRecipNonce(nonce); return this; } public ProtectedPkiMessageBuilder SetSenderKID(byte[] id) { - hdrBuilBuilder.SetSenderKID(id); + m_hdrBuilder.SetSenderKID(id); return this; } public ProtectedPkiMessageBuilder SetSenderNonce(byte[] nonce) { - hdrBuilBuilder.SetSenderNonce(nonce); + m_hdrBuilder.SetSenderNonce(nonce); return this; } @@ -95,86 +100,60 @@ public ProtectedPkiMessage Build(ISignatureFactory signatureFactory) if (null == body) throw new InvalidOperationException("body must be set before building"); - IStreamCalculator calculator = signatureFactory.CreateCalculator(); + IStreamCalculator calculator = signatureFactory.CreateCalculator(); - if (!(signatureFactory.AlgorithmDetails is AlgorithmIdentifier)) - { + if (!(signatureFactory.AlgorithmDetails is AlgorithmIdentifier algorithmDetails)) throw new ArgumentException("AlgorithmDetails is not AlgorithmIdentifier"); - } - FinalizeHeader((AlgorithmIdentifier)signatureFactory.AlgorithmDetails); - PkiHeader header = hdrBuilBuilder.Build(); + FinalizeHeader(algorithmDetails); + PkiHeader header = m_hdrBuilder.Build(); DerBitString protection = new DerBitString(CalculateSignature(calculator, header, body)); return FinalizeMessage(header, protection); } - public ProtectedPkiMessage Build(IMacFactory factory) + public ProtectedPkiMessage Build(IMacFactory macFactory) { if (null == body) throw new InvalidOperationException("body must be set before building"); - IStreamCalculator calculator = factory.CreateCalculator(); - FinalizeHeader((AlgorithmIdentifier)factory.AlgorithmDetails); - PkiHeader header = hdrBuilBuilder.Build(); + IStreamCalculator calculator = macFactory.CreateCalculator(); + + if (!(macFactory.AlgorithmDetails is AlgorithmIdentifier algorithmDetails)) + throw new ArgumentException("AlgorithmDetails is not AlgorithmIdentifier"); + + FinalizeHeader(algorithmDetails); + PkiHeader header = m_hdrBuilder.Build(); DerBitString protection = new DerBitString(CalculateSignature(calculator, header, body)); return FinalizeMessage(header, protection); } private void FinalizeHeader(AlgorithmIdentifier algorithmIdentifier) { - hdrBuilBuilder.SetProtectionAlg(algorithmIdentifier); + m_hdrBuilder.SetProtectionAlg(algorithmIdentifier); if (generalInfos.Count > 0) { - InfoTypeAndValue[] genInfos = new InfoTypeAndValue[generalInfos.Count]; - for (int t = 0; t < genInfos.Length; t++) - { - genInfos[t] = (InfoTypeAndValue)generalInfos[t]; - } - - hdrBuilBuilder.SetGeneralInfo(genInfos); + m_hdrBuilder.SetGeneralInfo(generalInfos.ToArray()); } } private ProtectedPkiMessage FinalizeMessage(PkiHeader header, DerBitString protection) { - if (extraCerts.Count > 0) + if (extraCerts.Count < 1) + return new ProtectedPkiMessage(new PkiMessage(header, body, protection)); + + CmpCertificate[] cmpCertificates = new CmpCertificate[extraCerts.Count]; + for (int i = 0; i < cmpCertificates.Length; i++) { - CmpCertificate[] cmpCertificates = new CmpCertificate[extraCerts.Count]; - for (int i = 0; i < cmpCertificates.Length; i++) - { - byte[] cert = ((X509Certificate)extraCerts[i]).GetEncoded(); - cmpCertificates[i] = CmpCertificate.GetInstance((Asn1Sequence.FromByteArray(cert))); - } - - return new ProtectedPkiMessage(new PkiMessage(header, body, protection, cmpCertificates)); + cmpCertificates[i] = new CmpCertificate(extraCerts[i].CertificateStructure); } - return new ProtectedPkiMessage(new PkiMessage(header, body, protection)); + return new ProtectedPkiMessage(new PkiMessage(header, body, protection, cmpCertificates)); } - private byte[] CalculateSignature(IStreamCalculator signer, PkiHeader header, PkiBody body) + private byte[] CalculateSignature(IStreamCalculator signer, PkiHeader header, PkiBody body) { - Asn1EncodableVector avec = new Asn1EncodableVector(); - avec.Add(header); - avec.Add(body); - byte[] encoded = new DerSequence(avec).GetEncoded(); - signer.Stream.Write(encoded, 0, encoded.Length); - object result = signer.GetResult(); - - if (result is DefaultSignatureResult) - { - return ((DefaultSignatureResult)result).Collect(); - } - else if (result is IBlockResult) - { - return ((IBlockResult)result).Collect(); - } - else if (result is byte[]) - { - return (byte[])result; - } - - throw new InvalidOperationException("result is not byte[] or DefaultSignatureResult"); + new DerSequence(header, body).EncodeTo(signer.Stream); + return signer.GetResult().Collect(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/RevocationDetails.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/RevocationDetails.cs index 97a5e00..690558b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/RevocationDetails.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/RevocationDetails.cs @@ -1,41 +1,27 @@ #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.Math; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cmp { - public class RevocationDetails + public struct RevocationDetails { - private readonly RevDetails revDetails; + private readonly RevDetails m_revDetails; public RevocationDetails(RevDetails revDetails) { - this.revDetails = revDetails; + m_revDetails = revDetails; } - public X509Name Subject - { - get { return revDetails.CertDetails.Subject; } - } + public X509Name Subject => m_revDetails.CertDetails.Subject; - public X509Name Issuer - { - get { return revDetails.CertDetails.Issuer; } - } + public X509Name Issuer => m_revDetails.CertDetails.Issuer; - public BigInteger SerialNumber - { - get { return revDetails.CertDetails.SerialNumber.Value; } - } + public BigInteger SerialNumber => m_revDetails.CertDetails.SerialNumber.Value; - public RevDetails ToASN1Structure() - { - return revDetails; - } + public RevDetails ToASN1Structure() => m_revDetails; } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/RevocationDetailsBuilder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/RevocationDetailsBuilder.cs index 9affc19..618a00c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/RevocationDetailsBuilder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cmp/RevocationDetailsBuilder.cs @@ -1,7 +1,5 @@ #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.Cmp; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Crmf; @@ -10,15 +8,15 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cmp { - public class RevocationDetailsBuilder + public sealed class RevocationDetailsBuilder { - private readonly CertTemplateBuilder _templateBuilder = new CertTemplateBuilder(); + private readonly CertTemplateBuilder m_templateBuilder = new CertTemplateBuilder(); public RevocationDetailsBuilder SetPublicKey(SubjectPublicKeyInfo publicKey) { if (publicKey != null) { - _templateBuilder.SetPublicKey(publicKey); + m_templateBuilder.SetPublicKey(publicKey); } return this; @@ -28,7 +26,7 @@ public RevocationDetailsBuilder SetIssuer(X509Name issuer) { if (issuer != null) { - _templateBuilder.SetIssuer(issuer); + m_templateBuilder.SetIssuer(issuer); } return this; @@ -38,7 +36,7 @@ public RevocationDetailsBuilder SetSerialNumber(BigInteger serialNumber) { if (serialNumber != null) { - _templateBuilder.SetSerialNumber(new DerInteger(serialNumber)); + m_templateBuilder.SetSerialNumber(new DerInteger(serialNumber)); } return this; @@ -48,7 +46,7 @@ public RevocationDetailsBuilder SetSubject(X509Name subject) { if (subject != null) { - _templateBuilder.SetSubject(subject); + m_templateBuilder.SetSubject(subject); } return this; @@ -56,7 +54,7 @@ public RevocationDetailsBuilder SetSubject(X509Name subject) public RevocationDetails Build() { - return new RevocationDetails(new RevDetails(_templateBuilder.Build())); + return new RevocationDetails(new RevDetails(m_templateBuilder.Build())); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAttributeTableGenerationException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAttributeTableGenerationException.cs index 2aae9bd..9918f74 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAttributeTableGenerationException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAttributeTableGenerationException.cs @@ -1,31 +1,33 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms { -#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE) [Serializable] -#endif public class CmsAttributeTableGenerationException : CmsException { - public CmsAttributeTableGenerationException() - { - } + public CmsAttributeTableGenerationException() + : base() + { + } + + public CmsAttributeTableGenerationException(string message) + : base(message) + { + } - public CmsAttributeTableGenerationException( - string name) - : base(name) - { - } + public CmsAttributeTableGenerationException(string message, Exception innerException) + : base(message, innerException) + { + } - public CmsAttributeTableGenerationException( - string name, - Exception e) - : base(name, e) - { - } + protected CmsAttributeTableGenerationException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAttributeTableGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAttributeTableGenerator.cs index 5513236..888bee5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAttributeTableGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAttributeTableGenerator.cs @@ -1,7 +1,6 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms; @@ -22,7 +21,7 @@ public enum CmsAttributeTableParameter public interface CmsAttributeTableGenerator { - AttributeTable GetAttributes(IDictionary parameters); + AttributeTable GetAttributes(IDictionary parameters); } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthEnvelopedData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthEnvelopedData.cs index a6830c9..97b4127 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthEnvelopedData.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthEnvelopedData.cs @@ -1,7 +1,6 @@ #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; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedData.cs index 873d974..3e0baca 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedData.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedData.cs @@ -1,7 +1,6 @@ #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; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedDataGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedDataGenerator.cs index 4cb7d54..0890322 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedDataGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedDataGenerator.cs @@ -7,7 +7,6 @@ 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.Generators; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; @@ -32,20 +31,14 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms 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) + /// Constructor allowing specific source of randomness + /// Instance of SecureRandom to use. + public CmsAuthenticatedDataGenerator(SecureRandom random) + : base(random) { } @@ -71,9 +64,7 @@ private CmsAuthenticatedData Generate( Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, encKeyBytes); - ICipherParameters cipherParameters; - macAlgId = GetAlgorithmIdentifier( - macOid, encKey, asn1Params, out cipherParameters); + macAlgId = GetAlgorithmIdentifier(macOid, encKey, asn1Params, out var cipherParameters); IMac mac = MacUtilities.GetMac(macOid); // TODO Confirm no ParametersWithRandom needed @@ -81,12 +72,11 @@ private CmsAuthenticatedData Generate( // 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); + var bOut = new MemoryStream(); + using (var mOut = new TeeOutputStream(bOut, new MacSink(mac))) + { + content.Write(mOut); + } encContent = new BerOctetString(bOut.ToArray()); @@ -106,13 +96,13 @@ private CmsAuthenticatedData Generate( throw new CmsException("exception decoding algorithm parameters.", e); } - Asn1EncodableVector recipientInfos = new Asn1EncodableVector(); + var recipientInfos = new Asn1EncodableVector(); foreach (RecipientInfoGenerator rig in recipientInfoGenerators) { try { - recipientInfos.Add(rig.Generate(encKey, rand)); + recipientInfos.Add(rig.Generate(encKey, m_random)); } catch (InvalidKeyException e) { @@ -124,11 +114,11 @@ private CmsAuthenticatedData Generate( } } - 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)); + var eci = new ContentInfo(CmsObjectIdentifiers.Data, encContent); + + var contentInfo = new ContentInfo( + CmsObjectIdentifiers.AuthenticatedData, + new AuthenticatedData(null, new DerSet(recipientInfos), macAlgId, null, eci, null, macResult, null)); return new CmsAuthenticatedData(contentInfo); } @@ -145,7 +135,7 @@ public CmsAuthenticatedData Generate( // FIXME Will this work for macs? CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid); - keyGen.Init(new KeyGenerationParameters(rand, keyGen.DefaultStrength)); + keyGen.Init(new KeyGenerationParameters(m_random, keyGen.DefaultStrength)); return Generate(content, encryptionOid, keyGen); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedDataParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedDataParser.cs index 6198e34..f2e4ad1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedDataParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedDataParser.cs @@ -1,7 +1,6 @@ #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; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedDataStreamGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedDataStreamGenerator.cs index df89098..16eb120 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedDataStreamGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedDataStreamGenerator.cs @@ -44,20 +44,14 @@ public class CmsAuthenticatedDataStreamGenerator private int _bufferSize; private bool _berEncodeRecipientSet; - /** - * base constructor - */ public CmsAuthenticatedDataStreamGenerator() { } - /** - * constructor allowing specific source of randomness - * @param rand instance of SecureRandom to use - */ - public CmsAuthenticatedDataStreamGenerator( - SecureRandom rand) - : base(rand) + /// Constructor allowing specific source of randomness + /// Instance of SecureRandom to use. + public CmsAuthenticatedDataStreamGenerator(SecureRandom random) + : base(random) { } @@ -107,7 +101,7 @@ private Stream Open( { try { - recipientInfos.Add(rig.Generate(encKey, rand)); + recipientInfos.Add(rig.Generate(encKey, m_random)); } catch (InvalidKeyException e) { @@ -197,7 +191,7 @@ public Stream Open( { CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid); - keyGen.Init(new KeyGenerationParameters(rand, keyGen.DefaultStrength)); + keyGen.Init(new KeyGenerationParameters(m_random, keyGen.DefaultStrength)); return Open(outStr, encryptionOid, keyGen); } @@ -212,7 +206,7 @@ public Stream Open( { CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid); - keyGen.Init(new KeyGenerationParameters(rand, keySize)); + keyGen.Init(new KeyGenerationParameters(m_random, keySize)); return Open(outStr, encryptionOid, keyGen); } @@ -240,26 +234,28 @@ public CmsAuthenticatedDataOutputStream( this.eiGen = eiGen; } - public override void WriteByte( - byte b) - { - macStream.WriteByte(b); - } + public override void Write(byte[] buffer, int offset, int count) + { + macStream.Write(buffer, offset, count); + } - public override void Write( - byte[] bytes, - int off, - int len) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) + { + macStream.Write(buffer); + } +#endif + + public override void WriteByte(byte value) { - macStream.Write(bytes, off, len); + macStream.WriteByte(value); } -#if PORTABLE || NETFX_CORE protected override void Dispose(bool disposing) { if (disposing) { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(macStream); + macStream.Dispose(); // TODO Parent context(s) should really be be closed explicitly @@ -275,25 +271,6 @@ protected override void Dispose(bool disposing) } base.Dispose(disposing); } -#else - public override void Close() - { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(macStream); - - // TODO Parent context(s) should really be be closed explicitly - - eiGen.Close(); - - // [TODO] auth attributes go here - byte[] macOctets = MacUtilities.DoFinal(mac); - authGen.AddObject(new DerOctetString(macOctets)); - // [TODO] unauth attributes go here - - authGen.Close(); - cGen.Close(); - base.Close(); - } -#endif } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedGenerator.cs index e8a8e3a..2815e0d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSAuthenticatedGenerator.cs @@ -16,21 +16,14 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms public class CmsAuthenticatedGenerator : CmsEnvelopedGenerator { - /** - * base constructor - */ public CmsAuthenticatedGenerator() { } - /** - * constructor allowing specific source of randomness - * - * @param rand instance of SecureRandom to use - */ - public CmsAuthenticatedGenerator( - SecureRandom rand) - : base(rand) + /// Constructor allowing specific source of randomness + /// Instance of SecureRandom to use. + public CmsAuthenticatedGenerator(SecureRandom random) + : base(random) { } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSCompressedData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSCompressedData.cs index c97ad66..9e6696c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSCompressedData.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSCompressedData.cs @@ -1,12 +1,11 @@ #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.Utilities; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Zlib; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Compression; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms { @@ -47,7 +46,7 @@ public byte[] GetContent() ContentInfo content = comData.EncapContentInfo; Asn1OctetString bytes = (Asn1OctetString) content.Content; - ZInputStream zIn = new ZInputStream(bytes.GetOctetStream()); + Stream zIn = ZLib.DecompressInput(bytes.GetOctetStream()); try { @@ -59,7 +58,7 @@ public byte[] GetContent() } finally { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(zIn); + zIn.Dispose(); } } @@ -78,8 +77,7 @@ public byte[] GetContent(int limit) ContentInfo content = comData.EncapContentInfo; Asn1OctetString bytes = (Asn1OctetString)content.Content; - - ZInputStream zIn = new ZInputStream(new MemoryStream(bytes.GetOctets(), false)); + Stream zIn = ZLib.DecompressInput(bytes.GetOctetStream()); try { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSCompressedDataGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSCompressedDataGenerator.cs index 0ed4a4f..47cd011 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSCompressedDataGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSCompressedDataGenerator.cs @@ -1,14 +1,12 @@ #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; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Zlib; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms { @@ -25,32 +23,34 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms */ public class CmsCompressedDataGenerator { - public const string ZLib = "1.2.840.113549.1.9.16.3.8"; + public static readonly string ZLib = CmsObjectIdentifiers.ZlibCompress.Id; - public CmsCompressedDataGenerator() + public CmsCompressedDataGenerator() { } /** * Generate an object that contains an CMS Compressed Data */ - public CmsCompressedData Generate( - CmsProcessable content, - string compressionOid) + public CmsCompressedData Generate(CmsProcessable content, string compressionOid) { + if (ZLib != compressionOid) + throw new ArgumentException("Unsupported compression algorithm: " + compressionOid, + nameof(compressionOid)); + AlgorithmIdentifier comAlgId; Asn1OctetString comOcts; try { MemoryStream bOut = new MemoryStream(); - ZOutputStream zOut = new ZOutputStream(bOut, JZlib.Z_DEFAULT_COMPRESSION); - - content.Write(zOut); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(zOut); + using (var zOut = Utilities.IO.Compression.ZLib.CompressOutput(bOut, -1)) + { + content.Write(zOut); + } - comAlgId = new AlgorithmIdentifier(new DerObjectIdentifier(compressionOid)); + comAlgId = new AlgorithmIdentifier(CmsObjectIdentifiers.ZlibCompress); comOcts = new BerOctetString(bOut.ToArray()); } catch (IOException e) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSCompressedDataParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSCompressedDataParser.cs index a44d910..280fda9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSCompressedDataParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSCompressedDataParser.cs @@ -1,12 +1,11 @@ #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.Utilities.Zlib; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Compression; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms { @@ -47,8 +46,9 @@ public CmsTypedStream GetContent() ContentInfoParser content = comData.GetEncapContentInfo(); Asn1OctetStringParser bytes = (Asn1OctetStringParser)content.GetContent(Asn1Tags.OctetString); + Stream zIn = ZLib.DecompressInput(bytes.GetOctetStream()); - return new CmsTypedStream(content.ContentType.ToString(), new ZInputStream(bytes.GetOctetStream())); + return new CmsTypedStream(content.ContentType.ToString(), zIn); } catch (IOException e) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSCompressedDataStreamGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSCompressedDataStreamGenerator.cs index d55df66..f223591 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSCompressedDataStreamGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSCompressedDataStreamGenerator.cs @@ -6,9 +6,9 @@ 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.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Zlib; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms { @@ -29,10 +29,10 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms */ public class CmsCompressedDataStreamGenerator { - public const string ZLib = "1.2.840.113549.1.9.16.3.8"; + public static readonly string ZLib = CmsObjectIdentifiers.ZlibCompress.Id; + + private int _bufferSize; - private int _bufferSize; - /** * base constructor */ @@ -45,24 +45,27 @@ public CmsCompressedDataStreamGenerator() * * @param bufferSize length of octet strings to buffer the data. */ - public void SetBufferSize( - int bufferSize) + public void SetBufferSize(int bufferSize) { _bufferSize = bufferSize; } - public Stream Open( - Stream outStream, - string compressionOID) + public Stream Open(Stream outStream) + { + return Open(outStream, CmsObjectIdentifiers.Data.Id, ZLib); + } + + public Stream Open(Stream outStream, string compressionOid) { - return Open(outStream, CmsObjectIdentifiers.Data.Id, compressionOID); + return Open(outStream, CmsObjectIdentifiers.Data.Id, compressionOid); } - public Stream Open( - Stream outStream, - string contentOID, - string compressionOID) + public Stream Open(Stream outStream, string contentOid, string compressionOid) { + if (ZLib != compressionOid) + throw new ArgumentException("Unsupported compression algorithm: " + compressionOid, + nameof(compressionOid)); + BerSequenceGenerator sGen = new BerSequenceGenerator(outStream); sGen.AddObject(CmsObjectIdentifiers.CompressedData); @@ -77,32 +80,32 @@ public Stream Open( cGen.AddObject(new DerInteger(0)); // CompressionAlgorithmIdentifier - cGen.AddObject(new AlgorithmIdentifier(new DerObjectIdentifier(ZLib))); + cGen.AddObject(new AlgorithmIdentifier(CmsObjectIdentifiers.ZlibCompress)); // // Encapsulated ContentInfo // BerSequenceGenerator eiGen = new BerSequenceGenerator(cGen.GetRawOutputStream()); - eiGen.AddObject(new DerObjectIdentifier(contentOID)); + eiGen.AddObject(new DerObjectIdentifier(contentOid)); Stream octetStream = CmsUtilities.CreateBerOctetOutputStream( eiGen.GetRawOutputStream(), 0, true, _bufferSize); return new CmsCompressedOutputStream( - new ZOutputStream(octetStream, JZlib.Z_DEFAULT_COMPRESSION), sGen, cGen, eiGen); + Utilities.IO.Compression.ZLib.CompressOutput(octetStream, -1), sGen, cGen, eiGen); } private class CmsCompressedOutputStream : BaseOutputStream { - private ZOutputStream _out; + private Stream _out; private BerSequenceGenerator _sGen; private BerSequenceGenerator _cGen; private BerSequenceGenerator _eiGen; internal CmsCompressedOutputStream( - ZOutputStream outStream, + Stream outStream, BerSequenceGenerator sGen, BerSequenceGenerator cGen, BerSequenceGenerator eiGen) @@ -113,26 +116,28 @@ internal CmsCompressedOutputStream( _eiGen = eiGen; } - public override void WriteByte( - byte b) + public override void Write(byte[] buffer, int offset, int count) { - _out.WriteByte(b); + _out.Write(buffer, offset, count); } - public override void Write( - byte[] bytes, - int off, - int len) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) + { + _out.Write(buffer); + } +#endif + + public override void WriteByte(byte value) { - _out.Write(bytes, off, len); + _out.WriteByte(value); } -#if PORTABLE || NETFX_CORE protected override void Dispose(bool disposing) { if (disposing) { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(_out); + _out.Dispose(); // TODO Parent context(s) should really be be closed explicitly @@ -142,19 +147,6 @@ protected override void Dispose(bool disposing) } base.Dispose(disposing); } -#else - public override void Close() - { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(_out); - - // TODO Parent context(s) should really be be closed explicitly - - _eiGen.Close(); - _cGen.Close(); - _sGen.Close(); - base.Close(); - } -#endif } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSContentInfoParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSContentInfoParser.cs index 3357048..4de7428 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSContentInfoParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSContentInfoParser.cs @@ -44,7 +44,7 @@ protected CmsContentInfoParser( */ public void Close() { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(this.data); + data.Dispose(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedData.cs index cf9570b..3d0d143 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedData.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedData.cs @@ -1,14 +1,11 @@ #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.Security; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedDataGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedDataGenerator.cs index 8ea1451..b0e69b6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedDataGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedDataGenerator.cs @@ -1,24 +1,16 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw; 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.IO; 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.Date; -using BestHTTP.SecureProtocol.Org.BouncyCastle.X509; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms { @@ -43,10 +35,9 @@ public CmsEnvelopedDataGenerator() } /// Constructor allowing specific source of randomness - /// Instance of SecureRandom to use. - public CmsEnvelopedDataGenerator( - SecureRandom rand) - : base(rand) + /// Instance of SecureRandom to use. + public CmsEnvelopedDataGenerator(SecureRandom random) + : base(random) { } @@ -75,14 +66,13 @@ private CmsEnvelopedData Generate( encryptionOid, encKey, asn1Params, out cipherParameters); IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid); - cipher.Init(true, new ParametersWithRandom(cipherParameters, rand)); + cipher.Init(true, new ParametersWithRandom(cipherParameters, m_random)); MemoryStream bOut = new MemoryStream(); - CipherStream cOut = new CipherStream(bOut, null, cipher); - - content.Write(cOut); - - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(cOut); + using (var cOut = new CipherStream(bOut, null, cipher)) + { + content.Write(cOut); + } encContent = new BerOctetString(bOut.ToArray()); } @@ -106,7 +96,7 @@ private CmsEnvelopedData Generate( { try { - recipientInfos.Add(rig.Generate(encKey, rand)); + recipientInfos.Add(rig.Generate(encKey, m_random)); } catch (InvalidKeyException e) { @@ -126,7 +116,8 @@ private CmsEnvelopedData Generate( Asn1Set unprotectedAttrSet = null; if (unprotectedAttributeGenerator != null) { - Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable()); + Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes( + new Dictionary()); unprotectedAttrSet = new BerSet(attrTable.ToAsn1EncodableVector()); } @@ -147,7 +138,7 @@ public CmsEnvelopedData Generate( { CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid); - keyGen.Init(new KeyGenerationParameters(rand, keyGen.DefaultStrength)); + keyGen.Init(new KeyGenerationParameters(m_random, keyGen.DefaultStrength)); return Generate(content, encryptionOid, keyGen); } @@ -169,9 +160,12 @@ public CmsEnvelopedData Generate(CmsProcessable content, ICipherBuilderWithKey c encKey = (KeyParameter) cipherBuilder.Key; MemoryStream collector = new MemoryStream(); - Stream bOut = cipherBuilder.BuildCipher(collector).Stream; - content.Write(bOut); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(bOut); + var cipher = cipherBuilder.BuildCipher(collector); + using (var bOut = cipher.Stream) + { + content.Write(bOut); + } + encContent = new BerOctetString(collector.ToArray()); } catch (SecurityUtilityException e) @@ -194,7 +188,7 @@ public CmsEnvelopedData Generate(CmsProcessable content, ICipherBuilderWithKey c { try { - recipientInfos.Add(rig.Generate(encKey, rand)); + recipientInfos.Add(rig.Generate(encKey, m_random)); } catch (InvalidKeyException e) { @@ -214,7 +208,8 @@ public CmsEnvelopedData Generate(CmsProcessable content, ICipherBuilderWithKey c Asn1Set unprotectedAttrSet = null; if (unprotectedAttributeGenerator != null) { - Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable()); + Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes( + new Dictionary()); unprotectedAttrSet = new BerSet(attrTable.ToAsn1EncodableVector()); } @@ -236,7 +231,7 @@ public CmsEnvelopedData Generate( { CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid); - keyGen.Init(new KeyGenerationParameters(rand, keySize)); + keyGen.Init(new KeyGenerationParameters(m_random, keySize)); return Generate(content, encryptionOid, keyGen); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedDataParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedDataParser.cs index 57fcc7b..a13ae5a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedDataParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedDataParser.cs @@ -1,13 +1,11 @@ #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 { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedDataStreamGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedDataStreamGenerator.cs index 7b82027..cdc8e07 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedDataStreamGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedDataStreamGenerator.cs @@ -1,23 +1,18 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist; 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.Generators; 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.IO; -using BestHTTP.SecureProtocol.Org.BouncyCastle.X509; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms { @@ -53,10 +48,9 @@ public CmsEnvelopedDataStreamGenerator() } /// Constructor allowing specific source of randomness - /// Instance of SecureRandom to use. - public CmsEnvelopedDataStreamGenerator( - SecureRandom rand) - : base(rand) + /// Instance of SecureRandom to use. + public CmsEnvelopedDataStreamGenerator(SecureRandom random) + : base(random) { } @@ -111,7 +105,7 @@ private Stream Open( { try { - recipientInfos.Add(rig.Generate(encKey, rand)); + recipientInfos.Add(rig.Generate(encKey, m_random)); } catch (InvalidKeyException e) { @@ -169,7 +163,7 @@ private Stream Open( eiGen.GetRawOutputStream(), 0, false, _bufferSize); IBufferedCipher cipher = CipherUtilities.GetCipher(encAlgID.Algorithm); - cipher.Init(true, new ParametersWithRandom(cipherParameters, rand)); + cipher.Init(true, new ParametersWithRandom(cipherParameters, m_random)); CipherStream cOut = new CipherStream(octetOutputStream, null, cipher); return new CmsEnvelopedDataOutputStream(this, cOut, cGen, envGen, eiGen); @@ -198,7 +192,7 @@ public Stream Open( { CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid); - keyGen.Init(new KeyGenerationParameters(rand, keyGen.DefaultStrength)); + keyGen.Init(new KeyGenerationParameters(m_random, keyGen.DefaultStrength)); return Open(outStream, encryptionOid, keyGen); } @@ -214,7 +208,7 @@ public Stream Open( { CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid); - keyGen.Init(new KeyGenerationParameters(rand, keySize)); + keyGen.Init(new KeyGenerationParameters(m_random, keySize)); return Open(outStream, encryptionOid, keyGen); } @@ -243,68 +237,48 @@ public CmsEnvelopedDataOutputStream( _eiGen = eiGen; } - public override void WriteByte( - byte b) + public override void Write(byte[] buffer, int offset, int count) { - _out.WriteByte(b); + _out.Write(buffer, offset, count); } - public override void Write( - byte[] bytes, - int off, - int len) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) + { + _out.Write(buffer); + } +#endif + + public override void WriteByte(byte value) { - _out.Write(bytes, off, len); + _out.WriteByte(value); } -#if PORTABLE || NETFX_CORE protected override void Dispose(bool disposing) { if (disposing) - { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(_out); + { + _out.Dispose(); // TODO Parent context(s) should really be closed explicitly - _eiGen.Close(); + _eiGen.Close(); if (_outer.unprotectedAttributeGenerator != null) { - Asn1.Cms.AttributeTable attrTable = _outer.unprotectedAttributeGenerator.GetAttributes(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable()); + Asn1.Cms.AttributeTable attrTable = _outer.unprotectedAttributeGenerator.GetAttributes( + new Dictionary()); Asn1Set unprotectedAttrs = new BerSet(attrTable.ToAsn1EncodableVector()); _envGen.AddObject(new DerTaggedObject(false, 1, unprotectedAttrs)); } - _envGen.Close(); - _cGen.Close(); + _envGen.Close(); + _cGen.Close(); } base.Dispose(disposing); } -#else - public override void Close() - { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(_out); - - // TODO Parent context(s) should really be closed explicitly - - _eiGen.Close(); - - if (_outer.unprotectedAttributeGenerator != null) - { - Asn1.Cms.AttributeTable attrTable = _outer.unprotectedAttributeGenerator.GetAttributes(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable()); - - Asn1Set unprotectedAttrs = new BerSet(attrTable.ToAsn1EncodableVector()); - - _envGen.AddObject(new DerTaggedObject(false, 1, unprotectedAttrs)); - } - - _envGen.Close(); - _cGen.Close(); - base.Close(); - } -#endif } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedGenerator.cs index 4517fa3..21b55b2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedGenerator.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms; @@ -15,7 +15,6 @@ using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.X509; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms @@ -33,7 +32,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms * CMSEnvelopedData data = fact.generate(content, algorithm, "BC"); * */ - public class CmsEnvelopedGenerator + public abstract class CmsEnvelopedGenerator { // Note: These tables are complementary: If rc2Table[i]==j, then rc2Ekb[j]==i internal static readonly short[] rc2Table = @@ -102,22 +101,24 @@ public class CmsEnvelopedGenerator public static readonly string ECDHSha1Kdf = X9ObjectIdentifiers.DHSinglePassStdDHSha1KdfScheme.Id; public static readonly string ECMqvSha1Kdf = X9ObjectIdentifiers.MqvSinglePassSha1KdfScheme.Id; - internal readonly IList recipientInfoGenerators = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); - internal readonly SecureRandom rand; + internal readonly IList recipientInfoGenerators = new List(); + internal readonly SecureRandom m_random; internal CmsAttributeTableGenerator unprotectedAttributeGenerator = null; - public CmsEnvelopedGenerator() - : this(new SecureRandom()) + protected CmsEnvelopedGenerator() + : this(CryptoServicesRegistrar.GetSecureRandom()) { } /// Constructor allowing specific source of randomness - /// Instance of SecureRandom to use. - public CmsEnvelopedGenerator( - SecureRandom rand) + /// Instance of SecureRandom to use. + protected CmsEnvelopedGenerator(SecureRandom random) { - this.rand = rand; + if (random == null) + throw new ArgumentNullException(nameof(random)); + + m_random = random; } public CmsAttributeTableGenerator UnprotectedAttributeGenerator @@ -218,7 +219,7 @@ public void AddKeyAgreementRecipient( X509Certificate recipientCert, string cekWrapAlgorithm) { - IList recipientCerts = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(1); + var recipientCerts = new List(1); recipientCerts.Add(recipientCert); AddKeyAgreementRecipients(agreementAlgorithm, senderPrivateKey, senderPublicKey, @@ -240,7 +241,7 @@ public void AddKeyAgreementRecipients( string agreementAlgorithm, AsymmetricKeyParameter senderPrivateKey, AsymmetricKeyParameter senderPublicKey, - ICollection recipientCerts, + IEnumerable recipientCerts, string cekWrapAlgorithm) { if (!senderPrivateKey.IsPrivate) @@ -256,7 +257,7 @@ public void AddKeyAgreementRecipients( KeyAgreeRecipientInfoGenerator karig = new KeyAgreeRecipientInfoGenerator(); karig.KeyAgreementOID = new DerObjectIdentifier(agreementAlgorithm); karig.KeyEncryptionOID = new DerObjectIdentifier(cekWrapAlgorithm); - karig.RecipientCerts = recipientCerts; + karig.RecipientCerts = new List(recipientCerts); karig.SenderKeyPair = new AsymmetricCipherKeyPair(senderPublicKey, senderPrivateKey); recipientInfoGenerators.Add(karig); @@ -307,7 +308,7 @@ protected internal virtual Asn1Encodable GenerateAsn1Parameters( if (encryptionOid.Equals(RC2Cbc)) { byte[] iv = new byte[8]; - rand.NextBytes(iv); + m_random.NextBytes(iv); // TODO Is this detailed repeat of Java version really necessary? int effKeyBits = encKeyBytes.Length * 8; @@ -326,7 +327,7 @@ protected internal virtual Asn1Encodable GenerateAsn1Parameters( } else { - asn1Params = ParameterUtilities.GenerateParameters(encryptionOid, rand); + asn1Params = ParameterUtilities.GenerateParameters(encryptionOid, m_random); } } catch (SecurityUtilityException) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedHelper.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedHelper.cs index 837667e..c95aee1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedHelper.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSEnvelopedHelper.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; @@ -11,7 +11,6 @@ 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.IO; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms @@ -20,8 +19,8 @@ class CmsEnvelopedHelper { internal static readonly CmsEnvelopedHelper Instance = new CmsEnvelopedHelper(); - private static readonly IDictionary KeySizes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private static readonly IDictionary BaseCipherNames = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + private static readonly IDictionary KeySizes = new Dictionary(); + private static readonly IDictionary BaseCipherNames = new Dictionary(); static CmsEnvelopedHelper() { @@ -78,35 +77,32 @@ internal IWrapper CreateWrapper( } } - internal string GetRfc3211WrapperName( - string oid) + internal string GetRfc3211WrapperName(string oid) { if (oid == null) - throw new ArgumentNullException("oid"); + throw new ArgumentNullException(nameof(oid)); - string alg = (string) BaseCipherNames[oid]; - - if (alg == null) - throw new ArgumentException("no name for " + oid, "oid"); + if (!BaseCipherNames.TryGetValue(oid, out var alg)) + throw new ArgumentException("no name for " + oid, nameof(oid)); return alg + "RFC3211Wrap"; } - internal int GetKeySize( - string oid) + internal int GetKeySize(string oid) { - if (!KeySizes.Contains(oid)) - { + if (oid == null) + throw new ArgumentNullException(nameof(oid)); + + if (!KeySizes.TryGetValue(oid, out var keySize)) throw new ArgumentException("no keysize for " + oid, "oid"); - } - return (int) KeySizes[oid]; + return keySize; } internal static RecipientInformationStore BuildRecipientInformationStore( Asn1Set recipientInfos, CmsSecureReadable secureReadable) { - IList infos = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var infos = new List(); for (int i = 0; i != recipientInfos.Count; i++) { RecipientInfo info = RecipientInfo.GetInstance(recipientInfos[i]); @@ -116,25 +112,25 @@ internal static RecipientInformationStore BuildRecipientInformationStore( return new RecipientInformationStore(infos); } - private static void ReadRecipientInfo( - IList infos, RecipientInfo info, CmsSecureReadable secureReadable) + private static void ReadRecipientInfo(IList infos, RecipientInfo info, + CmsSecureReadable secureReadable) { Asn1Encodable recipInfo = info.Info; - if (recipInfo is KeyTransRecipientInfo) + if (recipInfo is KeyTransRecipientInfo keyTransRecipientInfo) { - infos.Add(new KeyTransRecipientInformation((KeyTransRecipientInfo)recipInfo, secureReadable)); + infos.Add(new KeyTransRecipientInformation(keyTransRecipientInfo, secureReadable)); } - else if (recipInfo is KekRecipientInfo) + else if (recipInfo is KekRecipientInfo kekRecipientInfo) { - infos.Add(new KekRecipientInformation((KekRecipientInfo)recipInfo, secureReadable)); + infos.Add(new KekRecipientInformation(kekRecipientInfo, secureReadable)); } - else if (recipInfo is KeyAgreeRecipientInfo) + else if (recipInfo is KeyAgreeRecipientInfo keyAgreeRecipientInfo) { - KeyAgreeRecipientInformation.ReadRecipientInfo(infos, (KeyAgreeRecipientInfo)recipInfo, secureReadable); + KeyAgreeRecipientInformation.ReadRecipientInfo(infos, keyAgreeRecipientInfo, secureReadable); } - else if (recipInfo is PasswordRecipientInfo) + else if (recipInfo is PasswordRecipientInfo passwordRecipientInfo) { - infos.Add(new PasswordRecipientInformation((PasswordRecipientInfo)recipInfo, secureReadable)); + infos.Add(new PasswordRecipientInformation(passwordRecipientInfo, secureReadable)); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSException.cs index 72d1ded..e60631f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSException.cs @@ -1,29 +1,31 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms { -#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE) [Serializable] -#endif public class CmsException : Exception { public CmsException() + : base() + { + } + + public CmsException(string message) + : base(message) { } - public CmsException( - string msg) - : base(msg) + public CmsException(string message, Exception innerException) + : base(message, innerException) { } - public CmsException( - string msg, - Exception e) - : base(msg, e) + protected CmsException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSPBEKey.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSPBEKey.cs index 066ebc2..f19cc3c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSPBEKey.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSPBEKey.cs @@ -21,23 +21,6 @@ public abstract class CmsPbeKey internal readonly byte[] salt; internal readonly int iterationCount; - - public CmsPbeKey( - string password, - byte[] salt, - int iterationCount) - : this(password.ToCharArray(), salt, iterationCount) - { - } - - - public CmsPbeKey( - string password, - AlgorithmIdentifier keyDerivationAlgorithm) - : this(password.ToCharArray(), keyDerivationAlgorithm) - { - } - public CmsPbeKey( char[] password, byte[] salt, @@ -69,23 +52,11 @@ public CmsPbeKey( Array.Clear(this.password, 0, this.password.Length); } - - public string Password - { - get { return new string(password); } - } - public byte[] Salt { get { return Arrays.Clone(salt); } } - - public byte[] GetSalt() - { - return Salt; - } - public int IterationCount { get { return iterationCount; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSProcessable.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSProcessable.cs index a281503..d38ab09 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSProcessable.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSProcessable.cs @@ -14,9 +14,6 @@ public interface CmsProcessable /// This routine may be called multiple times. /// void Write(Stream outStream); - - [Obsolete] - object GetContent(); } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSProcessableByteArray.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSProcessableByteArray.cs index a86007c..8570ed7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSProcessableByteArray.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSProcessableByteArray.cs @@ -2,6 +2,7 @@ #pragma warning disable using System; using System.IO; + using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms; @@ -42,13 +43,6 @@ public virtual void Write(Stream zOut) { zOut.Write(bytes, 0, bytes.Length); } - - /// A clone of the byte array - [Obsolete] - public virtual object GetContent() - { - return bytes.Clone(); - } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSProcessableFile.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSProcessableFile.cs index e66bb22..f3a1f3d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSProcessableFile.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSProcessableFile.cs @@ -1,7 +1,5 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -#if !PORTABLE || NETFX_CORE || DOTNET -using System; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -38,19 +36,12 @@ public virtual Stream GetInputStream() public virtual void Write(Stream zOut) { - Stream inStr = _file.OpenRead(); - Streams.PipeAll(inStr, zOut, _bufSize); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(inStr); - } - - /// The file handle - [Obsolete] - public virtual object GetContent() - { - return _file; + using (var inStr = _file.OpenRead()) + { + Streams.PipeAll(inStr, zOut, _bufSize); + } } } } -#endif #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSProcessableInputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSProcessableInputStream.cs index 702b2dd..0a8a4b3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSProcessableInputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSProcessableInputStream.cs @@ -32,13 +32,7 @@ public virtual void Write(Stream output) CheckSingleUsage(); Streams.PipeAll(input, output); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(input); - } - - [Obsolete] - public virtual object GetContent() - { - return GetInputStream(); + input.Dispose(); } protected virtual void CheckSingleUsage() diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedData.cs index f267b79..ab49bbb 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedData.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedData.cs @@ -1,16 +1,13 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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.Collections; using BestHTTP.SecureProtocol.Org.BouncyCastle.X509; -using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms { @@ -45,13 +42,9 @@ public class CmsSignedData private SignedData signedData; private ContentInfo contentInfo; private SignerInformationStore signerInfoStore; - private IX509Store attrCertStore; - private IX509Store certificateStore; - private IX509Store crlStore; - private IDictionary hashes; + private IDictionary m_hashes; - private CmsSignedData( - CmsSignedData c) + private CmsSignedData(CmsSignedData c) { this.signedData = c.signedData; this.contentInfo = c.contentInfo; @@ -59,15 +52,12 @@ private CmsSignedData( this.signerInfoStore = c.signerInfoStore; } - public CmsSignedData( - byte[] sigBlock) + public CmsSignedData(byte[] sigBlock) : this(CmsUtilities.ReadContentInfo(new MemoryStream(sigBlock, false))) { } - public CmsSignedData( - CmsProcessable signedContent, - byte[] sigBlock) + public CmsSignedData(CmsProcessable signedContent, byte[] sigBlock) : this(signedContent, CmsUtilities.ReadContentInfo(new MemoryStream(sigBlock, false))) { } @@ -78,9 +68,7 @@ public CmsSignedData( * @param hashes a map of precomputed digests for content indexed by name of hash. * @param sigBlock the signature object. */ - public CmsSignedData( - IDictionary hashes, - byte[] sigBlock) + public CmsSignedData(IDictionary hashes, byte[] sigBlock) : this(hashes, CmsUtilities.ReadContentInfo(sigBlock)) { } @@ -91,9 +79,7 @@ public CmsSignedData( * @param signedContent the content that was signed. * @param sigData the signature object. */ - public CmsSignedData( - CmsProcessable signedContent, - Stream sigData) + public CmsSignedData(CmsProcessable signedContent, Stream sigData) : this(signedContent, CmsUtilities.ReadContentInfo(sigData)) { } @@ -101,32 +87,26 @@ public CmsSignedData( /** * base constructor - with encapsulated content */ - public CmsSignedData( - Stream sigData) + public CmsSignedData(Stream sigData) : this(CmsUtilities.ReadContentInfo(sigData)) { } - public CmsSignedData( - CmsProcessable signedContent, - ContentInfo sigData) + public CmsSignedData(CmsProcessable signedContent, ContentInfo sigData) { this.signedContent = signedContent; this.contentInfo = sigData; this.signedData = SignedData.GetInstance(contentInfo.Content); } - public CmsSignedData( - IDictionary hashes, - ContentInfo sigData) + public CmsSignedData(IDictionary hashes, ContentInfo sigData) { - this.hashes = hashes; + this.m_hashes = hashes; this.contentInfo = sigData; this.signedData = SignedData.GetInstance(contentInfo.Content); } - public CmsSignedData( - ContentInfo sigData) + public CmsSignedData(ContentInfo sigData) { this.contentInfo = sigData; this.signedData = SignedData.GetInstance(contentInfo.Content); @@ -152,11 +132,6 @@ public int Version get { return signedData.Version.IntValueExact; } } - internal IX509Store GetCertificates() - { - return Helper.GetCertificates(signedData.Certificates); - } - /** * return the collection of signers that are associated with the * signatures for the message. @@ -165,7 +140,7 @@ public SignerInformationStore GetSignerInfos() { if (signerInfoStore == null) { - IList signerInfos = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var signerInfos = new List(); Asn1Set s = signedData.SignerInfos; foreach (object obj in s) @@ -173,16 +148,18 @@ public SignerInformationStore GetSignerInfos() SignerInfo info = SignerInfo.GetInstance(obj); DerObjectIdentifier contentType = signedData.EncapContentInfo.ContentType; - if (hashes == null) + if (m_hashes == null) { signerInfos.Add(new SignerInformation(info, contentType, signedContent, null)); } - else + else if (m_hashes.TryGetValue(info.DigestAlgorithm.Algorithm.Id, out var hash)) { - byte[] hash = (byte[])hashes[info.DigestAlgorithm.Algorithm.Id]; - signerInfos.Add(new SignerInformation(info, contentType, null, new BaseDigestCalculator(hash))); } + else + { + throw new InvalidOperationException(); + } } signerInfoStore = new SignerInformationStore(signerInfos); @@ -200,61 +177,38 @@ public SignerInformationStore GetSignerInfos() * @exception NoSuchStoreException if the store type isn't available. * @exception CmsException if a general exception prevents creation of the X509Store */ - public IX509Store GetAttributeCertificates( - string type) + public IStore GetAttributeCertificates() { - if (attrCertStore == null) - { - attrCertStore = Helper.CreateAttributeStore(type, signedData.Certificates); - } - - return attrCertStore; + return Helper.GetAttributeCertificates(signedData.Certificates); } /** - * return a X509Store containing the public key certificates, if any, contained - * in this message. + * 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) + public IStore GetCertificates() { - if (certificateStore == null) - { - certificateStore = Helper.CreateCertificateStore(type, signedData.Certificates); - } - - return certificateStore; + return Helper.GetCertificates(signedData.Certificates); } /** - * return a X509Store containing CRLs, if any, contained - * in this message. + * 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) + public IStore GetCrls() { - if (crlStore == null) - { - crlStore = Helper.CreateCrlStore(type, signedData.CRLs); - } - - return crlStore; + return Helper.GetCrls(signedData.CRLs); } - - public string SignedContentTypeOid + public IStore GetOtherRevInfos(DerObjectIdentifier otherRevInfoFormat) { - get { return signedData.EncapContentInfo.ContentType.Id; } + return Helper.GetOtherRevInfos(signedData.CRLs, otherRevInfoFormat); } /// @@ -361,7 +315,7 @@ public static CmsSignedData ReplaceSigners( return cms; } - /** + /** * Replace the certificate and CRL information associated with this * CmsSignedData object with the new one passed in. * @@ -371,54 +325,71 @@ public static CmsSignedData ReplaceSigners( * @return a new signed data object. * @exception CmsException if there is an error processing the stores */ - public static CmsSignedData ReplaceCertificatesAndCrls( - CmsSignedData signedData, - IX509Store x509Certs, - IX509Store x509Crls, - IX509Store x509AttrCerts) + public static CmsSignedData ReplaceCertificatesAndCrls(CmsSignedData signedData, + IStore x509Certs, IStore x509Crls) + { + return ReplaceCertificatesAndRevocations(signedData, x509Certs, x509Crls, null, null); + } + + public static CmsSignedData ReplaceCertificatesAndCrls(CmsSignedData signedData, + IStore x509Certs, IStore x509Crls, + IStore x509AttrCerts) { - if (x509AttrCerts != null) - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("Currently can't replace attribute certificates"); + return ReplaceCertificatesAndRevocations(signedData, x509Certs, x509Crls, x509AttrCerts, null); + } - // - // copy - // - CmsSignedData cms = new CmsSignedData(signedData); + public static CmsSignedData ReplaceCertificatesAndRevocations(CmsSignedData signedData, + IStore x509Certs, IStore x509Crls, + IStore x509AttrCerts, IStore otherRevocationInfos) + { + // + // copy + // + CmsSignedData cms = new CmsSignedData(signedData); // // replace the certs and crls in the SignedData object // - Asn1Set certs = null; - try + Asn1Set certSet = null; + Asn1Set revocationSet = null; + + if (x509Certs != null || x509AttrCerts != null) { - Asn1Set asn1Set = CmsUtilities.CreateBerSetFromList( - CmsUtilities.GetCertificatesFromStore(x509Certs)); + var certificates = new List(); + if (x509Certs != null) + { + certificates.AddRange(CmsUtilities.GetCertificatesFromStore(x509Certs)); + } + if (x509AttrCerts != null) + { + certificates.AddRange(CmsUtilities.GetAttributeCertificatesFromStore(x509AttrCerts)); + } - if (asn1Set.Count != 0) + Asn1Set berSet = CmsUtilities.CreateBerSetFromList(certificates); + if (berSet.Count > 0) { - certs = asn1Set; + certSet = berSet; } } - catch (X509StoreException e) - { - throw new CmsException("error getting certificates from store", e); - } - Asn1Set crls = null; - try + if (x509Crls != null || otherRevocationInfos != null) { - Asn1Set asn1Set = CmsUtilities.CreateBerSetFromList( - CmsUtilities.GetCrlsFromStore(x509Crls)); + var revocations = new List(); + if (x509Crls != null) + { + revocations.AddRange(CmsUtilities.GetCrlsFromStore(x509Crls)); + } + if (otherRevocationInfos != null) + { + revocations.AddRange(CmsUtilities.GetOtherRevocationInfosFromStore(otherRevocationInfos)); + } - if (asn1Set.Count != 0) + Asn1Set berSet = CmsUtilities.CreateBerSetFromList(revocations); + if (berSet.Count > 0) { - crls = asn1Set; + revocationSet = berSet; } } - catch (X509StoreException e) - { - throw new CmsException("error getting CRLs from store", e); - } // // replace the CMS structure. @@ -427,8 +398,8 @@ public static CmsSignedData ReplaceCertificatesAndCrls( cms.signedData = new SignedData( old.DigestAlgorithms, old.EncapContentInfo, - certs, - crls, + certSet, + revocationSet, old.SignerInfos); // diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedDataGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedDataGenerator.cs index e0082e6..a9dbdaa 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedDataGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedDataGenerator.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; @@ -40,13 +40,13 @@ public class CmsSignedDataGenerator { private static readonly CmsSignedHelper Helper = CmsSignedHelper.Instance; - private readonly IList signerInfs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + private readonly IList signerInfs = new List(); private class SignerInf { private readonly CmsSignedGenerator outer; - private readonly ISignatureFactory sigCalc; + private readonly ISignatureFactory sigCalc; private readonly SignerIdentifier signerIdentifier; private readonly string digestOID; private readonly string encOID; @@ -57,6 +57,7 @@ private class SignerInf internal SignerInf( CmsSignedGenerator outer, AsymmetricKeyParameter key, + SecureRandom random, SignerIdentifier signerIdentifier, string digestOID, string encOID, @@ -69,7 +70,7 @@ internal SignerInf( string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(encOID); this.outer = outer; - this.sigCalc = new Asn1SignatureFactory(signatureName, key); + this.sigCalc = new Asn1SignatureFactory(signatureName, key, random); this.signerIdentifier = signerIdentifier; this.digestOID = digestOID; this.encOID = encOID; @@ -89,7 +90,8 @@ internal SignerInf( this.outer = outer; this.sigCalc = sigCalc; this.signerIdentifier = signerIdentifier; - this.digestOID = new DefaultDigestAlgorithmIdentifierFinder().find((AlgorithmIdentifier)sigCalc.AlgorithmDetails).Algorithm.Id; + this.digestOID = new DefaultDigestAlgorithmIdentifierFinder().Find( + (AlgorithmIdentifier)sigCalc.AlgorithmDetails).Algorithm.Id; this.encOID = ((AlgorithmIdentifier)sigCalc.AlgorithmDetails).Algorithm.Id; this.sAttr = sAttr; this.unsAttr = unsAttr; @@ -111,22 +113,14 @@ internal CmsAttributeTableGenerator UnsignedAttributes get { return unsAttr; } } - internal SignerInfo ToSignerInfo( - DerObjectIdentifier contentType, - CmsProcessable content, - SecureRandom random) + internal SignerInfo ToSignerInfo(DerObjectIdentifier contentType, CmsProcessable content) { 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 + + if (!outer.m_digests.TryGetValue(digestOID, out var hash)) { IDigest dig = Helper.GetDigestInstance(digestName); if (content != null) @@ -134,55 +128,49 @@ internal SignerInfo ToSignerInfo( content.Write(new DigestSink(dig)); } hash = DigestUtilities.DoFinal(dig); - outer._digests.Add(digestOID, hash.Clone()); + outer.m_digests.Add(digestOID, (byte[])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. - signedAttr.EncodeTo(sigStr, Asn1Encodable.Der); - } - else if (content != null) + IStreamCalculator calculator = sigCalc.CreateCalculator(); + using (Stream sigStr = calculator.Stream) { - // TODO Use raw signature of the hash value instead - content.Write(sigStr); - } + if (sAttr != null) + { + var 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) + { + signed = signed.Remove(CmsAttributes.ContentType); + } + } + + // TODO Validate proposed signed attributes + + signedAttr = outer.GetAttributeSet(signed); + + // sig must be composed from the DER encoding. + signedAttr.EncodeTo(sigStr, Asn1Encodable.Der); + } + 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(); + byte[] sigBytes = calculator.GetResult().Collect(); Asn1Set unsignedAttr = null; if (unsAttr != null) { - IDictionary baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash); + var baseParameters = outer.GetBaseParameters(contentType, digAlgId, hash); baseParameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone(); // Asn1.Cms.AttributeTable unsigned = unsAttr.GetAttributes(Collections.unmodifiableMap(baseParameters)); @@ -208,10 +196,9 @@ public CmsSignedDataGenerator() } /// Constructor allowing specific source of randomness - /// Instance of SecureRandom to use. - public CmsSignedDataGenerator( - SecureRandom rand) - : base(rand) + /// Instance of SecureRandom to use. + public CmsSignedDataGenerator(SecureRandom random) + : base(random) { } @@ -437,7 +424,7 @@ private void doAddSigner( CmsAttributeTableGenerator unsignedAttrGen, Asn1.Cms.AttributeTable baseSignedTable) { - signerInfs.Add(new SignerInf(this, privateKey, signerIdentifier, digestOID, encryptionOID, + signerInfs.Add(new SignerInf(this, privateKey, m_random, signerIdentifier, digestOID, encryptionOID, signedAttrGen, unsignedAttrGen, baseSignedTable)); } @@ -465,7 +452,7 @@ public CmsSignedData Generate( Asn1EncodableVector digestAlgs = new Asn1EncodableVector(); Asn1EncodableVector signerInfos = new Asn1EncodableVector(); - _digests.Clear(); // clear the current preserved digest state + m_digests.Clear(); // clear the current preserved digest state // // add the precalculated SignerInfo objects. @@ -492,7 +479,7 @@ public CmsSignedData Generate( try { digestAlgs.Add(signer.DigestAlgorithmID); - signerInfos.Add(signer.ToSignerInfo(contentTypeOid, content, rand)); + signerInfos.Add(signer.ToSignerInfo(contentTypeOid, content)); } catch (IOException e) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedDataParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedDataParser.cs index 2087897..9f0febf 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedDataParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedDataParser.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; @@ -10,12 +10,10 @@ 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 { @@ -65,15 +63,12 @@ public class CmsSignedDataParser private SignedDataParser _signedData; private DerObjectIdentifier _signedContentType; private CmsTypedStream _signedContent; - private IDictionary _digests; - private ISet _digestOids; + private IDictionary m_digests; + private HashSet _digestOids; private SignerInformationStore _signerInfoStore; private Asn1Set _certSet, _crlSet; private bool _isCertCrlParsed; - private IX509Store _attributeStore; - private IX509Store _certificateStore; - private IX509Store _crlStore; public CmsSignedDataParser( byte[] sigBlock) @@ -112,8 +107,8 @@ public CmsSignedDataParser( { 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(); + this.m_digests = new Dictionary(StringComparer.OrdinalIgnoreCase); + this._digestOids = new HashSet(); Asn1SetParser digAlgs = _signedData.GetDigestAlgorithms(); IAsn1Convertible o; @@ -127,9 +122,9 @@ public CmsSignedDataParser( string digestOid = id.Algorithm.Id; string digestName = Helper.GetDigestAlgName(digestOid); - if (!this._digests.Contains(digestName)) + if (!this.m_digests.ContainsKey(digestName)) { - this._digests[digestName] = Helper.GetDigestInstance(digestName); + this.m_digests[digestName] = Helper.GetDigestInstance(digestName); this._digestOids.Add(digestOid); } } @@ -184,9 +179,9 @@ public int Version get { return _signedData.Version.IntValueExact; } } - public ISet DigestOids + public ISet DigestOids { - get { return new HashSet(_digestOids); } + get { return new HashSet(_digestOids); } } /** @@ -200,13 +195,12 @@ public SignerInformationStore GetSignerInfos() { PopulateCertCrlSets(); - IList signerInfos = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); - IDictionary hashes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + var signerInfos = new List(); + var hashes = new Dictionary(StringComparer.OrdinalIgnoreCase); - foreach (object digestKey in _digests.Keys) + foreach (var digest in m_digests) { - hashes[digestKey] = DigestUtilities.DoFinal( - (IDigest)_digests[digestKey]); + hashes[digest.Key] = DigestUtilities.DoFinal(digest.Value); } try @@ -217,10 +211,9 @@ public SignerInformationStore GetSignerInfos() while ((o = s.ReadObject()) != null) { SignerInfo info = SignerInfo.GetInstance(o.ToAsn1Object()); - string digestName = Helper.GetDigestAlgName( - info.DigestAlgorithm.Algorithm.Id); + string digestName = Helper.GetDigestAlgName(info.DigestAlgorithm.Algorithm.Id); - byte[] hash = (byte[]) hashes[digestName]; + byte[] hash = hashes[digestName]; signerInfos.Add(new SignerInformation(info, _signedContentType, null, new BaseDigestCalculator(hash))); } @@ -245,17 +238,11 @@ public SignerInformationStore GetSignerInfos() * @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) + public IStore GetAttributeCertificates() { - if (_attributeStore == null) - { - PopulateCertCrlSets(); + PopulateCertCrlSets(); - _attributeStore = Helper.CreateAttributeStore(type, _certSet); - } - - return _attributeStore; + return Helper.GetAttributeCertificates(_certSet); } /** @@ -267,17 +254,11 @@ public IX509Store GetAttributeCertificates( * @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) + public IStore GetCertificates() { - if (_certificateStore == null) - { - PopulateCertCrlSets(); - - _certificateStore = Helper.CreateCertificateStore(type, _certSet); - } + PopulateCertCrlSets(); - return _certificateStore; + return Helper.GetCertificates(_certSet); } /** @@ -289,20 +270,21 @@ public IX509Store GetCertificates( * @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) + public IStore GetCrls() { - if (_crlStore == null) - { - PopulateCertCrlSets(); - - _crlStore = Helper.CreateCrlStore(type, _crlSet); - } + PopulateCertCrlSets(); - return _crlStore; + return Helper.GetCrls(_crlSet); } - private void PopulateCertCrlSets() + public IStore GetOtherRevInfos(DerObjectIdentifier otherRevInfoFormat) + { + PopulateCertCrlSets(); + + return Helper.GetOtherRevInfos(_crlSet, otherRevInfoFormat); + } + + private void PopulateCertCrlSets() { if (_isCertCrlParsed) return; @@ -339,7 +321,7 @@ public CmsTypedStream GetSignedContent() Stream digStream = _signedContent.ContentStream; - foreach (IDigest digest in _digests.Values) + foreach (var digest in m_digests.Values) { digStream = new DigestStream(digStream, digest, null); } @@ -380,13 +362,13 @@ public static Stream ReplaceSigners( Streams.PipeAll(signedContent.ContentStream, contentOut); } - gen.AddAttributeCertificates(parser.GetAttributeCertificates("Collection")); - gen.AddCertificates(parser.GetCertificates("Collection")); - gen.AddCrls(parser.GetCrls("Collection")); + gen.AddAttributeCertificates(parser.GetAttributeCertificates()); + gen.AddCertificates(parser.GetCertificates()); + gen.AddCrls(parser.GetCrls()); // gen.AddSigners(parser.GetSignerInfos()); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(contentOut); + contentOut.Dispose(); return outStr; } @@ -403,12 +385,8 @@ public static Stream ReplaceSigners( * @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) + public static Stream ReplaceCertificatesAndCrls(Stream original, IStore x509Certs, + IStore x509Crls, IStore x509AttrCerts, Stream outStr) { // NB: SecureRandom would be ignored since using existing signatures only CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator(); @@ -424,19 +402,22 @@ public static Stream ReplaceCertificatesAndCrls( 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); + contentOut.Dispose(); return outStr; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedDataStreamGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedDataStreamGenerator.cs index 5943f29..f538bff 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedDataStreamGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedDataStreamGenerator.cs @@ -1,8 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; -using System.Diagnostics; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; @@ -12,9 +11,7 @@ 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; @@ -45,19 +42,22 @@ public class CmsSignedDataStreamGenerator { 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 readonly IList _signerInfs = + new List(); + private readonly HashSet _messageDigestOids = new HashSet(); + private readonly IDictionary m_messageDigests = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private readonly IDictionary m_messageHashes = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private bool _messageDigestsLocked; + private int _bufferSize; private class DigestAndSignerInfoGeneratorHolder { internal readonly ISignerInfoGenerator signerInf; internal readonly string digestOID; - internal DigestAndSignerInfoGeneratorHolder(ISignerInfoGenerator signerInf, String digestOID) + internal DigestAndSignerInfoGeneratorHolder(ISignerInfoGenerator signerInf, string digestOID) { this.signerInf = signerInf; this.digestOID = digestOID; @@ -139,7 +139,7 @@ internal SignerInfoGeneratorImpl( } } - _sig.Init(true, new ParametersWithRandom(key, outer.rand)); + _sig.Init(true, new ParametersWithRandom(key, outer.m_random)); } public SignerInfo Generate(DerObjectIdentifier contentType, AlgorithmIdentifier digestAlgorithm, @@ -169,7 +169,7 @@ public SignerInfo Generate(DerObjectIdentifier contentType, AlgorithmIdentifier Asn1Set signedAttr = null; if (_sAttr != null) { - IDictionary parameters = outer.GetBaseParameters(contentType, digestAlgorithm, calculatedDigest); + var parameters = outer.GetBaseParameters(contentType, digestAlgorithm, calculatedDigest); // Asn1.Cms.AttributeTable signed = _sAttr.GetAttributes(Collections.unmodifiableMap(parameters)); Asn1.Cms.AttributeTable signed = _sAttr.GetAttributes(parameters); @@ -178,9 +178,7 @@ public SignerInfo Generate(DerObjectIdentifier contentType, AlgorithmIdentifier { if (signed != null && signed[CmsAttributes.ContentType] != null) { - IDictionary tmpSigned = signed.ToDictionary(); - tmpSigned.Remove(CmsAttributes.ContentType); - signed = new Asn1.Cms.AttributeTable(tmpSigned); + signed = signed.Remove(CmsAttributes.ContentType); } } @@ -205,8 +203,7 @@ public SignerInfo Generate(DerObjectIdentifier contentType, AlgorithmIdentifier Asn1Set unsignedAttr = null; if (_unsAttr != null) { - IDictionary parameters = outer.GetBaseParameters( - contentType, digestAlgorithm, calculatedDigest); + var parameters = outer.GetBaseParameters(contentType, digestAlgorithm, calculatedDigest); parameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone(); // Asn1.Cms.AttributeTable unsigned = _unsAttr.getAttributes(Collections.unmodifiableMap(parameters)); @@ -239,10 +236,9 @@ public CmsSignedDataStreamGenerator() } /// Constructor allowing specific source of randomness - /// Instance of SecureRandom to use. - public CmsSignedDataStreamGenerator( - SecureRandom rand) - : base(rand) + /// Instance of SecureRandom to use. + public CmsSignedDataStreamGenerator(SecureRandom random) + : base(random) { } @@ -251,20 +247,20 @@ public CmsSignedDataStreamGenerator( * * @param bufferSize length of octet strings to buffer the data. */ - public void SetBufferSize( - int bufferSize) + public void SetBufferSize(int bufferSize) { _bufferSize = bufferSize; } - public void AddDigests( - params string[] digestOids) + public void AddDigests(params string[] digestOids) { - AddDigests((IEnumerable) digestOids); + foreach (string digestOid in digestOids) + { + ConfigureDigest(digestOid); + } } - public void AddDigests( - IEnumerable digestOids) + public void AddDigests(IEnumerable digestOids) { foreach (string digestOid in digestOids) { @@ -568,14 +564,10 @@ public Stream Open( foreach (string digestOid in _messageDigestOids) { - digestAlgs.Add( - new AlgorithmIdentifier(new DerObjectIdentifier(digestOid), DerNull.Instance)); + digestAlgs.Add(new AlgorithmIdentifier(new DerObjectIdentifier(digestOid), DerNull.Instance)); } - { - byte[] tmp = new DerSet(digestAlgs).GetEncoded(); - sigGen.GetRawOutputStream().Write(tmp, 0, tmp.Length); - } + new DerSet(digestAlgs).EncodeTo(sigGen.GetRawOutputStream()); BerSequenceGenerator eiGen = new BerSequenceGenerator(sigGen.GetRawOutputStream()); eiGen.AddObject(contentTypeOid); @@ -589,7 +581,7 @@ public Stream Open( Stream teeStream = GetSafeTeeOutputStream(dataOutputStream, encapStream); // Let all the digests see the data as it is written - Stream digStream = AttachDigestsToOutputStream(_messageDigests.Values, teeStream); + Stream digStream = AttachDigestsToOutputStream(m_messageDigests.Values, teeStream); return new CmsSignedDataOutputStream(this, digStream, signedContentType, sGen, sigGen, eiGen); } @@ -608,20 +600,18 @@ private void RegisterDigestOid( } } - private void ConfigureDigest( - string digestOid) + private void ConfigureDigest(string digestOid) { RegisterDigestOid(digestOid); string digestName = Helper.GetDigestAlgName(digestOid); - IDigest dig = (IDigest)_messageDigests[digestName]; - if (dig == null) + + if (!m_messageDigests.ContainsKey(digestName)) { if (_messageDigestsLocked) throw new InvalidOperationException("Cannot configure new digests after the data stream is opened"); - dig = Helper.GetDigestInstance(digestName); - _messageDigests[digestName] = dig; + m_messageDigests[digestName] = Helper.GetDigestInstance(digestName); } } @@ -633,12 +623,13 @@ internal void Generate( Stream dataOutputStream, CmsProcessable content) { - Stream signedOut = Open(outStream, eContentType, encapsulate, dataOutputStream); - if (content != null) + using (var signedOut = Open(outStream, eContentType, encapsulate, dataOutputStream)) { - content.Write(signedOut); - } - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(signedOut); + if (content != null) + { + content.Write(signedOut); + } + } } // RFC3852, section 5.1: @@ -671,10 +662,8 @@ private DerInteger CalculateVersion( { foreach (object obj in _certs) { - if (obj is Asn1TaggedObject) + if (obj is Asn1TaggedObject tagged) { - Asn1TaggedObject tagged = (Asn1TaggedObject) obj; - if (tagged.TagNo == 1) { attrCertV1Found = true; @@ -727,23 +716,20 @@ private DerInteger CalculateVersion( return new DerInteger(1); } - private bool CheckForVersion3( - IList signerInfos) + private bool CheckForVersion3(IList signerInfos) { foreach (SignerInformation si in signerInfos) { SignerInfo s = SignerInfo.GetInstance(si.ToSignerInfo()); if (s.Version.IntValueExact == 3) - { return true; - } } return false; } - private static Stream AttachDigestsToOutputStream(ICollection digests, Stream s) + private static Stream AttachDigestsToOutputStream(IEnumerable digests, Stream s) { Stream result = s; foreach (IDigest digest in digests) @@ -755,9 +741,7 @@ private static Stream AttachDigestsToOutputStream(ICollection digests, Stream s) private static Stream GetSafeOutputStream(Stream s) { - if (s == null) - return new NullOutputStream(); - return s; + return s ?? Stream.Null; } private static Stream GetSafeTeeOutputStream(Stream s1, Stream s2) @@ -797,21 +781,23 @@ public CmsSignedDataOutputStream( _eiGen = eiGen; } - public override void WriteByte( - byte b) - { - _out.WriteByte(b); - } + public override void Write(byte[] buffer, int offset, int count) + { + _out.Write(buffer, offset, count); + } - public override void Write( - byte[] bytes, - int off, - int len) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) { - _out.Write(bytes, off, len); + _out.Write(buffer); } +#endif + + public override void WriteByte(byte value) + { + _out.WriteByte(value); + } -#if PORTABLE || NETFX_CORE protected override void Dispose(bool disposing) { if (disposing) @@ -820,23 +806,16 @@ protected override void Dispose(bool disposing) } base.Dispose(disposing); } -#else - public override void Close() - { - DoClose(); - base.Close(); - } -#endif private void DoClose() { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(_out); + _out.Dispose(); // TODO Parent context(s) should really be be closed explicitly _eiGen.Close(); - outer._digests.Clear(); // clear the current preserved digest state + outer.m_digests.Clear(); // clear the current preserved digest state if (outer._certs.Count > 0) { @@ -844,8 +823,8 @@ private void DoClose() ? CmsUtilities.CreateDerSetFromList(outer._certs) : CmsUtilities.CreateBerSetFromList(outer._certs); - WriteToGenerator(_sigGen, new BerTaggedObject(false, 0, certs)); - } + WriteToGenerator(_sigGen, new BerTaggedObject(false, 0, certs)); + } if (outer._crls.Count > 0) { @@ -853,48 +832,48 @@ private void DoClose() ? CmsUtilities.CreateDerSetFromList(outer._crls) : CmsUtilities.CreateBerSetFromList(outer._crls); - WriteToGenerator(_sigGen, new BerTaggedObject(false, 1, 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)); - } + // + // Calculate the digest hashes + // + foreach (var de in outer.m_messageDigests) + { + outer.m_messageHashes.Add(de.Key, DigestUtilities.DoFinal(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 + // 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 - // + // + // collect all the SignerInfo objects + // Asn1EncodableVector signerInfos = new Asn1EncodableVector(); - // + // // add the generated SignerInfo objects // - { - foreach (DigestAndSignerInfoGeneratorHolder holder in outer._signerInfs) - { - AlgorithmIdentifier digestAlgorithm = holder.DigestAlgorithm; + { + 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(); + byte[] calculatedDigest = outer.m_messageHashes[ + Helper.GetDigestAlgName(holder.digestOID)]; + outer.m_digests[holder.digestOID] = (byte[])calculatedDigest.Clone(); - signerInfos.Add(holder.signerInf.Generate(_contentOID, digestAlgorithm, calculatedDigest)); - } - } + 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 + { + 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? @@ -913,22 +892,19 @@ private void DoClose() // } // } - signerInfos.Add(signer.ToSignerInfo()); - } - } + signerInfos.Add(signer.ToSignerInfo()); + } + } - WriteToGenerator(_sigGen, new DerSet(signerInfos)); + WriteToGenerator(_sigGen, new DerSet(signerInfos)); _sigGen.Close(); _sGen.Close(); } - private static void WriteToGenerator( - Asn1Generator ag, - Asn1Encodable ae) + private static void WriteToGenerator(Asn1Generator ag, Asn1Encodable ae) { - byte[] encoded = ae.GetEncoded(); - ag.GetRawOutputStream().Write(encoded, 0, encoded.Length); + ae.EncodeTo(ag.GetRawOutputStream()); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedGenerator.cs index 93bd789..b55b948 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedGenerator.cs @@ -1,8 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; -using System.IO; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.BC; @@ -19,344 +18,336 @@ 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 DefaultSignatureAlgorithmIdentifierFinder { - private static readonly IDictionary algorithms = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private static readonly ISet noParams = new HashSet(); - private static readonly IDictionary _params = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private static readonly ISet pkcs15RsaEncryption = new HashSet(); - private static readonly IDictionary digestOids = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - - private static readonly IDictionary digestBuilders = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - - private static readonly DerObjectIdentifier ENCRYPTION_RSA = PkcsObjectIdentifiers.RsaEncryption; - private static readonly DerObjectIdentifier ENCRYPTION_DSA = X9ObjectIdentifiers.IdDsaWithSha1; - private static readonly DerObjectIdentifier ENCRYPTION_ECDSA = X9ObjectIdentifiers.ECDsaWithSha1; - private static readonly DerObjectIdentifier ENCRYPTION_RSA_PSS = PkcsObjectIdentifiers.IdRsassaPss; - private static readonly DerObjectIdentifier ENCRYPTION_GOST3410 = CryptoProObjectIdentifiers.GostR3410x94; - private static readonly DerObjectIdentifier ENCRYPTION_ECGOST3410 = CryptoProObjectIdentifiers.GostR3410x2001; - private static readonly DerObjectIdentifier ENCRYPTION_ECGOST3410_2012_256 = RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256; - private static readonly DerObjectIdentifier ENCRYPTION_ECGOST3410_2012_512 = RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512; + private static readonly IDictionary m_algorithms = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly HashSet noParams = new HashSet(); + private static readonly IDictionary m_params = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly HashSet pkcs15RsaEncryption = new HashSet(); + private static readonly IDictionary m_digestOids = + new Dictionary(); + + //private static readonly DerObjectIdentifier ENCRYPTION_RSA = PkcsObjectIdentifiers.RsaEncryption; + //private static readonly DerObjectIdentifier ENCRYPTION_DSA = X9ObjectIdentifiers.IdDsaWithSha1; + //private static readonly DerObjectIdentifier ENCRYPTION_ECDSA = X9ObjectIdentifiers.ECDsaWithSha1; + //private static readonly DerObjectIdentifier ENCRYPTION_RSA_PSS = PkcsObjectIdentifiers.IdRsassaPss; + //private static readonly DerObjectIdentifier ENCRYPTION_GOST3410 = CryptoProObjectIdentifiers.GostR3410x94; + //private static readonly DerObjectIdentifier ENCRYPTION_ECGOST3410 = CryptoProObjectIdentifiers.GostR3410x2001; + //private static readonly DerObjectIdentifier ENCRYPTION_ECGOST3410_2012_256 = RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256; + //private static readonly DerObjectIdentifier ENCRYPTION_ECGOST3410_2012_512 = RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512; static DefaultSignatureAlgorithmIdentifierFinder() { - algorithms["MD2WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.MD2WithRsaEncryption; - algorithms["MD2WITHRSA"] = PkcsObjectIdentifiers.MD2WithRsaEncryption; - algorithms["MD5WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.MD5WithRsaEncryption; - algorithms["MD5WITHRSA"] = PkcsObjectIdentifiers.MD5WithRsaEncryption; - algorithms["SHA1WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha1WithRsaEncryption; - algorithms["SHA-1WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha1WithRsaEncryption; - algorithms["SHA1WITHRSA"] = PkcsObjectIdentifiers.Sha1WithRsaEncryption; - algorithms["SHA-1WITHRSA"] = PkcsObjectIdentifiers.Sha1WithRsaEncryption; - algorithms["SHA224WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha224WithRsaEncryption; - algorithms["SHA-224WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha224WithRsaEncryption; - algorithms["SHA224WITHRSA"] = PkcsObjectIdentifiers.Sha224WithRsaEncryption; - algorithms["SHA-224WITHRSA"] = PkcsObjectIdentifiers.Sha224WithRsaEncryption; - algorithms["SHA256WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha256WithRsaEncryption; - algorithms["SHA-256WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha256WithRsaEncryption; - algorithms["SHA256WITHRSA"] = PkcsObjectIdentifiers.Sha256WithRsaEncryption; - algorithms["SHA-256WITHRSA"] = PkcsObjectIdentifiers.Sha256WithRsaEncryption; - algorithms["SHA384WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha384WithRsaEncryption; - algorithms["SHA-384WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha384WithRsaEncryption; - algorithms["SHA384WITHRSA"] = PkcsObjectIdentifiers.Sha384WithRsaEncryption; - algorithms["SHA-384WITHRSA"] = PkcsObjectIdentifiers.Sha384WithRsaEncryption; - algorithms["SHA512WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha512WithRsaEncryption; - algorithms["SHA-512WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha512WithRsaEncryption; - algorithms["SHA512WITHRSA"] = PkcsObjectIdentifiers.Sha512WithRsaEncryption; - algorithms["SHA-512WITHRSA"] = PkcsObjectIdentifiers.Sha512WithRsaEncryption; - algorithms["SHA512(224)WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha512_224WithRSAEncryption; - algorithms["SHA-512(224)WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha512_224WithRSAEncryption; - algorithms["SHA512(224)WITHRSA"] = PkcsObjectIdentifiers.Sha512_224WithRSAEncryption; - algorithms["SHA-512(224)WITHRSA"] = PkcsObjectIdentifiers.Sha512_224WithRSAEncryption; - algorithms["SHA512(256)WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha512_256WithRSAEncryption; - algorithms["SHA-512(256)WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha512_256WithRSAEncryption; - algorithms["SHA512(256)WITHRSA"] = PkcsObjectIdentifiers.Sha512_256WithRSAEncryption; - algorithms["SHA-512(256)WITHRSA"] = PkcsObjectIdentifiers.Sha512_256WithRSAEncryption; - algorithms["SHA1WITHRSAANDMGF1"] = PkcsObjectIdentifiers.IdRsassaPss; - algorithms["SHA224WITHRSAANDMGF1"] = PkcsObjectIdentifiers.IdRsassaPss; - algorithms["SHA256WITHRSAANDMGF1"] = PkcsObjectIdentifiers.IdRsassaPss; - algorithms["SHA384WITHRSAANDMGF1"] = PkcsObjectIdentifiers.IdRsassaPss; - algorithms["SHA512WITHRSAANDMGF1"] = PkcsObjectIdentifiers.IdRsassaPss; - algorithms["SHA3-224WITHRSAANDMGF1"] = PkcsObjectIdentifiers.IdRsassaPss; - algorithms["SHA3-256WITHRSAANDMGF1"] = PkcsObjectIdentifiers.IdRsassaPss; - algorithms["SHA3-384WITHRSAANDMGF1"] = PkcsObjectIdentifiers.IdRsassaPss; - algorithms["SHA3-512WITHRSAANDMGF1"] = PkcsObjectIdentifiers.IdRsassaPss; - algorithms["RIPEMD160WITHRSAENCRYPTION"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160; - algorithms["RIPEMD160WITHRSA"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160; - algorithms["RIPEMD128WITHRSAENCRYPTION"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128; - algorithms["RIPEMD128WITHRSA"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128; - algorithms["RIPEMD256WITHRSAENCRYPTION"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256; - algorithms["RIPEMD256WITHRSA"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256; - algorithms["SHA1WITHDSA"] = X9ObjectIdentifiers.IdDsaWithSha1; - algorithms["SHA-1WITHDSA"] = X9ObjectIdentifiers.IdDsaWithSha1; - algorithms["DSAWITHSHA1"] = X9ObjectIdentifiers.IdDsaWithSha1; - algorithms["SHA224WITHDSA"] = NistObjectIdentifiers.DsaWithSha224; - algorithms["SHA256WITHDSA"] = NistObjectIdentifiers.DsaWithSha256; - algorithms["SHA384WITHDSA"] = NistObjectIdentifiers.DsaWithSha384; - algorithms["SHA512WITHDSA"] = NistObjectIdentifiers.DsaWithSha512; - algorithms["SHA3-224WITHDSA"] = NistObjectIdentifiers.IdDsaWithSha3_224; - algorithms["SHA3-256WITHDSA"] = NistObjectIdentifiers.IdDsaWithSha3_256; - algorithms["SHA3-384WITHDSA"] = NistObjectIdentifiers.IdDsaWithSha3_384; - algorithms["SHA3-512WITHDSA"] = NistObjectIdentifiers.IdDsaWithSha3_512; - algorithms["SHA3-224WITHECDSA"] = NistObjectIdentifiers.IdEcdsaWithSha3_224; - algorithms["SHA3-256WITHECDSA"] = NistObjectIdentifiers.IdEcdsaWithSha3_256; - algorithms["SHA3-384WITHECDSA"] = NistObjectIdentifiers.IdEcdsaWithSha3_384; - algorithms["SHA3-512WITHECDSA"] = NistObjectIdentifiers.IdEcdsaWithSha3_512; - algorithms["SHA3-224WITHRSA"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_224; - algorithms["SHA3-256WITHRSA"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_256; - algorithms["SHA3-384WITHRSA"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_384; - algorithms["SHA3-512WITHRSA"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_512; - algorithms["SHA3-224WITHRSAENCRYPTION"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_224; - algorithms["SHA3-256WITHRSAENCRYPTION"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_256; - algorithms["SHA3-384WITHRSAENCRYPTION"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_384; - algorithms["SHA3-512WITHRSAENCRYPTION"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_512; - algorithms["SHA1WITHECDSA"] = X9ObjectIdentifiers.ECDsaWithSha1; - algorithms["ECDSAWITHSHA1"] = X9ObjectIdentifiers.ECDsaWithSha1; - algorithms["SHA224WITHECDSA"] = X9ObjectIdentifiers.ECDsaWithSha224; - algorithms["SHA256WITHECDSA"] = X9ObjectIdentifiers.ECDsaWithSha256; - algorithms["SHA384WITHECDSA"] = X9ObjectIdentifiers.ECDsaWithSha384; - algorithms["SHA512WITHECDSA"] = X9ObjectIdentifiers.ECDsaWithSha512; - - - algorithms["GOST3411WITHGOST3410"] = CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94; - algorithms["GOST3411WITHGOST3410-94"] = CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94; - algorithms["GOST3411WITHECGOST3410"] = CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001; - algorithms["GOST3411WITHECGOST3410-2001"] = CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001; - algorithms["GOST3411WITHGOST3410-2001"] = CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001; - algorithms["GOST3411WITHECGOST3410-2012-256"] = RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256; - algorithms["GOST3411WITHECGOST3410-2012-512"] = RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512; - algorithms["GOST3411WITHGOST3410-2012-256"] = RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256; - algorithms["GOST3411WITHGOST3410-2012-512"] = RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512; - algorithms["GOST3411-2012-256WITHECGOST3410-2012-256"] = RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256; - algorithms["GOST3411-2012-512WITHECGOST3410-2012-512"] = RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512; - algorithms["GOST3411-2012-256WITHGOST3410-2012-256"] = RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256; - algorithms["GOST3411-2012-512WITHGOST3410-2012-512"] = RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512; - algorithms["SHA1WITHPLAIN-ECDSA"] = BsiObjectIdentifiers.ecdsa_plain_SHA1; - algorithms["SHA224WITHPLAIN-ECDSA"] = BsiObjectIdentifiers.ecdsa_plain_SHA224; - algorithms["SHA256WITHPLAIN-ECDSA"] = BsiObjectIdentifiers.ecdsa_plain_SHA256; - algorithms["SHA384WITHPLAIN-ECDSA"] = BsiObjectIdentifiers.ecdsa_plain_SHA384; - algorithms["SHA512WITHPLAIN-ECDSA"] = BsiObjectIdentifiers.ecdsa_plain_SHA512; - algorithms["RIPEMD160WITHPLAIN-ECDSA"] = BsiObjectIdentifiers.ecdsa_plain_RIPEMD160; - algorithms["SHA1WITHCVC-ECDSA"] = EacObjectIdentifiers.id_TA_ECDSA_SHA_1; - algorithms["SHA224WITHCVC-ECDSA"] = EacObjectIdentifiers.id_TA_ECDSA_SHA_224; - algorithms["SHA256WITHCVC-ECDSA"] = EacObjectIdentifiers.id_TA_ECDSA_SHA_256; - algorithms["SHA384WITHCVC-ECDSA"] = EacObjectIdentifiers.id_TA_ECDSA_SHA_384; - algorithms["SHA512WITHCVC-ECDSA"] = EacObjectIdentifiers.id_TA_ECDSA_SHA_512; - algorithms["SHA3-512WITHSPHINCS256"] = BCObjectIdentifiers.sphincs256_with_SHA3_512; - algorithms["SHA512WITHSPHINCS256"] = BCObjectIdentifiers.sphincs256_with_SHA512; - - algorithms["SHA256WITHSM2"] = GMObjectIdentifiers.sm2sign_with_sha256; - algorithms["SM3WITHSM2"] = GMObjectIdentifiers.sm2sign_with_sm3; - - algorithms["SHA256WITHXMSS"] = BCObjectIdentifiers.xmss_with_SHA256; - algorithms["SHA512WITHXMSS"] = BCObjectIdentifiers.xmss_with_SHA512; - algorithms["SHAKE128WITHXMSS"] = BCObjectIdentifiers.xmss_with_SHAKE128; - algorithms["SHAKE256WITHXMSS"] = BCObjectIdentifiers.xmss_with_SHAKE256; - - algorithms["SHA256WITHXMSSMT"] = BCObjectIdentifiers.xmss_mt_with_SHA256; - algorithms["SHA512WITHXMSSMT"] = BCObjectIdentifiers.xmss_mt_with_SHA512; - algorithms["SHAKE128WITHXMSSMT"] = BCObjectIdentifiers.xmss_mt_with_SHAKE128; - algorithms["SHAKE256WITHXMSSMT"] = BCObjectIdentifiers.xmss_mt_with_SHAKE256; + m_algorithms["MD2WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.MD2WithRsaEncryption; + m_algorithms["MD2WITHRSA"] = PkcsObjectIdentifiers.MD2WithRsaEncryption; + m_algorithms["MD5WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.MD5WithRsaEncryption; + m_algorithms["MD5WITHRSA"] = PkcsObjectIdentifiers.MD5WithRsaEncryption; + m_algorithms["SHA1WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha1WithRsaEncryption; + m_algorithms["SHA-1WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha1WithRsaEncryption; + m_algorithms["SHA1WITHRSA"] = PkcsObjectIdentifiers.Sha1WithRsaEncryption; + m_algorithms["SHA-1WITHRSA"] = PkcsObjectIdentifiers.Sha1WithRsaEncryption; + m_algorithms["SHA224WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha224WithRsaEncryption; + m_algorithms["SHA-224WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha224WithRsaEncryption; + m_algorithms["SHA224WITHRSA"] = PkcsObjectIdentifiers.Sha224WithRsaEncryption; + m_algorithms["SHA-224WITHRSA"] = PkcsObjectIdentifiers.Sha224WithRsaEncryption; + m_algorithms["SHA256WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha256WithRsaEncryption; + m_algorithms["SHA-256WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha256WithRsaEncryption; + m_algorithms["SHA256WITHRSA"] = PkcsObjectIdentifiers.Sha256WithRsaEncryption; + m_algorithms["SHA-256WITHRSA"] = PkcsObjectIdentifiers.Sha256WithRsaEncryption; + m_algorithms["SHA384WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha384WithRsaEncryption; + m_algorithms["SHA-384WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha384WithRsaEncryption; + m_algorithms["SHA384WITHRSA"] = PkcsObjectIdentifiers.Sha384WithRsaEncryption; + m_algorithms["SHA-384WITHRSA"] = PkcsObjectIdentifiers.Sha384WithRsaEncryption; + m_algorithms["SHA512WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha512WithRsaEncryption; + m_algorithms["SHA-512WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha512WithRsaEncryption; + m_algorithms["SHA512WITHRSA"] = PkcsObjectIdentifiers.Sha512WithRsaEncryption; + m_algorithms["SHA-512WITHRSA"] = PkcsObjectIdentifiers.Sha512WithRsaEncryption; + m_algorithms["SHA512(224)WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha512_224WithRSAEncryption; + m_algorithms["SHA-512(224)WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha512_224WithRSAEncryption; + m_algorithms["SHA512(224)WITHRSA"] = PkcsObjectIdentifiers.Sha512_224WithRSAEncryption; + m_algorithms["SHA-512(224)WITHRSA"] = PkcsObjectIdentifiers.Sha512_224WithRSAEncryption; + m_algorithms["SHA512(256)WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha512_256WithRSAEncryption; + m_algorithms["SHA-512(256)WITHRSAENCRYPTION"] = PkcsObjectIdentifiers.Sha512_256WithRSAEncryption; + m_algorithms["SHA512(256)WITHRSA"] = PkcsObjectIdentifiers.Sha512_256WithRSAEncryption; + m_algorithms["SHA-512(256)WITHRSA"] = PkcsObjectIdentifiers.Sha512_256WithRSAEncryption; + m_algorithms["SHA1WITHRSAANDMGF1"] = PkcsObjectIdentifiers.IdRsassaPss; + m_algorithms["SHA224WITHRSAANDMGF1"] = PkcsObjectIdentifiers.IdRsassaPss; + m_algorithms["SHA256WITHRSAANDMGF1"] = PkcsObjectIdentifiers.IdRsassaPss; + m_algorithms["SHA384WITHRSAANDMGF1"] = PkcsObjectIdentifiers.IdRsassaPss; + m_algorithms["SHA512WITHRSAANDMGF1"] = PkcsObjectIdentifiers.IdRsassaPss; + m_algorithms["SHA3-224WITHRSAANDMGF1"] = PkcsObjectIdentifiers.IdRsassaPss; + m_algorithms["SHA3-256WITHRSAANDMGF1"] = PkcsObjectIdentifiers.IdRsassaPss; + m_algorithms["SHA3-384WITHRSAANDMGF1"] = PkcsObjectIdentifiers.IdRsassaPss; + m_algorithms["SHA3-512WITHRSAANDMGF1"] = PkcsObjectIdentifiers.IdRsassaPss; + m_algorithms["RIPEMD160WITHRSAENCRYPTION"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160; + m_algorithms["RIPEMD160WITHRSA"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160; + m_algorithms["RIPEMD128WITHRSAENCRYPTION"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128; + m_algorithms["RIPEMD128WITHRSA"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128; + m_algorithms["RIPEMD256WITHRSAENCRYPTION"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256; + m_algorithms["RIPEMD256WITHRSA"] = TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256; + m_algorithms["SHA1WITHDSA"] = X9ObjectIdentifiers.IdDsaWithSha1; + m_algorithms["SHA-1WITHDSA"] = X9ObjectIdentifiers.IdDsaWithSha1; + m_algorithms["DSAWITHSHA1"] = X9ObjectIdentifiers.IdDsaWithSha1; + m_algorithms["SHA224WITHDSA"] = NistObjectIdentifiers.DsaWithSha224; + m_algorithms["SHA256WITHDSA"] = NistObjectIdentifiers.DsaWithSha256; + m_algorithms["SHA384WITHDSA"] = NistObjectIdentifiers.DsaWithSha384; + m_algorithms["SHA512WITHDSA"] = NistObjectIdentifiers.DsaWithSha512; + m_algorithms["SHA3-224WITHDSA"] = NistObjectIdentifiers.IdDsaWithSha3_224; + m_algorithms["SHA3-256WITHDSA"] = NistObjectIdentifiers.IdDsaWithSha3_256; + m_algorithms["SHA3-384WITHDSA"] = NistObjectIdentifiers.IdDsaWithSha3_384; + m_algorithms["SHA3-512WITHDSA"] = NistObjectIdentifiers.IdDsaWithSha3_512; + m_algorithms["SHA3-224WITHECDSA"] = NistObjectIdentifiers.IdEcdsaWithSha3_224; + m_algorithms["SHA3-256WITHECDSA"] = NistObjectIdentifiers.IdEcdsaWithSha3_256; + m_algorithms["SHA3-384WITHECDSA"] = NistObjectIdentifiers.IdEcdsaWithSha3_384; + m_algorithms["SHA3-512WITHECDSA"] = NistObjectIdentifiers.IdEcdsaWithSha3_512; + m_algorithms["SHA3-224WITHRSA"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_224; + m_algorithms["SHA3-256WITHRSA"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_256; + m_algorithms["SHA3-384WITHRSA"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_384; + m_algorithms["SHA3-512WITHRSA"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_512; + m_algorithms["SHA3-224WITHRSAENCRYPTION"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_224; + m_algorithms["SHA3-256WITHRSAENCRYPTION"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_256; + m_algorithms["SHA3-384WITHRSAENCRYPTION"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_384; + m_algorithms["SHA3-512WITHRSAENCRYPTION"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_512; + m_algorithms["SHA1WITHECDSA"] = X9ObjectIdentifiers.ECDsaWithSha1; + m_algorithms["ECDSAWITHSHA1"] = X9ObjectIdentifiers.ECDsaWithSha1; + m_algorithms["SHA224WITHECDSA"] = X9ObjectIdentifiers.ECDsaWithSha224; + m_algorithms["SHA256WITHECDSA"] = X9ObjectIdentifiers.ECDsaWithSha256; + m_algorithms["SHA384WITHECDSA"] = X9ObjectIdentifiers.ECDsaWithSha384; + m_algorithms["SHA512WITHECDSA"] = X9ObjectIdentifiers.ECDsaWithSha512; + + + m_algorithms["GOST3411WITHGOST3410"] = CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94; + m_algorithms["GOST3411WITHGOST3410-94"] = CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94; + m_algorithms["GOST3411WITHECGOST3410"] = CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001; + m_algorithms["GOST3411WITHECGOST3410-2001"] = CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001; + m_algorithms["GOST3411WITHGOST3410-2001"] = CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001; + m_algorithms["GOST3411WITHECGOST3410-2012-256"] = RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256; + m_algorithms["GOST3411WITHECGOST3410-2012-512"] = RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512; + m_algorithms["GOST3411-2012-256WITHECGOST3410"] = RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256; + m_algorithms["GOST3411-2012-256WITHECGOST3410-2012-256"] = RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256; + m_algorithms["GOST3411-2012-512WITHECGOST3410"] = RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512; + m_algorithms["GOST3411-2012-512WITHECGOST3410-2012-512"] = RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512; + m_algorithms["SHA1WITHPLAIN-ECDSA"] = BsiObjectIdentifiers.ecdsa_plain_SHA1; + m_algorithms["SHA224WITHPLAIN-ECDSA"] = BsiObjectIdentifiers.ecdsa_plain_SHA224; + m_algorithms["SHA256WITHPLAIN-ECDSA"] = BsiObjectIdentifiers.ecdsa_plain_SHA256; + m_algorithms["SHA384WITHPLAIN-ECDSA"] = BsiObjectIdentifiers.ecdsa_plain_SHA384; + m_algorithms["SHA512WITHPLAIN-ECDSA"] = BsiObjectIdentifiers.ecdsa_plain_SHA512; + m_algorithms["RIPEMD160WITHPLAIN-ECDSA"] = BsiObjectIdentifiers.ecdsa_plain_RIPEMD160; + m_algorithms["SHA1WITHCVC-ECDSA"] = EacObjectIdentifiers.id_TA_ECDSA_SHA_1; + m_algorithms["SHA224WITHCVC-ECDSA"] = EacObjectIdentifiers.id_TA_ECDSA_SHA_224; + m_algorithms["SHA256WITHCVC-ECDSA"] = EacObjectIdentifiers.id_TA_ECDSA_SHA_256; + m_algorithms["SHA384WITHCVC-ECDSA"] = EacObjectIdentifiers.id_TA_ECDSA_SHA_384; + m_algorithms["SHA512WITHCVC-ECDSA"] = EacObjectIdentifiers.id_TA_ECDSA_SHA_512; + m_algorithms["SHA3-512WITHSPHINCS256"] = BCObjectIdentifiers.sphincs256_with_SHA3_512; + m_algorithms["SHA512WITHSPHINCS256"] = BCObjectIdentifiers.sphincs256_with_SHA512; + + m_algorithms["SHA256WITHSM2"] = GMObjectIdentifiers.sm2sign_with_sha256; + m_algorithms["SM3WITHSM2"] = GMObjectIdentifiers.sm2sign_with_sm3; + + m_algorithms["SHA256WITHXMSS"] = BCObjectIdentifiers.xmss_with_SHA256; + m_algorithms["SHA512WITHXMSS"] = BCObjectIdentifiers.xmss_with_SHA512; + m_algorithms["SHAKE128WITHXMSS"] = BCObjectIdentifiers.xmss_with_SHAKE128; + m_algorithms["SHAKE256WITHXMSS"] = BCObjectIdentifiers.xmss_with_SHAKE256; + + m_algorithms["SHA256WITHXMSSMT"] = BCObjectIdentifiers.xmss_mt_with_SHA256; + m_algorithms["SHA512WITHXMSSMT"] = BCObjectIdentifiers.xmss_mt_with_SHA512; + m_algorithms["SHAKE128WITHXMSSMT"] = BCObjectIdentifiers.xmss_mt_with_SHAKE128; + m_algorithms["SHAKE256WITHXMSSMT"] = BCObjectIdentifiers.xmss_mt_with_SHAKE256; // // 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((object)X9ObjectIdentifiers.ECDsaWithSha1); - noParams.Add((object)X9ObjectIdentifiers.ECDsaWithSha224); - noParams.Add((object)X9ObjectIdentifiers.ECDsaWithSha256); - noParams.Add((object)X9ObjectIdentifiers.ECDsaWithSha384); - noParams.Add((object)X9ObjectIdentifiers.ECDsaWithSha512); - noParams.Add((object)X9ObjectIdentifiers.IdDsaWithSha1); - noParams.Add((object)NistObjectIdentifiers.DsaWithSha224); - noParams.Add((object)NistObjectIdentifiers.DsaWithSha256); - noParams.Add((object)NistObjectIdentifiers.DsaWithSha384); - noParams.Add((object)NistObjectIdentifiers.DsaWithSha512); - noParams.Add((object)NistObjectIdentifiers.IdDsaWithSha3_224); - noParams.Add((object)NistObjectIdentifiers.IdDsaWithSha3_256); - noParams.Add((object)NistObjectIdentifiers.IdDsaWithSha3_384); - noParams.Add((object)NistObjectIdentifiers.IdDsaWithSha3_512); - noParams.Add((object)NistObjectIdentifiers.IdEcdsaWithSha3_224); - noParams.Add((object)NistObjectIdentifiers.IdEcdsaWithSha3_256); - noParams.Add((object)NistObjectIdentifiers.IdEcdsaWithSha3_384); - noParams.Add((object)NistObjectIdentifiers.IdEcdsaWithSha3_512); + 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); + noParams.Add(NistObjectIdentifiers.IdDsaWithSha3_224); + noParams.Add(NistObjectIdentifiers.IdDsaWithSha3_256); + noParams.Add(NistObjectIdentifiers.IdDsaWithSha3_384); + noParams.Add(NistObjectIdentifiers.IdDsaWithSha3_512); + noParams.Add(NistObjectIdentifiers.IdEcdsaWithSha3_224); + noParams.Add(NistObjectIdentifiers.IdEcdsaWithSha3_256); + noParams.Add(NistObjectIdentifiers.IdEcdsaWithSha3_384); + noParams.Add(NistObjectIdentifiers.IdEcdsaWithSha3_512); // // RFC 4491 // - noParams.Add((object)CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94); - noParams.Add((object)CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001); - noParams.Add((object)RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256); - noParams.Add((object)RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512); + noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94); + noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001); + noParams.Add(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256); + noParams.Add(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512); // // SPHINCS-256 // - noParams.Add((object)BCObjectIdentifiers.sphincs256_with_SHA512); - noParams.Add((object)BCObjectIdentifiers.sphincs256_with_SHA3_512); + noParams.Add(BCObjectIdentifiers.sphincs256_with_SHA512); + noParams.Add(BCObjectIdentifiers.sphincs256_with_SHA3_512); // // XMSS // - noParams.Add((object)BCObjectIdentifiers.xmss_with_SHA256); - noParams.Add((object)BCObjectIdentifiers.xmss_with_SHA512); - noParams.Add((object)BCObjectIdentifiers.xmss_with_SHAKE128); - noParams.Add((object)BCObjectIdentifiers.xmss_with_SHAKE256); - noParams.Add((object)BCObjectIdentifiers.xmss_mt_with_SHA256); - noParams.Add((object)BCObjectIdentifiers.xmss_mt_with_SHA512); - noParams.Add((object)BCObjectIdentifiers.xmss_mt_with_SHAKE128); - noParams.Add((object)BCObjectIdentifiers.xmss_mt_with_SHAKE256); + noParams.Add(BCObjectIdentifiers.xmss_with_SHA256); + noParams.Add(BCObjectIdentifiers.xmss_with_SHA512); + noParams.Add(BCObjectIdentifiers.xmss_with_SHAKE128); + noParams.Add(BCObjectIdentifiers.xmss_with_SHAKE256); + noParams.Add(BCObjectIdentifiers.xmss_mt_with_SHA256); + noParams.Add(BCObjectIdentifiers.xmss_mt_with_SHA512); + noParams.Add(BCObjectIdentifiers.xmss_mt_with_SHAKE128); + noParams.Add(BCObjectIdentifiers.xmss_mt_with_SHAKE256); // // SM2 // - noParams.Add((object)GMObjectIdentifiers.sm2sign_with_sha256); - noParams.Add((object)GMObjectIdentifiers.sm2sign_with_sm3); + noParams.Add(GMObjectIdentifiers.sm2sign_with_sha256); + noParams.Add(GMObjectIdentifiers.sm2sign_with_sm3); // // PKCS 1.5 encrypted algorithms // - pkcs15RsaEncryption.Add((object)PkcsObjectIdentifiers.Sha1WithRsaEncryption); - pkcs15RsaEncryption.Add((object)PkcsObjectIdentifiers.Sha224WithRsaEncryption); - pkcs15RsaEncryption.Add((object)PkcsObjectIdentifiers.Sha256WithRsaEncryption); - pkcs15RsaEncryption.Add((object)PkcsObjectIdentifiers.Sha384WithRsaEncryption); - pkcs15RsaEncryption.Add((object)PkcsObjectIdentifiers.Sha512WithRsaEncryption); - pkcs15RsaEncryption.Add((object)PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); - pkcs15RsaEncryption.Add((object)PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); - pkcs15RsaEncryption.Add((object)TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128); - pkcs15RsaEncryption.Add((object)TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160); - pkcs15RsaEncryption.Add((object)TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256); - pkcs15RsaEncryption.Add((object)NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_224); - pkcs15RsaEncryption.Add((object)NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_256); - pkcs15RsaEncryption.Add((object)NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_384); - pkcs15RsaEncryption.Add((object)NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_512); + pkcs15RsaEncryption.Add(PkcsObjectIdentifiers.Sha1WithRsaEncryption); + pkcs15RsaEncryption.Add(PkcsObjectIdentifiers.Sha224WithRsaEncryption); + pkcs15RsaEncryption.Add(PkcsObjectIdentifiers.Sha256WithRsaEncryption); + pkcs15RsaEncryption.Add(PkcsObjectIdentifiers.Sha384WithRsaEncryption); + pkcs15RsaEncryption.Add(PkcsObjectIdentifiers.Sha512WithRsaEncryption); + pkcs15RsaEncryption.Add(PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); + pkcs15RsaEncryption.Add(PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); + pkcs15RsaEncryption.Add(TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128); + pkcs15RsaEncryption.Add(TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160); + pkcs15RsaEncryption.Add(TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256); + pkcs15RsaEncryption.Add(NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_224); + pkcs15RsaEncryption.Add(NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_256); + pkcs15RsaEncryption.Add(NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_384); + pkcs15RsaEncryption.Add(NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_512); // // explicit params // AlgorithmIdentifier sha1AlgId = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance); - _params["SHA1WITHRSAANDMGF1"] = CreatePssParams(sha1AlgId, 20); + m_params["SHA1WITHRSAANDMGF1"] = CreatePssParams(sha1AlgId, 20); AlgorithmIdentifier sha224AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha224, DerNull.Instance); - _params["SHA224WITHRSAANDMGF1"] = CreatePssParams(sha224AlgId, 28); + m_params["SHA224WITHRSAANDMGF1"] = CreatePssParams(sha224AlgId, 28); AlgorithmIdentifier sha256AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256, DerNull.Instance); - _params["SHA256WITHRSAANDMGF1"] = CreatePssParams(sha256AlgId, 32); + m_params["SHA256WITHRSAANDMGF1"] = CreatePssParams(sha256AlgId, 32); AlgorithmIdentifier sha384AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha384, DerNull.Instance); - _params["SHA384WITHRSAANDMGF1"] = CreatePssParams(sha384AlgId, 48); + m_params["SHA384WITHRSAANDMGF1"] = CreatePssParams(sha384AlgId, 48); AlgorithmIdentifier sha512AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha512, DerNull.Instance); - _params["SHA512WITHRSAANDMGF1"] = CreatePssParams(sha512AlgId, 64); + m_params["SHA512WITHRSAANDMGF1"] = CreatePssParams(sha512AlgId, 64); AlgorithmIdentifier sha3_224AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha3_224, DerNull.Instance); - _params["SHA3-224WITHRSAANDMGF1"] = CreatePssParams(sha3_224AlgId, 28); + m_params["SHA3-224WITHRSAANDMGF1"] = CreatePssParams(sha3_224AlgId, 28); AlgorithmIdentifier sha3_256AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha3_256, DerNull.Instance); - _params["SHA3-256WITHRSAANDMGF1"] = CreatePssParams(sha3_256AlgId, 32); + m_params["SHA3-256WITHRSAANDMGF1"] = CreatePssParams(sha3_256AlgId, 32); AlgorithmIdentifier sha3_384AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha3_384, DerNull.Instance); - _params["SHA3-384WITHRSAANDMGF1"] = CreatePssParams(sha3_384AlgId, 48); + m_params["SHA3-384WITHRSAANDMGF1"] = CreatePssParams(sha3_384AlgId, 48); AlgorithmIdentifier sha3_512AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha3_512, DerNull.Instance); - _params["SHA3-512WITHRSAANDMGF1"] = CreatePssParams(sha3_512AlgId, 64); + m_params["SHA3-512WITHRSAANDMGF1"] = CreatePssParams(sha3_512AlgId, 64); // // digests // - digestOids[PkcsObjectIdentifiers.Sha224WithRsaEncryption] = NistObjectIdentifiers.IdSha224; - digestOids[PkcsObjectIdentifiers.Sha256WithRsaEncryption] = NistObjectIdentifiers.IdSha256; - digestOids[PkcsObjectIdentifiers.Sha384WithRsaEncryption] = NistObjectIdentifiers.IdSha384; - digestOids[PkcsObjectIdentifiers.Sha512WithRsaEncryption] = NistObjectIdentifiers.IdSha512; - digestOids[PkcsObjectIdentifiers.Sha512_224WithRSAEncryption] = NistObjectIdentifiers.IdSha512_224; - digestOids[PkcsObjectIdentifiers.Sha512_256WithRSAEncryption] = NistObjectIdentifiers.IdSha512_256; - digestOids[NistObjectIdentifiers.DsaWithSha224] = NistObjectIdentifiers.IdSha224; - digestOids[NistObjectIdentifiers.DsaWithSha256] = NistObjectIdentifiers.IdSha256; - digestOids[NistObjectIdentifiers.DsaWithSha384] = NistObjectIdentifiers.IdSha384; - digestOids[NistObjectIdentifiers.DsaWithSha512] = NistObjectIdentifiers.IdSha512; - digestOids[NistObjectIdentifiers.IdDsaWithSha3_224] = NistObjectIdentifiers.IdSha3_224; - digestOids[NistObjectIdentifiers.IdDsaWithSha3_256] = NistObjectIdentifiers.IdSha3_256; - digestOids[NistObjectIdentifiers.IdDsaWithSha3_384] = NistObjectIdentifiers.IdSha3_384; - digestOids[NistObjectIdentifiers.IdDsaWithSha3_512] = NistObjectIdentifiers.IdSha3_512; - digestOids[NistObjectIdentifiers.IdEcdsaWithSha3_224] = NistObjectIdentifiers.IdSha3_224; - digestOids[NistObjectIdentifiers.IdEcdsaWithSha3_256] = NistObjectIdentifiers.IdSha3_256; - digestOids[NistObjectIdentifiers.IdEcdsaWithSha3_384] = NistObjectIdentifiers.IdSha3_384; - digestOids[NistObjectIdentifiers.IdEcdsaWithSha3_512] = NistObjectIdentifiers.IdSha3_512; - digestOids[NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_224] = NistObjectIdentifiers.IdSha3_224; - digestOids[NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_256] = NistObjectIdentifiers.IdSha3_256; - digestOids[NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_384] = NistObjectIdentifiers.IdSha3_384; - digestOids[NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_512] = NistObjectIdentifiers.IdSha3_512; - - digestOids[PkcsObjectIdentifiers.MD2WithRsaEncryption] = PkcsObjectIdentifiers.MD2; - digestOids[PkcsObjectIdentifiers.MD4WithRsaEncryption] = PkcsObjectIdentifiers.MD4; - digestOids[PkcsObjectIdentifiers.MD5WithRsaEncryption] = PkcsObjectIdentifiers.MD5; - digestOids[PkcsObjectIdentifiers.Sha1WithRsaEncryption] = OiwObjectIdentifiers.IdSha1; - digestOids[TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128] = TeleTrusTObjectIdentifiers.RipeMD128; - digestOids[TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160] = TeleTrusTObjectIdentifiers.RipeMD160; - digestOids[TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256] = TeleTrusTObjectIdentifiers.RipeMD256; - digestOids[CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94] = CryptoProObjectIdentifiers.GostR3411; - digestOids[CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001] = CryptoProObjectIdentifiers.GostR3411; - digestOids[RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256] = RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256; - digestOids[RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512] = RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512; - - digestOids[GMObjectIdentifiers.sm2sign_with_sha256] = NistObjectIdentifiers.IdSha256; - digestOids[GMObjectIdentifiers.sm2sign_with_sm3] = GMObjectIdentifiers.sm3; + m_digestOids[PkcsObjectIdentifiers.Sha224WithRsaEncryption] = NistObjectIdentifiers.IdSha224; + m_digestOids[PkcsObjectIdentifiers.Sha256WithRsaEncryption] = NistObjectIdentifiers.IdSha256; + m_digestOids[PkcsObjectIdentifiers.Sha384WithRsaEncryption] = NistObjectIdentifiers.IdSha384; + m_digestOids[PkcsObjectIdentifiers.Sha512WithRsaEncryption] = NistObjectIdentifiers.IdSha512; + m_digestOids[PkcsObjectIdentifiers.Sha512_224WithRSAEncryption] = NistObjectIdentifiers.IdSha512_224; + m_digestOids[PkcsObjectIdentifiers.Sha512_256WithRSAEncryption] = NistObjectIdentifiers.IdSha512_256; + m_digestOids[NistObjectIdentifiers.DsaWithSha224] = NistObjectIdentifiers.IdSha224; + m_digestOids[NistObjectIdentifiers.DsaWithSha256] = NistObjectIdentifiers.IdSha256; + m_digestOids[NistObjectIdentifiers.DsaWithSha384] = NistObjectIdentifiers.IdSha384; + m_digestOids[NistObjectIdentifiers.DsaWithSha512] = NistObjectIdentifiers.IdSha512; + m_digestOids[NistObjectIdentifiers.IdDsaWithSha3_224] = NistObjectIdentifiers.IdSha3_224; + m_digestOids[NistObjectIdentifiers.IdDsaWithSha3_256] = NistObjectIdentifiers.IdSha3_256; + m_digestOids[NistObjectIdentifiers.IdDsaWithSha3_384] = NistObjectIdentifiers.IdSha3_384; + m_digestOids[NistObjectIdentifiers.IdDsaWithSha3_512] = NistObjectIdentifiers.IdSha3_512; + m_digestOids[NistObjectIdentifiers.IdEcdsaWithSha3_224] = NistObjectIdentifiers.IdSha3_224; + m_digestOids[NistObjectIdentifiers.IdEcdsaWithSha3_256] = NistObjectIdentifiers.IdSha3_256; + m_digestOids[NistObjectIdentifiers.IdEcdsaWithSha3_384] = NistObjectIdentifiers.IdSha3_384; + m_digestOids[NistObjectIdentifiers.IdEcdsaWithSha3_512] = NistObjectIdentifiers.IdSha3_512; + m_digestOids[NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_224] = NistObjectIdentifiers.IdSha3_224; + m_digestOids[NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_256] = NistObjectIdentifiers.IdSha3_256; + m_digestOids[NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_384] = NistObjectIdentifiers.IdSha3_384; + m_digestOids[NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_512] = NistObjectIdentifiers.IdSha3_512; + + m_digestOids[PkcsObjectIdentifiers.MD2WithRsaEncryption] = PkcsObjectIdentifiers.MD2; + m_digestOids[PkcsObjectIdentifiers.MD4WithRsaEncryption] = PkcsObjectIdentifiers.MD4; + m_digestOids[PkcsObjectIdentifiers.MD5WithRsaEncryption] = PkcsObjectIdentifiers.MD5; + m_digestOids[PkcsObjectIdentifiers.Sha1WithRsaEncryption] = OiwObjectIdentifiers.IdSha1; + m_digestOids[TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128] = TeleTrusTObjectIdentifiers.RipeMD128; + m_digestOids[TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160] = TeleTrusTObjectIdentifiers.RipeMD160; + m_digestOids[TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256] = TeleTrusTObjectIdentifiers.RipeMD256; + m_digestOids[CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94] = CryptoProObjectIdentifiers.GostR3411; + m_digestOids[CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001] = CryptoProObjectIdentifiers.GostR3411; + m_digestOids[RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256] = RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256; + m_digestOids[RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512] = RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512; + + m_digestOids[GMObjectIdentifiers.sm2sign_with_sha256] = NistObjectIdentifiers.IdSha256; + m_digestOids[GMObjectIdentifiers.sm2sign_with_sm3] = GMObjectIdentifiers.sm3; } private static AlgorithmIdentifier Generate(string signatureAlgorithm) { AlgorithmIdentifier sigAlgId; - AlgorithmIdentifier encAlgId; - AlgorithmIdentifier digAlgId; + //AlgorithmIdentifier encAlgId; + //AlgorithmIdentifier digAlgId; - string algorithmName = Strings.ToUpperCase(signatureAlgorithm); - DerObjectIdentifier sigOID = (DerObjectIdentifier)algorithms[algorithmName]; - if (sigOID == null) - { - throw new ArgumentException("Unknown signature type requested: " + algorithmName); - } + if (!m_algorithms.TryGetValue(signatureAlgorithm, out var sigOid)) + throw new ArgumentException("Unknown signature type requested: " + signatureAlgorithm); - if (noParams.Contains(sigOID)) - { - sigAlgId = new AlgorithmIdentifier(sigOID); - } - else if (_params.Contains(algorithmName)) + if (noParams.Contains(sigOid)) { - sigAlgId = new AlgorithmIdentifier(sigOID, (Asn1Encodable)_params[algorithmName]); + sigAlgId = new AlgorithmIdentifier(sigOid); } - else + else if (m_params.TryGetValue(signatureAlgorithm, out var explicitParameters)) { - sigAlgId = new AlgorithmIdentifier(sigOID, DerNull.Instance); - } - - if (pkcs15RsaEncryption.Contains(sigOID)) - { - encAlgId = new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance); + sigAlgId = new AlgorithmIdentifier(sigOid, explicitParameters); } else { - encAlgId = sigAlgId; + sigAlgId = new AlgorithmIdentifier(sigOid, DerNull.Instance); } - if (sigAlgId.Algorithm.Equals(PkcsObjectIdentifiers.IdRsassaPss)) - { - digAlgId = ((RsassaPssParameters)sigAlgId.Parameters).HashAlgorithm; - } - else - { - digAlgId = new AlgorithmIdentifier((DerObjectIdentifier)digestOids[sigOID], DerNull.Instance); - } + //if (pkcs15RsaEncryption.Contains(sigOid)) + //{ + // encAlgId = new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance); + //} + //else + //{ + // encAlgId = sigAlgId; + //} + + //if (sigAlgId.Algorithm.Equals(PkcsObjectIdentifiers.IdRsassaPss)) + //{ + // digAlgId = ((RsassaPssParameters)sigAlgId.Parameters).HashAlgorithm; + //} + //else + //{ + // digAlgId = new AlgorithmIdentifier(m_digestOids[sigOid], DerNull.Instance); + //} return sigAlgId; } @@ -378,96 +369,98 @@ public AlgorithmIdentifier Find(string sigAlgName) 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(); + private static readonly IDictionary m_digestOids = + new Dictionary(); + private static readonly IDictionary m_digestNameToOids = + new Dictionary(StringComparer.OrdinalIgnoreCase); 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.Sha512_224WithRSAEncryption, NistObjectIdentifiers.IdSha512_224); - digestOids.Add(PkcsObjectIdentifiers.Sha512_256WithRSAEncryption, NistObjectIdentifiers.IdSha512_256); - - digestOids.Add(NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_224, NistObjectIdentifiers.IdSha3_224); - digestOids.Add(NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_256, NistObjectIdentifiers.IdSha3_256); - digestOids.Add(NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_384, NistObjectIdentifiers.IdSha3_384); - digestOids.Add(NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_512, NistObjectIdentifiers.IdSha3_512); - - 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("SHA-512/224", NistObjectIdentifiers.IdSha512_224); - digestNameToOids.Add("SHA-512(224)", NistObjectIdentifiers.IdSha512_224); - digestNameToOids.Add("SHA-512/256", NistObjectIdentifiers.IdSha512_256); - digestNameToOids.Add("SHA-512(256)", NistObjectIdentifiers.IdSha512_256); - - 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("SHA512/224", NistObjectIdentifiers.IdSha512_224); - digestNameToOids.Add("SHA512(224)", NistObjectIdentifiers.IdSha512_224); - digestNameToOids.Add("SHA512/256", NistObjectIdentifiers.IdSha512_256); - digestNameToOids.Add("SHA512(256)", NistObjectIdentifiers.IdSha512_256); - - 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); + m_digestOids.Add(OiwObjectIdentifiers.MD4WithRsaEncryption, PkcsObjectIdentifiers.MD4); + m_digestOids.Add(OiwObjectIdentifiers.MD4WithRsa, PkcsObjectIdentifiers.MD4); + m_digestOids.Add(OiwObjectIdentifiers.MD5WithRsa, PkcsObjectIdentifiers.MD5); + m_digestOids.Add(OiwObjectIdentifiers.Sha1WithRsa, OiwObjectIdentifiers.IdSha1); + m_digestOids.Add(OiwObjectIdentifiers.DsaWithSha1, OiwObjectIdentifiers.IdSha1); + + m_digestOids.Add(PkcsObjectIdentifiers.Sha224WithRsaEncryption, NistObjectIdentifiers.IdSha224); + m_digestOids.Add(PkcsObjectIdentifiers.Sha256WithRsaEncryption, NistObjectIdentifiers.IdSha256); + m_digestOids.Add(PkcsObjectIdentifiers.Sha384WithRsaEncryption, NistObjectIdentifiers.IdSha384); + m_digestOids.Add(PkcsObjectIdentifiers.Sha512WithRsaEncryption, NistObjectIdentifiers.IdSha512); + m_digestOids.Add(PkcsObjectIdentifiers.Sha512_224WithRSAEncryption, NistObjectIdentifiers.IdSha512_224); + m_digestOids.Add(PkcsObjectIdentifiers.Sha512_256WithRSAEncryption, NistObjectIdentifiers.IdSha512_256); + + m_digestOids.Add(NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_224, NistObjectIdentifiers.IdSha3_224); + m_digestOids.Add(NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_256, NistObjectIdentifiers.IdSha3_256); + m_digestOids.Add(NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_384, NistObjectIdentifiers.IdSha3_384); + m_digestOids.Add(NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_512, NistObjectIdentifiers.IdSha3_512); + + m_digestOids.Add(PkcsObjectIdentifiers.MD2WithRsaEncryption, PkcsObjectIdentifiers.MD2); + m_digestOids.Add(PkcsObjectIdentifiers.MD4WithRsaEncryption, PkcsObjectIdentifiers.MD4); + m_digestOids.Add(PkcsObjectIdentifiers.MD5WithRsaEncryption, PkcsObjectIdentifiers.MD5); + m_digestOids.Add(PkcsObjectIdentifiers.Sha1WithRsaEncryption, OiwObjectIdentifiers.IdSha1); + + m_digestOids.Add(X9ObjectIdentifiers.ECDsaWithSha1, OiwObjectIdentifiers.IdSha1); + m_digestOids.Add(X9ObjectIdentifiers.ECDsaWithSha224, NistObjectIdentifiers.IdSha224); + m_digestOids.Add(X9ObjectIdentifiers.ECDsaWithSha256, NistObjectIdentifiers.IdSha256); + m_digestOids.Add(X9ObjectIdentifiers.ECDsaWithSha384, NistObjectIdentifiers.IdSha384); + m_digestOids.Add(X9ObjectIdentifiers.ECDsaWithSha512, NistObjectIdentifiers.IdSha512); + m_digestOids.Add(X9ObjectIdentifiers.IdDsaWithSha1, OiwObjectIdentifiers.IdSha1); + + m_digestOids.Add(NistObjectIdentifiers.DsaWithSha224, NistObjectIdentifiers.IdSha224); + m_digestOids.Add(NistObjectIdentifiers.DsaWithSha256, NistObjectIdentifiers.IdSha256); + m_digestOids.Add(NistObjectIdentifiers.DsaWithSha384, NistObjectIdentifiers.IdSha384); + m_digestOids.Add(NistObjectIdentifiers.DsaWithSha512, NistObjectIdentifiers.IdSha512); + + m_digestOids.Add(TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128, TeleTrusTObjectIdentifiers.RipeMD128); + m_digestOids.Add(TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160, TeleTrusTObjectIdentifiers.RipeMD160); + m_digestOids.Add(TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256, TeleTrusTObjectIdentifiers.RipeMD256); + + m_digestOids.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94, CryptoProObjectIdentifiers.GostR3411); + m_digestOids.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001, CryptoProObjectIdentifiers.GostR3411); + + m_digestNameToOids.Add("SHA-1", OiwObjectIdentifiers.IdSha1); + m_digestNameToOids.Add("SHA-224", NistObjectIdentifiers.IdSha224); + m_digestNameToOids.Add("SHA-256", NistObjectIdentifiers.IdSha256); + m_digestNameToOids.Add("SHA-384", NistObjectIdentifiers.IdSha384); + m_digestNameToOids.Add("SHA-512", NistObjectIdentifiers.IdSha512); + m_digestNameToOids.Add("SHA-512/224", NistObjectIdentifiers.IdSha512_224); + m_digestNameToOids.Add("SHA-512(224)", NistObjectIdentifiers.IdSha512_224); + m_digestNameToOids.Add("SHA-512/256", NistObjectIdentifiers.IdSha512_256); + m_digestNameToOids.Add("SHA-512(256)", NistObjectIdentifiers.IdSha512_256); + + m_digestNameToOids.Add("SHA1", OiwObjectIdentifiers.IdSha1); + m_digestNameToOids.Add("SHA224", NistObjectIdentifiers.IdSha224); + m_digestNameToOids.Add("SHA256", NistObjectIdentifiers.IdSha256); + m_digestNameToOids.Add("SHA384", NistObjectIdentifiers.IdSha384); + m_digestNameToOids.Add("SHA512", NistObjectIdentifiers.IdSha512); + m_digestNameToOids.Add("SHA512/224", NistObjectIdentifiers.IdSha512_224); + m_digestNameToOids.Add("SHA512(224)", NistObjectIdentifiers.IdSha512_224); + m_digestNameToOids.Add("SHA512/256", NistObjectIdentifiers.IdSha512_256); + m_digestNameToOids.Add("SHA512(256)", NistObjectIdentifiers.IdSha512_256); + + m_digestNameToOids.Add("SHA3-224", NistObjectIdentifiers.IdSha3_224); + m_digestNameToOids.Add("SHA3-256", NistObjectIdentifiers.IdSha3_256); + m_digestNameToOids.Add("SHA3-384", NistObjectIdentifiers.IdSha3_384); + m_digestNameToOids.Add("SHA3-512", NistObjectIdentifiers.IdSha3_512); + + m_digestNameToOids.Add("SHAKE-128", NistObjectIdentifiers.IdShake128); + m_digestNameToOids.Add("SHAKE-256", NistObjectIdentifiers.IdShake256); + + m_digestNameToOids.Add("GOST3411", CryptoProObjectIdentifiers.GostR3411); + + m_digestNameToOids.Add("MD2", PkcsObjectIdentifiers.MD2); + m_digestNameToOids.Add("MD4", PkcsObjectIdentifiers.MD4); + m_digestNameToOids.Add("MD5", PkcsObjectIdentifiers.MD5); + + m_digestNameToOids.Add("RIPEMD128", TeleTrusTObjectIdentifiers.RipeMD128); + m_digestNameToOids.Add("RIPEMD160", TeleTrusTObjectIdentifiers.RipeMD160); + m_digestNameToOids.Add("RIPEMD256", TeleTrusTObjectIdentifiers.RipeMD256); } - public AlgorithmIdentifier find(AlgorithmIdentifier sigAlgId) + public AlgorithmIdentifier Find(AlgorithmIdentifier sigAlgId) { AlgorithmIdentifier digAlgId; @@ -477,19 +470,19 @@ public AlgorithmIdentifier find(AlgorithmIdentifier sigAlgId) } else { - digAlgId = new AlgorithmIdentifier((DerObjectIdentifier)digestOids[sigAlgId.Algorithm], DerNull.Instance); + digAlgId = new AlgorithmIdentifier(m_digestOids[sigAlgId.Algorithm], DerNull.Instance); } return digAlgId; } - public AlgorithmIdentifier find(string digAlgName) + public AlgorithmIdentifier Find(string digAlgName) { - return new AlgorithmIdentifier((DerObjectIdentifier)digestNameToOids[digAlgName], DerNull.Instance); + return new AlgorithmIdentifier(m_digestNameToOids[digAlgName], DerNull.Instance); } } - public class CmsSignedGenerator + public abstract class CmsSignedGenerator { /** * Default type for the signed data. @@ -515,35 +508,38 @@ public class CmsSignedGenerator 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(); + public static readonly string EncryptionECGost3410_2012_256 = RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256.Id; + public static readonly string EncryptionECGost3410_2012_512 = RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512.Id; + + internal List _certs = new List(); + internal List _crls = new List(); + internal IList _signers = new List(); + internal IDictionary m_digests = + new Dictionary(StringComparer.OrdinalIgnoreCase); internal bool _useDerForCerts = false; internal bool _useDerForCrls = false; - protected readonly SecureRandom rand; + protected readonly SecureRandom m_random; protected CmsSignedGenerator() - : this(new SecureRandom()) + : this(CryptoServicesRegistrar.GetSecureRandom()) { } /// Constructor allowing specific source of randomness - /// Instance of SecureRandom to use. - protected CmsSignedGenerator( - SecureRandom rand) + /// Instance of SecureRandom to use. + protected CmsSignedGenerator(SecureRandom random) { - this.rand = rand; + if (random == null) + throw new ArgumentNullException(nameof(random)); + + m_random = random; } - internal protected virtual IDictionary GetBaseParameters( - DerObjectIdentifier contentType, - AlgorithmIdentifier digAlgId, - byte[] hash) + internal protected virtual IDictionary GetBaseParameters( + DerObjectIdentifier contentType, AlgorithmIdentifier digAlgId, byte[] hash) { - IDictionary param = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + var param = new Dictionary(); if (contentType != null) { @@ -564,40 +560,51 @@ internal protected virtual Asn1Set GetAttributeSet( : new DerSet(attr.ToAsn1EncodableVector()); } - public void AddCertificates( - IX509Store certStore) + public void AddAttributeCertificate(X509V2AttributeCertificate attrCert) { - CollectionUtilities.AddRange(_certs, CmsUtilities.GetCertificatesFromStore(certStore)); + _certs.Add(new DerTaggedObject(false, 2, attrCert.AttributeCertificate)); } - public void AddCrls( - IX509Store crlStore) + public void AddAttributeCertificates(IStore attrCertStore) { - CollectionUtilities.AddRange(_crls, CmsUtilities.GetCrlsFromStore(crlStore)); + _certs.AddRange(CmsUtilities.GetAttributeCertificatesFromStore(attrCertStore)); } - /** - * 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) + public void AddCertificate(X509Certificate cert) { - 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); - } + _certs.Add(cert.CertificateStructure); + } + + public void AddCertificates(IStore certStore) + { + _certs.AddRange(CmsUtilities.GetCertificatesFromStore(certStore)); + } + + public void AddCrl(X509Crl crl) + { + _crls.Add(crl.CertificateList); + } + + public void AddCrls(IStore crlStore) + { + _crls.AddRange(CmsUtilities.GetCrlsFromStore(crlStore)); + } + + public void AddOtherRevocationInfo(OtherRevocationInfoFormat otherRevocationInfo) + { + CmsUtilities.ValidateOtherRevocationInfo(otherRevocationInfo); + _crls.Add(new DerTaggedObject(false, 1, otherRevocationInfo)); + } + + public void AddOtherRevocationInfos(IStore otherRevocationInfoStore) + { + _crls.AddRange(CmsUtilities.GetOtherRevocationInfosFromStore(otherRevocationInfoStore)); + } + + public void AddOtherRevocationInfos(DerObjectIdentifier otherRevInfoFormat, + IStore otherRevInfoStore) + { + _crls.AddRange(CmsUtilities.GetOtherRevocationInfosFromStore(otherRevInfoStore, otherRevInfoFormat)); } /** @@ -605,8 +612,7 @@ public void AddAttributeCertificates( * * @param signerStore store of signers */ - public void AddSigners( - SignerInformationStore signerStore) + public void AddSigners(SignerInformationStore signerStore) { foreach (SignerInformation o in signerStore.GetSigners()) { @@ -621,9 +627,9 @@ public void AddSigners( * * @return a map of oids (as string objects) and byte[] representing digests. */ - public IDictionary GetGeneratedDigests() + public IDictionary GetGeneratedDigests() { - return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(_digests); + return new Dictionary(m_digests, StringComparer.OrdinalIgnoreCase); } public bool UseDerForCerts diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedHelper.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedHelper.cs index 364d7e2..0815c15 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedHelper.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSSignedHelper.cs @@ -1,27 +1,25 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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.Eac; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Iana; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Misc; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Esf; 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.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.Security; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; +using BestHTTP.SecureProtocol.Org.BouncyCastle.X509; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms { @@ -35,18 +33,18 @@ internal class CmsSignedHelper 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 IDictionary m_encryptionAlgs = new Dictionary(); + private static readonly IDictionary m_digestAlgs = new Dictionary(); + private static readonly IDictionary m_digestAliases = new Dictionary(); - private static readonly ISet noParams = new HashSet(); - private static readonly IDictionary ecAlgorithms = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + private static readonly HashSet noParams = new HashSet(); + private static readonly IDictionary m_ecAlgorithms = new Dictionary(); - private static void AddEntries(DerObjectIdentifier oid, string digest, string encryption) + private static void AddEntries(DerObjectIdentifier oid, string digest, string encryption) { string alias = oid.Id; - digestAlgs.Add(alias, digest); - encryptionAlgs.Add(alias, encryption); + m_digestAlgs.Add(alias, digest); + m_encryptionAlgs.Add(alias, encryption); } static CmsSignedHelper() @@ -89,95 +87,89 @@ static CmsSignedHelper() 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.Id, "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(NistObjectIdentifiers.IdSha512_224.Id, "SHA512(224)"); - digestAlgs.Add(NistObjectIdentifiers.IdSha512_256.Id, "SHA512(256)"); - digestAlgs.Add(NistObjectIdentifiers.IdSha3_224.Id, "SHA3-224"); - digestAlgs.Add(NistObjectIdentifiers.IdSha3_256.Id, "SHA3-256"); - digestAlgs.Add(NistObjectIdentifiers.IdSha3_384.Id, "SHA3-384"); - digestAlgs.Add(NistObjectIdentifiers.IdSha3_512.Id, "SHA3-512"); - 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" }); + AddEntries(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94, "GOST3411", "GOST3410"); + AddEntries(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001, "GOST3411", "ECGOST3410"); + AddEntries(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256, "GOST3411-2012-256", "ECGOST3410"); + AddEntries(RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512, "GOST3411-2012-512", "ECGOST3410"); + + m_encryptionAlgs.Add(X9ObjectIdentifiers.IdDsa.Id, "DSA"); + m_encryptionAlgs.Add(PkcsObjectIdentifiers.RsaEncryption.Id, "RSA"); + m_encryptionAlgs.Add(TeleTrusTObjectIdentifiers.TeleTrusTRsaSignatureAlgorithm.Id, "RSA"); + m_encryptionAlgs.Add(X509ObjectIdentifiers.IdEARsa.Id, "RSA"); + m_encryptionAlgs.Add(CmsSignedGenerator.EncryptionRsaPss, "RSAandMGF1"); + m_encryptionAlgs.Add(CryptoProObjectIdentifiers.GostR3410x94.Id, "GOST3410"); + m_encryptionAlgs.Add(CryptoProObjectIdentifiers.GostR3410x2001.Id, "ECGOST3410"); + m_encryptionAlgs.Add(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256.Id, "ECGOST3410"); + m_encryptionAlgs.Add(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512.Id, "ECGOST3410"); + m_encryptionAlgs.Add("1.3.6.1.4.1.5849.1.6.2", "ECGOST3410"); + m_encryptionAlgs.Add("1.3.6.1.4.1.5849.1.1.5", "GOST3410"); + + m_digestAlgs.Add(PkcsObjectIdentifiers.MD2.Id, "MD2"); + m_digestAlgs.Add(PkcsObjectIdentifiers.MD4.Id, "MD4"); + m_digestAlgs.Add(PkcsObjectIdentifiers.MD5.Id, "MD5"); + m_digestAlgs.Add(OiwObjectIdentifiers.IdSha1.Id, "SHA1"); + m_digestAlgs.Add(NistObjectIdentifiers.IdSha224.Id, "SHA224"); + m_digestAlgs.Add(NistObjectIdentifiers.IdSha256.Id, "SHA256"); + m_digestAlgs.Add(NistObjectIdentifiers.IdSha384.Id, "SHA384"); + m_digestAlgs.Add(NistObjectIdentifiers.IdSha512.Id, "SHA512"); + m_digestAlgs.Add(NistObjectIdentifiers.IdSha512_224.Id, "SHA512(224)"); + m_digestAlgs.Add(NistObjectIdentifiers.IdSha512_256.Id, "SHA512(256)"); + m_digestAlgs.Add(NistObjectIdentifiers.IdSha3_224.Id, "SHA3-224"); + m_digestAlgs.Add(NistObjectIdentifiers.IdSha3_256.Id, "SHA3-256"); + m_digestAlgs.Add(NistObjectIdentifiers.IdSha3_384.Id, "SHA3-384"); + m_digestAlgs.Add(NistObjectIdentifiers.IdSha3_512.Id, "SHA3-512"); + m_digestAlgs.Add(TeleTrusTObjectIdentifiers.RipeMD128.Id, "RIPEMD128"); + m_digestAlgs.Add(TeleTrusTObjectIdentifiers.RipeMD160.Id, "RIPEMD160"); + m_digestAlgs.Add(TeleTrusTObjectIdentifiers.RipeMD256.Id, "RIPEMD256"); + m_digestAlgs.Add(CryptoProObjectIdentifiers.GostR3411.Id, "GOST3411"); + m_digestAlgs.Add("1.3.6.1.4.1.5849.1.2.1", "GOST3411"); + m_digestAlgs.Add(RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256.Id, "GOST3411-2012-256"); + m_digestAlgs.Add(RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512.Id, "GOST3411-2012-512"); + + m_digestAliases.Add("SHA1", new string[]{ "SHA-1" }); + m_digestAliases.Add("SHA224", new string[]{ "SHA-224" }); + m_digestAliases.Add("SHA256", new string[]{ "SHA-256" }); + m_digestAliases.Add("SHA384", new string[]{ "SHA-384" }); + m_digestAliases.Add("SHA512", new string[]{ "SHA-512" }); noParams.Add(CmsSignedGenerator.EncryptionDsa); - // noParams.Add(EncryptionECDsa); + //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); - } - - + m_ecAlgorithms.Add(CmsSignedGenerator.DigestSha1, EncryptionECDsaWithSha1); + m_ecAlgorithms.Add(CmsSignedGenerator.DigestSha224, EncryptionECDsaWithSha224); + m_ecAlgorithms.Add(CmsSignedGenerator.DigestSha256, EncryptionECDsaWithSha256); + m_ecAlgorithms.Add(CmsSignedGenerator.DigestSha384, EncryptionECDsaWithSha384); + m_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) + internal string GetDigestAlgName(string digestAlgOid) { - string algName = (string)digestAlgs[digestAlgOid]; + return m_digestAlgs.TryGetValue(digestAlgOid, out var algName) ? algName : digestAlgOid; + } - if (algName != null) + internal AlgorithmIdentifier GetEncAlgorithmIdentifier(DerObjectIdentifier encOid, + Asn1Encodable sigX509Parameters) + { + if (noParams.Contains(encOid.Id)) { - return algName; + return new AlgorithmIdentifier(encOid); } - return digestAlgOid; - } - - internal AlgorithmIdentifier GetEncAlgorithmIdentifier( - DerObjectIdentifier encOid, - Asn1Encodable sigX509Parameters) - { - if (noParams.Contains(encOid.Id)) - { - return new AlgorithmIdentifier(encOid); - } - - return new AlgorithmIdentifier(encOid, sigX509Parameters); - } + return new AlgorithmIdentifier(encOid, sigX509Parameters); + } - internal string[] GetDigestAliases( - string algName) + internal string[] GetDigestAliases(string algName) { - string[] aliases = (string[]) digestAliases[algName]; - - return aliases == null ? new string[0] : (string[]) aliases.Clone(); + return m_digestAliases.TryGetValue(algName, out var aliases) ? (string[])aliases.Clone() : new string[0]; } /** @@ -185,17 +177,9 @@ internal string[] GetDigestAliases( * JCA string representations rather than the algorithm identifier (if * possible). */ - internal string GetEncryptionAlgName( - string encryptionAlgOid) + internal string GetEncryptionAlgName(string encryptionAlgOid) { - string algName = (string) encryptionAlgs[encryptionAlgOid]; - - if (algName != null) - { - return algName; - } - - return encryptionAlgOid; + return m_encryptionAlgs.TryGetValue(encryptionAlgOid, out var algName) ? algName : encryptionAlgOid; } internal IDigest GetDigestInstance( @@ -224,142 +208,6 @@ internal ISigner GetSignatureInstance( 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) { @@ -375,9 +223,9 @@ internal string GetEncOid( { string encOID = null; - if (key is RsaKeyParameters) + if (key is RsaKeyParameters rsaKeyParameters) { - if (!((RsaKeyParameters)key).IsPrivate) + if (!rsaKeyParameters.IsPrivate) throw new ArgumentException("Expected RSA private key"); encOID = CmsSignedGenerator.EncryptionRsa; @@ -409,22 +257,35 @@ internal string GetEncOid( throw new ArgumentException("can't mix DSA with anything but SHA1/SHA2"); } } - else if (key is ECPrivateKeyParameters) + else if (key is ECPrivateKeyParameters ecPrivKey) { - ECPrivateKeyParameters ecPrivKey = (ECPrivateKeyParameters)key; string algName = ecPrivKey.AlgorithmName; if (algName == "ECGOST3410") { encOID = CmsSignedGenerator.EncryptionECGost3410; } - else + else if (ecPrivKey.Parameters is ECGost3410Parameters ecGost3410Parameters) { - // 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"); + var digestParamSet = ecGost3410Parameters.DigestParamSet; + if (digestParamSet.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256)) + { + encOID = CmsSignedGenerator.EncryptionECGost3410_2012_256; + } + else if (digestParamSet.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512)) + { + encOID = CmsSignedGenerator.EncryptionECGost3410_2012_512; + } + else + { + throw new ArgumentException("can't determine GOST3410 algorithm"); + } + } + else + { + // TODO Should we insist on algName being one of "EC" or "ECDSA", as Java does? + if (!m_ecAlgorithms.TryGetValue(digestOID, out encOID)) + throw new ArgumentException("can't mix ECDSA with anything but SHA family digests"); } } else if (key is Gost3410PrivateKeyParameters) @@ -439,19 +300,83 @@ internal string GetEncOid( return encOID; } - public IX509Store GetCertificates(Asn1Set certificates) + internal IStore GetAttributeCertificates(Asn1Set attrCertSet) { - IList certList = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); - if (certificates != null) - { - foreach (Asn1Encodable enc in certificates) - { - certList.Add(X509CertificateStructure.GetInstance(enc)); - } + var contents = new List(); + if (attrCertSet != null) + { + foreach (Asn1Encodable ae in attrCertSet) + { + if (ae != null && ae.ToAsn1Object() is Asn1TaggedObject t) + { + if (t.HasContextTag(2)) + { + Asn1Sequence s = Asn1Sequence.GetInstance(t, false); + + contents.Add(new X509V2AttributeCertificate(AttributeCertificate.GetInstance(s))); + } + } + } } - return new X509CollectionStore(certList); + return CollectionUtilities.CreateStore(contents); } - } + + internal IStore GetCertificates(Asn1Set certSet) + { + var contents = new List(); + if (certSet != null) + { + foreach (Asn1Encodable ae in certSet) + { + if (ae != null && ae.ToAsn1Object() is Asn1Sequence s) + { + contents.Add(new X509Certificate(X509CertificateStructure.GetInstance(s))); + } + } + } + return CollectionUtilities.CreateStore(contents); + } + + internal IStore GetCrls(Asn1Set crlSet) + { + var contents = new List(); + if (crlSet != null) + { + foreach (Asn1Encodable ae in crlSet) + { + if (ae != null && ae.ToAsn1Object() is Asn1Sequence s) + { + contents.Add(new X509Crl(CertificateList.GetInstance(s))); + } + } + } + return CollectionUtilities.CreateStore(contents); + } + + internal IStore GetOtherRevInfos(Asn1Set crlSet, DerObjectIdentifier otherRevInfoFormat) + { + var contents = new List(); + if (crlSet != null && otherRevInfoFormat != null) + { + foreach (Asn1Encodable ae in crlSet) + { + if (ae != null && ae.ToAsn1Object() is Asn1TaggedObject taggedObject) + { + if (taggedObject.HasContextTag(1)) + { + var otherRevocationInfo = OtherRevocationInfoFormat.GetInstance(taggedObject, false); + + if (otherRevInfoFormat.Equals(otherRevocationInfo.InfoFormat)) + { + contents.Add(otherRevocationInfo.Info); + } + } + } + } + } + return CollectionUtilities.CreateStore(contents); + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSStreamException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSStreamException.cs index ef719d3..c617ec5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSStreamException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSStreamException.cs @@ -2,32 +2,34 @@ #pragma warning disable using System; using System.IO; +using System.Runtime.Serialization; 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() + : base() + { + } + + public CmsStreamException(string message) + : base(message) { } - public CmsStreamException( - string name) - : base(name) - { - } + public CmsStreamException(string message, Exception innerException) + : base(message, innerException) + { + } - public CmsStreamException( - string name, - Exception e) - : base(name, e) - { - } - } + protected CmsStreamException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSTypedStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSTypedStream.cs index c8b0529..b109e94 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSTypedStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSTypedStream.cs @@ -35,11 +35,7 @@ public CmsTypedStream( 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 @@ -55,7 +51,7 @@ public Stream ContentStream public void Drain() { Streams.Drain(_in); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(_in); + _in.Dispose(); } private class FullReaderStream : FilterStream @@ -65,12 +61,19 @@ internal FullReaderStream(Stream input) { } - public override int Read(byte[] buf, int off, int len) + public override int Read(byte[] buf, int off, int len) { - return Streams.ReadFully(base.s, buf, off, len); + return Streams.ReadFully(s, buf, off, len); } - } - } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int Read(Span buffer) + { + return Streams.ReadFully(s, buffer); + } +#endif + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSUtils.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSUtils.cs index b1a2b93..7b51d38 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSUtils.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/CMSUtils.cs @@ -1,17 +1,16 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ocsp; 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.Utilities.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.X509; -using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms { @@ -71,98 +70,109 @@ private static ContentInfo ReadContentInfo( } } - public static byte[] StreamToByteArray( - Stream inStream) + internal static byte[] StreamToByteArray(Stream inStream) { return Streams.ReadAll(inStream); } - public static byte[] StreamToByteArray( - Stream inStream, - int limit) + internal static byte[] StreamToByteArray(Stream inStream, int limit) { return Streams.ReadAllLimited(inStream, limit); } - public static IList GetCertificatesFromStore( - IX509Store certStore) + internal static List GetAttributeCertificatesFromStore( + IStore attrCertStore) { - try - { - IList certs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); - - if (certStore != null) + var result = new List(); + if (attrCertStore != null) + { + foreach (var attrCert in attrCertStore.EnumerateMatches(null)) { - foreach (X509Certificate c in certStore.GetMatches(null)) - { - certs.Add( - X509CertificateStructure.GetInstance( - Asn1Object.FromByteArray(c.GetEncoded()))); - } + result.Add(new DerTaggedObject(false, 2, attrCert.AttributeCertificate)); } + } + return result; + } - return certs; - } - catch (CertificateEncodingException e) - { - throw new CmsException("error encoding certs", e); - } - catch (Exception e) - { - throw new CmsException("error processing certs", e); + internal static List GetCertificatesFromStore(IStore certStore) + { + var result = new List(); + if (certStore != null) + { + foreach (var cert in certStore.EnumerateMatches(null)) + { + result.Add(cert.CertificateStructure); + } } + return result; } - public static IList GetCrlsFromStore( - IX509Store crlStore) + internal static List GetCrlsFromStore(IStore crlStore) { - try + var result = new List(); + if (crlStore != null) { - 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()))); - } + foreach (var crl in crlStore.EnumerateMatches(null)) + { + result.Add(crl.CertificateList); } - - return crls; - } - catch (CrlException e) - { - throw new CmsException("error encoding crls", e); } - catch (Exception e) + return result; + } + + internal static List GetOtherRevocationInfosFromStore( + IStore otherRevocationInfoStore) + { + var result = new List(); + if (otherRevocationInfoStore != null) + { + foreach (var otherRevocationInfo in otherRevocationInfoStore.EnumerateMatches(null)) + { + ValidateOtherRevocationInfo(otherRevocationInfo); + + result.Add(new DerTaggedObject(false, 1, otherRevocationInfo)); + } + } + return result; + } + + internal static List GetOtherRevocationInfosFromStore(IStore otherRevInfoStore, + DerObjectIdentifier otherRevInfoFormat) + { + var result = new List(); + if (otherRevInfoStore != null && otherRevInfoFormat != null) { - throw new CmsException("error processing crls", e); + foreach (var otherRevInfo in otherRevInfoStore.EnumerateMatches(null)) + { + var otherRevocationInfo = new OtherRevocationInfoFormat(otherRevInfoFormat, otherRevInfo); + + ValidateOtherRevocationInfo(otherRevocationInfo); + + result.Add(new DerTaggedObject(false, 1, otherRevocationInfo)); + } } - } + return result; + } - public static Asn1Set CreateBerSetFromList( - IList berObjects) + internal static Asn1Set CreateBerSetFromList(IEnumerable elements) { Asn1EncodableVector v = new Asn1EncodableVector(); - foreach (Asn1Encodable ae in berObjects) + foreach (Asn1Encodable element in elements) { - v.Add(ae); + v.Add(element); } return new BerSet(v); } - public static Asn1Set CreateDerSetFromList( - IList derObjects) + internal static Asn1Set CreateDerSetFromList(IEnumerable elements) { Asn1EncodableVector v = new Asn1EncodableVector(); - foreach (Asn1Encodable ae in derObjects) + foreach (Asn1Encodable element in elements) { - v.Add(ae); + v.Add(element); } return new DerSet(v); @@ -184,7 +194,18 @@ internal static IssuerAndSerialNumber GetIssuerAndSerialNumber(X509Certificate c TbsCertificateStructure tbsCert = GetTbsCertificateStructure(cert); return new IssuerAndSerialNumber(tbsCert.Issuer, tbsCert.SerialNumber.Value); } - } + + internal static void ValidateOtherRevocationInfo(OtherRevocationInfoFormat otherRevocationInfo) + { + if (CmsObjectIdentifiers.id_ri_ocsp_response.Equals(otherRevocationInfo.InfoFormat)) + { + OcspResponse ocspResponse = OcspResponse.GetInstance(otherRevocationInfo.Info); + + if (OcspResponseStatus.Successful != ocspResponse.ResponseStatus.IntValueExact) + throw new ArgumentException("cannot add unsuccessful OCSP response to CMS SignedData"); + } + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/DefaultAuthenticatedAttributeTableGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/DefaultAuthenticatedAttributeTableGenerator.cs index b588bde..c751e79 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/DefaultAuthenticatedAttributeTableGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/DefaultAuthenticatedAttributeTableGenerator.cs @@ -1,11 +1,10 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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 { @@ -15,14 +14,14 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms public class DefaultAuthenticatedAttributeTableGenerator : CmsAttributeTableGenerator { - private readonly IDictionary table; + private readonly IDictionary m_table; /** * Initialise to use all defaults */ public DefaultAuthenticatedAttributeTableGenerator() { - table = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + m_table = new Dictionary(); } /** @@ -35,11 +34,11 @@ public DefaultAuthenticatedAttributeTableGenerator( { if (attributeTable != null) { - table = attributeTable.ToDictionary(); + m_table = attributeTable.ToDictionary(); } else { - table = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + m_table = new Dictionary(); } } @@ -53,12 +52,12 @@ public DefaultAuthenticatedAttributeTableGenerator( * * @return a filled in IDictionary of attributes. */ - protected virtual IDictionary CreateStandardAttributeTable( - IDictionary parameters) + protected virtual IDictionary CreateStandardAttributeTable( + IDictionary parameters) { - IDictionary std = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(table); + var std = new Dictionary(m_table); - if (!std.Contains(CmsAttributes.ContentType)) + if (!std.ContainsKey(CmsAttributes.ContentType)) { DerObjectIdentifier contentType = (DerObjectIdentifier) parameters[CmsAttributeTableParameter.ContentType]; @@ -67,7 +66,7 @@ protected virtual IDictionary CreateStandardAttributeTable( std[attr.AttrType] = attr; } - if (!std.Contains(CmsAttributes.MessageDigest)) + if (!std.ContainsKey(CmsAttributes.MessageDigest)) { byte[] messageDigest = (byte[])parameters[CmsAttributeTableParameter.Digest]; Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(CmsAttributes.MessageDigest, @@ -78,14 +77,13 @@ protected virtual IDictionary CreateStandardAttributeTable( return std; } - /** + /** * @param parameters source parameters * @return the populated attribute table */ - public virtual AttributeTable GetAttributes( - IDictionary parameters) + public virtual AttributeTable GetAttributes(IDictionary parameters) { - IDictionary table = CreateStandardAttributeTable(parameters); + var table = CreateStandardAttributeTable(parameters); return new AttributeTable(table); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/DefaultSignedAttributeTableGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/DefaultSignedAttributeTableGenerator.cs index 44a4f04..49b76e2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/DefaultSignedAttributeTableGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/DefaultSignedAttributeTableGenerator.cs @@ -1,11 +1,10 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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 { @@ -15,14 +14,14 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms public class DefaultSignedAttributeTableGenerator : CmsAttributeTableGenerator { - private readonly IDictionary table; + private readonly IDictionary m_table; /** * Initialise to use all defaults */ public DefaultSignedAttributeTableGenerator() { - table = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + m_table = new Dictionary(); } /** @@ -30,38 +29,18 @@ public DefaultSignedAttributeTableGenerator() * * @param attributeTable initial attribute table to use. */ - public DefaultSignedAttributeTableGenerator( - AttributeTable attributeTable) + public DefaultSignedAttributeTableGenerator(AttributeTable attributeTable) { if (attributeTable != null) { - table = attributeTable.ToDictionary(); + m_table = attributeTable.ToDictionary(); } else { - table = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + m_table = new Dictionary(); } } -#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 @@ -70,23 +49,24 @@ protected virtual IDictionary createStandardAttributeTable( * * @param parameters source parameters for table generation. * - * @return a filled in Hashtable of attributes. + * @return a filled in Dictionary of attributes. */ - protected virtual Hashtable createStandardAttributeTable( - IDictionary parameters) + protected virtual IDictionary CreateStandardAttributeTable( + IDictionary parameters) { - Hashtable std = new Hashtable(table); + var std = new Dictionary(m_table); DoCreateStandardAttributeTable(parameters, std); return std; } -#endif - private void DoCreateStandardAttributeTable(IDictionary parameters, IDictionary std) + 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 (parameters.ContainsKey(CmsAttributeTableParameter.ContentType)) { - if (!std.Contains(CmsAttributes.ContentType)) + if (!std.ContainsKey(CmsAttributes.ContentType)) { DerObjectIdentifier contentType = (DerObjectIdentifier) parameters[CmsAttributeTableParameter.ContentType]; @@ -96,14 +76,14 @@ private void DoCreateStandardAttributeTable(IDictionary parameters, IDictionary } } - if (!std.Contains(CmsAttributes.SigningTime)) + if (!std.ContainsKey(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)) + if (!std.ContainsKey(CmsAttributes.MessageDigest)) { byte[] messageDigest = (byte[])parameters[CmsAttributeTableParameter.Digest]; Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(CmsAttributes.MessageDigest, @@ -116,10 +96,9 @@ private void DoCreateStandardAttributeTable(IDictionary parameters, IDictionary * @param parameters source parameters * @return the populated attribute table */ - public virtual AttributeTable GetAttributes( - IDictionary parameters) + public virtual AttributeTable GetAttributes(IDictionary parameters) { - IDictionary table = createStandardAttributeTable(parameters); + var table = CreateStandardAttributeTable(parameters); return new AttributeTable(table); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/EnvelopedDataHelper.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/EnvelopedDataHelper.cs index f633d18..1aad162 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/EnvelopedDataHelper.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/EnvelopedDataHelper.cs @@ -1,49 +1,43 @@ #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.Oiw; -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.Digests; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms { internal class EnvelopedDataHelper { - private static readonly IDictionary BaseCipherNames = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private static readonly IDictionary MacAlgNames = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - //private static readonly IDictionary PrfDigests = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + //private static readonly IDictionary BaseCipherNames = + // new Dictionary(); + //private static readonly IDictionary MacAlgNames = + // new Dictionary(); + //private static readonly IDictionary PrfDigests = + // new Dictionary(); - static EnvelopedDataHelper() - { - //PrfDigests.Add(PkcsObjectIdentifiers.IdHmacWithSha1, "SHA-1"); - //PrfDigests.Add(PkcsObjectIdentifiers.IdHmacWithSha224, "SHA-224"); - //PrfDigests.Add(PkcsObjectIdentifiers.IdHmacWithSha256, "SHA-256"); - //PrfDigests.Add(PkcsObjectIdentifiers.IdHmacWithSha384, "SHA-384"); - //PrfDigests.Add(PkcsObjectIdentifiers.IdHmacWithSha512, "SHA-512"); + //static EnvelopedDataHelper() + //{ + // PrfDigests.Add(PkcsObjectIdentifiers.IdHmacWithSha1, "SHA-1"); + // PrfDigests.Add(PkcsObjectIdentifiers.IdHmacWithSha224, "SHA-224"); + // PrfDigests.Add(PkcsObjectIdentifiers.IdHmacWithSha256, "SHA-256"); + // PrfDigests.Add(PkcsObjectIdentifiers.IdHmacWithSha384, "SHA-384"); + // PrfDigests.Add(PkcsObjectIdentifiers.IdHmacWithSha512, "SHA-512"); - BaseCipherNames.Add(PkcsObjectIdentifiers.DesEde3Cbc, "DESEDE"); - BaseCipherNames.Add(NistObjectIdentifiers.IdAes128Cbc, "AES"); - BaseCipherNames.Add(NistObjectIdentifiers.IdAes192Cbc, "AES"); - BaseCipherNames.Add(NistObjectIdentifiers.IdAes256Cbc, "AES"); + // BaseCipherNames.Add(PkcsObjectIdentifiers.DesEde3Cbc, "DESEDE"); + // BaseCipherNames.Add(NistObjectIdentifiers.IdAes128Cbc, "AES"); + // BaseCipherNames.Add(NistObjectIdentifiers.IdAes192Cbc, "AES"); + // BaseCipherNames.Add(NistObjectIdentifiers.IdAes256Cbc, "AES"); - MacAlgNames.Add(PkcsObjectIdentifiers.DesEde3Cbc, "DESEDEMac"); - MacAlgNames.Add(NistObjectIdentifiers.IdAes128Cbc, "AESMac"); - MacAlgNames.Add(NistObjectIdentifiers.IdAes192Cbc, "AESMac"); - MacAlgNames.Add(NistObjectIdentifiers.IdAes256Cbc, "AESMac"); - MacAlgNames.Add(PkcsObjectIdentifiers.RC2Cbc, "RC2Mac"); - } + // MacAlgNames.Add(PkcsObjectIdentifiers.DesEde3Cbc, "DESEDEMac"); + // MacAlgNames.Add(NistObjectIdentifiers.IdAes128Cbc, "AESMac"); + // MacAlgNames.Add(NistObjectIdentifiers.IdAes192Cbc, "AESMac"); + // MacAlgNames.Add(NistObjectIdentifiers.IdAes256Cbc, "AESMac"); + // MacAlgNames.Add(PkcsObjectIdentifiers.RC2Cbc, "RC2Mac"); + //} //internal static IDigest GetPrf(AlgorithmIdentifier algID) //{ @@ -58,7 +52,7 @@ static EnvelopedDataHelper() // || NistObjectIdentifiers.IdAes192Cbc.Equals(algorithm) // || NistObjectIdentifiers.IdAes256Cbc.Equals(algorithm)) // { - // return new Rfc3211WrapEngine(new AesEngine()); + // return new Rfc3211WrapEngine(AesUtilities.CreateEngine()); // } // else if (PkcsObjectIdentifiers.DesEde3Cbc.Equals(algorithm)) // { @@ -84,7 +78,8 @@ public static object CreateContentCipher(bool forEncryption, ICipherParameters e return CipherFactory.CreateContentCipher(forEncryption, encKey, encryptionAlgID); } - public AlgorithmIdentifier GenerateEncryptionAlgID(DerObjectIdentifier encryptionOID, KeyParameter encKey, SecureRandom random) + public AlgorithmIdentifier GenerateEncryptionAlgID(DerObjectIdentifier encryptionOID, KeyParameter encKey, + SecureRandom random) { return AlgorithmIdentifierFactory.GenerateEncryptionAlgID(encryptionOID, encKey.GetKey().Length * 8, random); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/KEKRecipientInfoGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/KEKRecipientInfoGenerator.cs index 703f62f..baea3d4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/KEKRecipientInfoGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/KEKRecipientInfoGenerator.cs @@ -66,19 +66,19 @@ public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom ra private static AlgorithmIdentifier DetermineKeyEncAlg( string algorithm, KeyParameter key) { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(algorithm, "DES")) + if (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")) + else if (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")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(algorithm, "AES")) { int length = key.GetKey().Length * 8; DerObjectIdentifier wrapOid; @@ -102,12 +102,12 @@ private static AlgorithmIdentifier DetermineKeyEncAlg( return new AlgorithmIdentifier(wrapOid); // parameters absent } - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(algorithm, "SEED")) + else if (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")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(algorithm, "CAMELLIA")) { int length = key.GetKey().Length * 8; DerObjectIdentifier wrapOid; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/KeyAgreeRecipientInfoGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/KeyAgreeRecipientInfoGenerator.cs index 614ca5b..4879aae 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/KeyAgreeRecipientInfoGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/KeyAgreeRecipientInfoGenerator.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; @@ -13,7 +13,6 @@ 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 @@ -24,7 +23,7 @@ internal class KeyAgreeRecipientInfoGenerator : RecipientInfoGenerator private DerObjectIdentifier keyAgreementOID; private DerObjectIdentifier keyEncryptionOID; - private IList recipientCerts; + private IList recipientCerts; private AsymmetricCipherKeyPair senderKeyPair; internal KeyAgreeRecipientInfoGenerator() @@ -41,9 +40,9 @@ internal DerObjectIdentifier KeyEncryptionOID set { this.keyEncryptionOID = value; } } - internal ICollection RecipientCerts + internal IEnumerable RecipientCerts { - set { this.recipientCerts = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(value); } + set { this.recipientCerts = new List(value); } } internal AsymmetricCipherKeyPair SenderKeyPair diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/KeyAgreeRecipientInformation.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/KeyAgreeRecipientInformation.cs index b6106e4..8d8f5f5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/KeyAgreeRecipientInformation.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/KeyAgreeRecipientInformation.cs @@ -1,14 +1,13 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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; @@ -16,7 +15,6 @@ 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 { @@ -30,7 +28,7 @@ public class KeyAgreeRecipientInformation private KeyAgreeRecipientInfo info; private Asn1OctetString encryptedKey; - internal static void ReadRecipientInfo(IList infos, KeyAgreeRecipientInfo info, + internal static void ReadRecipientInfo(IList infos, KeyAgreeRecipientInfo info, CmsSecureReadable secureReadable) { try @@ -212,11 +210,9 @@ internal KeyParameter GetSessionKey( public override CmsTypedStream GetContentStream( ICipherParameters key) { - if (!(key is AsymmetricKeyParameter)) + if (!(key is AsymmetricKeyParameter receiverPrivateKey)) throw new ArgumentException("KeyAgreement requires asymmetric key", "key"); - AsymmetricKeyParameter receiverPrivateKey = (AsymmetricKeyParameter) key; - if (!receiverPrivateKey.IsPrivate) throw new ArgumentException("Expected private key", "key"); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/KeyTransRecipientInfoGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/KeyTransRecipientInfoGenerator.cs index e2f697f..fff2b92 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/KeyTransRecipientInfoGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/KeyTransRecipientInfoGenerator.cs @@ -1,7 +1,6 @@ #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; @@ -13,52 +12,45 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms { - public class KeyTransRecipientInfoGenerator : RecipientInfoGenerator + public class KeyTransRecipientInfoGenerator + : RecipientInfoGenerator { - private static readonly CmsEnvelopedHelper Helper = CmsEnvelopedHelper.Instance; + private readonly IKeyWrapper m_keyWrapper; - private Asn1OctetString subjectKeyIdentifier; - private IKeyWrapper keyWrapper; - - // Derived fields - private SubjectPublicKeyInfo info; - private IssuerAndSerialNumber issuerAndSerialNumber; - private SecureRandom random; - + private IssuerAndSerialNumber m_issuerAndSerialNumber; + private Asn1OctetString m_subjectKeyIdentifier; public KeyTransRecipientInfoGenerator(X509Certificate recipCert, IKeyWrapper keyWrapper) - : this(new Asn1.Cms.IssuerAndSerialNumber(recipCert.IssuerDN, new DerInteger(recipCert.SerialNumber)), keyWrapper) + : this(new IssuerAndSerialNumber(recipCert.IssuerDN, new DerInteger(recipCert.SerialNumber)), keyWrapper) { } public KeyTransRecipientInfoGenerator(IssuerAndSerialNumber issuerAndSerial, IKeyWrapper keyWrapper) { - this.issuerAndSerialNumber = issuerAndSerial; - this.keyWrapper = keyWrapper; + m_issuerAndSerialNumber = issuerAndSerial; + m_keyWrapper = keyWrapper; } public KeyTransRecipientInfoGenerator(byte[] subjectKeyID, IKeyWrapper keyWrapper) { - this.subjectKeyIdentifier = new DerOctetString(subjectKeyIdentifier); - this.keyWrapper = keyWrapper; + m_subjectKeyIdentifier = new DerOctetString(subjectKeyID); + m_keyWrapper = keyWrapper; } public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random) { - AlgorithmIdentifier keyEncryptionAlgorithm = this.AlgorithmDetails; - - this.random = random; + AlgorithmIdentifier keyEncryptionAlgorithm = AlgorithmDetails; byte[] encryptedKeyBytes = GenerateWrappedKey(contentEncryptionKey); RecipientIdentifier recipId; - if (issuerAndSerialNumber != null) + if (m_issuerAndSerialNumber != null) { - recipId = new RecipientIdentifier(issuerAndSerialNumber); + recipId = new RecipientIdentifier(m_issuerAndSerialNumber); } else { - recipId = new RecipientIdentifier(subjectKeyIdentifier); + recipId = new RecipientIdentifier(m_subjectKeyIdentifier); } return new RecipientInfo(new KeyTransRecipientInfo(recipId, keyEncryptionAlgorithm, @@ -67,19 +59,12 @@ public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom ra protected virtual AlgorithmIdentifier AlgorithmDetails { - get - { - if (this.keyWrapper != null) - { - return (AlgorithmIdentifier)keyWrapper.AlgorithmDetails; - } - return info.AlgorithmID; - } + get { return (AlgorithmIdentifier)m_keyWrapper.AlgorithmDetails; } } protected virtual byte[] GenerateWrappedKey(KeyParameter contentEncryptionKey) { - return keyWrapper.Wrap(contentEncryptionKey.GetKey()).Collect(); + return m_keyWrapper.Wrap(contentEncryptionKey.GetKey()).Collect(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/OriginatorId.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/OriginatorId.cs index ff3f0b0..5ab836c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/OriginatorId.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/OriginatorId.cs @@ -46,7 +46,7 @@ public override bool Equals( return false; return Arrays.AreEqual(SubjectKeyIdentifier, id.SubjectKeyIdentifier) - && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(SerialNumber, id.SerialNumber) + && Org.BouncyCastle.Utilities.Platform.Equals(SerialNumber, id.SerialNumber) && IssuersMatch(Issuer, id.Issuer); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/OriginatorInfoGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/OriginatorInfoGenerator.cs index 6fcd715..72fee2e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/OriginatorInfoGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/OriginatorInfoGenerator.cs @@ -1,42 +1,73 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms; -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 OriginatorInfoGenerator { - private readonly IList origCerts; - private readonly IList origCrls; + private readonly List origCerts; + private readonly List origCrls; public OriginatorInfoGenerator(X509Certificate origCert) { - this.origCerts = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(1); + this.origCerts = new List{ origCert.CertificateStructure }; this.origCrls = null; - origCerts.Add(origCert.CertificateStructure); } - public OriginatorInfoGenerator(IX509Store origCerts) - : this(origCerts, null) + public OriginatorInfoGenerator(IStore x509Certs) + : this(x509Certs, null, null, null) { } - public OriginatorInfoGenerator(IX509Store origCerts, IX509Store origCrls) + public OriginatorInfoGenerator(IStore x509Certs, IStore x509Crls) + : this(x509Certs, x509Crls, null, null) { - this.origCerts = CmsUtilities.GetCertificatesFromStore(origCerts); - this.origCrls = origCrls == null ? null : CmsUtilities.GetCrlsFromStore(origCrls); + } + + public OriginatorInfoGenerator(IStore x509Certs, IStore x509Crls, + IStore x509AttrCerts, IStore otherRevocationInfos) + { + List certificates = null; + if (x509Certs != null || x509AttrCerts != null) + { + certificates = new List(); + if (x509Certs != null) + { + certificates.AddRange(CmsUtilities.GetCertificatesFromStore(x509Certs)); + } + if (x509AttrCerts != null) + { + certificates.AddRange(CmsUtilities.GetAttributeCertificatesFromStore(x509AttrCerts)); + } + } + + List revocations = null; + if (x509Crls != null || otherRevocationInfos != null) + { + revocations = new List(); + if (x509Crls != null) + { + revocations.AddRange(CmsUtilities.GetCrlsFromStore(x509Crls)); + } + if (otherRevocationInfos != null) + { + revocations.AddRange(CmsUtilities.GetOtherRevocationInfosFromStore(otherRevocationInfos)); + } + } + + this.origCerts = certificates; + this.origCrls = revocations; } public virtual OriginatorInfo Generate() { - Asn1Set certSet = CmsUtilities.CreateDerSetFromList(origCerts); + Asn1Set certSet = origCerts == null ? null : CmsUtilities.CreateDerSetFromList(origCerts); Asn1Set crlSet = origCrls == null ? null : CmsUtilities.CreateDerSetFromList(origCrls); return new OriginatorInfo(certSet, crlSet); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/OriginatorInformation.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/OriginatorInformation.cs index d122b6e..16b7fd1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/OriginatorInformation.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/OriginatorInformation.cs @@ -1,14 +1,10 @@ #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.Utilities.Collections; using BestHTTP.SecureProtocol.Org.BouncyCastle.X509; -using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms { @@ -26,31 +22,9 @@ internal OriginatorInformation(OriginatorInfo originatorInfo) * * @return a Store of X509CertificateHolder objects. */ - public virtual IX509Store GetCertificates() + public virtual IStore 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 CmsSignedHelper.Instance.GetCertificates(originatorInfo.Certificates); } /** @@ -58,31 +32,9 @@ public virtual IX509Store GetCertificates() * * @return a Store of X509CRLHolder objects. */ - public virtual IX509Store GetCrls() + public virtual IStore 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 CmsSignedHelper.Instance.GetCrls(originatorInfo.Crls); } /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/PKCS5Scheme2PBEKey.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/PKCS5Scheme2PBEKey.cs index 12aacd8..c32250a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/PKCS5Scheme2PBEKey.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/PKCS5Scheme2PBEKey.cs @@ -16,23 +16,6 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms public class Pkcs5Scheme2PbeKey : CmsPbeKey { - - public Pkcs5Scheme2PbeKey( - string password, - byte[] salt, - int iterationCount) - : this(password.ToCharArray(), salt, iterationCount) - { - } - - - public Pkcs5Scheme2PbeKey( - string password, - AlgorithmIdentifier keyDerivationAlgorithm) - : this(password.ToCharArray(), keyDerivationAlgorithm) - { - } - public Pkcs5Scheme2PbeKey( char[] password, byte[] salt, diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/PKCS5Scheme2UTF8PBEKey.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/PKCS5Scheme2UTF8PBEKey.cs index bf5aae0..d6de0cd 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/PKCS5Scheme2UTF8PBEKey.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/PKCS5Scheme2UTF8PBEKey.cs @@ -16,23 +16,6 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Cms public class Pkcs5Scheme2Utf8PbeKey : CmsPbeKey { - - public Pkcs5Scheme2Utf8PbeKey( - string password, - byte[] salt, - int iterationCount) - : this(password.ToCharArray(), salt, iterationCount) - { - } - - - public Pkcs5Scheme2Utf8PbeKey( - string password, - AlgorithmIdentifier keyDerivationAlgorithm) - : this(password.ToCharArray(), keyDerivationAlgorithm) - { - } - public Pkcs5Scheme2Utf8PbeKey( char[] password, byte[] salt, diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/PasswordRecipientInfoGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/PasswordRecipientInfoGenerator.cs index 5f5dcb7..6efa8c7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/PasswordRecipientInfoGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/PasswordRecipientInfoGenerator.cs @@ -49,7 +49,7 @@ public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom ra 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; + int ivLength = Org.BouncyCastle.Utilities.Platform.StartsWith(rfc3211WrapperName, "DESEDE") ? 8 : 16; byte[] iv = new byte[ivLength]; random.NextBytes(iv); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/RecipientId.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/RecipientId.cs index 7a1a950..35413ea 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/RecipientId.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/RecipientId.cs @@ -53,7 +53,7 @@ public override bool Equals( return Arrays.AreEqual(keyIdentifier, id.keyIdentifier) && Arrays.AreEqual(SubjectKeyIdentifier, id.SubjectKeyIdentifier) - && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(SerialNumber, id.SerialNumber) + && Org.BouncyCastle.Utilities.Platform.Equals(SerialNumber, id.SerialNumber) && IssuersMatch(Issuer, id.Issuer); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/RecipientInformation.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/RecipientInformation.cs index af116d4..de92035 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/RecipientInformation.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/RecipientInformation.cs @@ -114,15 +114,15 @@ public byte[] GetMac() if (resultMac == null) { object cryptoObject = secureReadable.CryptoObject; - if (cryptoObject is IMac) + if (cryptoObject is IMac mac) { - resultMac = MacUtilities.DoFinal((IMac)cryptoObject); + resultMac = MacUtilities.DoFinal(mac); } } return Arrays.Clone(resultMac); } - + public abstract CmsTypedStream GetContentStream(ICipherParameters key); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/RecipientInformationStore.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/RecipientInformationStore.cs index e067b7c..89b777a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/RecipientInformationStore.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/RecipientInformationStore.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -9,26 +9,25 @@ 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]] + private readonly IList m_all; + private readonly IDictionary> m_table = + new Dictionary>(); - public RecipientInformationStore( - ICollection recipientInfos) + public RecipientInformationStore(IEnumerable 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); + if (!m_table.TryGetValue(rid, out var list)) + { + m_table[rid] = list = new List(1); } list.Add(recipientInformation); } - this.all = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(recipientInfos); + this.m_all = new List(recipientInfos); } public RecipientInformation this[RecipientID selector] @@ -43,12 +42,12 @@ public RecipientInformation this[RecipientID selector] * @param selector to identify a recipient * @return a single RecipientInformation object. Null if none matches. */ - public RecipientInformation GetFirstRecipient( - RecipientID selector) + public RecipientInformation GetFirstRecipient(RecipientID selector) { - IList list = (IList) table[selector]; + if (!m_table.TryGetValue(selector, out var list)) + return null; - return list == null ? null : (RecipientInformation) list[0]; + return list[0]; } /** @@ -58,7 +57,7 @@ public RecipientInformation GetFirstRecipient( */ public int Count { - get { return all.Count; } + get { return m_all.Count; } } /** @@ -66,9 +65,9 @@ public int Count * * @return a collection of recipients. */ - public ICollection GetRecipients() + public IList GetRecipients() { - return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(all); + return new List(m_all); } /** @@ -77,12 +76,12 @@ public ICollection GetRecipients() * @param selector a recipient id to select against. * @return a collection of RecipientInformation objects. */ - public ICollection GetRecipients( - RecipientID selector) + public IList GetRecipients(RecipientID selector) { - IList list = (IList)table[selector]; + if (!m_table.TryGetValue(selector, out var list)) + return new List(0); - return list == null ? BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList() : BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(list); + return new List(list); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/SignerId.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/SignerId.cs index f707a24..d58f685 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/SignerId.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/SignerId.cs @@ -46,7 +46,7 @@ public override bool Equals( return false; return Arrays.AreEqual(SubjectKeyIdentifier, id.SubjectKeyIdentifier) - && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(SerialNumber, id.SerialNumber) + && Org.BouncyCastle.Utilities.Platform.Equals(SerialNumber, id.SerialNumber) && IssuersMatch(Issuer, id.Issuer); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/SignerInformation.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/SignerInformation.cs index 83e244e..c8b9f7a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/SignerInformation.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/SignerInformation.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; @@ -258,10 +258,10 @@ public SignerInformationStore GetCounterSignatures() Asn1.Cms.AttributeTable unsignedAttributeTable = UnsignedAttributes; if (unsignedAttributeTable == null) { - return new SignerInformationStore(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(0)); + return new SignerInformationStore(new List(0)); } - IList counterSignatures = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var counterSignatures = new List(); /* The UnsignedAttributes syntax is defined as a SET OF Attributes. The @@ -435,11 +435,9 @@ private bool DoVerify( if (isCounterSignature) throw new CmsException("[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute"); - if (!(validContentType is DerObjectIdentifier)) + if (!(validContentType is DerObjectIdentifier signedContentType)) 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"); } @@ -456,12 +454,8 @@ private bool DoVerify( } else { - if (!(validMessageDigest is Asn1OctetString)) - { + if (!(validMessageDigest is Asn1OctetString signedMessageDigest)) 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"); @@ -659,7 +653,7 @@ public bool Verify( Asn1.Cms.Time signingTime = GetSigningTime(); if (signingTime != null) { - cert.CheckValidity(signingTime.Date); + cert.CheckValidity(signingTime.ToDateTime()); } return DoVerify(cert.GetPublicKey()); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/SignerInformationStore.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/SignerInformationStore.cs index 6e45fb6..ca8871b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/SignerInformationStore.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/SignerInformationStore.cs @@ -1,32 +1,29 @@ #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; +using System.Collections.Generic; 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]] + private readonly IList all; + private readonly IDictionary> m_table = + new Dictionary>(); /** * Create a store containing a single SignerInformation object. * * @param signerInfo the signer information to contain. */ - public SignerInformationStore( - SignerInformation signerInfo) + public SignerInformationStore(SignerInformation signerInfo) { - this.all = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(1); + this.all = new List(1); this.all.Add(signerInfo); SignerID sid = signerInfo.SignerID; - table[sid] = all; + m_table[sid] = all; } /** @@ -34,23 +31,21 @@ public SignerInformationStore( * * @param signerInfos a collection signer information objects to contain. */ - public SignerInformationStore( - ICollection signerInfos) + public SignerInformationStore(IEnumerable signerInfos) { foreach (SignerInformation signer in signerInfos) { SignerID sid = signer.SignerID; - IList list = (IList)table[sid]; - if (list == null) + if (!m_table.TryGetValue(sid, out var list)) { - table[sid] = list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(1); + m_table[sid] = list = new List(1); } list.Add(signer); } - this.all = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(signerInfos); + this.all = new List(signerInfos); } /** @@ -60,12 +55,12 @@ public SignerInformationStore( * @param selector to identify a signer * @return a single SignerInformation object. Null if none matches. */ - public SignerInformation GetFirstSigner( - SignerID selector) + public SignerInformation GetFirstSigner(SignerID selector) { - IList list = (IList) table[selector]; + if (m_table.TryGetValue(selector, out var list)) + return list[0]; - return list == null ? null : (SignerInformation) list[0]; + return null; } /// The number of signers in the collection. @@ -75,9 +70,9 @@ public int Count } /// An ICollection of all signers in the collection - public ICollection GetSigners() + public IList GetSigners() { - return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(all); + return new List(all); } /** @@ -86,12 +81,12 @@ public ICollection GetSigners() * @param selector a signer id to select against. * @return a collection of SignerInformation objects. */ - public ICollection GetSigners( - SignerID selector) + public IList GetSigners(SignerID selector) { - IList list = (IList) table[selector]; + if (m_table.TryGetValue(selector, out var list)) + return new List(list); - return list == null ? BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList() : BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(list); + return new List(0); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/SimpleAttributeTableGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/SimpleAttributeTableGenerator.cs index 8d846ac..b5260cb 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/cms/SimpleAttributeTableGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/cms/SimpleAttributeTableGenerator.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Cms; @@ -21,8 +21,7 @@ public SimpleAttributeTableGenerator( this.attributes = attributes; } - public virtual AttributeTable GetAttributes( - IDictionary parameters) + public virtual AttributeTable GetAttributes(IDictionary parameters) { return attributes; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/CertificateRequestMessage.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/CertificateRequestMessage.cs index a10935c..8d953dd 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/CertificateRequestMessage.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/CertificateRequestMessage.cs @@ -192,7 +192,7 @@ public bool IsValidSigningKeyPop(IVerifierFactoryProvider verifierProvider) private bool verifySignature(IVerifierFactoryProvider verifierFactoryProvider, PopoSigningKey signKey) { IVerifierFactory verifer; - IStreamCalculator calculator; + IStreamCalculator calculator; try { verifer = verifierFactoryProvider.CreateVerifierFactory(signKey.AlgorithmIdentifier); @@ -214,7 +214,7 @@ private bool verifySignature(IVerifierFactoryProvider verifierFactoryProvider, P calculator.Stream.Write(b, 0, b.Length); } - DefaultVerifierResult result = (DefaultVerifierResult)calculator.GetResult(); + IVerifier result = calculator.GetResult(); return result.IsVerified(signKey.Signature.GetBytes()); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/CertificateRequestMessageBuilder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/CertificateRequestMessageBuilder.cs index fc08937..b9392c8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/CertificateRequestMessageBuilder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/CertificateRequestMessageBuilder.cs @@ -1,15 +1,13 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Crmf; 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.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crmf { @@ -18,7 +16,7 @@ public class CertificateRequestMessageBuilder private readonly BigInteger _certReqId; private X509ExtensionsGenerator _extGenerator; private CertTemplateBuilder _templateBuilder; - private IList _controls = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + private IList m_controls = new List(); private ISignatureFactory _popSigner; private PKMacBuilder _pkMacBuilder; private char[] _password; @@ -75,9 +73,9 @@ public CertificateRequestMessageBuilder SetSerialNumber(BigInteger serialNumber) return this; } - public CertificateRequestMessageBuilder SetValidity(Time notBefore, Time notAfter) + public CertificateRequestMessageBuilder SetValidity(DateTime? notBefore, DateTime? notAfter) { - _templateBuilder.SetValidity(new OptionalValidity(notBefore, notAfter)); + _templateBuilder.SetValidity(new OptionalValidity(CreateTime(notBefore), CreateTime(notAfter))); return this; } @@ -97,7 +95,7 @@ public CertificateRequestMessageBuilder AddExtension(DerObjectIdentifier oid, bo public CertificateRequestMessageBuilder AddControl(IControl control) { - _controls.Add(control); + m_controls.Add(control); return this; } @@ -197,13 +195,12 @@ public CertificateRequestMessage Build() v.Add(_templateBuilder.Build()); - if (_controls.Count > 0) + if (m_controls.Count > 0) { Asn1EncodableVector controlV = new Asn1EncodableVector(); - foreach (object item in _controls) + foreach (var control in m_controls) { - IControl control = (IControl)item; controlV.Add(new AttributeTypeAndValue(control.Type, control.Value)); } @@ -261,6 +258,11 @@ public CertificateRequestMessage Build() return new CertificateRequestMessage(CertReqMsg.GetInstance(new DerSequence(v))); } + + private static Time CreateTime(DateTime? dateTime) + { + return dateTime == null ? null : new Time(dateTime.Value); + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/CrmfException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/CrmfException.cs index be252ed..3ee792a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/CrmfException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/CrmfException.cs @@ -1,26 +1,34 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crmf { - public class CrmfException + [Serializable] + public class CrmfException : Exception { - public CrmfException() - { - } + public CrmfException() + : base() + { + } - public CrmfException(string message) - : base(message) - { - } + public CrmfException(string message) + : base(message) + { + } - public CrmfException(string message, Exception innerException) - : base(message, innerException) - { - } - } + public CrmfException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected CrmfException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/EncryptedValueBuilder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/EncryptedValueBuilder.cs index 25a6efb..f1c70ac 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/EncryptedValueBuilder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/EncryptedValueBuilder.cs @@ -1,17 +1,13 @@ #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.Crmf; -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.Engines; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; using BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -118,12 +114,14 @@ public EncryptedValue Build(PrivateKeyInfo privateKeyInfo) private EncryptedValue EncryptData(byte[] data) { MemoryOutputStream bOut = new MemoryOutputStream(); - Stream eOut = encryptor.BuildCipher(bOut).Stream; + var cipher = encryptor.BuildCipher(bOut); try { - eOut.Write(data, 0, data.Length); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(eOut); + using (var eOut = cipher.Stream) + { + eOut.Write(data, 0, data.Length); + } } catch (IOException e) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/PKMacBuilder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/PKMacBuilder.cs index 08af959..f9b29ec 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/PKMacBuilder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/PKMacBuilder.cs @@ -17,7 +17,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crmf { internal class PKMacStreamCalculator - : IStreamCalculator + : IStreamCalculator { private readonly MacSink _stream; @@ -31,7 +31,7 @@ public Stream Stream get { return _stream; } } - public object GetResult() + public DefaultPKMacResult GetResult() { return new DefaultPKMacResult(_stream.Mac); } @@ -54,7 +54,7 @@ public virtual object AlgorithmDetails get { return new AlgorithmIdentifier(CmpObjectIdentifiers.passwordBasedMac, parameters); } } - public virtual IStreamCalculator CreateCalculator() + public virtual IStreamCalculator CreateCalculator() { IMac mac = MacUtilities.GetMac(parameters.Mac.Algorithm); mac.Init(new KeyParameter(key)); @@ -85,6 +85,15 @@ public int Collect(byte[] sig, int sigOff) signature.CopyTo(sig, sigOff); return signature.Length; } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int Collect(Span destination) + { + byte[] result = Collect(); + result.CopyTo(destination); + return result.Length; + } +#endif } public class PKMacBuilder @@ -217,10 +226,7 @@ public IMacFactory Build(char[] password) byte[] salt = new byte[saltLength]; - if (random == null) - { - this.random = new SecureRandom(); - } + this.random = CryptoServicesRegistrar.GetSecureRandom(random); random.NextBytes(salt); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/ProofOfPossessionSigningKeyBuilder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/ProofOfPossessionSigningKeyBuilder.cs index 8ced2b6..79e3808 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/ProofOfPossessionSigningKeyBuilder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crmf/ProofOfPossessionSigningKeyBuilder.cs @@ -1,6 +1,7 @@ #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.Crmf; @@ -39,15 +40,17 @@ public ProofOfPossessionSigningKeyBuilder SetPublicKeyMac(PKMacBuilder generator { IMacFactory fact = generator.Build(password); - IStreamCalculator calc = fact.CreateCalculator(); byte[] d = _pubKeyInfo.GetDerEncoded(); - calc.Stream.Write(d, 0, d.Length); - calc.Stream.Flush(); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(calc.Stream); + + IStreamCalculator calc = fact.CreateCalculator(); + using (var stream = calc.Stream) + { + stream.Write(d, 0, d.Length); + } this._publicKeyMAC = new PKMacValue( (AlgorithmIdentifier)fact.AlgorithmDetails, - new DerBitString(((IBlockResult)calc.GetResult()).Collect())); + new DerBitString(calc.GetResult().Collect())); return this; } @@ -60,32 +63,30 @@ public PopoSigningKey Build(ISignatureFactory signer) } PopoSigningKeyInput popo; - byte[] b; - IStreamCalculator calc = signer.CreateCalculator(); - if (_certRequest != null) - { - popo = null; - b = _certRequest.GetDerEncoded(); - calc.Stream.Write(b, 0, b.Length); - } - else if (_name != null) - { - popo = new PopoSigningKeyInput(_name, _pubKeyInfo); - b = popo.GetDerEncoded(); - calc.Stream.Write(b, 0, b.Length); - } - else + IStreamCalculator calc = signer.CreateCalculator(); + using (Stream sigStream = calc.Stream) { - popo = new PopoSigningKeyInput(_publicKeyMAC, _pubKeyInfo); - b = popo.GetDerEncoded(); - calc.Stream.Write(b, 0, b.Length); + if (_certRequest != null) + { + popo = null; + _certRequest.EncodeTo(sigStream, Asn1Encodable.Der); + } + else if (_name != null) + { + popo = new PopoSigningKeyInput(_name, _pubKeyInfo); + popo.EncodeTo(sigStream, Asn1Encodable.Der); + } + else + { + popo = new PopoSigningKeyInput(_publicKeyMAC, _pubKeyInfo); + popo.EncodeTo(sigStream, Asn1Encodable.Der); + } } - calc.Stream.Flush(); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(calc.Stream); - DefaultSignatureResult res = (DefaultSignatureResult)calc.GetResult(); - return new PopoSigningKey(popo, (AlgorithmIdentifier)signer.AlgorithmDetails, new DerBitString(res.Collect())); + var signature = calc.GetResult().Collect(); + + return new PopoSigningKey(popo, (AlgorithmIdentifier)signer.AlgorithmDetails, new DerBitString(signature)); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/AesUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/AesUtilities.cs new file mode 100644 index 0000000..3f34dd2 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/AesUtilities.cs @@ -0,0 +1,27 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto +{ + public static class AesUtilities + { + public static IBlockCipher CreateEngine() + { +#if NETCOREAPP3_0_OR_GREATER + if (AesEngine_X86.IsSupported) + return new AesEngine_X86(); +#endif + + return new AesEngine(); + } + +#if NETCOREAPP3_0_OR_GREATER + public static bool IsHardwareAccelerated => AesEngine_X86.IsSupported; +#else + public static bool IsHardwareAccelerated => false; +#endif + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/AesUtilities.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/AesUtilities.cs.meta new file mode 100644 index 0000000..83a9b14 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/AesUtilities.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4f78dabbad81b1942bbfcb6d20af6264 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedAeadBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedAeadBlockCipher.cs index 8488bae..423bea6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedAeadBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedAeadBlockCipher.cs @@ -99,12 +99,9 @@ public override int GetOutputSize( * @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 int ProcessByte(byte input, byte[] output, int outOff) + { + return cipher.ProcessByte(input, output, outOff); } public override byte[] ProcessByte( @@ -126,7 +123,14 @@ public override byte[] ProcessByte( return outBytes; } - public override byte[] ProcessBytes( +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int ProcessByte(byte input, Span output) + { + return cipher.ProcessByte(input, output); + } +#endif + + public override byte[] ProcessBytes( byte[] input, int inOff, int length) @@ -174,7 +178,14 @@ public override int ProcessBytes( return cipher.ProcessBytes(input, inOff, length, output, outOff); } - public override byte[] DoFinal() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int ProcessBytes(ReadOnlySpan input, Span output) + { + return cipher.ProcessBytes(input, output); + } +#endif + + public override byte[] DoFinal() { byte[] outBytes = new byte[GetOutputSize(0)]; @@ -237,11 +248,25 @@ public override int DoFinal( return cipher.DoFinal(output, outOff); } - /** +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + return cipher.DoFinal(output); + } + + public override int DoFinal(ReadOnlySpan input, Span output) + { + int len = cipher.ProcessBytes(input, output); + len += cipher.DoFinal(output[len..]); + return len; + } +#endif + + /** * 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() + public override void Reset() { cipher.Reset(); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedAeadCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedAeadCipher.cs index 74d2500..dd40195 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedAeadCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedAeadCipher.cs @@ -98,10 +98,7 @@ public override int GetOutputSize( * @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) + public override int ProcessByte(byte input, byte[] output, int outOff) { return cipher.ProcessByte(input, output, outOff); } @@ -125,6 +122,13 @@ public override byte[] ProcessByte( return outBytes; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int ProcessByte(byte input, Span output) + { + return cipher.ProcessByte(input, output); + } +#endif + public override byte[] ProcessBytes( byte[] input, int inOff, @@ -173,6 +177,13 @@ public override int ProcessBytes( return cipher.ProcessBytes(input, inOff, length, output, outOff); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int ProcessBytes(ReadOnlySpan input, Span output) + { + return cipher.ProcessBytes(input, output); + } +#endif + public override byte[] DoFinal() { byte[] outBytes = new byte[GetOutputSize(0)]; @@ -236,6 +247,20 @@ public override int DoFinal( return cipher.DoFinal(output, outOff); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + return cipher.DoFinal(output); + } + + public override int DoFinal(ReadOnlySpan input, Span output) + { + int len = cipher.ProcessBytes(input, output); + len += cipher.DoFinal(output[len..]); + return len; + } +#endif + /** * 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). diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedAsymmetricBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedAsymmetricBlockCipher.cs index 1ea3886..ea5f328 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedAsymmetricBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedAsymmetricBlockCipher.cs @@ -1,9 +1,6 @@ #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 { @@ -89,13 +86,33 @@ public override byte[] ProcessByte( byte input) { if (bufOff >= buffer.Length) - throw new DataLengthException("attempt to process message to long for cipher"); + throw new DataLengthException("attempt to process message too long for cipher"); buffer[bufOff++] = input; return null; } - public override byte[] ProcessBytes( + public override int ProcessByte(byte input, byte[] output, int outOff) + { + if (bufOff >= buffer.Length) + throw new DataLengthException("attempt to process message too long for cipher"); + + buffer[bufOff++] = input; + return 0; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int ProcessByte(byte input, Span output) + { + if (bufOff >= buffer.Length) + throw new DataLengthException("attempt to process message too long for cipher"); + + buffer[bufOff++] = input; + return 0; + } +#endif + + public override byte[] ProcessBytes( byte[] input, int inOff, int length) @@ -106,14 +123,25 @@ public override byte[] ProcessBytes( if (input == null) throw new ArgumentNullException("input"); if (bufOff + length > buffer.Length) - throw new DataLengthException("attempt to process message to long for cipher"); + throw new DataLengthException("attempt to process message too long for cipher"); Array.Copy(input, inOff, buffer, bufOff, length); bufOff += length; return null; } - /** +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int ProcessBytes(ReadOnlySpan input, Span output) + { + Check.DataLength(input, buffer.Length - bufOff, "attempt to process message too long for cipher"); + + input.CopyTo(buffer.AsSpan(bufOff)); + bufOff += input.Length; + return 0; + } +#endif + + /** * process the contents of the buffer using the underlying * cipher. * @@ -141,7 +169,24 @@ public override byte[] DoFinal( return DoFinal(); } - /// Reset the buffer +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + int result = 0; + if (bufOff > 0) + { + byte[] outBytes = cipher.ProcessBlock(buffer, 0, bufOff); + outBytes.CopyTo(output); + result = outBytes.Length; + } + + Reset(); + + return result; + } +#endif + + /// Reset the buffer public override void Reset() { if (buffer != null) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedBlockCipher.cs index fcf48d2..ea3e388 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedBlockCipher.cs @@ -1,8 +1,8 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Diagnostics; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto @@ -19,10 +19,10 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto public class BufferedBlockCipher : BufferedCipherBase { - internal byte[] buf; - internal int bufOff; - internal bool forEncryption; - internal IBlockCipher cipher; + internal byte[] buf; + internal int bufOff; + internal bool forEncryption; + internal IBlockCipherMode m_cipherMode; /** * constructor for subclasses @@ -31,26 +31,30 @@ protected BufferedBlockCipher() { } - /** + public BufferedBlockCipher(IBlockCipher cipher) + : this(EcbBlockCipher.GetBlockCipherMode(cipher)) + { + } + + /** * Create a buffered block cipher without padding. * * @param cipher the underlying block cipher this buffering object wraps. * false otherwise. */ - public BufferedBlockCipher( - IBlockCipher cipher) + public BufferedBlockCipher(IBlockCipherMode cipherMode) { - if (cipher == null) - throw new ArgumentNullException("cipher"); + if (cipherMode == null) + throw new ArgumentNullException(nameof(cipherMode)); - this.cipher = cipher; - buf = new byte[cipher.GetBlockSize()]; + m_cipherMode = cipherMode; + buf = new byte[cipherMode.GetBlockSize()]; bufOff = 0; } public override string AlgorithmName { - get { return cipher.AlgorithmName; } + get { return m_cipherMode.AlgorithmName; } } /** @@ -63,19 +67,18 @@ public override string AlgorithmName * 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) + public override void Init(bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; - ParametersWithRandom pwr = parameters as ParametersWithRandom; - if (pwr != null) - parameters = pwr.Parameters; + if (parameters is ParametersWithRandom withRandom) + { + parameters = withRandom.Parameters; + } Reset(); - cipher.Init(forEncryption, parameters); + m_cipherMode.Init(forEncryption, parameters); } /** @@ -85,7 +88,7 @@ public override void Init( */ public override int GetBlockSize() { - return cipher.GetBlockSize(); + return m_cipherMode.GetBlockSize(); } /** @@ -96,8 +99,7 @@ public override int GetBlockSize() * @return the space required to accommodate a call to update * with len bytes of input. */ - public override int GetUpdateOutputSize( - int length) + public override int GetUpdateOutputSize(int length) { int total = length + bufOff; int leftOver = total % buf.Length; @@ -112,8 +114,7 @@ public override int GetUpdateOutputSize( * @return the space required to accommodate a call to update and doFinal * with len bytes of input. */ - public override int GetOutputSize( - int length) + public override int GetOutputSize(int length) { // Note: Can assume IsPartialBlockOkay is true for purposes of this calculation return length + bufOff; @@ -129,10 +130,7 @@ public override int GetOutputSize( * @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) + public override int ProcessByte(byte input, byte[] output, int outOff) { buf[bufOff++] = input; @@ -142,14 +140,13 @@ public override int ProcessByte( throw new DataLengthException("output buffer too short"); bufOff = 0; - return cipher.ProcessBlock(buf, 0, output, outOff); + return m_cipherMode.ProcessBlock(buf, 0, output, outOff); } return 0; } - public override byte[] ProcessByte( - byte input) + public override byte[] ProcessByte(byte input) { int outLength = GetUpdateOutputSize(1); @@ -167,13 +164,27 @@ public override byte[] ProcessByte( return outBytes; } - public override byte[] ProcessBytes( - byte[] input, - int inOff, - int length) - { - if (input == null) - throw new ArgumentNullException("input"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int ProcessByte(byte input, Span output) + { + buf[bufOff++] = input; + + if (bufOff == buf.Length) + { + Check.OutputLength(output, buf.Length, "output buffer too short"); + + bufOff = 0; + return m_cipherMode.ProcessBlock(buf, output); + } + + return 0; + } +#endif + + public override byte[] ProcessBytes(byte[] input, int inOff, int length) + { + if (input == null) + throw new ArgumentNullException(nameof(input)); if (length < 1) return null; @@ -193,7 +204,7 @@ public override byte[] ProcessBytes( return outBytes; } - /** + /** * process an array of bytes, producing output if necessary. * * @param in the input byte array. @@ -205,14 +216,9 @@ public override byte[] ProcessBytes( * @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) + 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!"); @@ -230,31 +236,60 @@ public override int ProcessBytes( int resultLen = 0; int gapLen = buf.Length - bufOff; - if (length > gapLen) + if (length >= gapLen) { Array.Copy(input, inOff, buf, bufOff, gapLen); - resultLen += cipher.ProcessBlock(buf, 0, output, outOff); + resultLen = m_cipherMode.ProcessBlock(buf, 0, output, outOff); bufOff = 0; length -= gapLen; inOff += gapLen; - while (length > buf.Length) + while (length >= buf.Length) { - resultLen += cipher.ProcessBlock(input, inOff, output, outOff + resultLen); + resultLen += m_cipherMode.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() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int ProcessBytes(ReadOnlySpan input, Span output) + { + if (input.IsEmpty) + return 0; + + int blockSize = GetBlockSize(); + int outLength = GetUpdateOutputSize(input.Length); + + if (outLength > 0) + { + Check.OutputLength(output, outLength, "output buffer too short"); + } + + int resultLen = 0; + int gapLen = buf.Length - bufOff; + if (input.Length >= gapLen) + { + input[..gapLen].CopyTo(buf.AsSpan(bufOff)); + resultLen = m_cipherMode.ProcessBlock(buf, output); + bufOff = 0; + input = input[gapLen..]; + while (input.Length >= buf.Length) + { + resultLen += m_cipherMode.ProcessBlock(input, output[resultLen..]); + input = input[blockSize..]; + } + } + input.CopyTo(buf.AsSpan(bufOff)); + bufOff += input.Length; + return resultLen; + } +#endif + + public override byte[] DoFinal() { byte[] outBytes = EmptyBuffer; @@ -279,13 +314,10 @@ public override byte[] DoFinal() return outBytes; } - public override byte[] DoFinal( - byte[] input, - int inOff, - int inLen) - { - if (input == null) - throw new ArgumentNullException("input"); + public override byte[] DoFinal(byte[] input, int inOff, int inLen) + { + if (input == null) + throw new ArgumentNullException(nameof(input)); int length = GetOutputSize(inLen); @@ -316,7 +348,7 @@ public override byte[] DoFinal( return outBytes; } - /** + /** * Process the last block in the buffer. * * @param out the array the block currently being held is copied into. @@ -330,19 +362,17 @@ public override byte[] DoFinal( * @exception DataLengthException if the input is not block size * aligned. */ - public override int DoFinal( - byte[] output, - int outOff) - { - try + public override int DoFinal(byte[] output, int outOff) + { + try { if (bufOff != 0) { - Check.DataLength(!cipher.IsPartialBlockOkay, "data not block size aligned"); + Check.DataLength(!m_cipherMode.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); + m_cipherMode.ProcessBlock(buf, 0, buf, 0); Array.Copy(buf, 0, output, outOff, bufOff); } @@ -354,7 +384,31 @@ public override int DoFinal( } } - /** +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + try + { + if (bufOff != 0) + { + Check.DataLength(!m_cipherMode.IsPartialBlockOkay, "data not block size aligned"); + Check.OutputLength(output, bufOff, "output buffer too short for DoFinal()"); + + // NB: Can't copy directly, or we may write too much output + m_cipherMode.ProcessBlock(buf, buf); + buf.AsSpan(0, bufOff).CopyTo(output); + } + + return bufOff; + } + finally + { + Reset(); + } + } +#endif + + /** * 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). */ @@ -363,7 +417,7 @@ public override void Reset() Array.Clear(buf, 0, buf.Length); bufOff = 0; - cipher.Reset(); + m_cipherMode.Reset(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedCipherBase.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedCipherBase.cs index 7476ab4..b79110c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedCipherBase.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedCipherBase.cs @@ -34,7 +34,11 @@ public virtual int ProcessByte( return outBytes.Length; } - public virtual byte[] ProcessBytes( +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public abstract int ProcessByte(byte input, Span output); +#endif + + public virtual byte[] ProcessBytes( byte[] input) { return ProcessBytes(input, 0, input.Length); @@ -66,6 +70,10 @@ public virtual int ProcessBytes( return outBytes.Length; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public abstract int ProcessBytes(ReadOnlySpan input, Span output); +#endif + public abstract byte[] DoFinal(); public virtual byte[] DoFinal( @@ -110,6 +118,17 @@ public virtual int DoFinal( return len; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public abstract int DoFinal(Span output); + + public virtual int DoFinal(ReadOnlySpan input, Span output) + { + int len = ProcessBytes(input, output); + len += DoFinal(output[len..]); + return len; + } +#endif + public abstract void Reset(); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedIesCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedIesCipher.cs index 855841a..f39ecd3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedIesCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedIesCipher.cs @@ -4,8 +4,6 @@ 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 { @@ -38,7 +36,7 @@ public override void Init( this.forEncryption = forEncryption; // TODO - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("IES"); + throw new NotImplementedException("IES"); } public override int GetBlockSize() @@ -52,7 +50,7 @@ public override int GetOutputSize( if (engine == null) throw new InvalidOperationException("cipher not initialised"); - int baseLen = inputLen + (int) buffer.Length; + int baseLen = inputLen + Convert.ToInt32(buffer.Length); return forEncryption ? baseLen + 20 : baseLen - 20; @@ -64,14 +62,27 @@ public override int GetUpdateOutputSize( return 0; } - public override byte[] ProcessByte( - byte input) + public override byte[] ProcessByte(byte input) { buffer.WriteByte(input); return null; } - public override byte[] ProcessBytes( + public override int ProcessByte(byte input, byte[] output, int outOff) + { + buffer.WriteByte(input); + return 0; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int ProcessByte(byte input, Span output) + { + buffer.WriteByte(input); + return 0; + } +#endif + + public override byte[] ProcessBytes( byte[] input, int inOff, int length) @@ -89,7 +100,15 @@ public override byte[] ProcessBytes( return null; } - public override byte[] DoFinal() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int ProcessBytes(ReadOnlySpan input, Span output) + { + buffer.Write(input); + return 0; + } +#endif + + public override byte[] DoFinal() { byte[] buf = buffer.ToArray(); @@ -107,7 +126,20 @@ public override byte[] DoFinal( return DoFinal(); } - public override void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + byte[] buf = buffer.ToArray(); + + Reset(); + + byte[] block = engine.ProcessBlock(buf, 0, buf.Length); + block.CopyTo(output); + return block.Length; + } +#endif + + public override void Reset() { buffer.SetLength(0); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedStreamCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedStreamCipher.cs index 20bc603..8d110d2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedStreamCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/BufferedStreamCipher.cs @@ -9,32 +9,29 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto public class BufferedStreamCipher : BufferedCipherBase { - private readonly IStreamCipher cipher; + private readonly IStreamCipher m_cipher; - public BufferedStreamCipher( - IStreamCipher cipher) + public BufferedStreamCipher(IStreamCipher cipher) { if (cipher == null) throw new ArgumentNullException("cipher"); - this.cipher = cipher; + this.m_cipher = cipher; } public override string AlgorithmName { - get { return cipher.AlgorithmName; } + get { return m_cipher.AlgorithmName; } } - public override void Init( - bool forEncryption, - ICipherParameters parameters) - { - if (parameters is ParametersWithRandom) + public override void Init(bool forEncryption, ICipherParameters parameters) + { + if (parameters is ParametersWithRandom withRandom) { - parameters = ((ParametersWithRandom) parameters).Parameters; + parameters = withRandom.Parameters; } - cipher.Init(forEncryption, parameters); + m_cipher.Init(forEncryption, parameters); } public override int GetBlockSize() @@ -42,92 +39,101 @@ public override int GetBlockSize() return 0; } - public override int GetOutputSize( - int inputLen) + public override int GetOutputSize(int inputLen) { return inputLen; } - public override int GetUpdateOutputSize( - int inputLen) + public override int GetUpdateOutputSize(int inputLen) { return inputLen; } - public override byte[] ProcessByte( - byte input) + public override byte[] ProcessByte(byte input) { - return new byte[]{ cipher.ReturnByte(input) }; + return new byte[]{ m_cipher.ReturnByte(input) }; } - public override int ProcessByte( - byte input, - byte[] output, - int outOff) - { - if (outOff >= output.Length) + 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); + output[outOff] = m_cipher.ReturnByte(input); return 1; } - public override byte[] ProcessBytes( - byte[] input, - int inOff, - int length) - { - if (length < 1) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int ProcessByte(byte input, Span output) + { + output[0] = m_cipher.ReturnByte(input); + return 1; + } +#endif + + 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); + m_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) + 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); - } - + m_cipher.ProcessBytes(input, inOff, length, output, outOff); return length; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int ProcessBytes(ReadOnlySpan input, Span output) + { + m_cipher.ProcessBytes(input, output); + return input.Length; + } +#endif + public override byte[] DoFinal() { - Reset(); + m_cipher.Reset(); return EmptyBuffer; } - public override byte[] DoFinal( - byte[] input, - int inOff, - int length) + public override byte[] DoFinal(byte[] input, int inOff, int length) { if (length < 1) return EmptyBuffer; - byte[] output = ProcessBytes(input, inOff, length); - - Reset(); + byte[] output = new byte[length]; + m_cipher.ProcessBytes(input, inOff, length, output, 0); + m_cipher.Reset(); + return output; + } - return output; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + m_cipher.Reset(); + return 0; } - public override void Reset() + public override int DoFinal(ReadOnlySpan input, Span output) + { + m_cipher.ProcessBytes(input, output); + m_cipher.Reset(); + return input.Length; + } +#endif + + public override void Reset() { - cipher.Reset(); + m_cipher.Reset(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/Check.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/Check.cs index 3bf652b..39190d2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/Check.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/Check.cs @@ -23,6 +23,20 @@ internal static void OutputLength(byte[] buf, int off, int len, string msg) if (off > (buf.Length - len)) throw new OutputLengthException(msg); } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal static void DataLength(ReadOnlySpan input, int len, string msg) + { + if (input.Length < len) + throw new DataLengthException(msg); + } + + internal static void OutputLength(Span output, int len, string msg) + { + if (output.Length < len) + throw new OutputLengthException(msg); + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/CipherKeyGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/CipherKeyGenerator.cs index 87e01e6..7d4e7a5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/CipherKeyGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/CipherKeyGenerator.cs @@ -39,19 +39,17 @@ public int DefaultStrength * * @param param the parameters to be used for key generation */ - public void Init( - KeyGenerationParameters parameters) + public void Init(KeyGenerationParameters parameters) { if (parameters == null) - throw new ArgumentNullException("parameters"); + throw new ArgumentNullException(nameof(parameters)); this.uninitialised = false; - engineInit(parameters); + EngineInit(parameters); } - protected virtual void engineInit( - KeyGenerationParameters parameters) + protected virtual void EngineInit(KeyGenerationParameters parameters) { this.random = parameters.Random; this.strength = (parameters.Strength + 7) / 8; @@ -71,13 +69,13 @@ public byte[] GenerateKey() uninitialised = false; - engineInit(new KeyGenerationParameters(new SecureRandom(), defaultStrength)); + EngineInit(new KeyGenerationParameters(CryptoServicesRegistrar.GetSecureRandom(), defaultStrength)); } - return engineGenerateKey(); + return EngineGenerateKey(); } - protected virtual byte[] engineGenerateKey() + protected virtual byte[] EngineGenerateKey() { return SecureRandom.GetNextBytes(random, strength); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/CryptoException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/CryptoException.cs index 9606804..19e4f16 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/CryptoException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/CryptoException.cs @@ -1,32 +1,34 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; 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() + : base() + { + } - public CryptoException( - string message) + public CryptoException(string message) : base(message) - { - } + { + } + + public CryptoException(string message, Exception innerException) + : base(message, innerException) + { + } - public CryptoException( - string message, - Exception exception) - : base(message, exception) - { - } - } + protected CryptoException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/CryptoServicesRegistrar.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/CryptoServicesRegistrar.cs new file mode 100644 index 0000000..cae2d0a --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/CryptoServicesRegistrar.cs @@ -0,0 +1,21 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto +{ + public static class CryptoServicesRegistrar + { + public static SecureRandom GetSecureRandom() + { + return new SecureRandom(); + } + + public static SecureRandom GetSecureRandom(SecureRandom secureRandom) + { + return secureRandom ?? new SecureRandom(); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/CryptoServicesRegistrar.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/CryptoServicesRegistrar.cs.meta new file mode 100644 index 0000000..e1b0aeb --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/CryptoServicesRegistrar.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5080aaa8a1b6a3a45a17cd1781379690 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/DataLengthException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/DataLengthException.cs index 6fecb95..a34abe5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/DataLengthException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/DataLengthException.cs @@ -1,45 +1,38 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; 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 + /// 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 . + /// + [Serializable] public class DataLengthException : CryptoException { - /** - * base constructor. - */ - public DataLengthException() - { - } + public DataLengthException() + : base() + { + } - /** - * create a DataLengthException with the given message. - * - * @param message the message to be carried with the exception. - */ - public DataLengthException( - string message) + public DataLengthException(string message) : base(message) - { + { } - public DataLengthException( - string message, - Exception exception) - : base(message, exception) - { - } + public DataLengthException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected DataLengthException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IBlockCipher.cs index ca98a4a..223c2be 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IBlockCipher.cs @@ -18,9 +18,6 @@ public interface IBlockCipher /// 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. @@ -30,10 +27,15 @@ public interface IBlockCipher /// 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(); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + + /// Process a block. + /// The input block as a span. + /// The output span. + /// If input block is wrong size, or output span too small. + /// The number of bytes processed and produced. + int ProcessBlock(ReadOnlySpan input, Span output); +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IBlockResult.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IBlockResult.cs index d003e0e..3372ba4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IBlockResult.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IBlockResult.cs @@ -1,5 +1,6 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable +using System; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto { @@ -22,6 +23,15 @@ public interface IBlockResult /// The byte array to copy the result into. /// The offset into destination to start copying the result at. int Collect(byte[] destination, int offset); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// + /// Store the final result of the operation by copying it into the destination span. + /// + /// The number of bytes copied into destination. + /// The span to copy the result into. + int Collect(Span destination); +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IBufferedCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IBufferedCipher.cs index 29d09e8..51cb224 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IBufferedCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IBufferedCipher.cs @@ -25,11 +25,19 @@ public interface IBufferedCipher byte[] ProcessByte(byte input); int ProcessByte(byte input, byte[] output, int outOff); - byte[] ProcessBytes(byte[] input); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int ProcessByte(byte input, Span output); +#endif + + 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); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int ProcessBytes(ReadOnlySpan input, Span output); +#endif + byte[] DoFinal(); byte[] DoFinal(byte[] input); byte[] DoFinal(byte[] input, int inOff, int length); @@ -37,6 +45,11 @@ public interface IBufferedCipher int DoFinal(byte[] input, byte[] output, int outOff); int DoFinal(byte[] input, int inOff, int length, byte[] output, int outOff); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int DoFinal(Span output); + int DoFinal(ReadOnlySpan input, Span output); +#endif + /// /// Reset the cipher. After resetting the cipher is in the same state /// as it was after the last init (if there was one). diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IDSA.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IDSA.cs index 7966c06..2a2371a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IDSA.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IDSA.cs @@ -6,38 +6,29 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto { - /** - * interface for classes implementing the Digital Signature Algorithm - */ + /// Interface for classes implementing the Digital Signature Algorithm public interface IDsa { + /// The algorithm name. 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. - */ + /// Initialise the signer for signature generation or signature verification. + /// true if we are generating a signature, false otherwise. + /// 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. - */ + /// Sign the passed in message (usually the output of a hash function). + /// the message to be signed. + /// 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. - */ + /// The order of the group that the r, s values in signatures belong to. + BigInteger Order { get; } + + /// Verify the message message against the signature values r and s. + /// the message that was supposed to have been signed. + /// the r signature value. + /// the s signature value. bool VerifySignature(byte[] message, BigInteger r, BigInteger s); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IDerivationFunction.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IDerivationFunction.cs index dda4764..bb1d013 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IDerivationFunction.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IDerivationFunction.cs @@ -14,15 +14,14 @@ public interface IDerivationFunction /** * return the message digest used as the basis for the function */ - IDigest Digest - { - get; - } + IDigest Digest { get; } int GenerateBytes(byte[] output, int outOff, int length); - //throws DataLengthException, ArgumentException; - } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int GenerateBytes(Span output); +#endif + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IDigest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IDigest.cs index db4d58c..669f567 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IDigest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IDigest.cs @@ -4,60 +4,52 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto { - /** - * interface that a message digest conforms to. - */ + /// Base interface for a message digest. public interface IDigest { - /** - * return the algorithm name - * - * @return the algorithm name - */ + /// 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 digest produced by this message digest. + /// 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(); + /// Return the size, in bytes, of the internal buffer used by this digest. + /// 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. - */ + /// Update the message digest with a single byte. + /// 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); + /// Update the message digest with a block of bytes. + /// the byte array containing the data. + /// the offset into the byte array where the data starts. + /// the length of the data. + void BlockUpdate(byte[] input, int inOff, int inLen); - /** - * 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. - */ +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// Update the message digest with a span of bytes. + /// the span containing the data. + void BlockUpdate(ReadOnlySpan input); +#endif + + /// Close the digest, producing the final digest value. + /// This call leaves the digest reset. + /// the byte array the digest is to be copied into. + /// the offset into the byte array the digest is to start at. + /// the number of bytes written int DoFinal(byte[] output, int outOff); - /** - * reset the digest back to it's initial state. - */ +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// Close the digest, producing the final digest value. + /// This call leaves the digest reset. + /// the span the digest is to be copied into. + /// the number of bytes written + int DoFinal(Span output); +#endif + + /// Reset the digest back to its initial state. void Reset(); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IDigestFactory.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IDigestFactory.cs index c52443c..a734799 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IDigestFactory.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IDigestFactory.cs @@ -22,7 +22,7 @@ public interface IDigestFactory /// and producing the digest block. /// /// A calculator producing an IBlockResult with the final digest in it. - IStreamCalculator CreateCalculator(); + IStreamCalculator CreateCalculator(); } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IEncapsulatedSecretExtractor.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IEncapsulatedSecretExtractor.cs new file mode 100644 index 0000000..505e39e --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IEncapsulatedSecretExtractor.cs @@ -0,0 +1,20 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto +{ + public interface IEncapsulatedSecretExtractor + { + /// + /// Generate an exchange pair based on the recipient public key. + /// + /// the encapsulated secret. + byte[] ExtractSecret(byte[] encapsulation); + + /// + /// The length in bytes of the encapsulation. + /// + int EncapsulationLength { get; } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IEncapsulatedSecretExtractor.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IEncapsulatedSecretExtractor.cs.meta new file mode 100644 index 0000000..fddc5af --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IEncapsulatedSecretExtractor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d43d7edf40e958546bc77bcb9954e1f8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IEncapsulatedSecretGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IEncapsulatedSecretGenerator.cs new file mode 100644 index 0000000..6318678 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IEncapsulatedSecretGenerator.cs @@ -0,0 +1,16 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto +{ + public interface IEncapsulatedSecretGenerator + { + /// + /// Generate an exchange pair based on the recipient public key. + /// + /// + /// An SecretWithEncapsulation derived from the recipient public key. + ISecretWithEncapsulation GenerateEncapsulated(AsymmetricKeyParameter recipientKey); + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IEncapsulatedSecretGenerator.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IEncapsulatedSecretGenerator.cs.meta new file mode 100644 index 0000000..6d09686 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IEncapsulatedSecretGenerator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 642c0e33a85937744af2d35b54685f2c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IEntropySource.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IEntropySource.cs index cfe0f69..00c8c32 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IEntropySource.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IEntropySource.cs @@ -21,6 +21,10 @@ public interface IEntropySource /// The entropy bytes. byte[] GetEntropy(); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int GetEntropy(Span output); +#endif + /// /// Return the number of bits of entropy this source can produce. /// diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IMac.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IMac.cs index e4810e1..7b3e53f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IMac.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IMac.cs @@ -4,68 +4,52 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto { - /** - * The base interface for implementations of message authentication codes (MACs). - */ + /// 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. - */ + /// Initialise the MAC. + /// The key or other data required by the MAC. void Init(ICipherParameters parameters); - /** - * Return the name of the algorithm the MAC implements. - * - * @return the name of the algorithm the MAC implements. - */ + /// The algorithm name. string AlgorithmName { get; } - /** - * Return the block size for this MAC (in bytes). - * - * @return the block size for this MAC in bytes. - */ - int GetMacSize(); + /// Return the size, in bytes, of the MAC produced by this implementation. + /// the size, in bytes, of the MAC produced by this implementation. + 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. - */ + /// Update the MAC with a single byte. + /// the input byte to be entered. 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); + /// Update the MAC with a block of bytes. + /// the byte array containing the data. + /// the offset into the byte array where the data starts. + /// the length of the data. + void BlockUpdate(byte[] input, int inOff, int inLen); - /** - * 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. - */ +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// Update the MAC with a span of bytes. + /// the span containing the data. + void BlockUpdate(ReadOnlySpan input); +#endif + + /// Perform final calculations, producing the result MAC. + /// This call leaves the MAC reset. + /// the byte array the MAC is to be copied into. + /// the offset into the byte array the MAC is to start at. + /// the number of bytes written 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). - */ +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// Perform final calculations, producing the result MAC. + /// This call leaves the MAC reset. + /// the span the MAC is to be copied into. + /// the number of bytes written + int DoFinal(Span output); +#endif + + /// Reset the MAC back to its initial state. void Reset(); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IMacDerivationFunction.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IMacDerivationFunction.cs index e3e0473..b05c7fa 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IMacDerivationFunction.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IMacDerivationFunction.cs @@ -2,9 +2,10 @@ #pragma warning disable namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto { - public interface IMacDerivationFunction:IDerivationFunction + public interface IMacDerivationFunction + : IDerivationFunction { - IMac GetMac(); + IMac Mac { get; } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IMacFactory.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IMacFactory.cs index cd19199..78f68f4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IMacFactory.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IMacFactory.cs @@ -15,7 +15,7 @@ public interface IMacFactory /// and producing the signature block. ///
/// A calculator producing an IBlockResult with a signature in it. - IStreamCalculator CreateCalculator(); + IStreamCalculator CreateCalculator(); } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IRawAgreement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IRawAgreement.cs index 91146e0..64ab5a6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IRawAgreement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IRawAgreement.cs @@ -11,6 +11,10 @@ public interface IRawAgreement int AgreementSize { get; } void CalculateAgreement(ICipherParameters publicKey, byte[] buf, int off); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + void CalculateAgreement(ICipherParameters publicKey, Span output); +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/ISecretWithEncapsulation.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/ISecretWithEncapsulation.cs new file mode 100644 index 0000000..3f74e87 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/ISecretWithEncapsulation.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 +{ + public interface ISecretWithEncapsulation + : IDisposable + { + + /// + /// Return the secret associated with the encapsulation. + /// + /// the secret the encapsulation is for. + byte[] GetSecret(); + + /// + /// Return the data that carries the secret in its encapsulated form. + /// + /// the encapsulation of the secret. + byte[] GetEncapsulation(); + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/ISecretWithEncapsulation.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/ISecretWithEncapsulation.cs.meta new file mode 100644 index 0000000..9fa953f --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/ISecretWithEncapsulation.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3160d4314f9a00f41823ce0d5bf32ea4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/ISignatureFactory.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/ISignatureFactory.cs index 95dba2e..14f0999 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/ISignatureFactory.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/ISignatureFactory.cs @@ -1,7 +1,5 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System; - namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto { /// @@ -10,7 +8,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto public interface ISignatureFactory { /// The algorithm details object for this calculator. - Object AlgorithmDetails { get ; } + object AlgorithmDetails { get; } /// /// Create a stream calculator for this signature calculator. The stream @@ -18,10 +16,8 @@ public interface ISignatureFactory /// and producing the signature block. /// /// A calculator producing an IBlockResult with a signature in it. - IStreamCalculator CreateCalculator(); + IStreamCalculator CreateCalculator(); } } - - #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/ISigner.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/ISigner.cs index 0d50cef..ca18fc9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/ISigner.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/ISigner.cs @@ -1,52 +1,47 @@ #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. - */ + /// The algorithm name. 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 - */ + /// Initialise the signer for signing or verification. + /// true if for signing, false otherwise. + /// necessary parameters. + void Init(bool forSigning, ICipherParameters parameters); + + /// Update the signer with a single byte. + /// the input byte to be entered. void Update(byte input); - /** - * update the internal digest with the byte array in - */ - void BlockUpdate(byte[] input, int inOff, int length); + /// Update the signer with a block of bytes. + /// the byte array containing the data. + /// the offset into the byte array where the data starts. + /// the length of the data. + void BlockUpdate(byte[] input, int inOff, int inLen); - /** - * Generate a signature for the message we've been loaded with using - * the key we were initialised with. - */ +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// Update the signer with a span of bytes. + /// the span containing the data. + void BlockUpdate(ReadOnlySpan input); +#endif + + /// Generate a signature for the message we've been loaded with using the key we were initialised with. + /// + /// A byte array containing the signature for the message. byte[] GenerateSignature(); - /** - * return true if the internal state represents the signature described - * in the passed in array. - */ + + /// Return true if the internal state represents the signature described in the passed in array. + /// + /// an array containing the candidate signature to verify. + /// true if the internal state represents the signature described in the passed in array. bool VerifySignature(byte[] signature); - /** - * reset the internal state - */ + /// Reset the signer back to its initial state. void Reset(); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IStreamCalculator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IStreamCalculator.cs index 2196684..2cc077f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IStreamCalculator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IStreamCalculator.cs @@ -1,6 +1,5 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System; using System.IO; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto @@ -9,7 +8,7 @@ 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 + 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. @@ -20,7 +19,7 @@ public interface IStreamCalculator /// has been closed. ///
/// The result of processing the stream. - Object GetResult(); + TResult GetResult(); } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IStreamCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IStreamCipher.cs index 5601718..e72c7e7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IStreamCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IStreamCipher.cs @@ -24,25 +24,36 @@ public interface IStreamCipher /// 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. + /// + /// Process a block of bytes from , putting the result into . + /// + /// 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 input buffer is too small. + /// 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(); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// + /// Process a block of bytes from , putting the result into . + /// + /// The input span. + /// The output span. + /// If the output span is too small. + void ProcessBytes(ReadOnlySpan input, Span output); +#endif + + /// + /// Reset the cipher to the same state as it was after the last init (if there was one). + /// + void Reset(); } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IVerifierFactory.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IVerifierFactory.cs index dc40f7d..a3000e8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IVerifierFactory.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IVerifierFactory.cs @@ -1,7 +1,5 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System; - namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto { /// @@ -10,7 +8,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto public interface IVerifierFactory { /// The algorithm details object for this verifier. - Object AlgorithmDetails { get ; } + object AlgorithmDetails { get; } /// /// Create a stream calculator for this verifier. The stream @@ -18,7 +16,7 @@ public interface IVerifierFactory /// 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(); + IStreamCalculator CreateCalculator(); } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IVerifierFactoryProvider.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IVerifierFactoryProvider.cs index 63133f9..84c0fc6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IVerifierFactoryProvider.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IVerifierFactoryProvider.cs @@ -14,7 +14,7 @@ public interface IVerifierFactoryProvider /// /// The details of the signature algorithm verification is required for. /// A new signature verifier. - IVerifierFactory CreateVerifierFactory (Object algorithmDetails); + IVerifierFactory CreateVerifierFactory (object algorithmDetails); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IWrapper.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IWrapper.cs index 4bf5a15..2b97d22 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IWrapper.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IWrapper.cs @@ -1,9 +1,5 @@ #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 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IXof.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IXof.cs index 88fe9a0..fc3a800 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IXof.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/IXof.cs @@ -6,29 +6,48 @@ 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. + /// This interface provides the extra methods 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 the results of the final calculation for this XOF 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); + int OutputFinal(byte[] output, int outOff, int outLen); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ /// - /// 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 the results of the final calculation for this XOF to fill the output span. + /// + /// span to fill with the output bytes. + /// the number of bytes written + int OutputFinal(Span output); +#endif + + /// + /// Start outputting the results of the final calculation for this XOF. 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); + int Output(byte[] output, int outOff, int outLen); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// + /// Start outputting the results of the final calculation for this XOF. Unlike OutputFinal, this method + /// will continue producing output until the XOF is explicitly reset, or signals otherwise. + /// + /// span to fill with the output bytes. + /// the number of bytes written + int Output(Span output); +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/InvalidCipherTextException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/InvalidCipherTextException.cs index a89918a..8ee6e31 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/InvalidCipherTextException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/InvalidCipherTextException.cs @@ -1,44 +1,35 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; 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) + /// This exception is thrown whenever we find something we don't expect in a message. [Serializable] -#endif public class InvalidCipherTextException : CryptoException { - /** - * base constructor. - */ - public InvalidCipherTextException() - { - } + public InvalidCipherTextException() + : base() + { + } - /** - * create a InvalidCipherTextException with the given message. - * - * @param message the message to be carried with the exception. - */ - public InvalidCipherTextException( - string message) + public InvalidCipherTextException(string message) : base(message) - { - } + { + } + + public InvalidCipherTextException(string message, Exception innerException) + : base(message, innerException) + { + } - public InvalidCipherTextException( - string message, - Exception exception) - : base(message, exception) - { - } - } + protected InvalidCipherTextException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/MaxBytesExceededException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/MaxBytesExceededException.cs index d09caf6..8ffd48e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/MaxBytesExceededException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/MaxBytesExceededException.cs @@ -1,33 +1,34 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; 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 + /// 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() + : base() { } - public MaxBytesExceededException( - string message) + public MaxBytesExceededException(string message) : base(message) { } - public MaxBytesExceededException( - string message, - Exception e) - : base(message, e) + public MaxBytesExceededException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected MaxBytesExceededException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/OutputLengthException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/OutputLengthException.cs index 6fa64ed..1516cec 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/OutputLengthException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/OutputLengthException.cs @@ -1,32 +1,34 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; 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() + : base() + { + } + + public OutputLengthException(string message) + : base(message) + { + } - public OutputLengthException( - string message) - : base(message) - { - } + public OutputLengthException(string message, Exception innerException) + : base(message, innerException) + { + } - public OutputLengthException( - string message, - Exception exception) - : base(message, exception) - { - } - } + protected OutputLengthException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/PbeParametersGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/PbeParametersGenerator.cs index 061791a..883b60e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/PbeParametersGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/PbeParametersGenerator.cs @@ -51,33 +51,11 @@ public virtual byte[] Password get { return Arrays.Clone(mPassword); } } - /** - * return the password byte array. - * - * @return the password byte array. - */ - - public byte[] GetPassword() - { - return Password; - } - public virtual byte[] Salt { get { return Arrays.Clone(mSalt); } } - /** - * return the salt byte array. - * - * @return the salt byte array. - */ - - public byte[] GetSalt() - { - return Salt; - } - /** * return the iteration count. * @@ -88,26 +66,7 @@ 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. - */ - - 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. - */ - - public abstract ICipherParameters GenerateDerivedParameters(int keySize, int ivSize); public abstract ICipherParameters GenerateDerivedParameters(string algorithm, int keySize, int ivSize); /** @@ -135,16 +94,6 @@ public static byte[] Pkcs5PasswordToBytes( return Strings.ToByteArray(password); } - - 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) @@ -161,16 +110,6 @@ public static byte[] Pkcs5PasswordToUtf8Bytes( return Encoding.UTF8.GetBytes(password); } - - 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). diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/Security.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/Security.cs index 22ddaba..0454b34 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/Security.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/Security.cs @@ -1,80 +1,3 @@ #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.Digests; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators; -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.Security; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders; - -namespace crypto -{ - public class Security - { - // USAGE - //var key = Security.GenerateText(32); - //var iv = Security.GenerateText(16); - //var encrypted = Security.Encrypt("MY SECRET", key, iv); - //var decrypted = Security.Decrypt(encrypted, key, iv); - - /// - /// Return a salted hash based on PBKDF2 for the UTF-8 encoding of the argument text. - /// - /// Provided key text - /// Base64 encoded string representing the salt - /// - public static string ComputeHash(string text, string salt) - { - byte[] data = Encoding.UTF8.GetBytes(text); - Sha512Digest sha = new Sha512Digest(); - Pkcs5S2ParametersGenerator gen = new Pkcs5S2ParametersGenerator(sha); - - gen.Init(data, Base64.Decode(salt), 2048); - - return Base64.ToBase64String(((KeyParameter)gen.GenerateDerivedParameters(sha.GetDigestSize() * 8)).GetKey()); - } - - public static string Decrypt(string cipherText, string key, string iv) - { - IBufferedCipher cipher = CreateCipher(false, key, iv); - byte[] textAsBytes = cipher.DoFinal(Base64.Decode(cipherText)); - - return Encoding.UTF8.GetString(textAsBytes, 0, textAsBytes.Length); - } - - public static string Encrypt(string plainText, string key, string iv) - { - IBufferedCipher cipher = CreateCipher(true, key, iv); - - return Base64.ToBase64String(cipher.DoFinal(Encoding.UTF8.GetBytes(plainText))); - } - - public static string GenerateText(int size) - { - byte[] textAsBytes = new byte[size]; - SecureRandom secureRandom = SecureRandom.GetInstance("SHA256PRNG", true); - - secureRandom.NextBytes(textAsBytes); - return Base64.ToBase64String(textAsBytes); - } - - private static IBufferedCipher CreateCipher(bool isEncryption, string key, string iv) - { - IBufferedCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new RijndaelEngine()), new ISO10126d2Padding()); - KeyParameter keyParam = new KeyParameter(Base64.Decode(key)); - ICipherParameters cipherParams = (null == iv || iv.Length < 1) - ? (ICipherParameters)keyParam - : new ParametersWithIV(keyParam, Base64.Decode(iv)); - cipher.Init(isEncryption, cipherParams); - return cipher; - } - } -} -#pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/Security.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/Security.cs.meta index cb59a06..ff7c0cf 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/Security.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/Security.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 5b5ac9913dade5a42b1cec926ef11336 +guid: b1d368c12b4edfe4b920a33d51d08c44 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/SimpleBlockResult.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/SimpleBlockResult.cs index edb23d0..46c2097 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/SimpleBlockResult.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/SimpleBlockResult.cs @@ -51,6 +51,15 @@ public int Collect(byte[] destination, int offset) return result.Length; } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int Collect(Span destination) + { + result.CopyTo(destination); + + return result.Length; + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/StreamBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/StreamBlockCipher.cs index fb40d16..f0a1fde 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/StreamBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/StreamBlockCipher.cs @@ -2,7 +2,7 @@ #pragma warning disable using System; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto { @@ -13,7 +13,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto public class StreamBlockCipher : IStreamCipher { - private readonly IBlockCipher cipher; + private readonly IBlockCipherMode m_cipherMode; private readonly byte[] oneByte = new byte[1]; /** @@ -23,28 +23,25 @@ public class StreamBlockCipher * @exception ArgumentException if the cipher has a block size other than * one. */ - public StreamBlockCipher( - IBlockCipher cipher) + public StreamBlockCipher(IBlockCipherMode cipherMode) { - if (cipher == null) - throw new ArgumentNullException("cipher"); - if (cipher.GetBlockSize() != 1) - throw new ArgumentException("block cipher block size != 1.", "cipher"); + if (cipherMode == null) + throw new ArgumentNullException(nameof(cipherMode)); + if (cipherMode.GetBlockSize() != 1) + throw new ArgumentException("block cipher block size != 1.", nameof(cipherMode)); - this.cipher = cipher; + m_cipherMode = cipherMode; } - /** + /** * 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); + public void Init(bool forEncryption, ICipherParameters parameters) + { + m_cipherMode.Init(forEncryption, parameters); } /** @@ -54,7 +51,7 @@ public void Init( */ public string AlgorithmName { - get { return cipher.AlgorithmName; } + get { return m_cipherMode.AlgorithmName; } } /** @@ -63,17 +60,16 @@ public string AlgorithmName * @param in the byte to be processed. * @return the result of processing the input byte. */ - public byte ReturnByte( - byte input) + public byte ReturnByte(byte input) { oneByte[0] = input; - cipher.ProcessBlock(oneByte, 0, oneByte, 0); + m_cipherMode.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. @@ -83,29 +79,36 @@ public byte ReturnByte( * @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()"); + public 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++) { - cipher.ProcessBlock(input, inOff + i, output, outOff + i); + m_cipherMode.ProcessBlock(input, inOff + i, output, outOff + i); } } - /** +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void ProcessBytes(ReadOnlySpan input, Span output) + { + Check.OutputLength(output, input.Length, "output buffer too short"); + + for (int i = 0; i != input.Length; i++) + { + m_cipherMode.ProcessBlock(input[i..], output[i..]); + } + } +#endif + + /** * 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() + public void Reset() { - cipher.Reset(); + m_cipherMode.Reset(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/DHAgreement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/DHAgreement.cs index cbf7bfa..8780e06 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/DHAgreement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/DHAgreement.cs @@ -28,30 +28,25 @@ public class DHAgreement private BigInteger privateValue; private SecureRandom random; - public void Init( - ICipherParameters parameters) + public void Init(ICipherParameters parameters) { AsymmetricKeyParameter kParam; - if (parameters is ParametersWithRandom) + if (parameters is ParametersWithRandom rParam) { - ParametersWithRandom rParam = (ParametersWithRandom)parameters; - this.random = rParam.Random; kParam = (AsymmetricKeyParameter)rParam.Parameters; } else { - this.random = new SecureRandom(); + this.random = CryptoServicesRegistrar.GetSecureRandom(); kParam = (AsymmetricKeyParameter)parameters; } - if (!(kParam is DHPrivateKeyParameters)) - { + if (!(kParam is DHPrivateKeyParameters dhPrivateKeyParameters)) throw new ArgumentException("DHEngine expects DHPrivateKeyParameters"); - } - this.key = (DHPrivateKeyParameters)kParam; - this.dhParams = key.Parameters; + this.key = dhPrivateKeyParameters; + this.dhParams = dhPrivateKeyParameters.Parameters; } /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/ECDHWithKdfBasicAgreement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/ECDHWithKdfBasicAgreement.cs index a1e1533..7622a5e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/ECDHWithKdfBasicAgreement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/ECDHWithKdfBasicAgreement.cs @@ -1,14 +1,10 @@ #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; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/ECMqvWithKdfBasicAgreement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/ECMqvWithKdfBasicAgreement.cs index fc5f473..82892db 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/ECMqvWithKdfBasicAgreement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/ECMqvWithKdfBasicAgreement.cs @@ -1,14 +1,10 @@ #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; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/X25519Agreement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/X25519Agreement.cs index 46aa12c..a8ebaa4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/X25519Agreement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/X25519Agreement.cs @@ -9,11 +9,11 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement public sealed class X25519Agreement : IRawAgreement { - private X25519PrivateKeyParameters privateKey; + private X25519PrivateKeyParameters m_privateKey; public void Init(ICipherParameters parameters) { - this.privateKey = (X25519PrivateKeyParameters)parameters; + m_privateKey = (X25519PrivateKeyParameters)parameters; } public int AgreementSize @@ -23,8 +23,19 @@ public int AgreementSize public void CalculateAgreement(ICipherParameters publicKey, byte[] buf, int off) { - privateKey.GenerateSecret((X25519PublicKeyParameters)publicKey, buf, off); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + CalculateAgreement(publicKey, buf.AsSpan(off)); +#else + m_privateKey.GenerateSecret((X25519PublicKeyParameters)publicKey, buf, off); +#endif } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void CalculateAgreement(ICipherParameters publicKey, Span buf) + { + m_privateKey.GenerateSecret((X25519PublicKeyParameters)publicKey, buf); + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/X448Agreement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/X448Agreement.cs index ffb70b6..06974b4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/X448Agreement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/X448Agreement.cs @@ -9,11 +9,11 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement public sealed class X448Agreement : IRawAgreement { - private X448PrivateKeyParameters privateKey; + private X448PrivateKeyParameters m_privateKey; public void Init(ICipherParameters parameters) { - this.privateKey = (X448PrivateKeyParameters)parameters; + m_privateKey = (X448PrivateKeyParameters)parameters; } public int AgreementSize @@ -23,8 +23,19 @@ public int AgreementSize public void CalculateAgreement(ICipherParameters publicKey, byte[] buf, int off) { - privateKey.GenerateSecret((X448PublicKeyParameters)publicKey, buf, off); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + CalculateAgreement(publicKey, buf.AsSpan(off)); +#else + m_privateKey.GenerateSecret((X448PublicKeyParameters)publicKey, buf, off); +#endif } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void CalculateAgreement(ICipherParameters publicKey, Span buf) + { + m_privateKey.GenerateSecret((X448PublicKeyParameters)publicKey, buf); + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/jpake/JPakeParticipant.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/jpake/JPakeParticipant.cs index f47d82c..2c88728 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/jpake/JPakeParticipant.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/jpake/JPakeParticipant.cs @@ -144,7 +144,7 @@ public JPakeParticipant(string participantId, char[] password) /// 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()) { } + : this(participantId, password, group, new Sha256Digest(), CryptoServicesRegistrar.GetSecureRandom()) { } /// @@ -164,7 +164,8 @@ public JPakeParticipant(string participantId, char[] password, JPakePrimeOrderGr /// 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) + public JPakeParticipant(string participantId, char[] password, JPakePrimeOrderGroup group, IDigest digest, + SecureRandom random) { JPakeUtilities.ValidateNotNull(participantId, "participantId"); JPakeUtilities.ValidateNotNull(password, "password"); @@ -173,9 +174,7 @@ public JPakeParticipant(string participantId, char[] password, JPakePrimeOrderGr JPakeUtilities.ValidateNotNull(random, "random"); if (password.Length == 0) - { throw new ArgumentException("Password must not be empty."); - } this.participantId = participantId; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/kdf/ConcatenationKdfGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/kdf/ConcatenationKdfGenerator.cs index 3347556..6d95fff 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/kdf/ConcatenationKdfGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/kdf/ConcatenationKdfGenerator.cs @@ -7,97 +7,111 @@ 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 + /// Generator for Concatenation Key Derivation Function defined in NIST SP 800-56A, Sect 5.8.1 + public sealed class ConcatenationKdfGenerator : IDerivationFunction { - private readonly IDigest mDigest; + private readonly IDigest m_digest; + private readonly int m_hLen; - private byte[] mShared; - private byte[] mOtherInfo; - private int mHLen; + private byte[] m_buffer; - /** - * @param digest the digest to be used as the source of generated bytes - */ + /// the digest to be used as the source of generated bytes public ConcatenationKdfGenerator(IDigest digest) { - this.mDigest = digest; - this.mHLen = digest.GetDigestSize(); + m_digest = digest; + m_hLen = digest.GetDigestSize(); } - public virtual void Init(IDerivationParameters param) + public void Init(IDerivationParameters param) { - if (!(param is KdfParameters)) + if (!(param is KdfParameters kdfParameters)) throw new ArgumentException("KDF parameters required for ConcatenationKdfGenerator"); - KdfParameters p = (KdfParameters)param; + byte[] sharedSecret = kdfParameters.GetSharedSecret(); + byte[] otherInfo = kdfParameters.GetIV(); - mShared = p.GetSharedSecret(); - mOtherInfo = p.GetIV(); + m_buffer = new byte[4 + sharedSecret.Length + otherInfo.Length + m_hLen]; + sharedSecret.CopyTo(m_buffer, 4); + otherInfo.CopyTo(m_buffer, 4 + sharedSecret.Length); } - /** - * return the underlying digest. - */ - public virtual IDigest Digest - { - get { return mDigest; } - } + /// the underlying digest. + public IDigest Digest => m_digest; - /** - * 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) + /// Fill len bytes of the output buffer with bytes generated from the derivation function. + /// + public int GenerateBytes(byte[] output, int outOff, int length) { - if ((outBytes.Length - len) < outOff) - throw new DataLengthException("output buffer too small"); + Check.OutputLength(output, outOff, length, "output buffer too small"); - byte[] hashBuf = new byte[mHLen]; - byte[] C = new byte[4]; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return GenerateBytes(output.AsSpan(outOff, length)); +#else + int hashPos = m_buffer.Length - m_hLen; uint counter = 1; - int outputLen = 0; - mDigest.Reset(); + m_digest.Reset(); + + int end = outOff + length; + int limit = end - m_hLen; - if (len > mHLen) + while (outOff <= limit) { - do - { - Pack.UInt32_To_BE(counter, C); + Pack.UInt32_To_BE(counter++, m_buffer, 0); + + m_digest.BlockUpdate(m_buffer, 0, hashPos); + m_digest.DoFinal(output, outOff); + + outOff += m_hLen; + } - mDigest.BlockUpdate(C, 0, C.Length); - mDigest.BlockUpdate(mShared, 0, mShared.Length); - mDigest.BlockUpdate(mOtherInfo, 0, mOtherInfo.Length); + if (outOff < end) + { + Pack.UInt32_To_BE(counter, m_buffer, 0); - mDigest.DoFinal(hashBuf, 0); + m_digest.BlockUpdate(m_buffer, 0, hashPos); + m_digest.DoFinal(m_buffer, hashPos); - Array.Copy(hashBuf, 0, outBytes, outOff + outputLen, mHLen); - outputLen += mHLen; - } - while ((counter++) < (len / mHLen)); + Array.Copy(m_buffer, hashPos, output, outOff, end - outOff); } - if (outputLen < len) + return length; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int GenerateBytes(Span output) + { + int hashPos = m_buffer.Length - m_hLen; + uint counter = 1; + + m_digest.Reset(); + + int pos = 0, length = output.Length, limit = length - m_hLen; + + while (pos <= limit) { - Pack.UInt32_To_BE(counter, C); + Pack.UInt32_To_BE(counter++, m_buffer.AsSpan()); - mDigest.BlockUpdate(C, 0, C.Length); - mDigest.BlockUpdate(mShared, 0, mShared.Length); - mDigest.BlockUpdate(mOtherInfo, 0, mOtherInfo.Length); + m_digest.BlockUpdate(m_buffer.AsSpan(0, hashPos)); + m_digest.DoFinal(output[pos..]); - mDigest.DoFinal(hashBuf, 0); + pos += m_hLen; + } + + if (pos < length) + { + Pack.UInt32_To_BE(counter, m_buffer.AsSpan()); - Array.Copy(hashBuf, 0, outBytes, outOff + outputLen, len - outputLen); + m_digest.BlockUpdate(m_buffer.AsSpan(0, hashPos)); + m_digest.DoFinal(m_buffer.AsSpan(hashPos)); + m_buffer.AsSpan(hashPos, length - pos).CopyTo(output[pos..]); } - return len; + return length; } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/kdf/DHKekGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/kdf/DHKekGenerator.cs index 3d92966..aa09fd2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/kdf/DHKekGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/kdf/DHKekGenerator.cs @@ -3,17 +3,19 @@ using System; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.Kdf { /** * RFC 2631 Diffie-hellman KEK derivation function. */ - public class DHKekGenerator + public sealed class DHKekGenerator : IDerivationFunction { - private readonly IDigest digest; + private readonly IDigest m_digest; private DerObjectIdentifier algorithm; private int keySize; @@ -22,10 +24,10 @@ public class DHKekGenerator public DHKekGenerator(IDigest digest) { - this.digest = digest; + m_digest = digest; } - public virtual void Init(IDerivationParameters param) + public void Init(IDerivationParameters param) { DHKdfParameters parameters = (DHKdfParameters)param; @@ -35,20 +37,79 @@ public virtual void Init(IDerivationParameters param) this.partyAInfo = parameters.GetExtraInfo(); // TODO Clone? } - public virtual IDigest Digest - { - get { return digest; } - } + public IDigest Digest => m_digest; - public virtual int GenerateBytes(byte[] outBytes, int outOff, int len) + public int GenerateBytes(byte[] outBytes, int outOff, int length) { - if ((outBytes.Length - len) < outOff) + Check.OutputLength(outBytes, outOff, length, "output buffer too small"); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return GenerateBytes(outBytes.AsSpan(outOff, length)); +#else + long oBytes = length; + int digestSize = m_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 + digestSize - 1) / digestSize); + + byte[] dig = new byte[digestSize]; + + uint counter = 1; + + for (int i = 0; i < cThreshold; i++) { - throw new DataLengthException("output buffer too small"); + // 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(); + + m_digest.BlockUpdate(z, 0, z.Length); + m_digest.BlockUpdate(other, 0, other.Length); + m_digest.DoFinal(dig, 0); + + if (length > digestSize) + { + Array.Copy(dig, 0, outBytes, outOff, digestSize); + outOff += digestSize; + length -= digestSize; + } + else + { + Array.Copy(dig, 0, outBytes, outOff, length); + } + + counter++; } - long oBytes = len; - int outLen = digest.GetDigestSize(); + m_digest.Reset(); + + return (int)oBytes; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int GenerateBytes(Span output) + { + long oBytes = output.Length; + int digestSize = m_digest.GetDigestSize(); // // this is at odds with the standard implementation, the @@ -57,24 +118,20 @@ public virtual int GenerateBytes(byte[] outBytes, int outOff, int len) // 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); + int cThreshold = (int)((oBytes + digestSize - 1) / digestSize); - byte[] dig = new byte[digest.GetDigestSize()]; + Span dig = digestSize <= 128 + ? stackalloc byte[digestSize] + : new byte[digestSize]; 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))); + DerSequence keyInfo = new DerSequence(algorithm, new DerOctetString(Pack.UInt32_To_BE(counter))); // OtherInfo Asn1EncodableVector v1 = new Asn1EncodableVector(keyInfo); @@ -88,28 +145,29 @@ public virtual int GenerateBytes(byte[] outBytes, int outOff, int len) byte[] other = new DerSequence(v1).GetDerEncoded(); - digest.BlockUpdate(other, 0, other.Length); - - digest.DoFinal(dig, 0); + m_digest.BlockUpdate(z); + m_digest.BlockUpdate(other); + m_digest.DoFinal(dig); - if (len > outLen) + int remaining = output.Length; + if (remaining > digestSize) { - Array.Copy(dig, 0, outBytes, outOff, outLen); - outOff += outLen; - len -= outLen; + dig.CopyTo(output); + output = output[digestSize..]; } else { - Array.Copy(dig, 0, outBytes, outOff, len); + dig[..remaining].CopyTo(output); } counter++; } - digest.Reset(); + m_digest.Reset(); return (int)oBytes; } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/kdf/ECDHKekGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/kdf/ECDHKekGenerator.cs index 14d5159..0859b04 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/kdf/ECDHKekGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/kdf/ECDHKekGenerator.cs @@ -13,10 +13,10 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.Kdf /** * X9.63 based key derivation function for ECDH CMS. */ - public class ECDHKekGenerator + public sealed class ECDHKekGenerator : IDerivationFunction { - private readonly IDerivationFunction kdf; + private readonly IDerivationFunction m_kdf; private DerObjectIdentifier algorithm; private int keySize; @@ -24,10 +24,10 @@ public class ECDHKekGenerator public ECDHKekGenerator(IDigest digest) { - this.kdf = new Kdf2BytesGenerator(digest); + m_kdf = new Kdf2BytesGenerator(digest); } - public virtual void Init(IDerivationParameters param) + public void Init(IDerivationParameters param) { DHKdfParameters parameters = (DHKdfParameters)param; @@ -36,12 +36,29 @@ public virtual void Init(IDerivationParameters param) this.z = parameters.GetZ(); // TODO Clone? } - public virtual IDigest Digest + public IDigest Digest => m_kdf.Digest; + + public int GenerateBytes(byte[] outBytes, int outOff, int length) { - get { return kdf.Digest; } + Check.OutputLength(outBytes, outOff, length, "output buffer too small"); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return GenerateBytes(outBytes.AsSpan(outOff, length)); +#else + // 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)))); + + m_kdf.Init(new KdfParameters(z, s.GetDerEncoded())); + + return m_kdf.GenerateBytes(outBytes, outOff, length); +#endif } - public virtual int GenerateBytes(byte[] outBytes, int outOff, int len) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int GenerateBytes(Span output) { // TODO Create an ASN.1 class for this (RFC3278) // ECC-CMS-SharedInfo @@ -49,10 +66,11 @@ public virtual int GenerateBytes(byte[] outBytes, int outOff, int len) new AlgorithmIdentifier(algorithm, DerNull.Instance), new DerTaggedObject(true, 2, new DerOctetString(Pack.UInt32_To_BE((uint)keySize)))); - kdf.Init(new KdfParameters(z, s.GetDerEncoded())); + m_kdf.Init(new KdfParameters(z, s.GetDerEncoded())); - return kdf.GenerateBytes(outBytes, outOff, len); + return m_kdf.GenerateBytes(output); } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/srp/SRP6Utilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/srp/SRP6Utilities.cs index 52941e9..bab787a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/srp/SRP6Utilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/agreement/srp/SRP6Utilities.cs @@ -22,7 +22,10 @@ public static BigInteger CalculateU(IDigest digest, BigInteger N, BigInteger A, public static BigInteger CalculateX(IDigest digest, BigInteger N, byte[] salt, byte[] identity, byte[] password) { - byte[] output = new byte[digest.GetDigestSize()]; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return CalculateX(digest, N, salt.AsSpan(), identity.AsSpan(), password.AsSpan()); +#else + byte[] output = new byte[digest.GetDigestSize()]; digest.BlockUpdate(identity, 0, identity.Length); digest.Update((byte)':'); @@ -34,9 +37,32 @@ public static BigInteger CalculateX(IDigest digest, BigInteger N, byte[] salt, b digest.DoFinal(output, 0); return new BigInteger(1, output); +#endif } - public static BigInteger GeneratePrivateValue(IDigest digest, BigInteger N, BigInteger g, SecureRandom random) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static BigInteger CalculateX(IDigest digest, BigInteger N, ReadOnlySpan salt, + ReadOnlySpan identity, ReadOnlySpan password) + { + int digestSize = digest.GetDigestSize(); + Span output = digestSize <= 128 + ? stackalloc byte[digestSize] + : new byte[digestSize]; + + digest.BlockUpdate(identity); + digest.Update((byte)':'); + digest.BlockUpdate(password); + digest.DoFinal(output); + + digest.BlockUpdate(salt); + digest.BlockUpdate(output); + digest.DoFinal(output); + + return new BigInteger(1, output); + } +#endif + + 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); @@ -97,60 +123,99 @@ public static BigInteger CalculateM2(IDigest digest, BigInteger N, BigInteger A, */ 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()]; + int paddedLength = (N.BitLength + 7) / 8; + int digestSize = digest.GetDigestSize(); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span bytes = paddedLength <= 512 + ? stackalloc byte[paddedLength] + : new byte[paddedLength]; + BigIntegers.AsUnsignedByteArray(S, bytes); + digest.BlockUpdate(bytes); + + Span output = digestSize <= 128 + ? stackalloc byte[digestSize] + : new byte[digestSize]; + digest.DoFinal(output); +#else + byte[] bytes = new byte[paddedLength]; + BigIntegers.AsUnsignedByteArray(S, bytes, 0, bytes.Length); + digest.BlockUpdate(bytes, 0, bytes.Length); + + byte[] output = new byte[digestSize]; digest.DoFinal(output, 0); +#endif + 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()]; + int paddedLength = (N.BitLength + 7) / 8; + int digestSize = digest.GetDigestSize(); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span bytes = paddedLength <= 512 + ? stackalloc byte[paddedLength] + : new byte[paddedLength]; + BigIntegers.AsUnsignedByteArray(n1, bytes); + digest.BlockUpdate(bytes); + BigIntegers.AsUnsignedByteArray(n2, bytes); + digest.BlockUpdate(bytes); + BigIntegers.AsUnsignedByteArray(n3, bytes); + digest.BlockUpdate(bytes); + + Span output = digestSize <= 128 + ? stackalloc byte[digestSize] + : new byte[digestSize]; + digest.DoFinal(output); +#else + byte[] bytes = new byte[paddedLength]; + BigIntegers.AsUnsignedByteArray(n1, bytes, 0, bytes.Length); + digest.BlockUpdate(bytes, 0, bytes.Length); + BigIntegers.AsUnsignedByteArray(n2, bytes, 0, bytes.Length); + digest.BlockUpdate(bytes, 0, bytes.Length); + BigIntegers.AsUnsignedByteArray(n3, bytes, 0, bytes.Length); + digest.BlockUpdate(bytes, 0, bytes.Length); + + byte[] output = new byte[digestSize]; digest.DoFinal(output, 0); +#endif 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()]; + int paddedLength = (N.BitLength + 7) / 8; + int digestSize = digest.GetDigestSize(); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span bytes = paddedLength <= 512 + ? stackalloc byte[paddedLength] + : new byte[paddedLength]; + BigIntegers.AsUnsignedByteArray(n1, bytes); + digest.BlockUpdate(bytes); + BigIntegers.AsUnsignedByteArray(n2, bytes); + digest.BlockUpdate(bytes); + + Span output = digestSize <= 128 + ? stackalloc byte[digestSize] + : new byte[digestSize]; + digest.DoFinal(output); +#else + byte[] bytes = new byte[paddedLength]; + BigIntegers.AsUnsignedByteArray(n1, bytes, 0, bytes.Length); + digest.BlockUpdate(bytes, 0, bytes.Length); + BigIntegers.AsUnsignedByteArray(n2, bytes, 0, bytes.Length); + digest.BlockUpdate(bytes, 0, bytes.Length); + + byte[] output = new byte[digestSize]; digest.DoFinal(output, 0); +#endif - 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; - } + return new BigInteger(1, output); + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake2bDigest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake2bDigest.cs index 07c5717..34a63bc 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake2bDigest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake2bDigest.cs @@ -1,6 +1,9 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER +using System.Runtime.CompilerServices; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -30,18 +33,18 @@ This implementation does not support the Tree Hashing Mode. */ /** - * Implementation of the cryptographic hash function Blakbe2b. - *

+ * Implementation of the cryptographic hash function Blake2b. + *

* 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 + public sealed class Blake2bDigest : IDigest { // Blake2b Initialization Vector: @@ -278,12 +281,10 @@ private void InitializeInternalState() * * @param b the input byte to be entered. */ - public virtual void Update(byte b) + public 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; + int remainingLength = BLOCK_LENGTH_BYTES - bufferPos; if (remainingLength == 0) { // full buffer t0 += BLOCK_LENGTH_BYTES; @@ -291,7 +292,11 @@ public virtual void Update(byte b) { // if message > 2^64 t1++; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Compress(buffer); +#else Compress(buffer, 0); +#endif Array.Clear(buffer, 0, buffer.Length);// clear buffer buffer[0] = b; bufferPos = 1; @@ -300,7 +305,6 @@ public virtual void Update(byte b) { buffer[bufferPos] = b; bufferPos++; - return; } } @@ -311,11 +315,14 @@ public virtual void Update(byte b) * @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) + public void BlockUpdate(byte[] message, int offset, int len) { if (message == null || len == 0) return; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BlockUpdate(message.AsSpan(offset, len)); +#else int remainingLength = 0; // left bytes of buffer if (bufferPos != 0) @@ -325,8 +332,7 @@ public virtual void BlockUpdate(byte[] message, int offset, int len) remainingLength = BLOCK_LENGTH_BYTES - bufferPos; if (remainingLength < len) { // full buffer + at least 1 byte - Array.Copy(message, offset, buffer, bufferPos, - remainingLength); + Array.Copy(message, offset, buffer, bufferPos, remainingLength); t0 += BLOCK_LENGTH_BYTES; if (t0 == 0) { // if message > 2^64 @@ -359,11 +365,64 @@ public virtual void BlockUpdate(byte[] message, int offset, int len) } // fill the buffer with left bytes, this might be a full block - Array.Copy(message, messagePos, buffer, 0, offset + len - - messagePos); + Array.Copy(message, messagePos, buffer, 0, offset + len - messagePos); bufferPos += offset + len - messagePos; +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + if (input.IsEmpty) + return; + + int remainingLength = 0; // left bytes of buffer + + if (bufferPos != 0) + { // commenced, incomplete buffer + + // complete the buffer: + remainingLength = BLOCK_LENGTH_BYTES - bufferPos; + if (remainingLength < input.Length) + { // full buffer + at least 1 byte + input[..remainingLength].CopyTo(buffer.AsSpan(bufferPos)); + t0 += BLOCK_LENGTH_BYTES; + if (t0 == 0) + { // if message > 2^64 + t1++; + } + Compress(buffer); + bufferPos = 0; + Array.Clear(buffer, 0, buffer.Length);// clear buffer + } + else + { + input.CopyTo(buffer.AsSpan(bufferPos)); + bufferPos += input.Length; + return; + } + } + + // process blocks except last block (also if last block is full) + int messagePos; + int blockWiseLastPos = input.Length - BLOCK_LENGTH_BYTES; + for (messagePos = remainingLength; messagePos < blockWiseLastPos; messagePos += BLOCK_LENGTH_BYTES) + { // block wise 128 bytes + // without buffer: + t0 += BLOCK_LENGTH_BYTES; + if (t0 == 0) + { + t1++; + } + Compress(input[messagePos..]); + } + + // fill the buffer with left bytes, this might be a full block + input[messagePos..].CopyTo(buffer.AsSpan()); + bufferPos += input.Length - messagePos; + } +#endif + /** * close the digest, producing the final digest value. The doFinal * call leaves the digest reset. @@ -372,8 +431,11 @@ public virtual void BlockUpdate(byte[] message, int offset, int len) * @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) + public int DoFinal(byte[] output, int outOffset) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(output.AsSpan(outOffset)); +#else f0 = 0xFFFFFFFFFFFFFFFFUL; t0 += (ulong)bufferPos; if (bufferPos > 0 && t0 == 0) @@ -384,18 +446,43 @@ public virtual int DoFinal(byte[] output, int outOffset) 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++) + int full = digestLength >> 3, partial = digestLength & 7; + Pack.UInt64_To_LE(chainValue, 0, full, output, outOffset); + if (partial > 0) + { + byte[] bytes = new byte[8]; + Pack.UInt64_To_LE(chainValue[full], bytes, 0); + Array.Copy(bytes, 0, output, outOffset + digestLength - partial, partial); + } + + Array.Clear(chainValue, 0, chainValue.Length); + + Reset(); + + return digestLength; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + f0 = 0xFFFFFFFFFFFFFFFFUL; + t0 += (ulong)bufferPos; + if (bufferPos > 0 && t0 == 0) { - byte[] bytes = Pack.UInt64_To_LE(chainValue[i]); + t1++; + } + Compress(buffer); + Array.Clear(buffer, 0, buffer.Length);// Holds eventually the key if input is null + Array.Clear(internalState, 0, internalState.Length); - 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)); - } + int full = digestLength >> 3, partial = digestLength & 7; + Pack.UInt64_To_LE(chainValue.AsSpan(0, full), output); + if (partial > 0) + { + Span bytes = stackalloc byte[8]; + Pack.UInt64_To_LE(chainValue[full], bytes); + bytes[..partial].CopyTo(output[(digestLength - partial)..]); } Array.Clear(chainValue, 0, chainValue.Length); @@ -404,13 +491,14 @@ public virtual int DoFinal(byte[] output, int outOffset) return digestLength; } +#endif /** * 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() + public void Reset() { bufferPos = 0; f0 = 0L; @@ -426,16 +514,42 @@ public virtual void Reset() Init(); } - private void Compress(byte[] message, int messagePos) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void Compress(ReadOnlySpan message) { InitializeInternalState(); - ulong[] m = new ulong[16]; - for (int j = 0; j < 16; j++) + Span m = stackalloc ulong[16]; + Pack.LE_To_UInt64(message, m); + + for (int round = 0; round < ROUNDS; round++) { - m[j] = Pack.LE_To_UInt64(message, messagePos + j * 8); + // 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]; + } + } +#else + private void Compress(byte[] message, int messagePos) + { + InitializeInternalState(); + + ulong[] m = new ulong[16]; + Pack.LE_To_UInt64(message, messagePos, m); + for (int round = 0; round < ROUNDS; round++) { // G apply to columns of internalState:m[blake2b_sigma[round][2 * blockPos]] /+1 @@ -456,7 +570,11 @@ private void Compress(byte[] message, int messagePos) chainValue[offset] = chainValue[offset] ^ internalState[offset] ^ internalState[offset + 8]; } } +#endif +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif private void G(ulong m1, ulong m2, int posA, int posB, int posC, int posD) { internalState[posA] = internalState[posA] + internalState[posB] + m1; @@ -479,17 +597,14 @@ private static ulong Rotr64(ulong x, int rot) * * @return the algorithm name */ - public virtual string AlgorithmName - { - get { return "BLAKE2b"; } - } + public string AlgorithmName => "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() + public int GetDigestSize() { return digestLength; } @@ -500,7 +615,7 @@ public virtual int GetDigestSize() * * @return byte length of the digests internal buffer. */ - public virtual int GetByteLength() + public int GetByteLength() { return BLOCK_LENGTH_BYTES; } @@ -509,7 +624,7 @@ public virtual int GetByteLength() * Overwrite the key * if it is no longer used (zeroization) */ - public virtual void ClearKey() + public void ClearKey() { if (key != null) { @@ -522,7 +637,7 @@ public virtual void ClearKey() * Overwrite the salt (pepper) if it * is secret and no longer used (zeroization) */ - public virtual void ClearSalt() + public void ClearSalt() { if (salt != null) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake2sDigest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake2sDigest.cs index fb94488..9460195 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake2sDigest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake2sDigest.cs @@ -1,6 +1,9 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER +using System.Runtime.CompilerServices; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -42,7 +45,7 @@ This implementation does not support the Tree Hashing Mode. * BLAKE2s is optimized for 32-bit platforms and produces digests of any size * between 1 and 32 bytes. */ - public class Blake2sDigest + public sealed class Blake2sDigest : IDigest { /** @@ -85,16 +88,13 @@ public class Blake2sDigest 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; - */ + // The Tree Hashing Mode is not supported but these are used for the XOF implementation + private int fanout = 1; // 0-255 + private int depth = 1; // 0-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() @@ -147,8 +147,19 @@ public Blake2sDigest(Blake2sDigest digest) this.keyLength = digest.keyLength; this.key = Arrays.Clone(digest.key); this.digestLength = digest.digestLength; + this.internalState = Arrays.Clone(digest.internalState); this.chainValue = Arrays.Clone(digest.chainValue); + this.t0 = digest.t0; + this.t1 = digest.t1; + this.f0 = digest.f0; + this.salt = Arrays.Clone(digest.salt); this.personalization = Arrays.Clone(digest.personalization); + this.fanout = digest.fanout; + this.depth = digest.depth; + this.leafLength = digest.leafLength; + this.nodeOffset = digest.nodeOffset; + this.nodeDepth = digest.nodeDepth; + this.innerHashLength = digest.innerHashLength; } /** @@ -161,10 +172,9 @@ public Blake2sDigest(int digestBits) if (digestBits < 8 || digestBits > 256 || digestBits % 8 != 0) throw new ArgumentException("BLAKE2s digest bit length must be a multiple of 8 and not greater than 256"); - buffer = new byte[BLOCK_LENGTH_BYTES]; - keyLength = 0; digestLength = digestBits / 8; - Init(); + + Init(null, null, null); } /** @@ -178,21 +188,7 @@ public Blake2sDigest(int digestBits) */ public Blake2sDigest(byte[] key) { - buffer = new byte[BLOCK_LENGTH_BYTES]; - if (key != null) - { - if (key.Length > 32) - throw new ArgumentException("Keys > 32 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 - } - digestLength = 32; - Init(); + Init(null, null, key); } /** @@ -208,65 +204,79 @@ public Blake2sDigest(byte[] key) * @param salt 8 bytes or null * @param personalization 8 bytes or null */ - public Blake2sDigest(byte[] key, int digestBytes, byte[] salt, - byte[] personalization) + public Blake2sDigest(byte[] key, int digestBytes, byte[] salt, byte[] personalization) { if (digestBytes < 1 || digestBytes > 32) throw new ArgumentException("Invalid digest length (required: 1 - 32)"); this.digestLength = digestBytes; - this.buffer = new byte[BLOCK_LENGTH_BYTES]; - if (salt != null) - { - if (salt.Length != 8) - throw new ArgumentException("Salt length must be exactly 8 bytes"); + Init(salt, personalization, key); + } - this.salt = new byte[8]; - Array.Copy(salt, 0, this.salt, 0, salt.Length); - } - if (personalization != null) - { - if (personalization.Length != 8) - throw new ArgumentException("Personalization length must be exactly 8 bytes"); + // XOF root hash parameters + internal Blake2sDigest(int digestBytes, byte[] key, byte[] salt, byte[] personalization, long offset) + { + digestLength = digestBytes; + nodeOffset = offset; - this.personalization = new byte[8]; - Array.Copy(personalization, 0, this.personalization, 0, personalization.Length); - } - if (key != null) - { - if (key.Length > 32) - throw new ArgumentException("Keys > 32 bytes are not supported"); + Init(salt, personalization, key); + } - this.key = new byte[key.Length]; - Array.Copy(key, 0, this.key, 0, key.Length); + // XOF internal hash parameters + internal Blake2sDigest(int digestBytes, int hashLength, long offset) + { + digestLength = digestBytes; + nodeOffset = offset; + fanout = 0; + depth = 0; + leafLength = hashLength; + innerHashLength = hashLength; + nodeDepth = 0; + + Init(null, null, null); + } + // initialize the digest's parameters + private void Init(byte[] salt, byte[] personalization, byte[] key) + { + buffer = new byte[BLOCK_LENGTH_BYTES]; + + if (key != null && key.Length > 0) + { keyLength = key.Length; - Array.Copy(key, 0, buffer, 0, key.Length); + if (keyLength > 32) + throw new ArgumentException("Keys > 32 bytes are not supported"); + + this.key = new byte[keyLength]; + Array.Copy(key, 0, this.key, 0, keyLength); + Array.Copy(key, 0, buffer, 0, keyLength); bufferPos = BLOCK_LENGTH_BYTES; // zero padding } - Init(); - } - // initialize chainValue - private void Init() - { if (chainValue == null) { chainValue = new uint[8]; - chainValue[0] = blake2s_IV[0] ^ (uint)(digestLength | (keyLength << 8) | 0x1010000); - // 0x1010000 = ((fanout << 16) | (depth << 24)); - // with fanout = 1; depth = 0; - chainValue[1] = blake2s_IV[1];// ^ leafLength; with leafLength = 0; - chainValue[2] = blake2s_IV[2];// ^ nodeOffset; with nodeOffset = 0; - chainValue[3] = blake2s_IV[3];// ^ ( (nodeOffset << 32) | (nodeDepth << 16) | (innerHashLength << 24) ); - // with nodeDepth = 0; innerHashLength = 0; + chainValue[0] = blake2s_IV[0] + ^ (uint)(digestLength | (keyLength << 8) | ((fanout << 16) | (depth << 24))); + chainValue[1] = blake2s_IV[1] ^ (uint)leafLength; + + int nofHi = (int)(nodeOffset >> 32); + int nofLo = (int)nodeOffset; + chainValue[2] = blake2s_IV[2] ^ (uint)nofLo; + chainValue[3] = blake2s_IV[3] ^ (uint)(nofHi | (nodeDepth << 16) | (innerHashLength << 24)); chainValue[4] = blake2s_IV[4]; chainValue[5] = blake2s_IV[5]; if (salt != null) { + if (salt.Length != 8) + throw new ArgumentException("Salt length must be exactly 8 bytes"); + + this.salt = new byte[8]; + Array.Copy(salt, 0, this.salt, 0, salt.Length); + chainValue[4] ^= Pack.LE_To_UInt32(salt, 0); chainValue[5] ^= Pack.LE_To_UInt32(salt, 4); } @@ -275,6 +285,12 @@ private void Init() chainValue[7] = blake2s_IV[7]; if (personalization != null) { + if (personalization.Length != 8) + throw new ArgumentException("Personalization length must be exactly 8 bytes"); + + this.personalization = new byte[8]; + Array.Copy(personalization, 0, this.personalization, 0, personalization.Length); + chainValue[6] ^= Pack.LE_To_UInt32(personalization, 0); chainValue[7] ^= Pack.LE_To_UInt32(personalization, 4); } @@ -297,12 +313,10 @@ private void InitializeInternalState() * * @param b the input byte to be entered. */ - public virtual void Update(byte b) + public void Update(byte b) { - int remainingLength; // left bytes of buffer - // process the buffer if full else add to buffer: - remainingLength = BLOCK_LENGTH_BYTES - bufferPos; + int remainingLength = BLOCK_LENGTH_BYTES - bufferPos; if (remainingLength == 0) { // full buffer t0 += BLOCK_LENGTH_BYTES; @@ -310,7 +324,11 @@ public virtual void Update(byte b) { // if message > 2^32 t1++; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Compress(buffer); +#else Compress(buffer, 0); +#endif Array.Clear(buffer, 0, buffer.Length);// clear buffer buffer[0] = b; bufferPos = 1; @@ -329,11 +347,14 @@ public virtual void Update(byte b) * @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) + public void BlockUpdate(byte[] message, int offset, int len) { if (message == null || len == 0) return; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BlockUpdate(message.AsSpan(offset, len)); +#else int remainingLength = 0; // left bytes of buffer if (bufferPos != 0) @@ -381,7 +402,63 @@ public virtual void BlockUpdate(byte[] message, int offset, int len) Array.Copy(message, messagePos, buffer, 0, offset + len - messagePos); bufferPos += offset + len - messagePos; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + if (input.IsEmpty) + return; + + int remainingLength = 0; // left bytes of buffer + + if (bufferPos != 0) + { // commenced, incomplete buffer + + // complete the buffer: + remainingLength = BLOCK_LENGTH_BYTES - bufferPos; + if (remainingLength < input.Length) + { // full buffer + at least 1 byte + input[..remainingLength].CopyTo(buffer.AsSpan(bufferPos)); + t0 += BLOCK_LENGTH_BYTES; + if (t0 == 0) + { // if message > 2^32 + t1++; + } + Compress(buffer); + bufferPos = 0; + Array.Clear(buffer, 0, buffer.Length);// clear buffer + } + else + { + input.CopyTo(buffer.AsSpan(bufferPos)); + bufferPos += input.Length; + return; + } + } + + // process blocks except last block (also if last block is full) + int messagePos; + int blockWiseLastPos = input.Length - BLOCK_LENGTH_BYTES; + for (messagePos = remainingLength; + messagePos < blockWiseLastPos; + messagePos += BLOCK_LENGTH_BYTES) + { // block wise 64 bytes + // without buffer: + t0 += BLOCK_LENGTH_BYTES; + if (t0 == 0) + { + t1++; + } + Compress(input[messagePos..]); + } + + // fill the buffer with left bytes, this might be a full block + input[messagePos..].CopyTo(buffer.AsSpan()); + bufferPos += input.Length - messagePos; } +#endif /** * Close the digest, producing the final digest value. The doFinal() call @@ -390,8 +467,11 @@ public virtual void BlockUpdate(byte[] message, int offset, int len) * @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) + public int DoFinal(byte[] output, int outOffset) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(output.AsSpan(outOffset)); +#else f0 = 0xFFFFFFFFU; t0 += (uint)bufferPos; // bufferPos may be < 64, so (t0 == 0) does not work @@ -404,18 +484,45 @@ public virtual int DoFinal(byte[] output, int outOffset) 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 * 4 < digestLength); i++) + int full = digestLength >> 2, partial = digestLength & 3; + Pack.UInt32_To_LE(chainValue, 0, full, output, outOffset); + if (partial > 0) { - byte[] bytes = Pack.UInt32_To_LE(chainValue[i]); + byte[] bytes = new byte[4]; + Pack.UInt32_To_LE(chainValue[full], bytes, 0); + Array.Copy(bytes, 0, output, outOffset + digestLength - partial, partial); + } - if (i * 4 < digestLength - 4) - { - Array.Copy(bytes, 0, output, outOffset + i * 4, 4); - } - else - { - Array.Copy(bytes, 0, output, outOffset + i * 4, digestLength - (i * 4)); - } + Array.Clear(chainValue, 0, chainValue.Length); + + Reset(); + + return digestLength; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + f0 = 0xFFFFFFFFU; + t0 += (uint)bufferPos; + // bufferPos may be < 64, so (t0 == 0) does not work + // for 2^32 < message length > 2^32 - 63 + if ((t0 < 0) && (bufferPos > -t0)) + { + t1++; + } + Compress(buffer); + Array.Clear(buffer, 0, buffer.Length);// Holds eventually the key if input is null + Array.Clear(internalState, 0, internalState.Length); + + int full = digestLength >> 2, partial = digestLength & 3; + Pack.UInt32_To_LE(chainValue.AsSpan(0, full), output); + if (partial > 0) + { + Span bytes = stackalloc byte[4]; + Pack.UInt32_To_LE(chainValue[full], bytes); + bytes[..partial].CopyTo(output[(digestLength - partial)..]); } Array.Clear(chainValue, 0, chainValue.Length); @@ -424,12 +531,13 @@ public virtual int DoFinal(byte[] output, int outOffset) return digestLength; } +#endif /** * Reset the digest back to its initial state. The key, the salt and the * personal string will remain for further computations. */ - public virtual void Reset() + public void Reset() { bufferPos = 0; f0 = 0; @@ -442,24 +550,49 @@ public virtual void Reset() Array.Copy(key, 0, buffer, 0, key.Length); bufferPos = BLOCK_LENGTH_BYTES; // zero padding } - Init(); + + Init(this.salt, this.personalization, this.key); } - private void Compress(byte[] message, int messagePos) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void Compress(ReadOnlySpan message) { InitializeInternalState(); - uint[] m = new uint[16]; - for (int j = 0; j < 16; j++) + Span m = stackalloc uint[16]; + Pack.LE_To_UInt32(message, m); + + for (int round = 0; round < ROUNDS; round++) { - m[j] = Pack.LE_To_UInt32(message, messagePos + j * 4); + // G apply to columns of internalState: m[blake2s_sigma[round][2 * blockPos]] /+1 + G(m[blake2s_sigma[round, 0]], m[blake2s_sigma[round, 1]], 0, 4, 8, 12); + G(m[blake2s_sigma[round, 2]], m[blake2s_sigma[round, 3]], 1, 5, 9, 13); + G(m[blake2s_sigma[round, 4]], m[blake2s_sigma[round, 5]], 2, 6, 10, 14); + G(m[blake2s_sigma[round, 6]], m[blake2s_sigma[round, 7]], 3, 7, 11, 15); + // G apply to diagonals of internalState: + G(m[blake2s_sigma[round, 8]], m[blake2s_sigma[round, 9]], 0, 5, 10, 15); + G(m[blake2s_sigma[round, 10]], m[blake2s_sigma[round, 11]], 1, 6, 11, 12); + G(m[blake2s_sigma[round, 12]], m[blake2s_sigma[round, 13]], 2, 7, 8, 13); + G(m[blake2s_sigma[round, 14]], m[blake2s_sigma[round, 15]], 3, 4, 9, 14); } - for (int round = 0; round < ROUNDS; round++) + // update chain values: + for (int offset = 0; offset < chainValue.Length; offset++) { + chainValue[offset] = chainValue[offset] ^ internalState[offset] ^ internalState[offset + 8]; + } + } +#else + private void Compress(byte[] message, int messagePos) + { + InitializeInternalState(); + + uint[] m = new uint[16]; + Pack.LE_To_UInt32(message, messagePos, m); - // G apply to columns of internalState:m[blake2s_sigma[round][2 * - // blockPos]] /+1 + for (int round = 0; round < ROUNDS; round++) + { + // G apply to columns of internalState: m[blake2s_sigma[round][2 * blockPos]] /+1 G(m[blake2s_sigma[round,0]], m[blake2s_sigma[round,1]], 0, 4, 8, 12); G(m[blake2s_sigma[round,2]], m[blake2s_sigma[round,3]], 1, 5, 9, 13); G(m[blake2s_sigma[round,4]], m[blake2s_sigma[round,5]], 2, 6, 10, 14); @@ -477,22 +610,21 @@ private void Compress(byte[] message, int messagePos) chainValue[offset] = chainValue[offset] ^ internalState[offset] ^ internalState[offset + 8]; } } +#endif +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif private void G(uint m1, uint m2, int posA, int posB, int posC, int posD) { internalState[posA] = internalState[posA] + internalState[posB] + m1; - internalState[posD] = rotr32(internalState[posD] ^ internalState[posA], 16); + internalState[posD] = Integers.RotateRight(internalState[posD] ^ internalState[posA], 16); internalState[posC] = internalState[posC] + internalState[posD]; - internalState[posB] = rotr32(internalState[posB] ^ internalState[posC], 12); + internalState[posB] = Integers.RotateRight(internalState[posB] ^ internalState[posC], 12); internalState[posA] = internalState[posA] + internalState[posB] + m2; - internalState[posD] = rotr32(internalState[posD] ^ internalState[posA], 8); + internalState[posD] = Integers.RotateRight(internalState[posD] ^ internalState[posA], 8); internalState[posC] = internalState[posC] + internalState[posD]; - internalState[posB] = rotr32(internalState[posB] ^ internalState[posC], 7); - } - - private uint rotr32(uint x, int rot) - { - return x >> rot | x << -rot; + internalState[posB] = Integers.RotateRight(internalState[posB] ^ internalState[posC], 7); } /** @@ -500,17 +632,14 @@ private uint rotr32(uint x, int rot) * * @return the algorithm name */ - public virtual string AlgorithmName - { - get { return "BLAKE2s"; } - } + public string AlgorithmName => "BLAKE2s"; /** * 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() + public int GetDigestSize() { return digestLength; } @@ -521,7 +650,7 @@ public virtual int GetDigestSize() * * @return byte length of the digest's internal buffer. */ - public virtual int GetByteLength() + public int GetByteLength() { return BLOCK_LENGTH_BYTES; } @@ -529,7 +658,7 @@ public virtual int GetByteLength() /** * Overwrite the key if it is no longer used (zeroization). */ - public virtual void ClearKey() + public void ClearKey() { if (key != null) { @@ -542,7 +671,7 @@ public virtual void ClearKey() * Overwrite the salt (pepper) if it is secret and no longer used * (zeroization). */ - public virtual void ClearSalt() + public void ClearSalt() { if (salt != null) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake2xsDigest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake2xsDigest.cs new file mode 100644 index 0000000..a981223 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake2xsDigest.cs @@ -0,0 +1,372 @@ +#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.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/blake2x.pdf + */ + + /** + * Implementation of the eXtendable Output Function (XOF) BLAKE2xs. + *

+ * BLAKE2xs offers a built-in keying mechanism to be used directly + * for authentication ("Prefix-MAC") rather than a HMAC construction. + *

+ * BLAKE2xs offers a built-in support for a salt for randomized hashing + * and a personal string for defining a unique hash function for each application. + *

+ * BLAKE2xs is optimized for 32-bit platforms and produces digests of any size + * between 1 and 2^16-2 bytes. The length can also be unknown and then the maximum + * length will be 2^32 blocks of 32 bytes. + */ + public sealed class Blake2xsDigest + : IXof + { + /** + * Magic number to indicate an unknown length of digest + */ + public const int UnknownDigestLength = 65535; + + private const int DigestLength = 32; + private const long MaxNumberBlocks = 1L << 32; + + /** + * Expected digest length for the xof. It can be unknown. + */ + private int digestLength; + + /** + * Root hash that will take the updates + */ + private Blake2sDigest hash; + + /** + * Digest of the root hash + */ + private byte[] h0 = null; + + /** + * Digest of each round of the XOF + */ + private byte[] buf = new byte[32]; + + /** + * Current position for a round + */ + private int bufPos = 32; + + /** + * Overall position of the digest. It is useful when the length is known + * in advance to get last block length. + */ + private int digestPos = 0; + + /** + * Keep track of the round number to detect the end of the digest after + * 2^32 blocks of 32 bytes. + */ + private long blockPos = 0; + + /** + * Current node offset incremented by 1 every round. + */ + private long nodeOffset; + + /** + * BLAKE2xs for hashing with unknown digest length + */ + public Blake2xsDigest() + : this(UnknownDigestLength) + { + } + + /** + * BLAKE2xs for hashing + * + * @param digestBytes The desired digest length in bytes. Must be above 1 and less than 2^16-1 + */ + public Blake2xsDigest(int digestBytes) + : this(digestBytes, null, null, null) + { + } + + /** + * BLAKE2xs with key + * + * @param digestBytes The desired digest length in bytes. Must be above 1 and less than 2^16-1 + * @param key A key up to 32 bytes or null + */ + public Blake2xsDigest(int digestBytes, byte[] key) + : this(digestBytes, key, null, null) + { + } + + /** + * BLAKE2xs with key, salt and personalization + * + * @param digestBytes The desired digest length in bytes. Must be above 1 and less than 2^16-1 + * @param key A key up to 32 bytes or null + * @param salt 8 bytes or null + * @param personalization 8 bytes or null + */ + public Blake2xsDigest(int digestBytes, byte[] key, byte[] salt, byte[] personalization) + { + if (digestBytes < 1 || digestBytes > UnknownDigestLength) + throw new ArgumentException("BLAKE2xs digest length must be between 1 and 2^16-1"); + + digestLength = digestBytes; + nodeOffset = ComputeNodeOffset(); + hash = new Blake2sDigest(DigestLength, key, salt, personalization, nodeOffset); + } + + public Blake2xsDigest(Blake2xsDigest digest) + { + digestLength = digest.digestLength; + hash = new Blake2sDigest(digest.hash); + h0 = Arrays.Clone(digest.h0); + buf = Arrays.Clone(digest.buf); + bufPos = digest.bufPos; + digestPos = digest.digestPos; + blockPos = digest.blockPos; + nodeOffset = digest.nodeOffset; + } + + /** + * Return the algorithm name. + * + * @return the algorithm name + */ + public string AlgorithmName => "BLAKE2xs"; + + /** + * 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 int GetDigestSize() => digestLength; + + /** + * Return the size in bytes of the internal buffer the digest applies its + * compression function to. + * + * @return byte length of the digest's internal buffer. + */ + public int GetByteLength() => hash.GetByteLength(); + + /** + * Return the maximum size in bytes the digest can produce when the length + * is unknown + * + * @return byte length of the largest digest with unknown length + */ + public long GetUnknownMaxLength() + { + return MaxNumberBlocks * DigestLength; + } + + /** + * Update the message digest with a single byte. + * + * @param in the input byte to be entered. + */ + public void Update(byte b) + { + hash.Update(b); + } + + /** + * Update the message digest with a block of bytes. + * + * @param in 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. + */ + public void BlockUpdate(byte[] input, int inOff, int inLen) + { + hash.BlockUpdate(input, inOff, inLen); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + hash.BlockUpdate(input); + } +#endif + + /** + * Reset the digest back to its initial state. The key, the salt and the + * personal string will remain for further computations. + */ + public void Reset() + { + hash.Reset(); + + h0 = null; + bufPos = DigestLength; + digestPos = 0; + blockPos = 0; + nodeOffset = ComputeNodeOffset(); + } + + /** + * 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 int DoFinal(byte[] output, int outOff) + { + return OutputFinal(output, outOff, digestLength); + } + + /** + * Close the digest, producing the final digest value. The doFinal() call + * leaves the digest reset. Key, salt, personal string remain. + * + * @param out output array to write the output bytes to. + * @param outOff offset to start writing the bytes at. + * @param outLen the number of output bytes requested. + */ + public int OutputFinal(byte[] output, int outOff, int outLen) + { + int ret = Output(output, outOff, outLen); + + Reset(); + + return ret; + } + + /** + * 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. + * + * @param out output array to write the output bytes to. + * @param outOff offset to start writing the bytes at. + * @param outLen the number of output bytes requested. + * @return the number of bytes written + */ + public int Output(byte[] output, int outOff, int outLen) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return Output(output.AsSpan(outOff, outLen)); +#else + if (h0 == null) + { + h0 = new byte[hash.GetDigestSize()]; + hash.DoFinal(h0, 0); + } + + if (digestLength != UnknownDigestLength) + { + if (digestPos + outLen > digestLength) + throw new ArgumentException("Output length is above the digest length"); + } + else if (blockPos << 5 >= GetUnknownMaxLength()) + { + throw new ArgumentException("Maximum length is 2^32 blocks of 32 bytes"); + } + + for (int i = 0; i < outLen; i++) + { + if (bufPos >= DigestLength) + { + Blake2sDigest h = new Blake2sDigest(ComputeStepLength(), DigestLength, nodeOffset); + h.BlockUpdate(h0, 0, h0.Length); + + Arrays.Fill(buf, 0); + h.DoFinal(buf, 0); + bufPos = 0; + nodeOffset++; + blockPos++; + } + output[outOff + i] = buf[bufPos]; + bufPos++; + digestPos++; + } + + return outLen; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + return OutputFinal(output[..digestLength]); + } + + public int OutputFinal(Span output) + { + int ret = Output(output); + + Reset(); + + return ret; + } + + public int Output(Span output) + { + int outLen = output.Length; + if (h0 == null) + { + h0 = new byte[hash.GetDigestSize()]; + hash.DoFinal(h0); + } + + if (digestLength != UnknownDigestLength) + { + if (digestPos + outLen > digestLength) + throw new ArgumentException("Output length is above the digest length"); + } + else if (blockPos << 5 >= GetUnknownMaxLength()) + { + throw new ArgumentException("Maximum length is 2^32 blocks of 32 bytes"); + } + + for (int i = 0; i < outLen; i++) + { + if (bufPos >= DigestLength) + { + Blake2sDigest h = new Blake2sDigest(ComputeStepLength(), DigestLength, nodeOffset); + h.BlockUpdate(h0); + + Arrays.Fill(buf, 0); + h.DoFinal(buf); + bufPos = 0; + nodeOffset++; + blockPos++; + } + output[i] = buf[bufPos]; + bufPos++; + digestPos++; + } + + return outLen; + } +#endif + + // get the next round length. If the length is unknown, the digest length is always the maximum. + private int ComputeStepLength() + { + if (digestLength == UnknownDigestLength) + return DigestLength; + + return System.Math.Min(DigestLength, digestLength - digestPos); + } + + private long ComputeNodeOffset() + { + return digestLength * 0x100000000L; + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake2xsDigest.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake2xsDigest.cs.meta new file mode 100644 index 0000000..551ef9f --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake2xsDigest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f547ae5de0f059b4b9098a1dcb31da14 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake3Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake3Digest.cs new file mode 100644 index 0000000..28e9d99 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake3Digest.cs @@ -0,0 +1,1051 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.Collections.Generic; +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER +using System.Runtime.CompilerServices; +#endif + +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.Digests +{ + public sealed class Blake3Digest + : IDigest, IMemoable, IXof + { + /** + * Already outputting error. + */ + private const string ERR_OUTPUTTING = "Already outputting"; + + /** + * Number of Words. + */ + private const int NUMWORDS = 8; + + /** + * Number of Rounds. + */ + private const int ROUNDS = 7; + + /** + * Buffer length. + */ + private const int BLOCKLEN = NUMWORDS * Integers.NumBytes * 2; + + /** + * Chunk length. + */ + private const int CHUNKLEN = 1024; + + /** + * ChunkStart Flag. + */ + private const int CHUNKSTART = 1; + + /** + * ChunkEnd Flag. + */ + private const int CHUNKEND = 2; + + /** + * Parent Flag. + */ + private const int PARENT = 4; + + /** + * Root Flag. + */ + private const int ROOT = 8; + + /** + * KeyedHash Flag. + */ + private const int KEYEDHASH = 16; + + /** + * DeriveContext Flag. + */ + private const int DERIVECONTEXT = 32; + + /** + * DeriveKey Flag. + */ + private const int DERIVEKEY = 64; + + /** + * Chaining0 State Locations. + */ + private const int CHAINING0 = 0; + + /** + * Chaining1 State Location. + */ + private const int CHAINING1 = 1; + + /** + * Chaining2 State Location. + */ + private const int CHAINING2 = 2; + + /** + * Chaining3 State Location. + */ + private const int CHAINING3 = 3; + + /** + * Chaining4 State Location. + */ + private const int CHAINING4 = 4; + + /** + * Chaining5 State Location. + */ + private const int CHAINING5 = 5; + + /** + * Chaining6 State Location. + */ + private const int CHAINING6 = 6; + + /** + * Chaining7 State Location. + */ + private const int CHAINING7 = 7; + + /** + * IV0 State Locations. + */ + private const int IV0 = 8; + + /** + * IV1 State Location. + */ + private const int IV1 = 9; + + /** + * IV2 State Location. + */ + private const int IV2 = 10; + + /** + * IV3 State Location. + */ + private const int IV3 = 11; + + /** + * Count0 State Location. + */ + private const int COUNT0 = 12; + + /** + * Count1 State Location. + */ + private const int COUNT1 = 13; + + /** + * DataLen State Location. + */ + private const int DATALEN = 14; + + /** + * Flags State Location. + */ + private const int FLAGS = 15; + + /** + * Message word permutations. + */ + private static readonly byte[] SIGMA = { 2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8 }; + + /** + * Blake3 Initialization Vector. + */ + private static readonly uint[] IV = { + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + }; + + /** + * The byte input/output buffer. + */ + private readonly byte[] m_theBuffer = new byte[BLOCKLEN]; + + /** + * The key. + */ + private readonly uint[] m_theK = new uint[NUMWORDS]; + + /** + * The chaining value. + */ + private readonly uint[] m_theChaining = new uint[NUMWORDS]; + + /** + * The state. + */ + private readonly uint[] m_theV = new uint[NUMWORDS << 1]; + + /** + * The message Buffer. + */ + private readonly uint[] m_theM = new uint[NUMWORDS << 1]; + + /** + * The indices. + */ + private readonly byte[] m_theIndices = new byte[NUMWORDS << 1]; + + /** + * The chainingStack. + */ + private readonly List m_theStack = new List(); + + /** + * The default digestLength. + */ + private readonly int m_theDigestLen; + + /** + * Are we outputting? + */ + private bool m_outputting; + + /** + * How many more bytes can we output? + */ + private long m_outputAvailable; + + /** + * The current mode. + */ + private int m_theMode; + + /** + * The output mode. + */ + private int m_theOutputMode; + + /** + * The output dataLen. + */ + private int m_theOutputDataLen; + + /** + * The block counter. + */ + private long m_theCounter; + + /** + * The # of bytes in the current block. + */ + private int m_theCurrBytes; + + /** + * The position of the next byte in the buffer. + */ + private int m_thePos; + + public Blake3Digest() + : this((BLOCKLEN >> 1) * 8) + { + } + + /// the default digest size (in bits) + public Blake3Digest(int pDigestSize) + { + m_theDigestLen = pDigestSize / 8; + + Init(null); + } + + /** + * Constructor. + * + * @param pSource the source digest. + */ + public Blake3Digest(Blake3Digest pSource) + { + /* Copy default digest length */ + m_theDigestLen = pSource.m_theDigestLen; + + /* Initialise from source */ + Reset(pSource); + } + + public int GetByteLength() => BLOCKLEN; + + public string AlgorithmName => "BLAKE3"; + + public int GetDigestSize() => m_theDigestLen; + + /** + * Initialise. + * + * @param pParams the parameters. + */ + public void Init(Blake3Parameters pParams) + { + /* Access key/context */ + byte[] myKey = pParams?.GetKey(); + byte[] myContext = pParams?.GetContext(); + + /* Reset the digest */ + Reset(); + + /* If we have a key */ + if (myKey != null) + { + /* Initialise with the key */ + InitKey(myKey); + Arrays.Fill(myKey, 0); + + /* else if we have a context */ + } + else if (myContext != null) + { + /* Initialise for deriving context */ + InitNullKey(); + m_theMode = DERIVECONTEXT; + + /* Derive key from context */ + BlockUpdate(myContext, 0, myContext.Length); + DoFinal(m_theBuffer, 0); + InitKeyFromContext(); + Reset(); + + /* Else init null key and reset mode */ + } + else + { + InitNullKey(); + m_theMode = 0; + } + } + + public void Update(byte b) + { + /* Check that we are not outputting */ + if (m_outputting) + throw new InvalidOperationException(ERR_OUTPUTTING); + + /* If the buffer is full */ + int blockLen = m_theBuffer.Length; + int remainingLength = blockLen - m_thePos; + if (remainingLength == 0) + { + /* Process the buffer */ +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + CompressBlock(m_theBuffer); +#else + CompressBlock(m_theBuffer, 0); +#endif + + /* Reset the buffer */ + Arrays.Fill(m_theBuffer, 0); + m_thePos = 0; + } + + /* Store the byte */ + m_theBuffer[m_thePos] = b; + m_thePos++; + } + + public void BlockUpdate(byte[] pMessage, int pOffset, int pLen) + { + /* Ignore null operation */ + if (pMessage == null) + return; + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BlockUpdate(pMessage.AsSpan(pOffset, pLen)); +#else + if (pLen == 0) + return; + + /* Check that we are not outputting */ + if (m_outputting) + throw new InvalidOperationException(ERR_OUTPUTTING); + + /* Process any bytes currently in the buffer */ + int remainingLen = 0; // left bytes of buffer + if (m_thePos != 0) + { + /* Calculate space remaining in the buffer */ + remainingLen = BLOCKLEN - m_thePos; + + /* If there is sufficient space in the buffer */ + if (remainingLen >= pLen) + { + /* Copy data into buffer and return */ + Array.Copy(pMessage, pOffset, m_theBuffer, m_thePos, pLen); + m_thePos += pLen; + return; + } + + /* Fill the buffer */ + Array.Copy(pMessage, pOffset, m_theBuffer, m_thePos, remainingLen); + + /* Process the buffer */ + CompressBlock(m_theBuffer, 0); + + /* Reset the buffer */ + m_thePos = 0; + Arrays.Fill(m_theBuffer, 0); + } + + /* process all blocks except the last one */ + int messagePos; + int blockWiseLastPos = pOffset + pLen - BLOCKLEN; + for (messagePos = pOffset + remainingLen; messagePos < blockWiseLastPos; messagePos += BLOCKLEN) + { + /* Process the buffer */ + CompressBlock(pMessage, messagePos); + } + + /* Fill the buffer with the remaining bytes of the message */ + int len = pLen - messagePos; + Array.Copy(pMessage, messagePos, m_theBuffer, 0, pOffset + len); + m_thePos += pOffset + len; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + if (input.IsEmpty) + return; + + /* Check that we are not outputting */ + if (m_outputting) + throw new InvalidOperationException(ERR_OUTPUTTING); + + int pLen = input.Length; + + /* Process any bytes currently in the buffer */ + int remainingLen = 0; // left bytes of buffer + if (m_thePos != 0) + { + /* Calculate space remaining in the buffer */ + remainingLen = BLOCKLEN - m_thePos; + + /* If there is sufficient space in the buffer */ + if (remainingLen >= pLen) + { + /* Copy data into buffer and return */ + input.CopyTo(m_theBuffer.AsSpan(m_thePos)); + m_thePos += pLen; + return; + } + + /* Fill the buffer */ + input[..remainingLen].CopyTo(m_theBuffer.AsSpan(m_thePos)); + + /* Process the buffer */ + CompressBlock(m_theBuffer); + + /* Reset the buffer */ + m_thePos = 0; + Arrays.Fill(m_theBuffer, 0); + } + + /* process all blocks except the last one */ + int messagePos; + int blockWiseLastPos = pLen - BLOCKLEN; + for (messagePos = remainingLen; messagePos < blockWiseLastPos; messagePos += BLOCKLEN) + { + /* Process the buffer */ + CompressBlock(input[messagePos..]); + } + + /* Fill the buffer with the remaining bytes of the message */ + input[messagePos..].CopyTo(m_theBuffer); + m_thePos += pLen - messagePos; + } +#endif + + public int DoFinal(byte[] pOutput, int pOutOffset) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return OutputFinal(pOutput.AsSpan(pOutOffset, GetDigestSize())); +#else + return OutputFinal(pOutput, pOutOffset, GetDigestSize()); +#endif + } + + public int OutputFinal(byte[] pOut, int pOutOffset, int pOutLen) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return OutputFinal(pOut.AsSpan(pOutOffset, pOutLen)); +#else + /* Reject if we are already outputting */ + if (m_outputting) + throw new InvalidOperationException(ERR_OUTPUTTING); + + /* Build the required output */ + int length = Output(pOut, pOutOffset, pOutLen); + + /* reset the underlying digest and return the length */ + Reset(); + return length; +#endif + } + + public int Output(byte[] pOut, int pOutOffset, int pOutLen) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return Output(pOut.AsSpan(pOutOffset, pOutLen)); +#else + /* If we have not started outputting yet */ + if (!m_outputting) + { + /* Process the buffer */ + CompressFinalBlock(m_thePos); + } + + /* Reject if there is insufficient Xof remaining */ + if (pOutLen < 0 || (m_outputAvailable >= 0 && pOutLen > m_outputAvailable)) + throw new ArgumentException("Insufficient bytes remaining"); + + /* If we have some remaining data in the current buffer */ + int dataLeft = pOutLen; + int outPos = pOutOffset; + if (m_thePos < BLOCKLEN) + { + /* Copy data from current hash */ + int dataToCopy = System.Math.Min(dataLeft, BLOCKLEN - m_thePos); + Array.Copy(m_theBuffer, m_thePos, pOut, outPos, dataToCopy); + + /* Adjust counters */ + m_thePos += dataToCopy; + outPos += dataToCopy; + dataLeft -= dataToCopy; + } + + /* Loop until we have completed the request */ + while (dataLeft > 0) + { + /* Calculate the next block */ + NextOutputBlock(); + + /* Copy data from current hash */ + int dataToCopy = System.Math.Min(dataLeft, BLOCKLEN); + Array.Copy(m_theBuffer, 0, pOut, outPos, dataToCopy); + + /* Adjust counters */ + m_thePos += dataToCopy; + outPos += dataToCopy; + dataLeft -= dataToCopy; + } + + /* Adjust outputAvailable */ + m_outputAvailable -= pOutLen; + + /* Return the number of bytes transferred */ + return pOutLen; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + return OutputFinal(output[..GetDigestSize()]); + } + + public int OutputFinal(Span output) + { + /* Reject if we are already outputting */ + if (m_outputting) + throw new InvalidOperationException(ERR_OUTPUTTING); + + /* Build the required output */ + int length = Output(output); + + /* reset the underlying digest and return the length */ + Reset(); + return length; + } + + public int Output(Span output) + { + /* If we have not started outputting yet */ + if (!m_outputting) + { + /* Process the buffer */ + CompressFinalBlock(m_thePos); + } + + int pOutOffset = 0, pOutLen = output.Length; + /* Reject if there is insufficient Xof remaining */ + if (pOutLen < 0 || (m_outputAvailable >= 0 && pOutLen > m_outputAvailable)) + throw new ArgumentException("Insufficient bytes remaining"); + + /* If we have some remaining data in the current buffer */ + int dataLeft = pOutLen; + int outPos = pOutOffset; + if (m_thePos < BLOCKLEN) + { + /* Copy data from current hash */ + int dataToCopy = System.Math.Min(dataLeft, BLOCKLEN - m_thePos); + m_theBuffer.AsSpan(m_thePos, dataToCopy).CopyTo(output[outPos..]); + + /* Adjust counters */ + m_thePos += dataToCopy; + outPos += dataToCopy; + dataLeft -= dataToCopy; + } + + /* Loop until we have completed the request */ + while (dataLeft > 0) + { + /* Calculate the next block */ + NextOutputBlock(); + + /* Copy data from current hash */ + int dataToCopy = System.Math.Min(dataLeft, BLOCKLEN); + m_theBuffer.AsSpan(0, dataToCopy).CopyTo(output[outPos..]); + + /* Adjust counters */ + m_thePos += dataToCopy; + outPos += dataToCopy; + dataLeft -= dataToCopy; + } + + /* Adjust outputAvailable */ + m_outputAvailable -= pOutLen; + + /* Return the number of bytes transferred */ + return pOutLen; + } +#endif + + public void Reset() + { + ResetBlockCount(); + m_thePos = 0; + m_outputting = false; + Arrays.Fill(m_theBuffer, 0); + } + + public void Reset(IMemoable pSource) + { + /* Access source */ + Blake3Digest mySource = (Blake3Digest)pSource; + + /* Reset counter */ + m_theCounter = mySource.m_theCounter; + m_theCurrBytes = mySource.m_theCurrBytes; + m_theMode = mySource.m_theMode; + + /* Reset output state */ + m_outputting = mySource.m_outputting; + m_outputAvailable = mySource.m_outputAvailable; + m_theOutputMode = mySource.m_theOutputMode; + m_theOutputDataLen = mySource.m_theOutputDataLen; + + /* Copy state */ + Array.Copy(mySource.m_theChaining, 0, m_theChaining, 0, m_theChaining.Length); + Array.Copy(mySource.m_theK, 0, m_theK, 0, m_theK.Length); + Array.Copy(mySource.m_theM, 0, m_theM, 0, m_theM.Length); + + /* Copy stack */ + m_theStack.Clear(); + foreach (var element in mySource.m_theStack) + { + m_theStack.Add(Arrays.Clone(element)); + } + + /* Copy buffer */ + Array.Copy(mySource.m_theBuffer, 0, m_theBuffer, 0, m_theBuffer.Length); + m_thePos = mySource.m_thePos; + } + + public IMemoable Copy() + { + return new Blake3Digest(this); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void CompressBlock(ReadOnlySpan block) + { + /* Initialise state and compress message */ + InitChunkBlock(BLOCKLEN, false); + InitM(block); + Compress(); + + /* Adjust stack if we have completed a block */ + if (m_theCurrBytes == 0) + { + AdjustStack(); + } + } + + private void InitM(ReadOnlySpan block) + { + /* Copy message bytes into word array */ + Pack.LE_To_UInt32(block, m_theM); + } +#else + /** + * Compress next block of the message. + * + * @param pMessage the message buffer + * @param pMsgPos the position within the message buffer + */ + private void CompressBlock(byte[] pMessage, int pMsgPos) + { + /* Initialise state and compress message */ + InitChunkBlock(BLOCKLEN, false); + InitM(pMessage, pMsgPos); + Compress(); + + /* Adjust stack if we have completed a block */ + if (m_theCurrBytes == 0) + { + AdjustStack(); + } + } + + /** + * Initialise M from message. + * + * @param pMessage the source message + * @param pMsgPos the message position + */ + private void InitM(byte[] pMessage, int pMsgPos) + { + /* Copy message bytes into word array */ + Pack.LE_To_UInt32(pMessage, pMsgPos, m_theM); + } +#endif + + /** + * Adjust the stack. + */ + private void AdjustStack() + { + /* Loop to combine blocks */ + long myCount = m_theCounter; + while (myCount > 0) + { + /* Break loop if we are not combining */ + if ((myCount & 1) == 1) + break; + + /* Build the message to be hashed */ + uint[] myLeft = m_theStack[m_theStack.Count - 1]; + m_theStack.RemoveAt(m_theStack.Count - 1); + + Array.Copy(myLeft, 0, m_theM, 0, NUMWORDS); + Array.Copy(m_theChaining, 0, m_theM, NUMWORDS, NUMWORDS); + + /* Create parent block */ + InitParentBlock(); + Compress(); + + /* Next block */ + myCount >>= 1; + } + + /* Add back to the stack */ + m_theStack.Add(Arrays.CopyOf(m_theChaining, NUMWORDS)); + } + + /** + * Compress final block. + * + * @param pDataLen the data length + */ + private void CompressFinalBlock(int pDataLen) + { + /* Initialise state and compress message */ + InitChunkBlock(pDataLen, true); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + InitM(m_theBuffer); +#else + InitM(m_theBuffer, 0); +#endif + Compress(); + + /* Finalise stack */ + ProcessStack(); + } + + /** + * Process the stack. + */ + private void ProcessStack() + { + /* Finalise stack */ + while (m_theStack.Count > 0) + { + /* Build the message to be hashed */ + uint[] myLeft = m_theStack[m_theStack.Count - 1]; + m_theStack.RemoveAt(m_theStack.Count - 1); + + Array.Copy(myLeft, 0, m_theM, 0, NUMWORDS); + Array.Copy(m_theChaining, 0, m_theM, NUMWORDS, NUMWORDS); + + /* Create parent block */ + InitParentBlock(); + if (m_theStack.Count < 1) + { + SetRoot(); + } + Compress(); + } + } + + /** + * Perform compression. + */ + private void Compress() + { + /* Initialise the buffers */ + InitIndices(); + + /* Loop through the rounds */ + for (int round = 0; round < ROUNDS - 1; round++) + { + /* Perform the round and permuteM */ + PerformRound(); + PermuteIndices(); + } + PerformRound(); + AdjustChaining(); + } + + /** + * Perform a round. + */ +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif + private void PerformRound() + { + /* Apply to columns of V */ + MixG(0, CHAINING0, CHAINING4, IV0, COUNT0); + MixG(1, CHAINING1, CHAINING5, IV1, COUNT1); + MixG(2, CHAINING2, CHAINING6, IV2, DATALEN); + MixG(3, CHAINING3, CHAINING7, IV3, FLAGS); + + /* Apply to diagonals of V */ + MixG(4, CHAINING0, CHAINING5, IV2, FLAGS); + MixG(5, CHAINING1, CHAINING6, IV3, COUNT0); + MixG(6, CHAINING2, CHAINING7, IV0, COUNT1); + MixG(7, CHAINING3, CHAINING4, IV1, DATALEN); + } + + /** + * Adjust Chaining after compression. + */ + private void AdjustChaining() + { + /* If we are outputting */ + if (m_outputting) + { + /* Adjust full state */ + for (int i = 0; i < NUMWORDS; i++) + { + m_theV[i] ^= m_theV[i + NUMWORDS]; + m_theV[i + NUMWORDS] ^= m_theChaining[i]; + } + + /* Output state to buffer */ + Pack.UInt32_To_LE(m_theV, m_theBuffer, 0); + m_thePos = 0; + + /* Else just build chain value */ + } + else + { + /* Combine V into Chaining */ + for (int i = 0; i < NUMWORDS; i++) + { + m_theChaining[i] = m_theV[i] ^ m_theV[i + NUMWORDS]; + } + } + } + + /** + * Mix function G. + * + * @param msgIdx the message index + * @param posA position A in V + * @param posB position B in V + * @param posC position C in V + * @param posD poistion D in V + */ +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif + private void MixG(int msgIdx, int posA, int posB, int posC, int posD) + { + /* Determine indices */ + int msg = msgIdx << 1; + + /* Perform the Round */ + m_theV[posA] += m_theV[posB] + m_theM[m_theIndices[msg++]]; + m_theV[posD] = Integers.RotateRight(m_theV[posD] ^ m_theV[posA], 16); + m_theV[posC] += m_theV[posD]; + m_theV[posB] = Integers.RotateRight(m_theV[posB] ^ m_theV[posC], 12); + m_theV[posA] += m_theV[posB] + m_theM[m_theIndices[msg]]; + m_theV[posD] = Integers.RotateRight(m_theV[posD] ^ m_theV[posA], 8); + m_theV[posC] += m_theV[posD]; + m_theV[posB] = Integers.RotateRight(m_theV[posB] ^ m_theV[posC], 7); + } + + /** + * initialise the indices. + */ + private void InitIndices() + { + for (byte i = 0; i < m_theIndices.Length; i++) + { + m_theIndices[i] = i; + } + } + + /** + * PermuteIndices. + */ + private void PermuteIndices() + { + for (byte i = 0; i < m_theIndices.Length; i++) + { + m_theIndices[i] = SIGMA[m_theIndices[i]]; + } + } + + /** + * Initialise null key. + */ + private void InitNullKey() + { + Array.Copy(IV, 0, m_theK, 0, NUMWORDS); + } + + /** + * Initialise key. + * + * @param pKey the keyBytes + */ + private void InitKey(byte[] pKey) + { + /* Copy message bytes into word array */ + Pack.LE_To_UInt32(pKey, 0, m_theK); + m_theMode = KEYEDHASH; + } + + /** + * Initialise key from context. + */ + private void InitKeyFromContext() + { + Array.Copy(m_theV, 0, m_theK, 0, NUMWORDS); + m_theMode = DERIVEKEY; + } + + /** + * Initialise chunk block. + * + * @param pDataLen the dataLength + * @param pFinal is this the final chunk? + */ + private void InitChunkBlock(int pDataLen, bool pFinal) + { + /* Initialise the block */ + Array.Copy(m_theCurrBytes == 0 ? m_theK : m_theChaining, 0, m_theV, 0, NUMWORDS); + Array.Copy(IV, 0, m_theV, NUMWORDS, NUMWORDS >> 1); + m_theV[COUNT0] = (uint)m_theCounter; + m_theV[COUNT1] = (uint)(m_theCounter >> Integers.NumBits); + m_theV[DATALEN] = (uint)pDataLen; + m_theV[FLAGS] = (uint)(m_theMode + + (m_theCurrBytes == 0 ? CHUNKSTART : 0) + + (pFinal ? CHUNKEND : 0)); + + /* * Adjust block count */ + m_theCurrBytes += pDataLen; + if (m_theCurrBytes >= CHUNKLEN) + { + IncrementBlockCount(); + m_theV[FLAGS] |= CHUNKEND; + } + + /* If we are single chunk */ + if (pFinal && m_theStack.Count < 1) + { + SetRoot(); + } + } + + /** + * Initialise parent block. + */ + private void InitParentBlock() + { + /* Initialise the block */ + Array.Copy(m_theK, 0, m_theV, 0, NUMWORDS); + Array.Copy(IV, 0, m_theV, NUMWORDS, NUMWORDS >> 1); + m_theV[COUNT0] = 0; + m_theV[COUNT1] = 0; + m_theV[DATALEN] = BLOCKLEN; + m_theV[FLAGS] = (uint)(m_theMode | PARENT); + } + + /** + * Initialise output block. + */ + private void NextOutputBlock() + { + /* Increment the counter */ + m_theCounter++; + + /* Initialise the block */ + Array.Copy(m_theChaining, 0, m_theV, 0, NUMWORDS); + Array.Copy(IV, 0, m_theV, NUMWORDS, NUMWORDS >> 1); + m_theV[COUNT0] = (uint)m_theCounter; + m_theV[COUNT1] = (uint)(m_theCounter >> Integers.NumBits); + m_theV[DATALEN] = (uint)m_theOutputDataLen; + m_theV[FLAGS] = (uint)m_theOutputMode; + + /* Generate output */ + Compress(); + } + + /** + * IncrementBlockCount. + */ + private void IncrementBlockCount() + { + m_theCounter++; + m_theCurrBytes = 0; + } + + /** + * ResetBlockCount. + */ + private void ResetBlockCount() + { + m_theCounter = 0; + m_theCurrBytes = 0; + } + + /** + * Set root indication. + */ + private void SetRoot() + { + m_theV[FLAGS] |= ROOT; + m_theOutputMode = (int)m_theV[FLAGS]; + m_theOutputDataLen = (int)m_theV[DATALEN]; + m_theCounter = 0; + m_outputting = true; + m_outputAvailable = -1; + Array.Copy(m_theV, 0, m_theChaining, 0, NUMWORDS); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake3Digest.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake3Digest.cs.meta new file mode 100644 index 0000000..e0dd25f --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Blake3Digest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ded5cb56c1e36294db2395e1831ee1a0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/CSHAKEDigest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/CSHAKEDigest.cs index e85b1ee..2a22723 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/CSHAKEDigest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/CSHAKEDigest.cs @@ -80,11 +80,11 @@ public override string AlgorithmName get { return "CSHAKE" + fixedOutputLength; } } - public override int DoOutput(byte[] output, int outOff, int outLen) + public override int Output(byte[] output, int outOff, int outLen) { if (diff == null) { - return base.DoOutput(output, outOff, outLen); + return base.Output(output, outOff, outLen); } if (!squeezing) @@ -97,6 +97,25 @@ public override int DoOutput(byte[] output, int outOff, int outLen) return outLen; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int Output(Span output) + { + if (diff == null) + { + return base.Output(output); + } + + if (!squeezing) + { + AbsorbBits(0x00, 2); + } + + Squeeze(output); + + return output.Length; + } +#endif + public override void Reset() { base.Reset(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/DSTU7564Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/DSTU7564Digest.cs index 72e7353..c50fa64 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/DSTU7564Digest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/DSTU7564Digest.cs @@ -2,12 +2,8 @@ #pragma warning disable using System; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines; -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.Digests { @@ -134,25 +130,103 @@ public virtual void BlockUpdate(byte[] input, int inOff, int length) --length; } - if (length > 0) + while (length >= blockSize) + { + ProcessBlock(input, inOff); + inOff += blockSize; + length -= blockSize; + ++inputBlocks; + } + + while (length > 0) + { + Update(input[inOff++]); + --length; + } + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) + { + while (bufOff != 0 && input.Length > 0) + { + Update(input[0]); + input = input[1..]; + } + + while (input.Length >= blockSize) + { + ProcessBlock(input); + input = input[blockSize..]; + ++inputBlocks; + } + + while (input.Length > 0) + { + Update(input[0]); + input = input[1..]; + } + } +#endif + + public virtual int DoFinal(byte[] output, int outOff) + { + // Apply padding: terminator byte and 96-bit length field { - while (length >= blockSize) + int inputBytes = bufOff; + buf[bufOff++] = (byte)0x80; + + int lenPos = blockSize - 12; + if (bufOff > lenPos) { - ProcessBlock(input, inOff); - inOff += blockSize; - length -= blockSize; - ++inputBlocks; + while (bufOff < blockSize) + { + buf[bufOff++] = 0; + } + bufOff = 0; + ProcessBlock(buf, 0); } - while (length > 0) + while (bufOff < lenPos) + { + buf[bufOff++] = 0; + } + + ulong c = ((inputBlocks & 0xFFFFFFFFUL) * (ulong)blockSize + (uint)inputBytes) << 3; + Pack.UInt32_To_LE((uint)c, buf, bufOff); + bufOff += 4; + c >>= 32; + c += ((inputBlocks >> 32) * (ulong)blockSize) << 3; + Pack.UInt64_To_LE(c, buf, bufOff); + //bufOff += 8; + ProcessBlock(buf, 0); + } + + { + Array.Copy(state, 0, tempState1, 0, columns); + + P(tempState1); + + for (int col = 0; col < columns; ++col) { - Update(input[inOff++]); - --length; + state[col] ^= tempState1[col]; } } + + int neededColumns = hashSize / 8; + for (int col = columns - neededColumns; col < columns; ++col) + { + Pack.UInt64_To_LE(state[col], output, outOff); + outOff += 8; + } + + Reset(); + + return hashSize; } - public virtual int DoFinal(byte[] output, int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int DoFinal(Span output) { // Apply padding: terminator byte and 96-bit length field { @@ -181,7 +255,7 @@ public virtual int DoFinal(byte[] output, int outOff) c >>= 32; c += ((inputBlocks >> 32) * (ulong)blockSize) << 3; Pack.UInt64_To_LE(c, buf, bufOff); - // bufOff += 8; + //bufOff += 8; ProcessBlock(buf, 0); } @@ -199,14 +273,15 @@ public virtual int DoFinal(byte[] output, int outOff) int neededColumns = hashSize / 8; for (int col = columns - neededColumns; col < columns; ++col) { - Pack.UInt64_To_LE(state[col], output, outOff); - outOff += 8; + Pack.UInt64_To_LE(state[col], output); + output = output[8..]; } Reset(); return hashSize; } +#endif public virtual void Reset() { @@ -238,6 +313,28 @@ protected virtual void ProcessBlock(byte[] input, int inOff) } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + protected virtual void ProcessBlock(ReadOnlySpan input) + { + for (int col = 0; col < columns; ++col) + { + ulong word = Pack.LE_To_UInt64(input); + input = input[8..]; + + tempState1[col] = state[col] ^ word; + tempState2[col] = word; + } + + P(tempState1); + Q(tempState2); + + for (int col = 0; col < columns; ++col) + { + state[col] ^= tempState1[col] ^ tempState2[col]; + } + } +#endif + private void P(ulong[] s) { for (int round = 0; round < rounds; ++round) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/GOST3411Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/GOST3411Digest.cs index 942bb88..c950d1c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/GOST3411Digest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/GOST3411Digest.cs @@ -93,10 +93,7 @@ public void Update( byteCount++; } - public void BlockUpdate( - byte[] input, - int inOff, - int length) + public void BlockUpdate(byte[] input, int inOff, int length) { while ((xBufOff != 0) && (length > 0)) { @@ -105,7 +102,7 @@ public void BlockUpdate( length--; } - while (length > xBuf.Length) + while (length >= xBuf.Length) { Array.Copy(input, inOff, xBuf, 0, xBuf.Length); @@ -125,6 +122,34 @@ public void BlockUpdate( } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + while ((xBufOff != 0) && (input.Length > 0)) + { + Update(input[0]); + input = input[1..]; + } + + while (input.Length >= xBuf.Length) + { + input[..xBuf.Length].CopyTo(xBuf.AsSpan()); + + sumByteArray(xBuf); // calc sum M + processBlock(xBuf, 0); + input = input[xBuf.Length..]; + byteCount += (uint)xBuf.Length; + } + + // load in the remainder. + while (input.Length > 0) + { + Update(input[0]); + input = input[1..]; + } + } +#endif + // (i + 1 + 4(k - 1)) = 8i + k i = 0-3, k = 1-8 private byte[] K = new byte[32]; @@ -236,7 +261,7 @@ private void processBlock(byte[] input, int inOff) Array.Copy(S, 0, H, 0, H.Length); } - private void finish() + private void Finish() { ulong bitCount = byteCount * 8; Pack.UInt64_To_LE(bitCount, L); @@ -250,11 +275,9 @@ private void finish() processBlock(Sum, 0); } - public int DoFinal( - byte[] output, - int outOff) + public int DoFinal(byte[] output, int outOff) { - finish(); + Finish(); H.CopyTo(output, outOff); @@ -263,6 +286,19 @@ public int DoFinal( return DIGEST_LENGTH; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + Finish(); + + H.CopyTo(output); + + Reset(); + + return DIGEST_LENGTH; + } +#endif + /** * reset the chaining variables to the IV values. */ diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/GOST3411_2012Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/GOST3411_2012Digest.cs index 7d5ee9b..1b1d5ad 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/GOST3411_2012Digest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/GOST3411_2012Digest.cs @@ -1,12 +1,13 @@ #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.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests { - public abstract class Gost3411_2012Digest:IDigest,IMemoable + public abstract class Gost3411_2012Digest + : IDigest, IMemoable { private readonly byte[] IV = new byte[64]; private readonly byte[] N = new byte[64]; @@ -23,8 +24,8 @@ public abstract class Gost3411_2012Digest:IDigest,IMemoable protected Gost3411_2012Digest(byte[] IV) { - System.Array.Copy(IV,this.IV,64); - System.Array.Copy(IV, h, 64); + Array.Copy(IV,this.IV,64); + Array.Copy(IV, h, 64); } public abstract string AlgorithmName { get; } @@ -45,7 +46,7 @@ public virtual int DoFinal(byte[] output, int outOff) if (bOff != 64) { - System.Array.Copy(block, bOff, m, 64 - lenM, lenM); + Array.Copy(block, bOff, m, 64 - lenM, lenM); } g_N(h, N, m); @@ -62,6 +63,39 @@ public virtual int DoFinal(byte[] output, int outOff) return 64; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int DoFinal(Span output) + { + int lenM = 64 - bOff; + + // At this point it is certain that lenM is smaller than 64 + for (int i = 0; i != 64 - lenM; i++) + { + m[i] = 0; + } + + m[63 - lenM] = 1; + + if (bOff != 64) + { + Array.Copy(block, bOff, m, 64 - lenM, lenM); + } + + g_N(h, N, m); + addMod512(N, lenM * 8); + addMod512(Sigma, m); + g_N(h, Zero, N); + g_N(h, Zero, Sigma); + + reverse(h, tmp); + + tmp.CopyTo(output); + + Reset(); + return 64; + } +#endif + public int GetByteLength() { return 64; @@ -75,7 +109,7 @@ public void Reset() bOff = 64; Arrays.Fill(N, (byte)0); Arrays.Fill(Sigma, (byte)0); - System.Array.Copy(IV, 0, h, 0, 64); + Array.Copy(IV, 0, h, 0, 64); Arrays.Fill(block, (byte)0); } @@ -83,14 +117,14 @@ public void Reset(IMemoable other) { Gost3411_2012Digest o = (Gost3411_2012Digest)other; - System.Array.Copy(o.IV, 0, this.IV, 0, 64); - System.Array.Copy(o.N, 0, this.N, 0, 64); - System.Array.Copy(o.Sigma, 0, this.Sigma, 0, 64); - System.Array.Copy(o.Ki, 0, this.Ki, 0, 64); - System.Array.Copy(o.m, 0, this.m, 0, 64); - System.Array.Copy(o.h, 0, this.h, 0, 64); + Array.Copy(o.IV, 0, this.IV, 0, 64); + Array.Copy(o.N, 0, this.N, 0, 64); + Array.Copy(o.Sigma, 0, this.Sigma, 0, 64); + Array.Copy(o.Ki, 0, this.Ki, 0, 64); + Array.Copy(o.m, 0, this.m, 0, 64); + Array.Copy(o.h, 0, this.h, 0, 64); - System.Array.Copy(o.block, 0, this.block, 0, 64); + Array.Copy(o.block, 0, this.block, 0, 64); this.bOff = o.bOff; } @@ -106,7 +140,6 @@ public void Update(byte input) } } - public void BlockUpdate(byte[] input, int inOff, int len) { while (bOff != 64 && len > 0) @@ -116,7 +149,7 @@ public void BlockUpdate(byte[] input, int inOff, int len) } while (len >= 64) { - System.Array.Copy(input, inOff, tmp, 0, 64); + Array.Copy(input, inOff, tmp, 0, 64); reverse(tmp, block); g_N(h, N, block); addMod512(N, 512); @@ -132,8 +165,31 @@ public void BlockUpdate(byte[] input, int inOff, int len) } } - +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + while (bOff != 64 && input.Length > 0) + { + Update(input[0]); + input = input[1..]; + } + while (input.Length >= 64) + { + input[..64].CopyTo(tmp.AsSpan()); + reverse(tmp, block); + g_N(h, N, block); + addMod512(N, 512); + addMod512(Sigma, block); + input = input[64..]; + } + while (input.Length > 0) + { + Update(input[0]); + input = input[1..]; + } + } +#endif private void F(byte[] V) { @@ -319,7 +375,7 @@ private void xor512(byte[] A, byte[] B) private void E(byte[] K, byte[] m) { - System.Array.Copy(K, 0, Ki, 0, 64); + Array.Copy(K, 0, Ki, 0, 64); xor512(K, m); F(K); for (int i = 0; i < 11; ++i) @@ -336,7 +392,7 @@ private void E(byte[] K, byte[] m) private void g_N(byte[] h, byte[] N, byte[] m) { - System.Array.Copy(h, 0, tmp, 0, 64); + Array.Copy(h, 0, tmp, 0, 64); xor512(h, N); F(h); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/GOST3411_2012_256Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/GOST3411_2012_256Digest.cs index 19233b7..67709d5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/GOST3411_2012_256Digest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/GOST3411_2012_256Digest.cs @@ -48,6 +48,18 @@ public override int DoFinal(byte[] output, int outOff) return 32; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + Span result = stackalloc byte[64]; + base.DoFinal(result); + + result[32..].CopyTo(output); + + return 32; + } +#endif + public override IMemoable Copy() { return new Gost3411_2012_256Digest(this); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/GeneralDigest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/GeneralDigest.cs index 638802b..f63a110 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/GeneralDigest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/GeneralDigest.cs @@ -10,10 +10,6 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests * base implementation of MD4 family style digest as outlined in * "Handbook of Applied Cryptography", pages 344 - 347. */ - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] public abstract class GeneralDigest : IDigest, IMemoable { @@ -56,7 +52,7 @@ public void Update(byte input) byteCount++; } - public unsafe void BlockUpdate( + public void BlockUpdate( byte[] input, int inOff, int length) @@ -69,23 +65,22 @@ public unsafe void BlockUpdate( int i = 0; if (xBufOff != 0) { - fixed (byte* pxBuf = xBuf, pinput = input) - while (i < length) + while (i < length) + { + xBuf[xBufOff++] = input[inOff + i++]; + if (xBufOff == 4) { - pxBuf[xBufOff++] = pinput[inOff + i++]; - if (xBufOff == 4) - { - ProcessWord(xBuf, 0); - xBufOff = 0; - break; - } + ProcessWord(xBuf, 0); + xBufOff = 0; + break; } + } } // // process whole words. // - int limit = ((length - i) & ~3) + i; + int limit = length - 3; for (; i < limit; i += 4) { ProcessWord(input, inOff + i); @@ -94,19 +89,57 @@ public unsafe void BlockUpdate( // // load in the remainder. // - //while (i < length) - //{ - // xBuf[xBufOff++] = input[inOff + i++]; - //} + while (i < length) + { + xBuf[xBufOff++] = input[inOff + i++]; + } + + byteCount += length; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + int length = input.Length; - fixed (byte* pxBuf = xBuf, pinput = input) + // + // fill the current word + // + int i = 0; + if (xBufOff != 0) { while (i < length) - pxBuf[xBufOff++] = pinput[inOff + i++]; + { + xBuf[xBufOff++] = input[i++]; + if (xBufOff == 4) + { + ProcessWord(xBuf, 0); + xBufOff = 0; + break; + } + } + } + + // + // process whole words. + // + int limit = length - 3; + for (; i < limit; i += 4) + { + ProcessWord(input.Slice(i, 4)); + } + + // + // load in the remainder. + // + while (i < length) + { + xBuf[xBufOff++] = input[i++]; } byteCount += length; } +#endif public void Finish() { @@ -135,6 +168,9 @@ public int GetByteLength() } internal abstract void ProcessWord(byte[] input, int inOff); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal abstract void ProcessWord(ReadOnlySpan word); +#endif internal abstract void ProcessLength(long bitLength); internal abstract void ProcessBlock(); public abstract string AlgorithmName { get; } @@ -142,6 +178,9 @@ public int GetByteLength() public abstract int DoFinal(byte[] output, int outOff); public abstract IMemoable Copy(); public abstract void Reset(IMemoable t); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public abstract int DoFinal(Span output); +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka256Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka256Digest.cs new file mode 100644 index 0000000..13a77bc --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka256Digest.cs @@ -0,0 +1,218 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests +{ + public sealed class Haraka256Digest + : HarakaBase + { + private readonly byte[] m_buf; + private int m_bufPos; + + public Haraka256Digest() + { + m_buf = new byte[32]; + m_bufPos = 0; + } + + public override string AlgorithmName => "Haraka-256"; + + public override int GetByteLength() => 32; + + public override void Update(byte input) + { + if (m_bufPos > 32 - 1) + throw new ArgumentException("total input cannot be more than 32 bytes"); + + m_buf[m_bufPos++] = input; + } + + public override void BlockUpdate(byte[] input, int inOff, int len) + { + if (m_bufPos > 32 - len) + throw new ArgumentException("total input cannot be more than 32 bytes"); + + Array.Copy(input, inOff, m_buf, m_bufPos, len); + m_bufPos += len; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void BlockUpdate(ReadOnlySpan input) + { + if (m_bufPos > 32 - input.Length) + throw new ArgumentException("total input cannot be more than 32 bytes"); + + input.CopyTo(m_buf.AsSpan(m_bufPos)); + m_bufPos += input.Length; + } +#endif + + public override int DoFinal(byte[] output, int outOff) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(output.AsSpan(outOff)); +#else + if (m_bufPos != 32) + throw new ArgumentException("input must be exactly 32 bytes"); + + if (output.Length - outOff < 32) + throw new ArgumentException("output too short to receive digest"); + + int rv = Haraka256256(m_buf, output, outOff); + + Reset(); + + return rv; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + if (m_bufPos != 32) + throw new ArgumentException("input must be exactly 32 bytes"); + + if (output.Length < 32) + throw new ArgumentException("output too short to receive digest"); + +#if NETCOREAPP3_0_OR_GREATER + if (Haraka256_X86.IsSupported) + { + Haraka256_X86.Hash(m_buf, output); + Reset(); + return 32; + } +#endif + + int rv = Haraka256256(m_buf, output); + + Reset(); + + return rv; + } +#endif + + public override void Reset() + { + m_bufPos = 0; + Array.Clear(m_buf, 0, 32); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static int Haraka256256(ReadOnlySpan msg, Span output) + { + byte[][] s1 = new byte[2][]; + s1[0] = new byte[16]; + s1[1] = new byte[16]; + byte[][] s2 = new byte[2][]; + s2[0] = new byte[16]; + s2[1] = new byte[16]; + + msg[ ..16].CopyTo(s1[0]); + msg[16..32].CopyTo(s1[1]); + + s1[0] = AesEnc(s1[0], RC[0]); + s1[1] = AesEnc(s1[1], RC[1]); + s1[0] = AesEnc(s1[0], RC[2]); + s1[1] = AesEnc(s1[1], RC[3]); + Mix256(s1, s2); + + s1[0] = AesEnc(s2[0], RC[4]); + s1[1] = AesEnc(s2[1], RC[5]); + s1[0] = AesEnc(s1[0], RC[6]); + s1[1] = AesEnc(s1[1], RC[7]); + Mix256(s1, s2); + + s1[0] = AesEnc(s2[0], RC[8]); + s1[1] = AesEnc(s2[1], RC[9]); + s1[0] = AesEnc(s1[0], RC[10]); + s1[1] = AesEnc(s1[1], RC[11]); + Mix256(s1, s2); + + s1[0] = AesEnc(s2[0], RC[12]); + s1[1] = AesEnc(s2[1], RC[13]); + s1[0] = AesEnc(s1[0], RC[14]); + s1[1] = AesEnc(s1[1], RC[15]); + Mix256(s1, s2); + + s1[0] = AesEnc(s2[0], RC[16]); + s1[1] = AesEnc(s2[1], RC[17]); + s1[0] = AesEnc(s1[0], RC[18]); + s1[1] = AesEnc(s1[1], RC[19]); + Mix256(s1, s2); + + Xor(s2[0], msg , output[ ..16]); + Xor(s2[1], msg[16..], output[16..32]); + + return DIGEST_SIZE; + } +#else + private static int Haraka256256(byte[] msg, byte[] output, int outOff) + { + byte[][] s1 = new byte[2][]; + s1[0] = new byte[16]; + s1[1] = new byte[16]; + byte[][] s2 = new byte[2][]; + s2[0] = new byte[16]; + s2[1] = new byte[16]; + + Array.Copy(msg, 0, s1[0], 0, 16); + Array.Copy(msg, 16, s1[1], 0, 16); + + s1[0] = AesEnc(s1[0], RC[0]); + s1[1] = AesEnc(s1[1], RC[1]); + s1[0] = AesEnc(s1[0], RC[2]); + s1[1] = AesEnc(s1[1], RC[3]); + Mix256(s1, s2); + + s1[0] = AesEnc(s2[0], RC[4]); + s1[1] = AesEnc(s2[1], RC[5]); + s1[0] = AesEnc(s1[0], RC[6]); + s1[1] = AesEnc(s1[1], RC[7]); + Mix256(s1, s2); + + s1[0] = AesEnc(s2[0], RC[8]); + s1[1] = AesEnc(s2[1], RC[9]); + s1[0] = AesEnc(s1[0], RC[10]); + s1[1] = AesEnc(s1[1], RC[11]); + Mix256(s1, s2); + + s1[0] = AesEnc(s2[0], RC[12]); + s1[1] = AesEnc(s2[1], RC[13]); + s1[0] = AesEnc(s1[0], RC[14]); + s1[1] = AesEnc(s1[1], RC[15]); + Mix256(s1, s2); + + s1[0] = AesEnc(s2[0], RC[16]); + s1[1] = AesEnc(s2[1], RC[17]); + s1[0] = AesEnc(s1[0], RC[18]); + s1[1] = AesEnc(s1[1], RC[19]); + Mix256(s1, s2); + + s1[0] = Xor(s2[0], msg, 0); + s1[1] = Xor(s2[1], msg, 16); + + Array.Copy(s1[0], 0, output, outOff , 16); + Array.Copy(s1[1], 0, output, outOff + 16, 16); + + return DIGEST_SIZE; + } +#endif + + private static void Mix256(byte[][] s1, byte[][] s2) + { + Array.Copy(s1[0], 0, s2[0], 0, 4); + Array.Copy(s1[1], 0, s2[0], 4, 4); + Array.Copy(s1[0], 4, s2[0], 8, 4); + Array.Copy(s1[1], 4, s2[0], 12, 4); + + Array.Copy(s1[0], 8, s2[1], 0, 4); + Array.Copy(s1[1], 8, s2[1], 4, 4); + Array.Copy(s1[0], 12, s2[1], 8, 4); + Array.Copy(s1[1], 12, s2[1], 12, 4); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka256Digest.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka256Digest.cs.meta new file mode 100644 index 0000000..3c12365 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka256Digest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5dfb21fc4cfa4394cb874f140dbe6c7a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka256_X86.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka256_X86.cs new file mode 100644 index 0000000..16aef10 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka256_X86.cs @@ -0,0 +1,148 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +#if NETCOREAPP3_0_OR_GREATER +using System; +using System.Buffers.Binary; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests +{ + using Aes = System.Runtime.Intrinsics.X86.Aes; + using Sse2 = System.Runtime.Intrinsics.X86.Sse2; + + public static class Haraka256_X86 + { + public static bool IsSupported => Aes.IsSupported; + + public static void Hash(ReadOnlySpan input, Span output) + { + if (!IsSupported) + throw new PlatformNotSupportedException(nameof(Haraka256_X86)); + + var s0 = Load128(input[ ..16]); + var s1 = Load128(input[16..32]); + + ImplRounds(ref s0, ref s1, Haraka512_X86.DefaultRoundConstants.AsSpan(0, 20)); + + s0 = Sse2.Xor(s0, Load128(input[ ..16])); + s1 = Sse2.Xor(s1, Load128(input[16..32])); + + Store128(s0, output[ ..16]); + Store128(s1, output[16..32]); + } + + public static void Hash(ReadOnlySpan input, Span output, + ReadOnlySpan> roundConstants) + { + if (!IsSupported) + throw new PlatformNotSupportedException(nameof(Haraka256_X86)); + + var s0 = Load128(input[ ..16]); + var s1 = Load128(input[16..32]); + + ImplRounds(ref s0, ref s1, roundConstants[..20]); + + s0 = Sse2.Xor(s0, Load128(input[ ..16])); + s1 = Sse2.Xor(s1, Load128(input[16..32])); + + Store128(s0, output[ ..16]); + Store128(s1, output[16..32]); + } + + public static void Permute(ReadOnlySpan input, Span output) + { + if (!IsSupported) + throw new PlatformNotSupportedException(nameof(Haraka256_X86)); + + var s0 = Load128(input[ ..16]); + var s1 = Load128(input[16..32]); + + ImplRounds(ref s0, ref s1, Haraka512_X86.DefaultRoundConstants.AsSpan(0, 20)); + + Store128(s0, output[ ..16]); + Store128(s1, output[16..32]); + } + + public static void Permute(ReadOnlySpan input, Span output, + ReadOnlySpan> roundConstants) + { + if (!IsSupported) + throw new PlatformNotSupportedException(nameof(Haraka256_X86)); + + var s0 = Load128(input[ ..16]); + var s1 = Load128(input[16..32]); + + ImplRounds(ref s0, ref s1, roundConstants[..20]); + + Store128(s0, output[ ..16]); + Store128(s1, output[16..32]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ImplRounds(ref Vector128 s0, ref Vector128 s1, ReadOnlySpan> rc) + { + ImplRound(ref s0, ref s1, rc[ .. 4]); + ImplRound(ref s0, ref s1, rc[ 4.. 8]); + ImplRound(ref s0, ref s1, rc[ 8..12]); + ImplRound(ref s0, ref s1, rc[12..16]); + ImplRound(ref s0, ref s1, rc[16..20]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ImplRound(ref Vector128 s0, ref Vector128 s1, ReadOnlySpan> rc) + { + ImplAes(ref s0, ref s1, rc[..4]); + ImplMix(ref s0, ref s1); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ImplAes(ref Vector128 s0, ref Vector128 s1, ReadOnlySpan> rc) + { + s0 = Aes.Encrypt(s0, rc[0]); + s1 = Aes.Encrypt(s1, rc[1]); + + s0 = Aes.Encrypt(s0, rc[2]); + s1 = Aes.Encrypt(s1, rc[3]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ImplMix(ref Vector128 s0, ref Vector128 s1) + { + Vector128 t0 = s0.AsUInt32(); + Vector128 t1 = s1.AsUInt32(); + s0 = Sse2.UnpackLow(t0, t1).AsByte(); + s1 = Sse2.UnpackHigh(t0, t1).AsByte(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector128 Load128(ReadOnlySpan t) + { + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 16) + return MemoryMarshal.Read>(t); + + return Vector128.Create( + BinaryPrimitives.ReadUInt64LittleEndian(t[..8]), + BinaryPrimitives.ReadUInt64LittleEndian(t[8..]) + ).AsByte(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Store128(Vector128 s, Span t) + { + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 16) + { + MemoryMarshal.Write(t, ref s); + return; + } + + var u = s.AsUInt64(); + BinaryPrimitives.WriteUInt64LittleEndian(t[..8], u.GetElement(0)); + BinaryPrimitives.WriteUInt64LittleEndian(t[8..], u.GetElement(1)); + } + } +} +#endif +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka256_X86.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka256_X86.cs.meta new file mode 100644 index 0000000..0cc919d --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka256_X86.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f5713a53a331cff40b1b1ca65f14b08d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka512Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka512Digest.cs new file mode 100644 index 0000000..cba22ef --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka512Digest.cs @@ -0,0 +1,291 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests +{ + public sealed class Haraka512Digest + : HarakaBase + { + private readonly byte[] m_buf; + private int m_bufPos; + + public Haraka512Digest() + { + m_buf = new byte[64]; + m_bufPos = 0; + } + + public override string AlgorithmName => "Haraka-512"; + + public override int GetByteLength() => 64; + + public override void Update(byte input) + { + if (m_bufPos > 64 - 1) + throw new ArgumentException("total input cannot be more than 64 bytes"); + + m_buf[m_bufPos++] = input; + } + + public override void BlockUpdate(byte[] input, int inOff, int len) + { + if (m_bufPos > 64 - len) + throw new ArgumentException("total input cannot be more than 64 bytes"); + + Array.Copy(input, inOff, m_buf, m_bufPos, len); + m_bufPos += len; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void BlockUpdate(ReadOnlySpan input) + { + if (m_bufPos > 64 - input.Length) + throw new ArgumentException("total input cannot be more than 64 bytes"); + + input.CopyTo(m_buf.AsSpan(m_bufPos)); + m_bufPos += input.Length; + } +#endif + + public override int DoFinal(byte[] output, int outOff) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(output.AsSpan(outOff)); +#else + if (m_bufPos != 64) + throw new ArgumentException("input must be exactly 64 bytes"); + + if (output.Length - outOff < 32) + throw new ArgumentException("output too short to receive digest"); + + int rv = Haraka512256(m_buf, output, outOff); + + Reset(); + + return rv; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + if (m_bufPos != 64) + throw new ArgumentException("input must be exactly 64 bytes"); + + if (output.Length < 32) + throw new ArgumentException("output too short to receive digest"); + +#if NETCOREAPP3_0_OR_GREATER + if (Haraka512_X86.IsSupported) + { + Haraka512_X86.Hash(m_buf, output); + Reset(); + return 32; + } +#endif + + int rv = Haraka512256(m_buf, output); + + Reset(); + + return rv; + } +#endif + + public override void Reset() + { + m_bufPos = 0; + Array.Clear(m_buf, 0, 64); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static int Haraka512256(ReadOnlySpan msg, Span output) + { + byte[][] s1 = new byte[4][]; + s1[0] = new byte[16]; + s1[1] = new byte[16]; + s1[2] = new byte[16]; + s1[3] = new byte[16]; + byte[][] s2 = new byte[4][]; + s2[0] = new byte[16]; + s2[1] = new byte[16]; + s2[2] = new byte[16]; + s2[3] = new byte[16]; + + msg[ ..16].CopyTo(s1[0]); + msg[16..32].CopyTo(s1[1]); + msg[32..48].CopyTo(s1[2]); + msg[48..64].CopyTo(s1[3]); + + s1[0] = AesEnc(s1[0], RC[0]); + s1[1] = AesEnc(s1[1], RC[1]); + s1[2] = AesEnc(s1[2], RC[2]); + s1[3] = AesEnc(s1[3], RC[3]); + s1[0] = AesEnc(s1[0], RC[4]); + s1[1] = AesEnc(s1[1], RC[5]); + s1[2] = AesEnc(s1[2], RC[6]); + s1[3] = AesEnc(s1[3], RC[7]); + Mix512(s1, s2); + + s1[0] = AesEnc(s2[0], RC[8]); + s1[1] = AesEnc(s2[1], RC[9]); + s1[2] = AesEnc(s2[2], RC[10]); + s1[3] = AesEnc(s2[3], RC[11]); + s1[0] = AesEnc(s1[0], RC[12]); + s1[1] = AesEnc(s1[1], RC[13]); + s1[2] = AesEnc(s1[2], RC[14]); + s1[3] = AesEnc(s1[3], RC[15]); + Mix512(s1, s2); + + s1[0] = AesEnc(s2[0], RC[16]); + s1[1] = AesEnc(s2[1], RC[17]); + s1[2] = AesEnc(s2[2], RC[18]); + s1[3] = AesEnc(s2[3], RC[19]); + s1[0] = AesEnc(s1[0], RC[20]); + s1[1] = AesEnc(s1[1], RC[21]); + s1[2] = AesEnc(s1[2], RC[22]); + s1[3] = AesEnc(s1[3], RC[23]); + Mix512(s1, s2); + + s1[0] = AesEnc(s2[0], RC[24]); + s1[1] = AesEnc(s2[1], RC[25]); + s1[2] = AesEnc(s2[2], RC[26]); + s1[3] = AesEnc(s2[3], RC[27]); + s1[0] = AesEnc(s1[0], RC[28]); + s1[1] = AesEnc(s1[1], RC[29]); + s1[2] = AesEnc(s1[2], RC[30]); + s1[3] = AesEnc(s1[3], RC[31]); + Mix512(s1, s2); + + s1[0] = AesEnc(s2[0], RC[32]); + s1[1] = AesEnc(s2[1], RC[33]); + s1[2] = AesEnc(s2[2], RC[34]); + s1[3] = AesEnc(s2[3], RC[35]); + s1[0] = AesEnc(s1[0], RC[36]); + s1[1] = AesEnc(s1[1], RC[37]); + s1[2] = AesEnc(s1[2], RC[38]); + s1[3] = AesEnc(s1[3], RC[39]); + Mix512(s1, s2); + + Xor(s2[0], msg, s1[0]); + Xor(s2[1], msg[16..], s1[1]); + Xor(s2[2], msg[32..], s1[2]); + Xor(s2[3], msg[48..], s1[3]); + + s1[0].AsSpan(8, 8).CopyTo(output); + s1[1].AsSpan(8, 8).CopyTo(output[8..]); + s1[2].AsSpan(0, 8).CopyTo(output[16..]); + s1[3].AsSpan(0, 8).CopyTo(output[24..]); + + return DIGEST_SIZE; + } +#else + private static int Haraka512256(byte[] msg, byte[] output, int outOff) + { + byte[][] s1 = new byte[4][]; + s1[0] = new byte[16]; + s1[1] = new byte[16]; + s1[2] = new byte[16]; + s1[3] = new byte[16]; + byte[][] s2 = new byte[4][]; + s2[0] = new byte[16]; + s2[1] = new byte[16]; + s2[2] = new byte[16]; + s2[3] = new byte[16]; + + Array.Copy(msg, 0, s1[0], 0, 16); + Array.Copy(msg, 16, s1[1], 0, 16); + Array.Copy(msg, 32, s1[2], 0, 16); + Array.Copy(msg, 48, s1[3], 0, 16); + + s1[0] = AesEnc(s1[0], RC[0]); + s1[1] = AesEnc(s1[1], RC[1]); + s1[2] = AesEnc(s1[2], RC[2]); + s1[3] = AesEnc(s1[3], RC[3]); + s1[0] = AesEnc(s1[0], RC[4]); + s1[1] = AesEnc(s1[1], RC[5]); + s1[2] = AesEnc(s1[2], RC[6]); + s1[3] = AesEnc(s1[3], RC[7]); + Mix512(s1, s2); + + s1[0] = AesEnc(s2[0], RC[8]); + s1[1] = AesEnc(s2[1], RC[9]); + s1[2] = AesEnc(s2[2], RC[10]); + s1[3] = AesEnc(s2[3], RC[11]); + s1[0] = AesEnc(s1[0], RC[12]); + s1[1] = AesEnc(s1[1], RC[13]); + s1[2] = AesEnc(s1[2], RC[14]); + s1[3] = AesEnc(s1[3], RC[15]); + Mix512(s1, s2); + + s1[0] = AesEnc(s2[0], RC[16]); + s1[1] = AesEnc(s2[1], RC[17]); + s1[2] = AesEnc(s2[2], RC[18]); + s1[3] = AesEnc(s2[3], RC[19]); + s1[0] = AesEnc(s1[0], RC[20]); + s1[1] = AesEnc(s1[1], RC[21]); + s1[2] = AesEnc(s1[2], RC[22]); + s1[3] = AesEnc(s1[3], RC[23]); + Mix512(s1, s2); + + s1[0] = AesEnc(s2[0], RC[24]); + s1[1] = AesEnc(s2[1], RC[25]); + s1[2] = AesEnc(s2[2], RC[26]); + s1[3] = AesEnc(s2[3], RC[27]); + s1[0] = AesEnc(s1[0], RC[28]); + s1[1] = AesEnc(s1[1], RC[29]); + s1[2] = AesEnc(s1[2], RC[30]); + s1[3] = AesEnc(s1[3], RC[31]); + Mix512(s1, s2); + + s1[0] = AesEnc(s2[0], RC[32]); + s1[1] = AesEnc(s2[1], RC[33]); + s1[2] = AesEnc(s2[2], RC[34]); + s1[3] = AesEnc(s2[3], RC[35]); + s1[0] = AesEnc(s1[0], RC[36]); + s1[1] = AesEnc(s1[1], RC[37]); + s1[2] = AesEnc(s1[2], RC[38]); + s1[3] = AesEnc(s1[3], RC[39]); + Mix512(s1, s2); + + s1[0] = Xor(s2[0], msg, 0); + s1[1] = Xor(s2[1], msg, 16); + s1[2] = Xor(s2[2], msg, 32); + s1[3] = Xor(s2[3], msg, 48); + + Array.Copy(s1[0], 8, output, outOff, 8); + Array.Copy(s1[1], 8, output, outOff + 8, 8); + Array.Copy(s1[2], 0, output, outOff + 16, 8); + Array.Copy(s1[3], 0, output, outOff + 24, 8); + + return DIGEST_SIZE; + } +#endif + + private static void Mix512(byte[][] s1, byte[][] s2) + { + Array.Copy(s1[0], 12, s2[0], 0, 4); + Array.Copy(s1[2], 12, s2[0], 4, 4); + Array.Copy(s1[1], 12, s2[0], 8, 4); + Array.Copy(s1[3], 12, s2[0], 12, 4); + + Array.Copy(s1[2], 0, s2[1], 0, 4); + Array.Copy(s1[0], 0, s2[1], 4, 4); + Array.Copy(s1[3], 0, s2[1], 8, 4); + Array.Copy(s1[1], 0, s2[1], 12, 4); + + Array.Copy(s1[2], 4, s2[2], 0, 4); + Array.Copy(s1[0], 4, s2[2], 4, 4); + Array.Copy(s1[3], 4, s2[2], 8, 4); + Array.Copy(s1[1], 4, s2[2], 12, 4); + + Array.Copy(s1[0], 8, s2[3], 0, 4); + Array.Copy(s1[2], 8, s2[3], 4, 4); + Array.Copy(s1[1], 8, s2[3], 8, 4); + Array.Copy(s1[3], 8, s2[3], 12, 4); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka512Digest.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka512Digest.cs.meta new file mode 100644 index 0000000..f1c0ee8 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka512Digest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 03a68d2e3101c084c95606cd3a16e70b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka512_X86.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka512_X86.cs new file mode 100644 index 0000000..e380b0b --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka512_X86.cs @@ -0,0 +1,244 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +#if NETCOREAPP3_0_OR_GREATER +using System; +using System.Buffers.Binary; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests +{ + using Aes = System.Runtime.Intrinsics.X86.Aes; + using Sse2 = System.Runtime.Intrinsics.X86.Sse2; + + public static class Haraka512_X86 + { + public static bool IsSupported => Aes.IsSupported; + + // Haraka round constants + internal static readonly Vector128[] DefaultRoundConstants = new Vector128[] + { + Vector128.Create(0x9D, 0x7B, 0x81, 0x75, 0xF0, 0xFE, 0xC5, 0xB2, 0x0A, 0xC0, 0x20, 0xE6, 0x4C, 0x70, 0x84, 0x06), + Vector128.Create(0x17, 0xF7, 0x08, 0x2F, 0xA4, 0x6B, 0x0F, 0x64, 0x6B, 0xA0, 0xF3, 0x88, 0xE1, 0xB4, 0x66, 0x8B), + Vector128.Create(0x14, 0x91, 0x02, 0x9F, 0x60, 0x9D, 0x02, 0xCF, 0x98, 0x84, 0xF2, 0x53, 0x2D, 0xDE, 0x02, 0x34), + Vector128.Create(0x79, 0x4F, 0x5B, 0xFD, 0xAF, 0xBC, 0xF3, 0xBB, 0x08, 0x4F, 0x7B, 0x2E, 0xE6, 0xEA, 0xD6, 0x0E), + Vector128.Create(0x44, 0x70, 0x39, 0xBE, 0x1C, 0xCD, 0xEE, 0x79, 0x8B, 0x44, 0x72, 0x48, 0xCB, 0xB0, 0xCF, 0xCB), + Vector128.Create(0x7B, 0x05, 0x8A, 0x2B, 0xED, 0x35, 0x53, 0x8D, 0xB7, 0x32, 0x90, 0x6E, 0xEE, 0xCD, 0xEA, 0x7E), + Vector128.Create(0x1B, 0xEF, 0x4F, 0xDA, 0x61, 0x27, 0x41, 0xE2, 0xD0, 0x7C, 0x2E, 0x5E, 0x43, 0x8F, 0xC2, 0x67), + Vector128.Create(0x3B, 0x0B, 0xC7, 0x1F, 0xE2, 0xFD, 0x5F, 0x67, 0x07, 0xCC, 0xCA, 0xAF, 0xB0, 0xD9, 0x24, 0x29), + Vector128.Create(0xEE, 0x65, 0xD4, 0xB9, 0xCA, 0x8F, 0xDB, 0xEC, 0xE9, 0x7F, 0x86, 0xE6, 0xF1, 0x63, 0x4D, 0xAB), + Vector128.Create(0x33, 0x7E, 0x03, 0xAD, 0x4F, 0x40, 0x2A, 0x5B, 0x64, 0xCD, 0xB7, 0xD4, 0x84, 0xBF, 0x30, 0x1C), + Vector128.Create(0x00, 0x98, 0xF6, 0x8D, 0x2E, 0x8B, 0x02, 0x69, 0xBF, 0x23, 0x17, 0x94, 0xB9, 0x0B, 0xCC, 0xB2), + Vector128.Create(0x8A, 0x2D, 0x9D, 0x5C, 0xC8, 0x9E, 0xAA, 0x4A, 0x72, 0x55, 0x6F, 0xDE, 0xA6, 0x78, 0x04, 0xFA), + Vector128.Create(0xD4, 0x9F, 0x12, 0x29, 0x2E, 0x4F, 0xFA, 0x0E, 0x12, 0x2A, 0x77, 0x6B, 0x2B, 0x9F, 0xB4, 0xDF), + Vector128.Create(0xEE, 0x12, 0x6A, 0xBB, 0xAE, 0x11, 0xD6, 0x32, 0x36, 0xA2, 0x49, 0xF4, 0x44, 0x03, 0xA1, 0x1E), + Vector128.Create(0xA6, 0xEC, 0xA8, 0x9C, 0xC9, 0x00, 0x96, 0x5F, 0x84, 0x00, 0x05, 0x4B, 0x88, 0x49, 0x04, 0xAF), + Vector128.Create(0xEC, 0x93, 0xE5, 0x27, 0xE3, 0xC7, 0xA2, 0x78, 0x4F, 0x9C, 0x19, 0x9D, 0xD8, 0x5E, 0x02, 0x21), + Vector128.Create(0x73, 0x01, 0xD4, 0x82, 0xCD, 0x2E, 0x28, 0xB9, 0xB7, 0xC9, 0x59, 0xA7, 0xF8, 0xAA, 0x3A, 0xBF), + Vector128.Create(0x6B, 0x7D, 0x30, 0x10, 0xD9, 0xEF, 0xF2, 0x37, 0x17, 0xB0, 0x86, 0x61, 0x0D, 0x70, 0x60, 0x62), + Vector128.Create(0xC6, 0x9A, 0xFC, 0xF6, 0x53, 0x91, 0xC2, 0x81, 0x43, 0x04, 0x30, 0x21, 0xC2, 0x45, 0xCA, 0x5A), + Vector128.Create(0x3A, 0x94, 0xD1, 0x36, 0xE8, 0x92, 0xAF, 0x2C, 0xBB, 0x68, 0x6B, 0x22, 0x3C, 0x97, 0x23, 0x92), + Vector128.Create(0xB4, 0x71, 0x10, 0xE5, 0x58, 0xB9, 0xBA, 0x6C, 0xEB, 0x86, 0x58, 0x22, 0x38, 0x92, 0xBF, 0xD3), + Vector128.Create(0x8D, 0x12, 0xE1, 0x24, 0xDD, 0xFD, 0x3D, 0x93, 0x77, 0xC6, 0xF0, 0xAE, 0xE5, 0x3C, 0x86, 0xDB), + Vector128.Create(0xB1, 0x12, 0x22, 0xCB, 0xE3, 0x8D, 0xE4, 0x83, 0x9C, 0xA0, 0xEB, 0xFF, 0x68, 0x62, 0x60, 0xBB), + Vector128.Create(0x7D, 0xF7, 0x2B, 0xC7, 0x4E, 0x1A, 0xB9, 0x2D, 0x9C, 0xD1, 0xE4, 0xE2, 0xDC, 0xD3, 0x4B, 0x73), + Vector128.Create(0x4E, 0x92, 0xB3, 0x2C, 0xC4, 0x15, 0x14, 0x4B, 0x43, 0x1B, 0x30, 0x61, 0xC3, 0x47, 0xBB, 0x43), + Vector128.Create(0x99, 0x68, 0xEB, 0x16, 0xDD, 0x31, 0xB2, 0x03, 0xF6, 0xEF, 0x07, 0xE7, 0xA8, 0x75, 0xA7, 0xDB), + Vector128.Create(0x2C, 0x47, 0xCA, 0x7E, 0x02, 0x23, 0x5E, 0x8E, 0x77, 0x59, 0x75, 0x3C, 0x4B, 0x61, 0xF3, 0x6D), + Vector128.Create(0xF9, 0x17, 0x86, 0xB8, 0xB9, 0xE5, 0x1B, 0x6D, 0x77, 0x7D, 0xDE, 0xD6, 0x17, 0x5A, 0xA7, 0xCD), + Vector128.Create(0x5D, 0xEE, 0x46, 0xA9, 0x9D, 0x06, 0x6C, 0x9D, 0xAA, 0xE9, 0xA8, 0x6B, 0xF0, 0x43, 0x6B, 0xEC), + Vector128.Create(0xC1, 0x27, 0xF3, 0x3B, 0x59, 0x11, 0x53, 0xA2, 0x2B, 0x33, 0x57, 0xF9, 0x50, 0x69, 0x1E, 0xCB), + Vector128.Create(0xD9, 0xD0, 0x0E, 0x60, 0x53, 0x03, 0xED, 0xE4, 0x9C, 0x61, 0xDA, 0x00, 0x75, 0x0C, 0xEE, 0x2C), + Vector128.Create(0x50, 0xA3, 0xA4, 0x63, 0xBC, 0xBA, 0xBB, 0x80, 0xAB, 0x0C, 0xE9, 0x96, 0xA1, 0xA5, 0xB1, 0xF0), + Vector128.Create(0x39, 0xCA, 0x8D, 0x93, 0x30, 0xDE, 0x0D, 0xAB, 0x88, 0x29, 0x96, 0x5E, 0x02, 0xB1, 0x3D, 0xAE), + Vector128.Create(0x42, 0xB4, 0x75, 0x2E, 0xA8, 0xF3, 0x14, 0x88, 0x0B, 0xA4, 0x54, 0xD5, 0x38, 0x8F, 0xBB, 0x17), + Vector128.Create(0xF6, 0x16, 0x0A, 0x36, 0x79, 0xB7, 0xB6, 0xAE, 0xD7, 0x7F, 0x42, 0x5F, 0x5B, 0x8A, 0xBB, 0x34), + Vector128.Create(0xDE, 0xAF, 0xBA, 0xFF, 0x18, 0x59, 0xCE, 0x43, 0x38, 0x54, 0xE5, 0xCB, 0x41, 0x52, 0xF6, 0x26), + Vector128.Create(0x78, 0xC9, 0x9E, 0x83, 0xF7, 0x9C, 0xCA, 0xA2, 0x6A, 0x02, 0xF3, 0xB9, 0x54, 0x9A, 0xE9, 0x4C), + Vector128.Create(0x35, 0x12, 0x90, 0x22, 0x28, 0x6E, 0xC0, 0x40, 0xBE, 0xF7, 0xDF, 0x1B, 0x1A, 0xA5, 0x51, 0xAE), + Vector128.Create(0xCF, 0x59, 0xA6, 0x48, 0x0F, 0xBC, 0x73, 0xC1, 0x2B, 0xD2, 0x7E, 0xBA, 0x3C, 0x61, 0xC1, 0xA0), + Vector128.Create(0xA1, 0x9D, 0xC5, 0xE9, 0xFD, 0xBD, 0xD6, 0x4A, 0x88, 0x82, 0x28, 0x02, 0x03, 0xCC, 0x6A, 0x75), + }; + + public static void Hash(ReadOnlySpan input, Span output) + { + if (!IsSupported) + throw new PlatformNotSupportedException(nameof(Haraka512_X86)); + + var s0 = Load128(input[ ..16]); + var s1 = Load128(input[16..32]); + var s2 = Load128(input[32..48]); + var s3 = Load128(input[48..64]); + + ImplRounds(ref s0, ref s1, ref s2, ref s3, DefaultRoundConstants.AsSpan(0, 40)); + + s0 = Sse2.Xor(s0, Load128(input[ ..16])); + s1 = Sse2.Xor(s1, Load128(input[16..32])); + s2 = Sse2.Xor(s2, Load128(input[32..48])); + s3 = Sse2.Xor(s3, Load128(input[48..64])); + + Store64(s0.GetUpper(), output[ .. 8]); + Store64(s1.GetUpper(), output[ 8..16]); + Store64(s2.GetLower(), output[16..24]); + Store64(s3.GetLower(), output[24..32]); + } + + public static void Hash(ReadOnlySpan input, Span output, + ReadOnlySpan> roundConstants) + { + if (!IsSupported) + throw new PlatformNotSupportedException(nameof(Haraka512_X86)); + + var s0 = Load128(input[ ..16]); + var s1 = Load128(input[16..32]); + var s2 = Load128(input[32..48]); + var s3 = Load128(input[48..64]); + + ImplRounds(ref s0, ref s1, ref s2, ref s3, roundConstants[..40]); + + s0 = Sse2.Xor(s0, Load128(input[ ..16])); + s1 = Sse2.Xor(s1, Load128(input[16..32])); + s2 = Sse2.Xor(s2, Load128(input[32..48])); + s3 = Sse2.Xor(s3, Load128(input[48..64])); + + Store64(s0.GetUpper(), output[ .. 8]); + Store64(s1.GetUpper(), output[ 8..16]); + Store64(s2.GetLower(), output[16..24]); + Store64(s3.GetLower(), output[24..32]); + } + + public static void Permute(ReadOnlySpan input, Span output) + { + if (!IsSupported) + throw new PlatformNotSupportedException(nameof(Haraka512_X86)); + + var s0 = Load128(input[ ..16]); + var s1 = Load128(input[16..32]); + var s2 = Load128(input[32..48]); + var s3 = Load128(input[48..64]); + + ImplRounds(ref s0, ref s1, ref s2, ref s3, DefaultRoundConstants.AsSpan(0, 40)); + + Store128(s0, output[ ..16]); + Store128(s1, output[16..32]); + Store128(s2, output[32..48]); + Store128(s3, output[48..64]); + } + + public static void Permute(ReadOnlySpan input, Span output, + ReadOnlySpan> roundConstants) + { + if (!IsSupported) + throw new PlatformNotSupportedException(nameof(Haraka512_X86)); + + var s0 = Load128(input[ ..16]); + var s1 = Load128(input[16..32]); + var s2 = Load128(input[32..48]); + var s3 = Load128(input[48..64]); + + ImplRounds(ref s0, ref s1, ref s2, ref s3, roundConstants[..40]); + + Store128(s0, output[ ..16]); + Store128(s1, output[16..32]); + Store128(s2, output[32..48]); + Store128(s3, output[48..64]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ImplRounds(ref Vector128 s0, ref Vector128 s1, ref Vector128 s2, + ref Vector128 s3, ReadOnlySpan> rc) + { + ImplRound(ref s0, ref s1, ref s2, ref s3, rc[ .. 8]); + ImplRound(ref s0, ref s1, ref s2, ref s3, rc[ 8..16]); + ImplRound(ref s0, ref s1, ref s2, ref s3, rc[16..24]); + ImplRound(ref s0, ref s1, ref s2, ref s3, rc[24..32]); + ImplRound(ref s0, ref s1, ref s2, ref s3, rc[32..40]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ImplRound(ref Vector128 s0, ref Vector128 s1, ref Vector128 s2, + ref Vector128 s3, ReadOnlySpan> rc) + { + ImplAes(ref s0, ref s1, ref s2, ref s3, rc[..8]); + ImplMix(ref s0, ref s1, ref s2, ref s3); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ImplAes(ref Vector128 s0, ref Vector128 s1, ref Vector128 s2, + ref Vector128 s3, ReadOnlySpan> rc) + { + s0 = Aes.Encrypt(s0, rc[0]); + s1 = Aes.Encrypt(s1, rc[1]); + s2 = Aes.Encrypt(s2, rc[2]); + s3 = Aes.Encrypt(s3, rc[3]); + + s0 = Aes.Encrypt(s0, rc[4]); + s1 = Aes.Encrypt(s1, rc[5]); + s2 = Aes.Encrypt(s2, rc[6]); + s3 = Aes.Encrypt(s3, rc[7]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ImplMix(ref Vector128 s0, ref Vector128 s1, ref Vector128 s2, + ref Vector128 s3) + { + var t0 = s0.AsUInt32(); + var t1 = s1.AsUInt32(); + var t2 = s2.AsUInt32(); + var t3 = s3.AsUInt32(); + + var u0 = Sse2.UnpackLow(t0, t1); + var u1 = Sse2.UnpackHigh(t0, t1); + var u2 = Sse2.UnpackLow(t2, t3); + var u3 = Sse2.UnpackHigh(t2, t3); + + s0 = Sse2.UnpackHigh(u1, u3).AsByte(); + s1 = Sse2.UnpackLow(u2, u0).AsByte(); + s2 = Sse2.UnpackHigh(u2, u0).AsByte(); + s3 = Sse2.UnpackLow(u1, u3).AsByte(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector128 Load128(ReadOnlySpan t) + { + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 16) + return MemoryMarshal.Read>(t); + + return Vector128.Create( + BinaryPrimitives.ReadUInt64LittleEndian(t[..8]), + BinaryPrimitives.ReadUInt64LittleEndian(t[8..]) + ).AsByte(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Store128(Vector128 s, Span t) + { + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 16) + { + MemoryMarshal.Write(t, ref s); + return; + } + + var u = s.AsUInt64(); + BinaryPrimitives.WriteUInt64LittleEndian(t[..8], u.GetElement(0)); + BinaryPrimitives.WriteUInt64LittleEndian(t[8..], u.GetElement(1)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Store64(Vector64 s, Span t) + { + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 8) + { + MemoryMarshal.Write(t, ref s); + return; + } + + var u = s.AsUInt64(); + BinaryPrimitives.WriteUInt64LittleEndian(t, u.ToScalar()); + } + } +} +#endif +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka512_X86.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka512_X86.cs.meta new file mode 100644 index 0000000..a62134c --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Haraka512_X86.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 54e732781fc194d428d4900db7245296 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/HarakaBase.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/HarakaBase.cs new file mode 100644 index 0000000..27632e5 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/HarakaBase.cs @@ -0,0 +1,188 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests +{ + public abstract class HarakaBase + : IDigest + { + internal static readonly int DIGEST_SIZE = 32; + + // Haraka round constants + internal static readonly byte[][] RC = new byte[][] + { + new byte[]{ 0x9D, 0x7B, 0x81, 0x75, 0xF0, 0xFE, 0xC5, 0xB2, 0x0A, 0xC0, 0x20, 0xE6, 0x4C, 0x70, 0x84, 0x06 }, + new byte[]{ 0x17, 0xF7, 0x08, 0x2F, 0xA4, 0x6B, 0x0F, 0x64, 0x6B, 0xA0, 0xF3, 0x88, 0xE1, 0xB4, 0x66, 0x8B }, + new byte[]{ 0x14, 0x91, 0x02, 0x9F, 0x60, 0x9D, 0x02, 0xCF, 0x98, 0x84, 0xF2, 0x53, 0x2D, 0xDE, 0x02, 0x34 }, + new byte[]{ 0x79, 0x4F, 0x5B, 0xFD, 0xAF, 0xBC, 0xF3, 0xBB, 0x08, 0x4F, 0x7B, 0x2E, 0xE6, 0xEA, 0xD6, 0x0E }, + new byte[]{ 0x44, 0x70, 0x39, 0xBE, 0x1C, 0xCD, 0xEE, 0x79, 0x8B, 0x44, 0x72, 0x48, 0xCB, 0xB0, 0xCF, 0xCB }, + new byte[]{ 0x7B, 0x05, 0x8A, 0x2B, 0xED, 0x35, 0x53, 0x8D, 0xB7, 0x32, 0x90, 0x6E, 0xEE, 0xCD, 0xEA, 0x7E }, + new byte[]{ 0x1B, 0xEF, 0x4F, 0xDA, 0x61, 0x27, 0x41, 0xE2, 0xD0, 0x7C, 0x2E, 0x5E, 0x43, 0x8F, 0xC2, 0x67 }, + new byte[]{ 0x3B, 0x0B, 0xC7, 0x1F, 0xE2, 0xFD, 0x5F, 0x67, 0x07, 0xCC, 0xCA, 0xAF, 0xB0, 0xD9, 0x24, 0x29 }, + new byte[]{ 0xEE, 0x65, 0xD4, 0xB9, 0xCA, 0x8F, 0xDB, 0xEC, 0xE9, 0x7F, 0x86, 0xE6, 0xF1, 0x63, 0x4D, 0xAB }, + new byte[]{ 0x33, 0x7E, 0x03, 0xAD, 0x4F, 0x40, 0x2A, 0x5B, 0x64, 0xCD, 0xB7, 0xD4, 0x84, 0xBF, 0x30, 0x1C }, + new byte[]{ 0x00, 0x98, 0xF6, 0x8D, 0x2E, 0x8B, 0x02, 0x69, 0xBF, 0x23, 0x17, 0x94, 0xB9, 0x0B, 0xCC, 0xB2 }, + new byte[]{ 0x8A, 0x2D, 0x9D, 0x5C, 0xC8, 0x9E, 0xAA, 0x4A, 0x72, 0x55, 0x6F, 0xDE, 0xA6, 0x78, 0x04, 0xFA }, + new byte[]{ 0xD4, 0x9F, 0x12, 0x29, 0x2E, 0x4F, 0xFA, 0x0E, 0x12, 0x2A, 0x77, 0x6B, 0x2B, 0x9F, 0xB4, 0xDF }, + new byte[]{ 0xEE, 0x12, 0x6A, 0xBB, 0xAE, 0x11, 0xD6, 0x32, 0x36, 0xA2, 0x49, 0xF4, 0x44, 0x03, 0xA1, 0x1E }, + new byte[]{ 0xA6, 0xEC, 0xA8, 0x9C, 0xC9, 0x00, 0x96, 0x5F, 0x84, 0x00, 0x05, 0x4B, 0x88, 0x49, 0x04, 0xAF }, + new byte[]{ 0xEC, 0x93, 0xE5, 0x27, 0xE3, 0xC7, 0xA2, 0x78, 0x4F, 0x9C, 0x19, 0x9D, 0xD8, 0x5E, 0x02, 0x21 }, + new byte[]{ 0x73, 0x01, 0xD4, 0x82, 0xCD, 0x2E, 0x28, 0xB9, 0xB7, 0xC9, 0x59, 0xA7, 0xF8, 0xAA, 0x3A, 0xBF }, + new byte[]{ 0x6B, 0x7D, 0x30, 0x10, 0xD9, 0xEF, 0xF2, 0x37, 0x17, 0xB0, 0x86, 0x61, 0x0D, 0x70, 0x60, 0x62 }, + new byte[]{ 0xC6, 0x9A, 0xFC, 0xF6, 0x53, 0x91, 0xC2, 0x81, 0x43, 0x04, 0x30, 0x21, 0xC2, 0x45, 0xCA, 0x5A }, + new byte[]{ 0x3A, 0x94, 0xD1, 0x36, 0xE8, 0x92, 0xAF, 0x2C, 0xBB, 0x68, 0x6B, 0x22, 0x3C, 0x97, 0x23, 0x92 }, + new byte[]{ 0xB4, 0x71, 0x10, 0xE5, 0x58, 0xB9, 0xBA, 0x6C, 0xEB, 0x86, 0x58, 0x22, 0x38, 0x92, 0xBF, 0xD3 }, + new byte[]{ 0x8D, 0x12, 0xE1, 0x24, 0xDD, 0xFD, 0x3D, 0x93, 0x77, 0xC6, 0xF0, 0xAE, 0xE5, 0x3C, 0x86, 0xDB }, + new byte[]{ 0xB1, 0x12, 0x22, 0xCB, 0xE3, 0x8D, 0xE4, 0x83, 0x9C, 0xA0, 0xEB, 0xFF, 0x68, 0x62, 0x60, 0xBB }, + new byte[]{ 0x7D, 0xF7, 0x2B, 0xC7, 0x4E, 0x1A, 0xB9, 0x2D, 0x9C, 0xD1, 0xE4, 0xE2, 0xDC, 0xD3, 0x4B, 0x73 }, + new byte[]{ 0x4E, 0x92, 0xB3, 0x2C, 0xC4, 0x15, 0x14, 0x4B, 0x43, 0x1B, 0x30, 0x61, 0xC3, 0x47, 0xBB, 0x43 }, + new byte[]{ 0x99, 0x68, 0xEB, 0x16, 0xDD, 0x31, 0xB2, 0x03, 0xF6, 0xEF, 0x07, 0xE7, 0xA8, 0x75, 0xA7, 0xDB }, + new byte[]{ 0x2C, 0x47, 0xCA, 0x7E, 0x02, 0x23, 0x5E, 0x8E, 0x77, 0x59, 0x75, 0x3C, 0x4B, 0x61, 0xF3, 0x6D }, + new byte[]{ 0xF9, 0x17, 0x86, 0xB8, 0xB9, 0xE5, 0x1B, 0x6D, 0x77, 0x7D, 0xDE, 0xD6, 0x17, 0x5A, 0xA7, 0xCD }, + new byte[]{ 0x5D, 0xEE, 0x46, 0xA9, 0x9D, 0x06, 0x6C, 0x9D, 0xAA, 0xE9, 0xA8, 0x6B, 0xF0, 0x43, 0x6B, 0xEC }, + new byte[]{ 0xC1, 0x27, 0xF3, 0x3B, 0x59, 0x11, 0x53, 0xA2, 0x2B, 0x33, 0x57, 0xF9, 0x50, 0x69, 0x1E, 0xCB }, + new byte[]{ 0xD9, 0xD0, 0x0E, 0x60, 0x53, 0x03, 0xED, 0xE4, 0x9C, 0x61, 0xDA, 0x00, 0x75, 0x0C, 0xEE, 0x2C }, + new byte[]{ 0x50, 0xA3, 0xA4, 0x63, 0xBC, 0xBA, 0xBB, 0x80, 0xAB, 0x0C, 0xE9, 0x96, 0xA1, 0xA5, 0xB1, 0xF0 }, + new byte[]{ 0x39, 0xCA, 0x8D, 0x93, 0x30, 0xDE, 0x0D, 0xAB, 0x88, 0x29, 0x96, 0x5E, 0x02, 0xB1, 0x3D, 0xAE }, + new byte[]{ 0x42, 0xB4, 0x75, 0x2E, 0xA8, 0xF3, 0x14, 0x88, 0x0B, 0xA4, 0x54, 0xD5, 0x38, 0x8F, 0xBB, 0x17 }, + new byte[]{ 0xF6, 0x16, 0x0A, 0x36, 0x79, 0xB7, 0xB6, 0xAE, 0xD7, 0x7F, 0x42, 0x5F, 0x5B, 0x8A, 0xBB, 0x34 }, + new byte[]{ 0xDE, 0xAF, 0xBA, 0xFF, 0x18, 0x59, 0xCE, 0x43, 0x38, 0x54, 0xE5, 0xCB, 0x41, 0x52, 0xF6, 0x26 }, + new byte[]{ 0x78, 0xC9, 0x9E, 0x83, 0xF7, 0x9C, 0xCA, 0xA2, 0x6A, 0x02, 0xF3, 0xB9, 0x54, 0x9A, 0xE9, 0x4C }, + new byte[]{ 0x35, 0x12, 0x90, 0x22, 0x28, 0x6E, 0xC0, 0x40, 0xBE, 0xF7, 0xDF, 0x1B, 0x1A, 0xA5, 0x51, 0xAE }, + new byte[]{ 0xCF, 0x59, 0xA6, 0x48, 0x0F, 0xBC, 0x73, 0xC1, 0x2B, 0xD2, 0x7E, 0xBA, 0x3C, 0x61, 0xC1, 0xA0 }, + new byte[]{ 0xA1, 0x9D, 0xC5, 0xE9, 0xFD, 0xBD, 0xD6, 0x4A, 0x88, 0x82, 0x28, 0x02, 0x03, 0xCC, 0x6A, 0x75 }, + }; + + private static readonly byte[,] S = + { + { 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76 }, + { 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0 }, + { 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15 }, + { 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75 }, + { 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84 }, + { 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF }, + { 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8 }, + { 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2 }, + { 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73 }, + { 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB }, + { 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79 }, + { 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08 }, + { 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A }, + { 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E }, + { 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF }, + { 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 }, + }; + + private static byte SBox(byte x) + { + return S[(uint)x >> 4, x & 0xFU]; + } + + private static byte[] SubBytes(byte[] s) + { + byte[] output = new byte[s.Length]; + for(int i = 0; i < 16; ++i) + { + output[i] = SBox(s[i]); + } + return output; + } + + private static byte[] ShiftRows(byte[] s) + { + return new byte[]{ + s[0], s[5], s[10], s[15], + s[4], s[9], s[14], s[3], + s[8], s[13], s[2], s[7], + s[12], s[1], s[6], s[11] + }; + } + + internal static byte[] AesEnc(byte[] s, byte[] rk) + { + s = SubBytes(s); + s = ShiftRows(s); + s = MixColumns(s); + XorTo(rk, s); + return s; + } + + private static byte MulX(byte p) + { + return (byte)(((p & 0x7F) << 1) ^ (((uint)p >> 7) * 0x1BU)); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal static void Xor(ReadOnlySpan x, ReadOnlySpan y, Span z) + { + for (int i = 0; i < z.Length; i++) + { + z[i] = (byte)(x[i] ^ y[i]); + } + } +#else + internal static byte[] Xor(byte[] x, byte[] y, int yStart) + { + byte[] output = new byte[16]; + for (int i = 0; i < output.Length; i++) + { + output[i] = (byte)(x[i] ^ y[yStart++]); + } + return output; + } +#endif + + private static void XorTo(byte[] x, byte[] z) + { + for (int i = 0; i < 16; i += 4) + { + z[i + 0] ^= x[i + 0]; + z[i + 1] ^= x[i + 1]; + z[i + 2] ^= x[i + 2]; + z[i + 3] ^= x[i + 3]; + } + } + + private static byte[] MixColumns(byte[] s) + { + byte[] output = new byte[s.Length]; + int j = 0, i4; + for (int i = 0; i < 4; i++) + { + i4 = i << 2; + output[j++] = (byte)(MulX(s[i4]) ^ MulX(s[i4 + 1]) ^ s[i4 + 1] ^ s[i4 + 2] ^ s[i4 + 3]); + output[j++] = (byte)(s[i4] ^ MulX(s[i4 + 1]) ^ MulX(s[i4 + 2]) ^ s[i4 + 2] ^ s[i4 + 3]); + output[j++] = (byte)(s[i4] ^ s[i4 + 1] ^ MulX(s[i4 + 2]) ^ MulX(s[i4 + 3]) ^ s[i4 + 3]); + output[j++] = (byte)(MulX(s[i4]) ^ s[i4] ^ s[i4 + 1] ^ s[i4 + 2] ^ MulX(s[i4 + 3])); + } + + return output; + } + + public abstract string AlgorithmName { get; } + + public int GetDigestSize() + { + return DIGEST_SIZE; + } + + public abstract int GetByteLength(); + + public abstract void Update(byte input); + + public abstract void BlockUpdate(byte[] input, int inOff, int length); + + public abstract int DoFinal(byte[] output, int outOff); + + public abstract void Reset(); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public abstract void BlockUpdate(ReadOnlySpan input); + + public abstract int DoFinal(Span output); +#endif + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/HarakaBase.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/HarakaBase.cs.meta new file mode 100644 index 0000000..2166c7c --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/HarakaBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2cb5624e262e7964babc76f5311ba8ff +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/KeccakDigest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/KeccakDigest.cs index 9870c63..32d72f9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/KeccakDigest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/KeccakDigest.cs @@ -78,6 +78,13 @@ public virtual void BlockUpdate(byte[] input, int inOff, int len) Absorb(input, inOff, len); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) + { + Absorb(input); + } +#endif + public virtual int DoFinal(byte[] output, int outOff) { Squeeze(output, outOff, fixedOutputLength); @@ -87,6 +94,18 @@ public virtual int DoFinal(byte[] output, int outOff) return GetDigestSize(); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int DoFinal(Span output) + { + int digestSize = GetDigestSize(); + Squeeze(output[..digestSize]); + + Reset(); + + return digestSize; + } +#endif + /* * TODO Possible API change to support partial-byte suffixes. */ @@ -201,6 +220,46 @@ protected void Absorb(byte[] data, int off, int len) this.bitsInQueue = remaining << 3; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + protected void Absorb(ReadOnlySpan data) + { + if ((bitsInQueue & 7) != 0) + throw new InvalidOperationException("attempt to absorb with odd length queue"); + if (squeezing) + throw new InvalidOperationException("attempt to absorb while squeezing"); + + int bytesInQueue = bitsInQueue >> 3; + int rateBytes = rate >> 3; + + int len = data.Length; + int available = rateBytes - bytesInQueue; + if (len < available) + { + data.CopyTo(dataQueue.AsSpan(bytesInQueue)); + this.bitsInQueue += len << 3; + return; + } + + int count = 0; + if (bytesInQueue > 0) + { + data[..available].CopyTo(dataQueue.AsSpan(bytesInQueue)); + count += available; + KeccakAbsorb(dataQueue, 0); + } + + int remaining; + while ((remaining = len - count) >= rateBytes) + { + KeccakAbsorb(data[count..]); + count += rateBytes; + } + + data[count..].CopyTo(dataQueue.AsSpan()); + this.bitsInQueue = remaining << 3; + } +#endif + protected void AbsorbBits(int data, int bits) { if (bits < 1 || bits > 7) @@ -272,6 +331,30 @@ protected void Squeeze(byte[] output, int offset, long outputLength) } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + protected void Squeeze(Span output) + { + if (!squeezing) + { + PadAndSwitchToSqueezingPhase(); + } + long outputLength = (long)output.Length << 3; + + long i = 0; + while (i < outputLength) + { + if (bitsInQueue == 0) + { + KeccakExtract(); + } + int partialBlock = (int)System.Math.Min(bitsInQueue, outputLength - i); + dataQueue.AsSpan((rate - bitsInQueue) >> 3, partialBlock >> 3).CopyTo(output[(int)(i >> 3)..]); + bitsInQueue -= partialBlock; + i += partialBlock; + } + } +#endif + private void KeccakAbsorb(byte[] data, int off) { int count = rate >> 6; @@ -284,6 +367,20 @@ private void KeccakAbsorb(byte[] data, int off) KeccakPermutation(); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void KeccakAbsorb(ReadOnlySpan data) + { + int count = rate >> 6, off = 0; + for (int i = 0; i < count; ++i) + { + state[i] ^= Pack.LE_To_UInt64(data[off..]); + off += 8; + } + + KeccakPermutation(); + } +#endif + private void KeccakExtract() { KeccakPermutation(); @@ -312,11 +409,11 @@ private void KeccakPermutation() ulong c3 = a03 ^ a08 ^ a13 ^ a18 ^ a23; ulong c4 = a04 ^ a09 ^ a14 ^ a19 ^ a24; - ulong d1 = (c1 << 1 | c1 >> -1) ^ c4; - ulong d2 = (c2 << 1 | c2 >> -1) ^ c0; - ulong d3 = (c3 << 1 | c3 >> -1) ^ c1; - ulong d4 = (c4 << 1 | c4 >> -1) ^ c2; - ulong d0 = (c0 << 1 | c0 >> -1) ^ c3; + ulong d1 = Longs.RotateLeft(c1, 1) ^ c4; + ulong d2 = Longs.RotateLeft(c2, 1) ^ c0; + ulong d3 = Longs.RotateLeft(c3, 1) ^ c1; + ulong d4 = Longs.RotateLeft(c4, 1) ^ c2; + ulong d0 = Longs.RotateLeft(c0, 1) ^ c3; a00 ^= d1; a05 ^= d1; a10 ^= d1; a15 ^= d1; a20 ^= d1; a01 ^= d2; a06 ^= d2; a11 ^= d2; a16 ^= d2; a21 ^= d2; @@ -325,30 +422,30 @@ private void KeccakPermutation() a04 ^= d0; a09 ^= d0; a14 ^= d0; a19 ^= d0; a24 ^= d0; // rho/pi - c1 = a01 << 1 | a01 >> 63; - a01 = a06 << 44 | a06 >> 20; - a06 = a09 << 20 | a09 >> 44; - a09 = a22 << 61 | a22 >> 3; - a22 = a14 << 39 | a14 >> 25; - a14 = a20 << 18 | a20 >> 46; - a20 = a02 << 62 | a02 >> 2; - a02 = a12 << 43 | a12 >> 21; - a12 = a13 << 25 | a13 >> 39; - a13 = a19 << 8 | a19 >> 56; - a19 = a23 << 56 | a23 >> 8; - a23 = a15 << 41 | a15 >> 23; - a15 = a04 << 27 | a04 >> 37; - a04 = a24 << 14 | a24 >> 50; - a24 = a21 << 2 | a21 >> 62; - a21 = a08 << 55 | a08 >> 9; - a08 = a16 << 45 | a16 >> 19; - a16 = a05 << 36 | a05 >> 28; - a05 = a03 << 28 | a03 >> 36; - a03 = a18 << 21 | a18 >> 43; - a18 = a17 << 15 | a17 >> 49; - a17 = a11 << 10 | a11 >> 54; - a11 = a07 << 6 | a07 >> 58; - a07 = a10 << 3 | a10 >> 61; + c1 = Longs.RotateLeft(a01, 1); + a01 = Longs.RotateLeft(a06, 44); + a06 = Longs.RotateLeft(a09, 20); + a09 = Longs.RotateLeft(a22, 61); + a22 = Longs.RotateLeft(a14, 39); + a14 = Longs.RotateLeft(a20, 18); + a20 = Longs.RotateLeft(a02, 62); + a02 = Longs.RotateLeft(a12, 43); + a12 = Longs.RotateLeft(a13, 25); + a13 = Longs.RotateLeft(a19, 8); + a19 = Longs.RotateLeft(a23, 56); + a23 = Longs.RotateLeft(a15, 41); + a15 = Longs.RotateLeft(a04, 27); + a04 = Longs.RotateLeft(a24, 14); + a24 = Longs.RotateLeft(a21, 2); + a21 = Longs.RotateLeft(a08, 55); + a08 = Longs.RotateLeft(a16, 45); + a16 = Longs.RotateLeft(a05, 36); + a05 = Longs.RotateLeft(a03, 28); + a03 = Longs.RotateLeft(a18, 21); + a18 = Longs.RotateLeft(a17, 15); + a17 = Longs.RotateLeft(a11, 10); + a11 = Longs.RotateLeft(a07, 6); + a07 = Longs.RotateLeft(a10, 3); a10 = c1; // chi diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/LongDigest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/LongDigest.cs index 9401793..f68aea0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/LongDigest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/LongDigest.cs @@ -11,51 +11,47 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests /** * Base class for SHA-384 and SHA-512. */ - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] public abstract class LongDigest - : IDigest, IMemoable + : IDigest, IMemoable { - private int MyByteLength = 128; + private int MyByteLength = 128; - private byte[] xBuf; - private int xBufOff; + private byte[] xBuf; + private int xBufOff; - private long byteCount1; - private long byteCount2; + private long byteCount1; + private long byteCount2; internal ulong H1, H2, H3, H4, H5, H6, H7, H8; private ulong[] W = new ulong[80]; private int wOff; - /** + /** * Constructor for variable length word */ internal LongDigest() { xBuf = new byte[8]; - Reset(); + Reset(); } - /** + /** * Copy constructor. We are using copy constructors in place * of the object.Clone() interface as this interface is not * supported by J2ME. */ internal LongDigest( - LongDigest t) - { - xBuf = new byte[t.xBuf.Length]; + LongDigest t) + { + xBuf = new byte[t.xBuf.Length]; - CopyIn(t); - } + CopyIn(t); + } - protected void CopyIn(LongDigest t) - { + protected void CopyIn(LongDigest t) + { Array.Copy(t.xBuf, 0, xBuf, 0, t.xBuf.Length); xBufOff = t.xBufOff; @@ -90,9 +86,9 @@ public void Update( } public void BlockUpdate( - byte[] input, - int inOff, - int length) + byte[] input, + int inOff, + int length) { // // fill the current word @@ -108,7 +104,7 @@ public void BlockUpdate( // // process whole words. // - while (length > xBuf.Length) + while (length >= xBuf.Length) { ProcessWord(input, inOff); @@ -129,12 +125,54 @@ public void BlockUpdate( } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + int inOff = 0; + int length = input.Length; + + // + // fill the current word + // + while ((xBufOff != 0) && (length > 0)) + { + Update(input[inOff]); + + inOff++; + length--; + } + + // + // process whole words. + // + while (length >= xBuf.Length) + { + ProcessWord(input.Slice(inOff, xBuf.Length)); + + inOff += xBuf.Length; + length -= xBuf.Length; + byteCount1 += xBuf.Length; + } + + // + // load in the remainder. + // + while (length > 0) + { + Update(input[inOff]); + + inOff++; + length--; + } + } +#endif + public void Finish() { AdjustByteCounts(); - long lowBitLength = byteCount1 << 3; - long hiBitLength = byteCount2; + long lowBitLength = byteCount1 << 3; + long hiBitLength = byteCount2; // // add the pad bytes. @@ -157,20 +195,20 @@ public virtual void Reset() byteCount2 = 0; xBufOff = 0; - for ( int i = 0; i < xBuf.Length; i++ ) + for (int i = 0; i < xBuf.Length; i++) { xBuf[i] = 0; } wOff = 0; - Array.Clear(W, 0, W.Length); + Array.Clear(W, 0, W.Length); } internal void ProcessWord( - byte[] input, - int inOff) + byte[] input, + int inOff) { - W[wOff] = Pack.BE_To_UInt64(input, inOff); + W[wOff] = Pack.BE_To_UInt64(input, inOff); if (++wOff == 16) { @@ -178,7 +216,19 @@ internal void ProcessWord( } } - /** +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal void ProcessWord(ReadOnlySpan word) + { + W[wOff] = Pack.BE_To_UInt64(word); + + if (++wOff == 16) + { + ProcessBlock(); + } + } +#endif + + /** * adjust the byte counts so that byteCount2 represents the * upper long (less 3 bits) word of the byte count. */ @@ -186,14 +236,14 @@ private void AdjustByteCounts() { if (byteCount1 > 0x1fffffffffffffffL) { - byteCount2 += (long) ((ulong) byteCount1 >> 61); + byteCount2 += (long)((ulong)byteCount1 >> 61); byteCount1 &= 0x1fffffffffffffffL; } } internal void ProcessLength( - long lowW, - long hiW) + long lowW, + long hiW) { if (wOff > 14) { @@ -228,51 +278,51 @@ internal void ProcessBlock() ulong g = H7; ulong h = H8; - int t = 0; - for(int i = 0; i < 10; i ++) - { - // t = 8 * i - h += Sum1(e) + Ch(e, f, g) + K[t] + W[t++]; - d += h; - h += Sum0(a) + Maj(a, b, c); - - // t = 8 * i + 1 - g += Sum1(d) + Ch(d, e, f) + K[t] + W[t++]; - c += g; - g += Sum0(h) + Maj(h, a, b); - - // t = 8 * i + 2 - f += Sum1(c) + Ch(c, d, e) + K[t] + W[t++]; - b += f; - f += Sum0(g) + Maj(g, h, a); - - // t = 8 * i + 3 - e += Sum1(b) + Ch(b, c, d) + K[t] + W[t++]; - a += e; - e += Sum0(f) + Maj(f, g, h); - - // t = 8 * i + 4 - d += Sum1(a) + Ch(a, b, c) + K[t] + W[t++]; - h += d; - d += Sum0(e) + Maj(e, f, g); - - // t = 8 * i + 5 - c += Sum1(h) + Ch(h, a, b) + K[t] + W[t++]; - g += c; - c += Sum0(d) + Maj(d, e, f); - - // t = 8 * i + 6 - b += Sum1(g) + Ch(g, h, a) + K[t] + W[t++]; - f += b; - b += Sum0(c) + Maj(c, d, e); - - // t = 8 * i + 7 - a += Sum1(f) + Ch(f, g, h) + K[t] + W[t++]; - e += a; - a += Sum0(b) + Maj(b, c, d); - } - - H1 += a; + int t = 0; + for (int i = 0; i < 10; i++) + { + // t = 8 * i + h += Sum1(e) + Ch(e, f, g) + K[t] + W[t++]; + d += h; + h += Sum0(a) + Maj(a, b, c); + + // t = 8 * i + 1 + g += Sum1(d) + Ch(d, e, f) + K[t] + W[t++]; + c += g; + g += Sum0(h) + Maj(h, a, b); + + // t = 8 * i + 2 + f += Sum1(c) + Ch(c, d, e) + K[t] + W[t++]; + b += f; + f += Sum0(g) + Maj(g, h, a); + + // t = 8 * i + 3 + e += Sum1(b) + Ch(b, c, d) + K[t] + W[t++]; + a += e; + e += Sum0(f) + Maj(f, g, h); + + // t = 8 * i + 4 + d += Sum1(a) + Ch(a, b, c) + K[t] + W[t++]; + h += d; + d += Sum0(e) + Maj(e, f, g); + + // t = 8 * i + 5 + c += Sum1(h) + Ch(h, a, b) + K[t] + W[t++]; + g += c; + c += Sum0(d) + Maj(d, e, f); + + // t = 8 * i + 6 + b += Sum1(g) + Ch(g, h, a) + K[t] + W[t++]; + f += b; + b += Sum0(c) + Maj(c, d, e); + + // t = 8 * i + 7 + a += Sum1(f) + Ch(f, g, h) + K[t] + W[t++]; + e += a; + a += Sum0(b) + Maj(b, c, d); + } + + H1 += a; H2 += b; H3 += c; H4 += d; @@ -281,14 +331,14 @@ internal void ProcessBlock() H7 += g; H8 += h; - // + // // reset the offset and clean out the word buffer. // wOff = 0; - Array.Clear(W, 0, 16); - } + Array.Clear(W, 0, 16); + } - /* SHA-384 and SHA-512 functions (as for SHA-256 but for longs) */ + /* SHA-384 and SHA-512 functions (as for SHA-256 but for longs) */ private static ulong Ch(ulong x, ulong y, ulong z) { return (x & y) ^ (~x & z); @@ -301,62 +351,65 @@ private static ulong Maj(ulong x, ulong y, ulong z) private static ulong Sum0(ulong x) { - return ((x << 36) | (x >> 28)) ^ ((x << 30) | (x >> 34)) ^ ((x << 25) | (x >> 39)); + return ((x << 36) | (x >> 28)) ^ ((x << 30) | (x >> 34)) ^ ((x << 25) | (x >> 39)); } - private static ulong Sum1(ulong x) + private static ulong Sum1(ulong x) { - return ((x << 50) | (x >> 14)) ^ ((x << 46) | (x >> 18)) ^ ((x << 23) | (x >> 41)); + return ((x << 50) | (x >> 14)) ^ ((x << 46) | (x >> 18)) ^ ((x << 23) | (x >> 41)); } private static ulong Sigma0(ulong x) { - return ((x << 63) | (x >> 1)) ^ ((x << 56) | (x >> 8)) ^ (x >> 7); + return ((x << 63) | (x >> 1)) ^ ((x << 56) | (x >> 8)) ^ (x >> 7); } private static ulong Sigma1(ulong x) { - return ((x << 45) | (x >> 19)) ^ ((x << 3) | (x >> 61)) ^ (x >> 6); + return ((x << 45) | (x >> 19)) ^ ((x << 3) | (x >> 61)) ^ (x >> 6); } /* SHA-384 and SHA-512 Constants * (represent the first 64 bits of the fractional parts of the * cube roots of the first sixty-four prime numbers) */ - internal static readonly ulong[] K = - { - 0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, - 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, - 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, - 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694, - 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, - 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, - 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, - 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70, - 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df, - 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, - 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, - 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, - 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, - 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3, - 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, - 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, - 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, - 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b, - 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c, - 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817 - }; - - public int GetByteLength() - { - return MyByteLength; - } - - public abstract string AlgorithmName { get; } - public abstract int GetDigestSize(); + internal static readonly ulong[] K = + { + 0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, + 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, + 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, + 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694, + 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, + 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, + 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, + 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70, + 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df, + 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, + 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, + 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, + 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, + 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3, + 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, + 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, + 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, + 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b, + 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c, + 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817 + }; + + public int GetByteLength() + { + return MyByteLength; + } + + public abstract string AlgorithmName { get; } + public abstract int GetDigestSize(); public abstract int DoFinal(byte[] output, int outOff); - public abstract IMemoable Copy(); - public abstract void Reset(IMemoable t); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public abstract int DoFinal(Span output); +#endif + public abstract IMemoable Copy(); + public abstract void Reset(IMemoable t); } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/MD2Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/MD2Digest.cs index f8e528b..cf0d081 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/MD2Digest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/MD2Digest.cs @@ -2,7 +2,6 @@ #pragma warning disable using System; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests @@ -101,6 +100,30 @@ public int DoFinal(byte[] output, int outOff) return DigestLength; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + // add padding + byte paddingByte = (byte)(M.Length - mOff); + for (int i = mOff; i < M.Length; i++) + { + M[i] = paddingByte; + } + //do final check sum + ProcessChecksum(M); + // do final block process + ProcessBlock(M); + + ProcessBlock(C); + + X.AsSpan(xOff, 16).CopyTo(output); + + Reset(); + + return DigestLength; + } +#endif + /** * reset the digest back to it's initial state. */ @@ -161,7 +184,7 @@ public void BlockUpdate(byte[] input, int inOff, int length) // // process whole words. // - while (length > 16) + while (length >= 16) { Array.Copy(input,inOff,M,0,16); ProcessChecksum(M); @@ -181,6 +204,40 @@ public void BlockUpdate(byte[] input, int inOff, int length) } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + // + // fill the current word + // + while ((mOff != 0) && (input.Length > 0)) + { + Update(input[0]); + input = input[1..]; + } + + // + // process whole words. + // + while (input.Length >= 16) + { + input[..16].CopyTo(M); + ProcessChecksum(M); + ProcessBlock(M); + input = input[16..]; + } + + // + // load in the remainder. + // + while (input.Length > 0) + { + Update(input[0]); + input = input[1..]; + } + } +#endif + internal void ProcessChecksum(byte[] m) { int L = C[15]; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/MD4Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/MD4Digest.cs index 9ea8dda..bc430a1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/MD4Digest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/MD4Digest.cs @@ -2,6 +2,7 @@ #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 @@ -62,12 +63,9 @@ public override int GetDigestSize() return DigestLength; } - internal override void ProcessWord( - byte[] input, - int inOff) + internal override void ProcessWord(byte[] input, int inOff) { - X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8) - | ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24); + X[xOff++] = (int)Pack.LE_To_UInt32(input, inOff); if (xOff == 16) { @@ -75,6 +73,18 @@ internal override void ProcessWord( } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal override void ProcessWord(ReadOnlySpan word) + { + X[xOff++] = (int)Pack.LE_To_UInt32(word); + + if (xOff == 16) + { + ProcessBlock(); + } + } +#endif + internal override void ProcessLength( long bitLength) { @@ -87,32 +97,35 @@ internal override void ProcessLength( X[15] = (int)((ulong) bitLength >> 32); } - private void UnpackWord( - int word, - byte[] outBytes, - int outOff) + public override int DoFinal(byte[] output, int outOff) { - outBytes[outOff] = (byte)word; - outBytes[outOff + 1] = (byte)((uint) word >> 8); - outBytes[outOff + 2] = (byte)((uint) word >> 16); - outBytes[outOff + 3] = (byte)((uint) word >> 24); + Finish(); + + Pack.UInt32_To_LE((uint)H1, output, outOff); + Pack.UInt32_To_LE((uint)H2, output, outOff + 4); + Pack.UInt32_To_LE((uint)H3, output, outOff + 8); + Pack.UInt32_To_LE((uint)H4, output, outOff + 12); + + Reset(); + + return DigestLength; } - public override int DoFinal( - byte[] output, - int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) { Finish(); - UnpackWord(H1, output, outOff); - UnpackWord(H2, output, outOff + 4); - UnpackWord(H3, output, outOff + 8); - UnpackWord(H4, output, outOff + 12); + Pack.UInt32_To_LE((uint)H1, output); + Pack.UInt32_To_LE((uint)H2, output[4..]); + Pack.UInt32_To_LE((uint)H3, output[8..]); + Pack.UInt32_To_LE((uint)H4, output[12..]); Reset(); return DigestLength; } +#endif /** * reset the chaining variables to the IV values. @@ -158,16 +171,6 @@ public override void Reset() private const int S33 = 11; private const int S34 = 15; - /* - * rotate int x left n bits. - */ - private int RotateLeft( - int x, - int n) - { - return (x << n) | (int) ((uint) x >> (32 - n)); - } - /* * F, G, H and I are the basic MD4 functions. */ @@ -205,62 +208,62 @@ internal override void ProcessBlock() // // Round 1 - F cycle, 16 times. // - a = RotateLeft((a + F(b, c, d) + X[ 0]), S11); - d = RotateLeft((d + F(a, b, c) + X[ 1]), S12); - c = RotateLeft((c + F(d, a, b) + X[ 2]), S13); - b = RotateLeft((b + F(c, d, a) + X[ 3]), S14); - a = RotateLeft((a + F(b, c, d) + X[ 4]), S11); - d = RotateLeft((d + F(a, b, c) + X[ 5]), S12); - c = RotateLeft((c + F(d, a, b) + X[ 6]), S13); - b = RotateLeft((b + F(c, d, a) + X[ 7]), S14); - a = RotateLeft((a + F(b, c, d) + X[ 8]), S11); - d = RotateLeft((d + F(a, b, c) + X[ 9]), S12); - c = RotateLeft((c + F(d, a, b) + X[10]), S13); - b = RotateLeft((b + F(c, d, a) + X[11]), S14); - a = RotateLeft((a + F(b, c, d) + X[12]), S11); - d = RotateLeft((d + F(a, b, c) + X[13]), S12); - c = RotateLeft((c + F(d, a, b) + X[14]), S13); - b = RotateLeft((b + F(c, d, a) + X[15]), S14); + a = Integers.RotateLeft((a + F(b, c, d) + X[ 0]), S11); + d = Integers.RotateLeft((d + F(a, b, c) + X[ 1]), S12); + c = Integers.RotateLeft((c + F(d, a, b) + X[ 2]), S13); + b = Integers.RotateLeft((b + F(c, d, a) + X[ 3]), S14); + a = Integers.RotateLeft((a + F(b, c, d) + X[ 4]), S11); + d = Integers.RotateLeft((d + F(a, b, c) + X[ 5]), S12); + c = Integers.RotateLeft((c + F(d, a, b) + X[ 6]), S13); + b = Integers.RotateLeft((b + F(c, d, a) + X[ 7]), S14); + a = Integers.RotateLeft((a + F(b, c, d) + X[ 8]), S11); + d = Integers.RotateLeft((d + F(a, b, c) + X[ 9]), S12); + c = Integers.RotateLeft((c + F(d, a, b) + X[10]), S13); + b = Integers.RotateLeft((b + F(c, d, a) + X[11]), S14); + a = Integers.RotateLeft((a + F(b, c, d) + X[12]), S11); + d = Integers.RotateLeft((d + F(a, b, c) + X[13]), S12); + c = Integers.RotateLeft((c + F(d, a, b) + X[14]), S13); + b = Integers.RotateLeft((b + F(c, d, a) + X[15]), S14); // // Round 2 - G cycle, 16 times. // - a = RotateLeft((a + G(b, c, d) + X[ 0] + 0x5a827999), S21); - d = RotateLeft((d + G(a, b, c) + X[ 4] + 0x5a827999), S22); - c = RotateLeft((c + G(d, a, b) + X[ 8] + 0x5a827999), S23); - b = RotateLeft((b + G(c, d, a) + X[12] + 0x5a827999), S24); - a = RotateLeft((a + G(b, c, d) + X[ 1] + 0x5a827999), S21); - d = RotateLeft((d + G(a, b, c) + X[ 5] + 0x5a827999), S22); - c = RotateLeft((c + G(d, a, b) + X[ 9] + 0x5a827999), S23); - b = RotateLeft((b + G(c, d, a) + X[13] + 0x5a827999), S24); - a = RotateLeft((a + G(b, c, d) + X[ 2] + 0x5a827999), S21); - d = RotateLeft((d + G(a, b, c) + X[ 6] + 0x5a827999), S22); - c = RotateLeft((c + G(d, a, b) + X[10] + 0x5a827999), S23); - b = RotateLeft((b + G(c, d, a) + X[14] + 0x5a827999), S24); - a = RotateLeft((a + G(b, c, d) + X[ 3] + 0x5a827999), S21); - d = RotateLeft((d + G(a, b, c) + X[ 7] + 0x5a827999), S22); - c = RotateLeft((c + G(d, a, b) + X[11] + 0x5a827999), S23); - b = RotateLeft((b + G(c, d, a) + X[15] + 0x5a827999), S24); + a = Integers.RotateLeft((a + G(b, c, d) + X[ 0] + 0x5a827999), S21); + d = Integers.RotateLeft((d + G(a, b, c) + X[ 4] + 0x5a827999), S22); + c = Integers.RotateLeft((c + G(d, a, b) + X[ 8] + 0x5a827999), S23); + b = Integers.RotateLeft((b + G(c, d, a) + X[12] + 0x5a827999), S24); + a = Integers.RotateLeft((a + G(b, c, d) + X[ 1] + 0x5a827999), S21); + d = Integers.RotateLeft((d + G(a, b, c) + X[ 5] + 0x5a827999), S22); + c = Integers.RotateLeft((c + G(d, a, b) + X[ 9] + 0x5a827999), S23); + b = Integers.RotateLeft((b + G(c, d, a) + X[13] + 0x5a827999), S24); + a = Integers.RotateLeft((a + G(b, c, d) + X[ 2] + 0x5a827999), S21); + d = Integers.RotateLeft((d + G(a, b, c) + X[ 6] + 0x5a827999), S22); + c = Integers.RotateLeft((c + G(d, a, b) + X[10] + 0x5a827999), S23); + b = Integers.RotateLeft((b + G(c, d, a) + X[14] + 0x5a827999), S24); + a = Integers.RotateLeft((a + G(b, c, d) + X[ 3] + 0x5a827999), S21); + d = Integers.RotateLeft((d + G(a, b, c) + X[ 7] + 0x5a827999), S22); + c = Integers.RotateLeft((c + G(d, a, b) + X[11] + 0x5a827999), S23); + b = Integers.RotateLeft((b + G(c, d, a) + X[15] + 0x5a827999), S24); // // Round 3 - H cycle, 16 times. // - a = RotateLeft((a + H(b, c, d) + X[ 0] + 0x6ed9eba1), S31); - d = RotateLeft((d + H(a, b, c) + X[ 8] + 0x6ed9eba1), S32); - c = RotateLeft((c + H(d, a, b) + X[ 4] + 0x6ed9eba1), S33); - b = RotateLeft((b + H(c, d, a) + X[12] + 0x6ed9eba1), S34); - a = RotateLeft((a + H(b, c, d) + X[ 2] + 0x6ed9eba1), S31); - d = RotateLeft((d + H(a, b, c) + X[10] + 0x6ed9eba1), S32); - c = RotateLeft((c + H(d, a, b) + X[ 6] + 0x6ed9eba1), S33); - b = RotateLeft((b + H(c, d, a) + X[14] + 0x6ed9eba1), S34); - a = RotateLeft((a + H(b, c, d) + X[ 1] + 0x6ed9eba1), S31); - d = RotateLeft((d + H(a, b, c) + X[ 9] + 0x6ed9eba1), S32); - c = RotateLeft((c + H(d, a, b) + X[ 5] + 0x6ed9eba1), S33); - b = RotateLeft((b + H(c, d, a) + X[13] + 0x6ed9eba1), S34); - a = RotateLeft((a + H(b, c, d) + X[ 3] + 0x6ed9eba1), S31); - d = RotateLeft((d + H(a, b, c) + X[11] + 0x6ed9eba1), S32); - c = RotateLeft((c + H(d, a, b) + X[ 7] + 0x6ed9eba1), S33); - b = RotateLeft((b + H(c, d, a) + X[15] + 0x6ed9eba1), S34); + a = Integers.RotateLeft((a + H(b, c, d) + X[ 0] + 0x6ed9eba1), S31); + d = Integers.RotateLeft((d + H(a, b, c) + X[ 8] + 0x6ed9eba1), S32); + c = Integers.RotateLeft((c + H(d, a, b) + X[ 4] + 0x6ed9eba1), S33); + b = Integers.RotateLeft((b + H(c, d, a) + X[12] + 0x6ed9eba1), S34); + a = Integers.RotateLeft((a + H(b, c, d) + X[ 2] + 0x6ed9eba1), S31); + d = Integers.RotateLeft((d + H(a, b, c) + X[10] + 0x6ed9eba1), S32); + c = Integers.RotateLeft((c + H(d, a, b) + X[ 6] + 0x6ed9eba1), S33); + b = Integers.RotateLeft((b + H(c, d, a) + X[14] + 0x6ed9eba1), S34); + a = Integers.RotateLeft((a + H(b, c, d) + X[ 1] + 0x6ed9eba1), S31); + d = Integers.RotateLeft((d + H(a, b, c) + X[ 9] + 0x6ed9eba1), S32); + c = Integers.RotateLeft((c + H(d, a, b) + X[ 5] + 0x6ed9eba1), S33); + b = Integers.RotateLeft((b + H(c, d, a) + X[13] + 0x6ed9eba1), S34); + a = Integers.RotateLeft((a + H(b, c, d) + X[ 3] + 0x6ed9eba1), S31); + d = Integers.RotateLeft((d + H(a, b, c) + X[11] + 0x6ed9eba1), S32); + c = Integers.RotateLeft((c + H(d, a, b) + X[ 7] + 0x6ed9eba1), S33); + b = Integers.RotateLeft((b + H(c, d, a) + X[15] + 0x6ed9eba1), S34); H1 += a; H2 += b; @@ -288,9 +291,7 @@ public override void Reset(IMemoable other) CopyIn(d); } - } - } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/MD5Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/MD5Digest.cs index 3930179..3d8bbd8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/MD5Digest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/MD5Digest.cs @@ -57,9 +57,7 @@ public override int GetDigestSize() return DigestLength; } - internal override void ProcessWord( - byte[] input, - int inOff) + internal override void ProcessWord(byte[] input, int inOff) { X[xOff] = Pack.LE_To_UInt32(input, inOff); @@ -69,6 +67,18 @@ internal override void ProcessWord( } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal override void ProcessWord(ReadOnlySpan word) + { + X[xOff] = Pack.LE_To_UInt32(word); + + if (++xOff == 16) + { + ProcessBlock(); + } + } +#endif + internal override void ProcessLength( long bitLength) { @@ -105,6 +115,22 @@ public override int DoFinal( return DigestLength; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + Finish(); + + Pack.UInt32_To_LE(H1, output); + Pack.UInt32_To_LE(H2, output[4..]); + Pack.UInt32_To_LE(H3, output[8..]); + Pack.UInt32_To_LE(H4, output[12..]); + + Reset(); + + return DigestLength; + } +#endif + /** * reset the chaining variables to the IV values. */ diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/NonMemoableDigest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/NonMemoableDigest.cs index 97170fa..5cbd463 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/NonMemoableDigest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/NonMemoableDigest.cs @@ -46,11 +46,25 @@ public virtual void BlockUpdate(byte[] input, int inOff, int len) mBaseDigest.BlockUpdate(input, inOff, len); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) + { + mBaseDigest.BlockUpdate(input); + } +#endif + public virtual int DoFinal(byte[] output, int outOff) { return mBaseDigest.DoFinal(output, outOff); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int DoFinal(Span output) + { + return mBaseDigest.DoFinal(output); + } +#endif + public virtual void Reset() { mBaseDigest.Reset(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/NullDigest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/NullDigest.cs index 241f3d0..0230a4e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/NullDigest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/NullDigest.cs @@ -24,7 +24,7 @@ public int GetByteLength() public int GetDigestSize() { - return (int)bOut.Length; + return Convert.ToInt32(bOut.Length); } public void Update(byte b) @@ -37,17 +37,48 @@ public void BlockUpdate(byte[] inBytes, int inOff, int len) bOut.Write(inBytes, inOff, len); } - public int DoFinal(byte[] outBytes, int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) { + bOut.Write(input); + } +#endif + + public int DoFinal(byte[] outBytes, int outOff) + { + try + { + byte[] data = bOut.GetBuffer(); + int length = Convert.ToInt32(bOut.Length); + + Array.Copy(data, 0, outBytes, outOff, length); + + return length; + } + finally + { + Reset(); + } + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { try { - return Streams.WriteBufTo(bOut, outBytes, outOff); + byte[] data = bOut.GetBuffer(); + int length = Convert.ToInt32(bOut.Length); + + data.AsSpan(0, length).CopyTo(output); + + return length; } finally { Reset(); } } +#endif public void Reset() { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/ParallelHash.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/ParallelHash.cs index 4639f64..73cadb2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/ParallelHash.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/ParallelHash.cs @@ -87,7 +87,7 @@ public virtual void Update(byte b) buffer[bufOff++] = b; if (bufOff == buffer.Length) { - compress(); + Compress(); } } @@ -108,15 +108,15 @@ public virtual void BlockUpdate(byte[] inBuf, int inOff, int len) if (bufOff == buffer.Length) { - compress(); + Compress(); } } if (i < len) { - while (len - i > B) + while (len - i >= B) { - compress(inBuf, inOff + i, B); + Compress(inBuf, inOff + i, B); i += B; } } @@ -127,27 +127,75 @@ public virtual void BlockUpdate(byte[] inBuf, int inOff, int len) } } - private void compress() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) { - compress(buffer, 0, bufOff); + // + // fill the current word + // + int i = 0; + if (bufOff != 0) + { + while (i < input.Length && bufOff != buffer.Length) + { + buffer[bufOff++] = input[i++]; + } + + if (bufOff == buffer.Length) + { + Compress(); + } + } + + if (i < input.Length) + { + while (input.Length - i >= B) + { + Compress(input, i, B); + i += B; + } + } + + while (i < input.Length) + { + Update(input[i++]); + } + } +#endif + + private void Compress() + { + Compress(buffer, 0, bufOff); bufOff = 0; } - private void compress(byte[] buf, int offSet, int len) + private void Compress(byte[] buf, int offSet, int len) { compressor.BlockUpdate(buf, offSet, len); - compressor.DoFinal(compressorBuffer, 0, compressorBuffer.Length); + compressor.OutputFinal(compressorBuffer, 0, compressorBuffer.Length); + + cshake.BlockUpdate(compressorBuffer, 0, compressorBuffer.Length); + + nCount++; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void Compress(ReadOnlySpan input, int pos, int len) + { + compressor.BlockUpdate(input.Slice(pos, len)); + compressor.OutputFinal(compressorBuffer, 0, compressorBuffer.Length); cshake.BlockUpdate(compressorBuffer, 0, compressorBuffer.Length); nCount++; } +#endif - private void wrapUp(int outputSize) + private void WrapUp(int outputSize) { if (bufOff != 0) { - compress(); + Compress(); } byte[] nOut = XofUtilities.RightEncode(nCount); byte[] encOut = XofUtilities.RightEncode(outputSize * 8); @@ -162,39 +210,83 @@ public virtual int DoFinal(byte[] outBuf, int outOff) { if (firstOutput) { - wrapUp(outputLength); + WrapUp(outputLength); } - int rv = cshake.DoFinal(outBuf, outOff, GetDigestSize()); + int rv = cshake.DoFinal(outBuf, outOff); Reset(); return rv; } - public virtual int DoFinal(byte[] outBuf, int outOff, int outLen) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int DoFinal(Span output) { if (firstOutput) { - wrapUp(outputLength); + WrapUp(outputLength); } - int rv = cshake.DoFinal(outBuf, outOff, outLen); + int rv = cshake.DoFinal(output); Reset(); return rv; } +#endif - public virtual int DoOutput(byte[] outBuf, int outOff, int outLen) + public virtual int OutputFinal(byte[] outBuf, int outOff, int outLen) { if (firstOutput) { - wrapUp(0); + WrapUp(outputLength); } - return cshake.DoOutput(outBuf, outOff, outLen); + int rv = cshake.OutputFinal(outBuf, outOff, outLen); + + Reset(); + + return rv; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int OutputFinal(Span output) + { + if (firstOutput) + { + WrapUp(outputLength); + } + + int rv = cshake.OutputFinal(output); + + Reset(); + + return rv; } +#endif + + public virtual int Output(byte[] outBuf, int outOff, int outLen) + { + if (firstOutput) + { + WrapUp(0); + } + + return cshake.Output(outBuf, outOff, outLen); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int Output(Span output) + { + if (firstOutput) + { + WrapUp(0); + } + + return cshake.Output(output); + } +#endif public virtual void Reset() { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/RipeMD128Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/RipeMD128Digest.cs index c209c0c..3f4b651 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/RipeMD128Digest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/RipeMD128Digest.cs @@ -2,6 +2,7 @@ #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 @@ -59,12 +60,9 @@ public override int GetDigestSize() return DigestLength; } - internal override void ProcessWord( - byte[] input, - int inOff) + internal override void ProcessWord(byte[] input, int inOff) { - X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8) - | ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24); + X[xOff++] = (int)Pack.LE_To_UInt32(input, inOff); if (xOff == 16) { @@ -72,6 +70,18 @@ internal override void ProcessWord( } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal override void ProcessWord(ReadOnlySpan word) + { + X[xOff++] = (int)Pack.LE_To_UInt32(word); + + if (xOff == 16) + { + ProcessBlock(); + } + } +#endif + internal override void ProcessLength( long bitLength) { @@ -84,32 +94,35 @@ internal override void ProcessLength( X[15] = (int)((ulong) bitLength >> 32); } - private void UnpackWord( - int word, - byte[] outBytes, - int outOff) + public override int DoFinal(byte[] output, int outOff) { - outBytes[outOff] = (byte)word; - outBytes[outOff + 1] = (byte)((uint) word >> 8); - outBytes[outOff + 2] = (byte)((uint) word >> 16); - outBytes[outOff + 3] = (byte)((uint) word >> 24); + Finish(); + + Pack.UInt32_To_LE((uint)H0, output, outOff); + Pack.UInt32_To_LE((uint)H1, output, outOff + 4); + Pack.UInt32_To_LE((uint)H2, output, outOff + 8); + Pack.UInt32_To_LE((uint)H3, output, outOff + 12); + + Reset(); + + return DigestLength; } - public override int DoFinal( - byte[] output, - int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) { Finish(); - UnpackWord(H0, output, outOff); - UnpackWord(H1, output, outOff + 4); - UnpackWord(H2, output, outOff + 8); - UnpackWord(H3, output, outOff + 12); + Pack.UInt32_To_LE((uint)H0, output); + Pack.UInt32_To_LE((uint)H1, output[4..]); + Pack.UInt32_To_LE((uint)H2, output[8..]); + Pack.UInt32_To_LE((uint)H3, output[12..]); Reset(); return DigestLength; } +#endif /** * reset the chaining variables to the IV values. @@ -480,9 +493,7 @@ public override void Reset(IMemoable other) CopyIn(d); } - } - } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/RipeMD160Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/RipeMD160Digest.cs index d75893c..a94bfa0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/RipeMD160Digest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/RipeMD160Digest.cs @@ -2,6 +2,7 @@ #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 @@ -61,12 +62,9 @@ public override int GetDigestSize() return DigestLength; } - internal override void ProcessWord( - byte[] input, - int inOff) + internal override void ProcessWord(byte[] input, int inOff) { - X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8) - | ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24); + X[xOff++] = (int)Pack.LE_To_UInt32(input, inOff); if (xOff == 16) { @@ -74,7 +72,19 @@ internal override void ProcessWord( } } - internal override void ProcessLength( +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal override void ProcessWord(ReadOnlySpan word) + { + X[xOff++] = (int)Pack.LE_To_UInt32(word); + + if (xOff == 16) + { + ProcessBlock(); + } + } +#endif + + internal override void ProcessLength( long bitLength) { if (xOff > 14) @@ -86,33 +96,37 @@ internal override void ProcessLength( X[15] = (int)((ulong) bitLength >> 32); } - private void UnpackWord( - int word, - byte[] outBytes, - int outOff) + public override int DoFinal(byte[] output, int outOff) { - outBytes[outOff] = (byte)word; - outBytes[outOff + 1] = (byte)((uint) word >> 8); - outBytes[outOff + 2] = (byte)((uint) word >> 16); - outBytes[outOff + 3] = (byte)((uint) word >> 24); + Finish(); + + Pack.UInt32_To_LE((uint)H0, output, outOff); + Pack.UInt32_To_LE((uint)H1, output, outOff + 4); + Pack.UInt32_To_LE((uint)H2, output, outOff + 8); + Pack.UInt32_To_LE((uint)H3, output, outOff + 12); + Pack.UInt32_To_LE((uint)H4, output, outOff + 16); + + Reset(); + + return DigestLength; } - public override int DoFinal( - byte[] output, - int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) { Finish(); - UnpackWord(H0, output, outOff); - UnpackWord(H1, output, outOff + 4); - UnpackWord(H2, output, outOff + 8); - UnpackWord(H3, output, outOff + 12); - UnpackWord(H4, output, outOff + 16); + Pack.UInt32_To_LE((uint)H0, output); + Pack.UInt32_To_LE((uint)H1, output[4..]); + Pack.UInt32_To_LE((uint)H2, output[8..]); + Pack.UInt32_To_LE((uint)H3, output[12..]); + Pack.UInt32_To_LE((uint)H4, output[16..]); Reset(); return DigestLength; } +#endif /** * reset the chaining variables to the IV values. @@ -441,9 +455,7 @@ public override void Reset(IMemoable other) CopyIn(d); } - } - } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/RipeMD256Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/RipeMD256Digest.cs index 8ecadd5..d708f63 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/RipeMD256Digest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/RipeMD256Digest.cs @@ -2,6 +2,7 @@ #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 @@ -61,12 +62,9 @@ private void CopyIn(RipeMD256Digest t) xOff = t.xOff; } - internal override void ProcessWord( - byte[] input, - int inOff) + internal override void ProcessWord(byte[] input, int inOff) { - X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8) - | ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24); + X[xOff++] = (int)Pack.LE_To_UInt32(input, inOff); if (xOff == 16) { @@ -74,6 +72,18 @@ internal override void ProcessWord( } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal override void ProcessWord(ReadOnlySpan word) + { + X[xOff++] = (int)Pack.LE_To_UInt32(word); + + if (xOff == 16) + { + ProcessBlock(); + } + } +#endif + internal override void ProcessLength( long bitLength) { @@ -86,34 +96,43 @@ internal override void ProcessLength( X[15] = (int)((ulong)bitLength >> 32); } - private void UnpackWord( - int word, - byte[] outBytes, - int outOff) + public override int DoFinal(byte[] output, int outOff) { - outBytes[outOff] = (byte)(uint)word; - outBytes[outOff + 1] = (byte)((uint)word >> 8); - outBytes[outOff + 2] = (byte)((uint)word >> 16); - outBytes[outOff + 3] = (byte)((uint)word >> 24); + Finish(); + + Pack.UInt32_To_LE((uint)H0, output, outOff); + Pack.UInt32_To_LE((uint)H1, output, outOff + 4); + Pack.UInt32_To_LE((uint)H2, output, outOff + 8); + Pack.UInt32_To_LE((uint)H3, output, outOff + 12); + Pack.UInt32_To_LE((uint)H4, output, outOff + 16); + Pack.UInt32_To_LE((uint)H5, output, outOff + 20); + Pack.UInt32_To_LE((uint)H6, output, outOff + 24); + Pack.UInt32_To_LE((uint)H7, output, outOff + 28); + + Reset(); + + return DigestLength; } - public override int DoFinal(byte[] output, int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) { Finish(); - UnpackWord(H0, output, outOff); - UnpackWord(H1, output, outOff + 4); - UnpackWord(H2, output, outOff + 8); - UnpackWord(H3, output, outOff + 12); - UnpackWord(H4, output, outOff + 16); - UnpackWord(H5, output, outOff + 20); - UnpackWord(H6, output, outOff + 24); - UnpackWord(H7, output, outOff + 28); + Pack.UInt32_To_LE((uint)H0, output); + Pack.UInt32_To_LE((uint)H1, output[4..]); + Pack.UInt32_To_LE((uint)H2, output[8..]); + Pack.UInt32_To_LE((uint)H3, output[12..]); + Pack.UInt32_To_LE((uint)H4, output[16..]); + Pack.UInt32_To_LE((uint)H5, output[20..]); + Pack.UInt32_To_LE((uint)H6, output[24..]); + Pack.UInt32_To_LE((uint)H7, output[28..]); Reset(); return DigestLength; } +#endif ///

reset the chaining variables to the IV values. public override void Reset() @@ -427,7 +446,6 @@ public override void Reset(IMemoable other) CopyIn(d); } - } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/RipeMD320Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/RipeMD320Digest.cs index ebe9c47..634dbab 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/RipeMD320Digest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/RipeMD320Digest.cs @@ -2,6 +2,7 @@ #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 @@ -64,12 +65,9 @@ private void CopyIn(RipeMD320Digest t) xOff = t.xOff; } - internal override void ProcessWord( - byte[] input, - int inOff) + internal override void ProcessWord(byte[] input, int inOff) { - X[xOff++] = (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8) - | ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24); + X[xOff++] = (int)Pack.LE_To_UInt32(input, inOff); if (xOff == 16) { @@ -77,6 +75,18 @@ internal override void ProcessWord( } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal override void ProcessWord(ReadOnlySpan word) + { + X[xOff++] = (int)Pack.LE_To_UInt32(word); + + if (xOff == 16) + { + ProcessBlock(); + } + } +#endif + internal override void ProcessLength( long bitLength) { @@ -89,36 +99,47 @@ internal override void ProcessLength( X[15] = (int)((ulong)bitLength >> 32); } - private void UnpackWord( - int word, - byte[] outBytes, - int outOff) + public override int DoFinal(byte[] output, int outOff) { - outBytes[outOff] = (byte)word; - outBytes[outOff + 1] = (byte)((uint)word >> 8); - outBytes[outOff + 2] = (byte)((uint)word >> 16); - outBytes[outOff + 3] = (byte)((uint)word >> 24); + Finish(); + + Pack.UInt32_To_LE((uint)H0, output, outOff); + Pack.UInt32_To_LE((uint)H1, output, outOff + 4); + Pack.UInt32_To_LE((uint)H2, output, outOff + 8); + Pack.UInt32_To_LE((uint)H3, output, outOff + 12); + Pack.UInt32_To_LE((uint)H4, output, outOff + 16); + Pack.UInt32_To_LE((uint)H5, output, outOff + 20); + Pack.UInt32_To_LE((uint)H6, output, outOff + 24); + Pack.UInt32_To_LE((uint)H7, output, outOff + 28); + Pack.UInt32_To_LE((uint)H8, output, outOff + 32); + Pack.UInt32_To_LE((uint)H9, output, outOff + 36); + + Reset(); + + return DigestLength; } - public override int DoFinal(byte[] output, int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) { Finish(); - UnpackWord(H0, output, outOff); - UnpackWord(H1, output, outOff + 4); - UnpackWord(H2, output, outOff + 8); - UnpackWord(H3, output, outOff + 12); - UnpackWord(H4, output, outOff + 16); - UnpackWord(H5, output, outOff + 20); - UnpackWord(H6, output, outOff + 24); - UnpackWord(H7, output, outOff + 28); - UnpackWord(H8, output, outOff + 32); - UnpackWord(H9, output, outOff + 36); + Pack.UInt32_To_LE((uint)H0, output); + Pack.UInt32_To_LE((uint)H1, output[4..]); + Pack.UInt32_To_LE((uint)H2, output[8..]); + Pack.UInt32_To_LE((uint)H3, output[12..]); + Pack.UInt32_To_LE((uint)H4, output[16..]); + Pack.UInt32_To_LE((uint)H5, output[20..]); + Pack.UInt32_To_LE((uint)H6, output[24..]); + Pack.UInt32_To_LE((uint)H7, output[28..]); + Pack.UInt32_To_LE((uint)H8, output[32..]); + Pack.UInt32_To_LE((uint)H9, output[36..]); Reset(); return DigestLength; } +#endif /// reset the chaining variables to the IV values. public override void Reset() @@ -456,7 +477,6 @@ public override void Reset(IMemoable other) CopyIn(d); } - } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/SHA3Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/SHA3Digest.cs index cfac406..7b13409 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/SHA3Digest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/SHA3Digest.cs @@ -57,6 +57,15 @@ public override int DoFinal(byte[] output, int outOff) return base.DoFinal(output, outOff); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + AbsorbBits(0x02, 2); + + return base.DoFinal(output); + } +#endif + /* * TODO Possible API change to support partial-byte suffixes. */ diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/SM3Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/SM3Digest.cs index c20c6b8..5d1cf15 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/SM3Digest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/SM3Digest.cs @@ -120,7 +120,6 @@ public override void Reset() this.xOff = 0; } - public override int DoFinal(byte[] output, int outOff) { Finish(); @@ -132,13 +131,22 @@ public override int DoFinal(byte[] output, int outOff) return DIGEST_LENGTH; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + Finish(); + + Pack.UInt32_To_BE(V, output); + + Reset(); + + return DIGEST_LENGTH; + } +#endif - internal override void ProcessWord(byte[] input, - int inOff) + internal override void ProcessWord(byte[] input, int inOff) { - uint n = Pack.BE_To_UInt32(input, inOff); - this.inwords[this.xOff] = n; - ++this.xOff; + inwords[xOff++] = Pack.BE_To_UInt32(input, inOff); if (this.xOff >= 16) { @@ -146,7 +154,19 @@ internal override void ProcessWord(byte[] input, } } - internal override void ProcessLength(long bitLength) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal override void ProcessWord(ReadOnlySpan word) + { + inwords[xOff++] = Pack.BE_To_UInt32(word); + + if (this.xOff >= 16) + { + ProcessBlock(); + } + } +#endif + + internal override void ProcessLength(long bitLength) { if (this.xOff > (BLOCK_SIZE - 2)) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha1Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha1Digest.cs index b53ec02..773f743 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha1Digest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha1Digest.cs @@ -14,10 +14,6 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests * It is interesting to ponder why the, apart from the extra IV, the other difference here from MD5 * is the "endianness" of the word processing! */ - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] public class Sha1Digest : GeneralDigest { @@ -67,9 +63,7 @@ public override int GetDigestSize() return DigestLength; } - internal override void ProcessWord( - byte[] input, - int inOff) + internal override void ProcessWord(byte[] input, int inOff) { X[xOff] = Pack.BE_To_UInt32(input, inOff); @@ -79,6 +73,18 @@ internal override void ProcessWord( } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal override void ProcessWord(ReadOnlySpan word) + { + X[xOff] = Pack.BE_To_UInt32(word); + + if (++xOff == 16) + { + ProcessBlock(); + } + } +#endif + internal override void ProcessLength(long bitLength) { if (xOff > 14) @@ -107,6 +113,23 @@ public override int DoFinal( return DigestLength; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + Finish(); + + Pack.UInt32_To_BE(H1, output); + Pack.UInt32_To_BE(H2, output[4..]); + Pack.UInt32_To_BE(H3, output[8..]); + Pack.UInt32_To_BE(H4, output[12..]); + Pack.UInt32_To_BE(H5, output[16..]); + + Reset(); + + return DigestLength; + } +#endif + /** * reset the chaining variables */ @@ -285,7 +308,6 @@ public override void Reset(IMemoable other) CopyIn(d); } - } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha224Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha224Digest.cs index 647f063..c9ee944 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha224Digest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha224Digest.cs @@ -74,9 +74,7 @@ public override int GetDigestSize() return DigestLength; } - internal override void ProcessWord( - byte[] input, - int inOff) + internal override void ProcessWord(byte[] input, int inOff) { X[xOff] = Pack.BE_To_UInt32(input, inOff); @@ -86,7 +84,19 @@ internal override void ProcessWord( } } - internal override void ProcessLength( +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal override void ProcessWord(ReadOnlySpan word) + { + X[xOff] = Pack.BE_To_UInt32(word); + + if (++xOff == 16) + { + ProcessBlock(); + } + } +#endif + + internal override void ProcessLength( long bitLength) { if (xOff > 14) @@ -98,9 +108,7 @@ internal override void ProcessLength( X[15] = (uint)((ulong)bitLength); } - public override int DoFinal( - byte[] output, - int outOff) + public override int DoFinal(byte[] output, int outOff) { Finish(); @@ -117,7 +125,26 @@ public override int DoFinal( return DigestLength; } - /** +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + Finish(); + + Pack.UInt32_To_BE(H1, output); + Pack.UInt32_To_BE(H2, output[4..]); + Pack.UInt32_To_BE(H3, output[8..]); + Pack.UInt32_To_BE(H4, output[12..]); + Pack.UInt32_To_BE(H5, output[16..]); + Pack.UInt32_To_BE(H6, output[20..]); + Pack.UInt32_To_BE(H7, output[24..]); + + Reset(); + + return DigestLength; + } +#endif + + /** * reset the chaining variables */ public override void Reset() @@ -286,7 +313,6 @@ public override void Reset(IMemoable other) CopyIn(d); } - } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha256Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha256Digest.cs index 3312d09..dff9aa3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha256Digest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha256Digest.cs @@ -19,11 +19,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests * SHA-512 1024 64 512 * */ - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] - public sealed class Sha256Digest + public class Sha256Digest : GeneralDigest { private const int DigestLength = 32; @@ -73,7 +69,29 @@ public override int GetDigestSize() return DigestLength; } - internal override void ProcessLength( + internal override void ProcessWord(byte[] input, int inOff) + { + X[xOff] = Pack.BE_To_UInt32(input, inOff); + + if (++xOff == 16) + { + ProcessBlock(); + } + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal override void ProcessWord(ReadOnlySpan word) + { + X[xOff] = Pack.BE_To_UInt32(word); + + if (++xOff == 16) + { + ProcessBlock(); + } + } +#endif + + internal override void ProcessLength( long bitLength) { if (xOff > 14) @@ -85,25 +103,43 @@ internal override void ProcessLength( X[15] = (uint)((ulong)bitLength); } - public override int DoFinal( - byte[] output, - int outOff) + public override int DoFinal(byte[] output, int outOff) + { + Finish(); + + Pack.UInt32_To_BE(H1, output, outOff); + Pack.UInt32_To_BE(H2, output, outOff + 4); + Pack.UInt32_To_BE(H3, output, outOff + 8); + Pack.UInt32_To_BE(H4, output, outOff + 12); + Pack.UInt32_To_BE(H5, output, outOff + 16); + Pack.UInt32_To_BE(H6, output, outOff + 20); + Pack.UInt32_To_BE(H7, output, outOff + 24); + Pack.UInt32_To_BE(H8, output, outOff + 28); + + Reset(); + + return DigestLength; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) { Finish(); - Pack.UInt32_To_BE((uint)H1, output, outOff); - Pack.UInt32_To_BE((uint)H2, output, outOff + 4); - Pack.UInt32_To_BE((uint)H3, output, outOff + 8); - Pack.UInt32_To_BE((uint)H4, output, outOff + 12); - Pack.UInt32_To_BE((uint)H5, output, outOff + 16); - Pack.UInt32_To_BE((uint)H6, output, outOff + 20); - Pack.UInt32_To_BE((uint)H7, output, outOff + 24); - Pack.UInt32_To_BE((uint)H8, output, outOff + 28); + Pack.UInt32_To_BE(H1, output); + Pack.UInt32_To_BE(H2, output[4..]); + Pack.UInt32_To_BE(H3, output[8..]); + Pack.UInt32_To_BE(H4, output[12..]); + Pack.UInt32_To_BE(H5, output[16..]); + Pack.UInt32_To_BE(H6, output[20..]); + Pack.UInt32_To_BE(H7, output[24..]); + Pack.UInt32_To_BE(H8, output[28..]); Reset(); return DigestLength; } +#endif /** * reset the chaining variables @@ -134,135 +170,14 @@ private void initHs() H8 = 0x5be0cd19; } - internal unsafe override void ProcessWord( - byte[] input, - int inOff) - { - fixed (uint* pX = X) - { - fixed (byte* bs = input) - pX[xOff] = (uint)bs[inOff] << 24 | (uint)bs[inOff + 1] << 16 | (uint)bs[inOff + 2] << 8 | (uint)bs[inOff + 3]; - - if (++xOff == 16) - { - // - // expand 16 word block into 64 word blocks. - // - for (int ti = 16; ti <= 63; ti++) - { - uint x = pX[ti - 2]; - uint y = pX[ti - 15]; - pX[ti] = (((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10)) - + pX[ti - 7] - + (((y >> 7) | (y << 25)) ^ ((y >> 18) | (y << 14)) ^ (y >> 3)) - + pX[ti - 16]; - } - - // - // set up working variables. - // - uint a = H1; - uint b = H2; - uint c = H3; - uint d = H4; - uint e = H5; - uint f = H6; - uint g = H7; - uint h = H8; - - int t = 0; - - fixed (uint* pK = K) - { - uint* pnfK = pK, pnfX = pX; - - for (int i = 0; i < 8; ++i) - { - // t = 8 * i - h += ((((e >> 6) | (e << 26)) ^ ((e >> 11) | (e << 21)) ^ ((e >> 25) | (e << 7))) + (g ^ (e & (f ^ g))))/*Sum1Ch(e, f, g)*/ + *pnfK++ + *pnfX++; - d += h; - h += ((((a >> 2) | (a << 30)) ^ ((a >> 13) | (a << 19)) ^ ((a >> 22) | (a << 10))) + ((a & b) | (c & (a ^ b))))/*Sum0Maj(a, b, c)*/; - - // t = 8 * i + 1 - g += ((((d >> 6) | (d << 26)) ^ ((d >> 11) | (d << 21)) ^ ((d >> 25) | (d << 7))) + (f ^ (d & (e ^ f))))/*Sum1Ch(d, e, f)*/ + *pnfK++ + *pnfX++; - c += g; - g += ((((h >> 2) | (h << 30)) ^ ((h >> 13) | (h << 19)) ^ ((h >> 22) | (h << 10))) + ((h & a) | (b & (h ^ a))))/*Sum0Maj(h, a, b)*/; - - // t = 8 * i + 2 - f += ((((c >> 6) | (c << 26)) ^ ((c >> 11) | (c << 21)) ^ ((c >> 25) | (c << 7))) + (e ^ (c & (d ^ e))))/*Sum1Ch(c, d, e)*/ + *pnfK++ + *pnfX++; - b += f; - f += ((((g >> 2) | (g << 30)) ^ ((g >> 13) | (g << 19)) ^ ((g >> 22) | (g << 10))) + ((g & h) | (a & (g ^ h))))/*Sum0Maj(g, h, a)*/; - - // t = 8 * i + 3 - e += ((((b >> 6) | (b << 26)) ^ ((b >> 11) | (b << 21)) ^ ((b >> 25) | (b << 7))) + (d ^ (b & (c ^ d))))/*Sum1Ch(b, c, d)*/ + *pnfK++ + *pnfX++; - a += e; - e += ((((f >> 2) | (f << 30)) ^ ((f >> 13) | (f << 19)) ^ ((f >> 22) | (f << 10))) + ((f & g) | (h & (f ^ g))))/*Sum0Maj(f, g, h)*/; - - // t = 8 * i + 4 - d += ((((a >> 6) | (a << 26)) ^ ((a >> 11) | (a << 21)) ^ ((a >> 25) | (a << 7))) + (c ^ (a & (b ^ c))))/*Sum1Ch(a, b, c)*/ + *pnfK++ + *pnfX++; - h += d; - d += ((((e >> 2) | (e << 30)) ^ ((e >> 13) | (e << 19)) ^ ((e >> 22) | (e << 10))) + ((e & f) | (g & (e ^ f))))/*Sum0Maj(e, f, g)*/; - - // t = 8 * i + 5 - c += ((((h >> 6) | (h << 26)) ^ ((h >> 11) | (h << 21)) ^ ((h >> 25) | (h << 7))) + (b ^ (h & (a ^ b))))/*Sum1Ch(h, a, b)*/ + *pnfK++ + *pnfX++; - g += c; - c += ((((d >> 2) | (d << 30)) ^ ((d >> 13) | (d << 19)) ^ ((d >> 22) | (d << 10))) + ((d & e) | (f & (d ^ e))))/*Sum0Maj(d, e, f)*/; - - // t = 8 * i + 6 - b += ((((g >> 6) | (g << 26)) ^ ((g >> 11) | (g << 21)) ^ ((g >> 25) | (g << 7))) + (a ^ (g & (h ^ a))))/*Sum1Ch(g, h, a)*/ + *pnfK++ + *pnfX++; - f += b; - b += ((((c >> 2) | (c << 30)) ^ ((c >> 13) | (c << 19)) ^ ((c >> 22) | (c << 10))) + ((c & d) | (e & (c ^ d))))/*Sum0Maj(c, d, e)*/; - - // t = 8 * i + 7 - a += ((((f >> 6) | (f << 26)) ^ ((f >> 11) | (f << 21)) ^ ((f >> 25) | (f << 7))) + (h ^ (f & (g ^ h))))/*Sum1Ch(f, g, h)*/ + *pnfK++ + *pnfX++; - e += a; - a += ((((b >> 2) | (b << 30)) ^ ((b >> 13) | (b << 19)) ^ ((b >> 22) | (b << 10))) + ((b & c) | (d & (b ^ c))))/*Sum0Maj(b, c, d)*/; - } - } - - H1 += a; - H2 += b; - H3 += c; - H4 += d; - H5 += e; - H6 += f; - H7 += g; - H8 += h; - - // - // reset the offset and clean out the word buffer. - // - xOff = 0; - - ulong* pulongX = (ulong*)pX; - *pulongX++ = 0; - *pulongX++ = 0; - *pulongX++ = 0; - *pulongX++ = 0; - *pulongX++ = 0; - *pulongX++ = 0; - *pulongX++ = 0; - *pulongX = 0; - } - } - } - - internal unsafe override void ProcessBlock() + internal override void ProcessBlock() { // // expand 16 word block into 64 word blocks. // - fixed(uint* pX = X) + for (int ti = 16; ti <= 63; ti++) { - for (int ti = 16; ti <= 63; ti++) - { - uint x = pX[ti - 2]; - uint y = pX[ti - 15]; - pX[ti] = (((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10)) - + pX[ti - 7] - + (((y >> 7) | (y << 25)) ^ ((y >> 18) | (y << 14)) ^ (y >> 3)) - + pX[ti - 16]; - } + X[ti] = Theta1(X[ti - 2]) + X[ti - 7] + Theta0(X[ti - 15]) + X[ti - 16]; } // @@ -278,56 +193,58 @@ internal unsafe override void ProcessBlock() uint h = H8; int t = 0; - - fixed(uint* pX = X, pK = K) - { - uint* pnfK = pK, pnfX = pX; - - for (int i = 0; i < 8; ++i) - { - // t = 8 * i - h += ((((e >> 6) | (e << 26)) ^ ((e >> 11) | (e << 21)) ^ ((e >> 25) | (e << 7))) + (g ^ (e & (f ^ g))))/*Sum1Ch(e, f, g)*/ + *pnfK++ + *pnfX++; - d += h; - h += ((((a >> 2) | (a << 30)) ^ ((a >> 13) | (a << 19)) ^ ((a >> 22) | (a << 10))) + ((a & b) | (c & (a ^ b))))/*Sum0Maj(a, b, c)*/; - - // t = 8 * i + 1 - g += ((((d >> 6) | (d << 26)) ^ ((d >> 11) | (d << 21)) ^ ((d >> 25) | (d << 7))) + (f ^ (d & (e ^ f))))/*Sum1Ch(d, e, f)*/ + *pnfK++ + *pnfX++; - c += g; - g += ((((h >> 2) | (h << 30)) ^ ((h >> 13) | (h << 19)) ^ ((h >> 22) | (h << 10))) + ((h & a) | (b & (h ^ a))))/*Sum0Maj(h, a, b)*/; - - // t = 8 * i + 2 - f += ((((c >> 6) | (c << 26)) ^ ((c >> 11) | (c << 21)) ^ ((c >> 25) | (c << 7))) + (e ^ (c & (d ^ e))))/*Sum1Ch(c, d, e)*/ + *pnfK++ + *pnfX++; - b += f; - f += ((((g >> 2) | (g << 30)) ^ ((g >> 13) | (g << 19)) ^ ((g >> 22) | (g << 10))) + ((g & h) | (a & (g ^ h))))/*Sum0Maj(g, h, a)*/; - - // t = 8 * i + 3 - e += ((((b >> 6) | (b << 26)) ^ ((b >> 11) | (b << 21)) ^ ((b >> 25) | (b << 7))) + (d ^ (b & (c ^ d))))/*Sum1Ch(b, c, d)*/ + *pnfK++ + *pnfX++; - a += e; - e += ((((f >> 2) | (f << 30)) ^ ((f >> 13) | (f << 19)) ^ ((f >> 22) | (f << 10))) + ((f & g) | (h & (f ^ g))))/*Sum0Maj(f, g, h)*/; - - // t = 8 * i + 4 - d += ((((a >> 6) | (a << 26)) ^ ((a >> 11) | (a << 21)) ^ ((a >> 25) | (a << 7))) + (c ^ (a & (b ^ c))))/*Sum1Ch(a, b, c)*/ + *pnfK++ + *pnfX++; - h += d; - d += ((((e >> 2) | (e << 30)) ^ ((e >> 13) | (e << 19)) ^ ((e >> 22) | (e << 10))) + ((e & f) | (g & (e ^ f))))/*Sum0Maj(e, f, g)*/; - - // t = 8 * i + 5 - c += ((((h >> 6) | (h << 26)) ^ ((h >> 11) | (h << 21)) ^ ((h >> 25) | (h << 7))) + (b ^ (h & (a ^ b))))/*Sum1Ch(h, a, b)*/ + *pnfK++ + *pnfX++; - g += c; - c += ((((d >> 2) | (d << 30)) ^ ((d >> 13) | (d << 19)) ^ ((d >> 22) | (d << 10))) + ((d & e) | (f & (d ^ e))))/*Sum0Maj(d, e, f)*/; - - // t = 8 * i + 6 - b += ((((g >> 6) | (g << 26)) ^ ((g >> 11) | (g << 21)) ^ ((g >> 25) | (g << 7))) + (a ^ (g & (h ^ a))))/*Sum1Ch(g, h, a)*/ + *pnfK++ + *pnfX++; - f += b; - b += ((((c >> 2) | (c << 30)) ^ ((c >> 13) | (c << 19)) ^ ((c >> 22) | (c << 10))) + ((c & d) | (e & (c ^ d))))/*Sum0Maj(c, d, e)*/; - - // t = 8 * i + 7 - a += ((((f >> 6) | (f << 26)) ^ ((f >> 11) | (f << 21)) ^ ((f >> 25) | (f << 7))) + (h ^ (f & (g ^ h))))/*Sum1Ch(f, g, h)*/ + *pnfK++ + *pnfX++; - e += a; - a += ((((b >> 2) | (b << 30)) ^ ((b >> 13) | (b << 19)) ^ ((b >> 22) | (b << 10))) + ((b & c) | (d & (b ^ c))))/*Sum0Maj(b, c, d)*/; - } - } - - H1 += a; + for(int i = 0; i < 8; ++i) + { + // t = 8 * i + h += Sum1Ch(e, f, g) + K[t] + X[t]; + d += h; + h += Sum0Maj(a, b, c); + ++t; + + // t = 8 * i + 1 + g += Sum1Ch(d, e, f) + K[t] + X[t]; + c += g; + g += Sum0Maj(h, a, b); + ++t; + + // t = 8 * i + 2 + f += Sum1Ch(c, d, e) + K[t] + X[t]; + b += f; + f += Sum0Maj(g, h, a); + ++t; + + // t = 8 * i + 3 + e += Sum1Ch(b, c, d) + K[t] + X[t]; + a += e; + e += Sum0Maj(f, g, h); + ++t; + + // t = 8 * i + 4 + d += Sum1Ch(a, b, c) + K[t] + X[t]; + h += d; + d += Sum0Maj(e, f, g); + ++t; + + // t = 8 * i + 5 + c += Sum1Ch(h, a, b) + K[t] + X[t]; + g += c; + c += Sum0Maj(d, e, f); + ++t; + + // t = 8 * i + 6 + b += Sum1Ch(g, h, a) + K[t] + X[t]; + f += b; + b += Sum0Maj(c, d, e); + ++t; + + // t = 8 * i + 7 + a += Sum1Ch(f, g, h) + K[t] + X[t]; + e += a; + a += Sum0Maj(b, c, d); + ++t; + } + + H1 += a; H2 += b; H3 += c; H4 += d; @@ -340,19 +257,56 @@ internal unsafe override void ProcessBlock() // reset the offset and clean out the word buffer. // xOff = 0; + Array.Clear(X, 0, 16); + } - fixed (uint* pX = X) - { - ulong* pulongX = (ulong*)pX; - *pulongX++ = 0; - *pulongX++ = 0; - *pulongX++ = 0; - *pulongX++ = 0; - *pulongX++ = 0; - *pulongX++ = 0; - *pulongX++ = 0; - *pulongX = 0; - } + private static uint Sum1Ch(uint x, uint y, uint z) + { +// return Sum1(x) + Ch(x, y, z); + return (((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7))) + //+ ((x & y) ^ ((~x) & z)); + + (z ^ (x & (y ^ z))); + } + + private static uint Sum0Maj(uint x, uint y, uint z) + { +// return Sum0(x) + Maj(x, y, z); + return (((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10))) + //+ ((x & y) ^ (x & z) ^ (y & z)); + + ((x & y) | (z & (x ^ y))); + } + +// /* SHA-256 functions */ +// private static uint Ch(uint x, uint y, uint z) +// { +// return (x & y) ^ ((~x) & z); +// //return z ^ (x & (y ^ z)); +// } +// +// private static uint Maj(uint x, uint y, uint z) +// { +// //return (x & y) ^ (x & z) ^ (y & z); +// return (x & y) | (z & (x ^ y)); +// } +// +// private static uint Sum0(uint x) +// { +// return ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10)); +// } +// +// private static uint Sum1(uint x) +// { +// return ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7)); +// } + + private static uint Theta0(uint x) + { + return ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3); + } + + private static uint Theta1(uint x) + { + return ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10); } /* SHA-256 Constants @@ -389,7 +343,6 @@ public override void Reset(IMemoable other) CopyIn(d); } - } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha384Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha384Digest.cs index 3ac970b..da5ce30 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha384Digest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha384Digest.cs @@ -19,10 +19,6 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests * SHA-512 1024 64 512 * */ - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] public class Sha384Digest : LongDigest { @@ -70,6 +66,24 @@ public override int DoFinal( return DigestLength; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + Finish(); + + Pack.UInt64_To_BE(H1, output); + Pack.UInt64_To_BE(H2, output[8..]); + Pack.UInt64_To_BE(H3, output[16..]); + Pack.UInt64_To_BE(H4, output[24..]); + Pack.UInt64_To_BE(H5, output[32..]); + Pack.UInt64_To_BE(H6, output[40..]); + + Reset(); + + return DigestLength; + } +#endif + /** * reset the chaining variables */ @@ -78,9 +92,9 @@ public override void Reset() base.Reset(); /* SHA-384 initial hash value - * The first 64 bits of the fractional parts of the square roots - * of the 9th through 16th prime numbers - */ + * The first 64 bits of the fractional parts of the square roots + * of the 9th through 16th prime numbers + */ H1 = 0xcbbb9d5dc1059ed8; H2 = 0x629a292a367cd507; H3 = 0x9159015a3070dd17; @@ -102,7 +116,6 @@ public override void Reset(IMemoable other) CopyIn(d); } - } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha512Digest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha512Digest.cs index a52322e..ec4be76 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha512Digest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha512Digest.cs @@ -69,6 +69,26 @@ public override int DoFinal( } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + Finish(); + + Pack.UInt64_To_BE(H1, output); + Pack.UInt64_To_BE(H2, output[8..]); + Pack.UInt64_To_BE(H3, output[16..]); + Pack.UInt64_To_BE(H4, output[24..]); + Pack.UInt64_To_BE(H5, output[32..]); + Pack.UInt64_To_BE(H6, output[40..]); + Pack.UInt64_To_BE(H7, output[48..]); + Pack.UInt64_To_BE(H8, output[56..]); + + Reset(); + + return DigestLength; + } +#endif + /** * reset the chaining variables */ @@ -101,7 +121,6 @@ public override void Reset(IMemoable other) CopyIn(d); } - } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha512tDigest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha512tDigest.cs index f3f28cc..f334c69 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha512tDigest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/Sha512tDigest.cs @@ -78,6 +78,26 @@ public override int DoFinal(byte[] output, int outOff) return digestLength; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + Finish(); + + UInt64_To_BE(H1, output, 0, digestLength); + UInt64_To_BE(H2, output, 8, digestLength - 8); + UInt64_To_BE(H3, output, 16, digestLength - 16); + UInt64_To_BE(H4, output, 24, digestLength - 24); + UInt64_To_BE(H5, output, 32, digestLength - 32); + UInt64_To_BE(H6, output, 40, digestLength - 40); + UInt64_To_BE(H7, output, 48, digestLength - 48); + UInt64_To_BE(H8, output, 56, digestLength - 56); + + Reset(); + + return digestLength; + } +#endif + /** * reset the chaining variables */ @@ -172,7 +192,32 @@ private static void UInt32_To_BE(uint n, byte[] bs, int off, int max) } } - public override IMemoable Copy() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void UInt64_To_BE(ulong n, Span bs, int off, int max) + { + if (max > 0) + { + UInt32_To_BE((uint)(n >> 32), bs, off, max); + + if (max > 4) + { + UInt32_To_BE((uint)n, bs, off + 4, max - 4); + } + } + } + + private static void UInt32_To_BE(uint n, Span bs, int off, int max) + { + int num = System.Math.Min(4, max); + while (--num >= 0) + { + int shift = 8 * (3 - num); + bs[off + num] = (byte)(n >> shift); + } + } +#endif + + public override IMemoable Copy() { return new Sha512tDigest(this); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/ShakeDigest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/ShakeDigest.cs index 7dbfc5d..32b3742 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/ShakeDigest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/ShakeDigest.cs @@ -55,19 +55,19 @@ public override int GetDigestSize() public override int DoFinal(byte[] output, int outOff) { - return DoFinal(output, outOff, GetDigestSize()); + return OutputFinal(output, outOff, GetDigestSize()); } - public virtual int DoFinal(byte[] output, int outOff, int outLen) + public virtual int OutputFinal(byte[] output, int outOff, int outLen) { - int length = DoOutput(output, outOff, outLen); + int length = Output(output, outOff, outLen); Reset(); return length; } - public virtual int DoOutput(byte[] output, int outOff, int outLen) + public virtual int Output(byte[] output, int outOff, int outLen) { if (!squeezing) { @@ -79,18 +79,46 @@ public virtual int DoOutput(byte[] output, int outOff, int outLen) return outLen; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + return OutputFinal(output[..GetDigestSize()]); + } + + public virtual int OutputFinal(Span output) + { + int length = Output(output); + + Reset(); + + return length; + } + + public virtual int Output(Span output) + { + if (!squeezing) + { + AbsorbBits(0x0F, 4); + } + + Squeeze(output); + + return output.Length; + } +#endif + /* * TODO Possible API change to support partial-byte suffixes. */ protected override int DoFinal(byte[] output, int outOff, byte partialByte, int partialBits) { - return DoFinal(output, outOff, GetDigestSize(), partialByte, partialBits); + return OutputFinal(output, outOff, GetDigestSize(), partialByte, partialBits); } /* * TODO Possible API change to support partial-byte suffixes. */ - protected virtual int DoFinal(byte[] output, int outOff, int outLen, byte partialByte, int partialBits) + protected virtual int OutputFinal(byte[] output, int outOff, int outLen, byte partialByte, int partialBits) { if (partialBits < 0 || partialBits > 7) throw new ArgumentException("must be in the range [0,7]", "partialBits"); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/ShortenedDigest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/ShortenedDigest.cs index f23d791..708ab7e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/ShortenedDigest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/ShortenedDigest.cs @@ -1,7 +1,6 @@ #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.Digests { @@ -60,7 +59,14 @@ public void BlockUpdate(byte[] input, int inOff, int length) baseDigest.BlockUpdate(input, inOff, length); } - public int DoFinal(byte[] output, int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + baseDigest.BlockUpdate(input); + } +#endif + + public int DoFinal(byte[] output, int outOff) { byte[] tmp = new byte[baseDigest.GetDigestSize()]; @@ -71,7 +77,23 @@ public int DoFinal(byte[] output, int outOff) return length; } - public void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + int baseDigestSize = baseDigest.GetDigestSize(); + Span tmp = baseDigestSize <= 128 + ? stackalloc byte[baseDigestSize] + : new byte[baseDigestSize]; + + baseDigest.DoFinal(tmp); + + tmp[..length].CopyTo(output); + + return length; + } +#endif + + public void Reset() { baseDigest.Reset(); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/SkeinDigest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/SkeinDigest.cs index b77f690..f307553 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/SkeinDigest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/SkeinDigest.cs @@ -1,15 +1,12 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; -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.Digests { - /// /// Implementation of the Skein parameterised hash function in 256, 512 and 1024 bit block sizes, /// based on the Threefish tweakable block cipher. @@ -70,7 +67,7 @@ public IMemoable Copy() return new SkeinDigest(this); } - public String AlgorithmName + public string AlgorithmName { get { return "Skein-" + (engine.BlockSize * 8) + "-" + (engine.OutputSize * 8); } } @@ -107,7 +104,7 @@ public void Update(byte inByte) public void BlockUpdate(byte[] inBytes, int inOff, int len) { - engine.Update(inBytes, inOff, len); + engine.BlockUpdate(inBytes, inOff, len); } public int DoFinal(byte[] outBytes, int outOff) @@ -115,7 +112,18 @@ public int DoFinal(byte[] outBytes, int outOff) return engine.DoFinal(outBytes, outOff); } - } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + engine.BlockUpdate(input); + } + + public int DoFinal(Span output) + { + return engine.DoFinal(output); + } +#endif + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/SkeinEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/SkeinEngine.cs index d39633c..220cf48 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/SkeinEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/SkeinEngine.cs @@ -1,11 +1,13 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines; 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.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests { @@ -76,7 +78,7 @@ public Configuration(long outputSizeBits) bytes[5] = 0; // 8..15 = output length - ThreefishEngine.WordToBytes((ulong)outputSizeBits, bytes, 8); + Pack.UInt64_To_LE((ulong)outputSizeBits, bytes, 8); } public byte[] Bytes @@ -133,7 +135,7 @@ public byte[] Value * Precalculated UBI(CFG) states for common state/output combinations without key or other * pre-message params. */ - private static readonly IDictionary INITIAL_STATES = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + private static readonly IDictionary InitialStates = new Dictionary(); static SkeinEngine() { @@ -215,7 +217,7 @@ static SkeinEngine() private static void InitialState(int blockSize, int outputSize, ulong[] state) { - INITIAL_STATES.Add(VariantIdentifier(blockSize / 8, outputSize / 8), state); + InitialStates.Add(VariantIdentifier(blockSize / 8, outputSize / 8), state); } private static int VariantIdentifier(int blockSizeBytes, int outputSizeBytes) @@ -228,7 +230,7 @@ private class UbiTweak /** * Point at which position might overflow long, so switch to add with carry logic */ - private const ulong LOW_RANGE = UInt64.MaxValue - UInt32.MaxValue; + private const ulong LOW_RANGE = ulong.MaxValue - uint.MaxValue; /** * Bit 127 = final @@ -431,7 +433,7 @@ public void Update(byte[] value, int offset, int len, ulong[] output) currentOffset = 0; } - int toCopy = System.Math.Min((len - copied), currentBlock.Length - currentOffset); + int toCopy = System.Math.Min(len - copied, currentBlock.Length - currentOffset); Array.Copy(value, offset + copied, currentBlock, currentOffset, toCopy); copied += toCopy; currentOffset += toCopy; @@ -439,13 +441,36 @@ public void Update(byte[] value, int offset, int len, ulong[] output) } } - private void ProcessBlock(ulong[] output) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Update(ReadOnlySpan input, ulong[] output) { - engine.threefish.Init(true, engine.chain, tweak.GetWords()); - for (int i = 0; i < message.Length; i++) + /* + * Buffer complete blocks for the underlying Threefish cipher, only flushing when there + * are subsequent bytes (last block must be processed in doFinal() with final=true set). + */ + int copied = 0, len = input.Length; + while (len > copied) { - message[i] = ThreefishEngine.BytesToWord(currentBlock, i * 8); + if (currentOffset == currentBlock.Length) + { + ProcessBlock(output); + tweak.First = false; + currentOffset = 0; + } + + int toCopy = System.Math.Min(len - copied, currentBlock.Length - currentOffset); + input.Slice(copied, toCopy).CopyTo(currentBlock.AsSpan(currentOffset)); + copied += toCopy; + currentOffset += toCopy; + tweak.AdvancePosition(toCopy); } + } +#endif + + private void ProcessBlock(ulong[] output) + { + engine.threefish.Init(true, engine.chain, tweak.GetWords()); + Pack.LE_To_UInt64(currentBlock, 0, message); engine.threefish.ProcessBlock(message, output); @@ -466,7 +491,6 @@ public void DoFinal(ulong[] output) tweak.Final = true; ProcessBlock(output); } - } /** @@ -619,16 +643,17 @@ public void Init(SkeinParameters parameters) UbiInit(PARAM_TYPE_MESSAGE); } - private void InitParams(IDictionary parameters) + private void InitParams(IDictionary parameters) { - IEnumerator keys = parameters.Keys.GetEnumerator(); - IList pre = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); - IList post = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + //IEnumerator keys = parameters.Keys.GetEnumerator(); + var pre = new List(); + var post = new List(); - while (keys.MoveNext()) + //while (keys.MoveNext()) + foreach (var parameter in parameters) { - int type = (int)keys.Current; - byte[] value = (byte[])parameters[type]; + int type = parameter.Key; + byte[] value = parameter.Value; if (type == PARAM_TYPE_KEY) { @@ -657,7 +682,7 @@ private void InitParams(IDictionary parameters) */ private void CreateInitialState() { - ulong[] precalc = (ulong[])INITIAL_STATES[VariantIdentifier(BlockSize, OutputSize)]; + var precalc = CollectionUtilities.GetValueOrNull(InitialStates, VariantIdentifier(BlockSize, OutputSize)); if ((key == null) && (precalc != null)) { // Precalculated UBI(CFG) @@ -729,15 +754,23 @@ private void CheckInitialised() public void Update(byte inByte) { singleByte[0] = inByte; - Update(singleByte, 0, 1); + BlockUpdate(singleByte, 0, 1); } - public void Update(byte[] inBytes, int inOff, int len) + public void BlockUpdate(byte[] inBytes, int inOff, int len) { CheckInitialised(); ubi.Update(inBytes, inOff, len, chain); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + CheckInitialised(); + ubi.Update(input, chain); + } +#endif + public int DoFinal(byte[] outBytes, int outOff) { CheckInitialised(); @@ -773,36 +806,98 @@ public int DoFinal(byte[] outBytes, int outOff) return outputSizeBytes; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + CheckInitialised(); + if (output.Length < outputSizeBytes) + throw new DataLengthException("Output span is too short to hold output"); + + // Finalise message block + UbiFinal(); + + // Process additional post-message parameters + if (postMessageParameters != null) + { + for (int i = 0; i < postMessageParameters.Length; i++) + { + Parameter param = postMessageParameters[i]; + UbiComplete(param.Type, param.Value); + } + } + + // Perform the output transform + int blockSize = BlockSize; + int blocksRequired = (outputSizeBytes + blockSize - 1) / blockSize; + for (int i = 0; i < blocksRequired; i++) + { + int toWrite = System.Math.Min(blockSize, outputSizeBytes - (i * blockSize)); + //Output((ulong)i, outBytes, outOff + (i * blockSize), toWrite); + Output((ulong)i, output[(i * blockSize)..], toWrite); + } + + Reset(); + + return outputSizeBytes; + } +#endif + private void Output(ulong outputSequence, byte[] outBytes, int outOff, int outputBytes) { byte[] currentBytes = new byte[8]; - ThreefishEngine.WordToBytes(outputSequence, currentBytes, 0); + Pack.UInt64_To_LE(outputSequence, currentBytes, 0); - // Output is a sequence of UBI invocations all of which use and preserve the pre-output - // state + // Output is a sequence of UBI invocations all of which use and preserve the pre-output state ulong[] outputWords = new ulong[chain.Length]; UbiInit(PARAM_TYPE_OUTPUT); this.ubi.Update(currentBytes, 0, currentBytes.Length, outputWords); ubi.DoFinal(outputWords); - int wordsRequired = ((outputBytes + 8 - 1) / 8); + int wordsRequired = (outputBytes + 8 - 1) / 8; for (int i = 0; i < wordsRequired; i++) { int toWrite = System.Math.Min(8, outputBytes - (i * 8)); if (toWrite == 8) { - ThreefishEngine.WordToBytes(outputWords[i], outBytes, outOff + (i * 8)); + Pack.UInt64_To_LE(outputWords[i], outBytes, outOff + (i * 8)); } else { - ThreefishEngine.WordToBytes(outputWords[i], currentBytes, 0); + Pack.UInt64_To_LE(outputWords[i], currentBytes, 0); Array.Copy(currentBytes, 0, outBytes, outOff + (i * 8), toWrite); } } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void Output(ulong outputSequence, Span output, int outputBytes) + { + Span currentBytes = stackalloc byte[8]; + Pack.UInt64_To_LE(outputSequence, currentBytes); + + // Output is a sequence of UBI invocations all of which use and preserve the pre-output state + ulong[] outputWords = new ulong[chain.Length]; + UbiInit(PARAM_TYPE_OUTPUT); + this.ubi.Update(currentBytes, outputWords); + ubi.DoFinal(outputWords); + + int wordsRequired = (outputBytes + 8 - 1) / 8; + for (int i = 0; i < wordsRequired; i++) + { + int toWrite = System.Math.Min(8, outputBytes - (i * 8)); + if (toWrite == 8) + { + Pack.UInt64_To_LE(outputWords[i], output[(i * 8)..]); + } + else + { + Pack.UInt64_To_LE(outputWords[i], currentBytes); + currentBytes[..toWrite].CopyTo(output[(i * 8)..]); + } + } + } +#endif } } - #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/TigerDigest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/TigerDigest.cs index a3b2160..5f28167 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/TigerDigest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/TigerDigest.cs @@ -2,7 +2,7 @@ #pragma warning disable using System; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests @@ -555,7 +555,7 @@ public class TigerDigest // // buffers // - private byte[] Buffer = new byte[8]; + private byte[] m_buffer = new byte[8]; private int bOff; private long[] x = new long[8]; @@ -593,18 +593,9 @@ public int GetByteLength() return MyByteLength; } - private void ProcessWord( - byte[] b, - int off) + private void ProcessWord(byte[] b, int off) { - x[xOff++] = ((long)(b[off + 7] & 0xff) << 56) - | ((long)(b[off + 6] & 0xff) << 48) - | ((long)(b[off + 5] & 0xff) << 40) - | ((long)(b[off + 4] & 0xff) << 32) - | ((long)(b[off + 3] & 0xff) << 24) - | ((long)(b[off + 2] & 0xff) << 16) - | ((long)(b[off + 1] & 0xff) << 8) - | ((uint)(b[off + 0] & 0xff)); + x[xOff++] = (long)Pack.LE_To_UInt64(b, off); if (xOff == x.Length) { @@ -614,14 +605,28 @@ private void ProcessWord( bOff = 0; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void ProcessWord(ReadOnlySpan b) + { + x[xOff++] = (long)Pack.LE_To_UInt64(b); + + if (xOff == x.Length) + { + ProcessBlock(); + } + + bOff = 0; + } +#endif + public void Update( byte input) { - Buffer[bOff++] = input; + m_buffer[bOff++] = input; - if (bOff == Buffer.Length) + if (bOff == m_buffer.Length) { - ProcessWord(Buffer, 0); + ProcessWord(m_buffer, 0); } byteCount++; @@ -646,7 +651,7 @@ public void BlockUpdate( // // process whole words. // - while (length > 8) + while (length >= 8) { ProcessWord(input, inOff); @@ -667,6 +672,47 @@ public void BlockUpdate( } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + int inOff = 0, length = input.Length; + + // + // fill the current word + // + while ((bOff != 0) && (length > 0)) + { + Update(input[inOff]); + + inOff++; + length--; + } + + // + // process whole words. + // + while (length >= 8) + { + ProcessWord(input[inOff..]); + + inOff += 8; + length -= 8; + byteCount += 8; + } + + // + // load in the remainder. + // + while (length > 0) + { + Update(input[inOff]); + + inOff++; + length--; + } + } +#endif + private void RoundABC( long x, long mul) @@ -783,21 +829,6 @@ private void ProcessBlock() } } - private void UnpackWord( - long r, - byte[] output, - int outOff) - { - output[outOff + 7] = (byte)(r >> 56); - output[outOff + 6] = (byte)(r >> 48); - output[outOff + 5] = (byte)(r >> 40); - output[outOff + 4] = (byte)(r >> 32); - output[outOff + 3] = (byte)(r >> 24); - output[outOff + 2] = (byte)(r >> 16); - output[outOff + 1] = (byte)(r >> 8); - output[outOff] = (byte)r; - } - private void ProcessLength( long bitLength) { @@ -826,15 +857,30 @@ public int DoFinal( { Finish(); - UnpackWord(a, output, outOff); - UnpackWord(b, output, outOff + 8); - UnpackWord(c, output, outOff + 16); + Pack.UInt64_To_LE((ulong)a, output, outOff); + Pack.UInt64_To_LE((ulong)b, output, outOff + 8); + Pack.UInt64_To_LE((ulong)c, output, outOff + 16); Reset(); return DigestLength; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + Finish(); + + Pack.UInt64_To_LE((ulong)a, output); + Pack.UInt64_To_LE((ulong)b, output[8..]); + Pack.UInt64_To_LE((ulong)c, output[16..]); + + Reset(); + + return DigestLength; + } +#endif + /** * reset the chaining variables */ @@ -851,9 +897,9 @@ public void Reset() } bOff = 0; - for (int i = 0; i != Buffer.Length; i++) + for (int i = 0; i != m_buffer.Length; i++) { - Buffer[i] = 0; + m_buffer[i] = 0; } byteCount = 0; @@ -875,12 +921,11 @@ public void Reset(IMemoable other) Array.Copy(t.x, 0, x, 0, t.x.Length); xOff = t.xOff; - Array.Copy(t.Buffer, 0, Buffer, 0, t.Buffer.Length); + Array.Copy(t.m_buffer, 0, m_buffer, 0, t.m_buffer.Length); bOff = t.bOff; byteCount = t.byteCount; } - } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/TupleHash.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/TupleHash.cs index e714edd..a0d11a3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/TupleHash.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/TupleHash.cs @@ -80,7 +80,7 @@ public virtual void BlockUpdate(byte[] inBuf, int inOff, int len) cshake.BlockUpdate(bytes, 0, bytes.Length); } - private void wrapUp(int outputSize) + private void WrapUp(int outputSize) { byte[] encOut = XofUtilities.RightEncode(outputSize * 8); @@ -90,48 +90,75 @@ private void wrapUp(int outputSize) } public virtual int DoFinal(byte[] outBuf, int outOff) + { + return OutputFinal(outBuf, outOff, GetDigestSize()); + } + + public virtual int OutputFinal(byte[] outBuf, int outOff, int outLen) { if (firstOutput) { - wrapUp(GetDigestSize()); + WrapUp(GetDigestSize()); } - int rv = cshake.DoFinal(outBuf, outOff, GetDigestSize()); + int rv = cshake.OutputFinal(outBuf, outOff, outLen); Reset(); return rv; } - public virtual int DoFinal(byte[] outBuf, int outOff, int outLen) + public virtual int Output(byte[] outBuf, int outOff, int outLen) { if (firstOutput) { - wrapUp(GetDigestSize()); + WrapUp(0); } - int rv = cshake.DoFinal(outBuf, outOff, outLen); + return cshake.Output(outBuf, outOff, outLen); + } - Reset(); + public virtual void Reset() + { + cshake.Reset(); + firstOutput = true; + } - return rv; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) + { + XofUtilities.EncodeTo(cshake, input); } - public virtual int DoOutput(byte[] outBuf, int outOff, int outLen) + public virtual int DoFinal(Span output) + { + return OutputFinal(output[..GetDigestSize()]); + } + + public virtual int OutputFinal(Span output) { if (firstOutput) { - wrapUp(0); + WrapUp(GetDigestSize()); } - return cshake.DoOutput(outBuf, outOff, outLen); + int rv = cshake.OutputFinal(output); + + Reset(); + + return rv; } - public virtual void Reset() + public virtual int Output(Span output) { - cshake.Reset(); - firstOutput = true; + if (firstOutput) + { + WrapUp(0); + } + + return cshake.Output(output); } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/WhirlpoolDigest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/WhirlpoolDigest.cs index cac00ce..429585e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/WhirlpoolDigest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/WhirlpoolDigest.cs @@ -2,24 +2,22 @@ #pragma warning disable using System; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests { /** - * Implementation of WhirlpoolDigest, based on Java source published by Barreto - * and Rijmen. - * + * Implementation of WhirlpoolDigest, based on Java source published by Barreto and Rijmen. */ public sealed class WhirlpoolDigest : IDigest, IMemoable { + private const int BITCOUNT_ARRAY_SIZE = 32; private const int BYTE_LENGTH = 64; - private const int DIGEST_LENGTH_BYTES = 512 / 8; - private const int ROUNDS = 10; private const int REDUCTION_POLYNOMIAL = 0x011d; // 2^8 + 2^4 + 2^3 + 2 + 1; + private const int ROUNDS = 10; private static readonly int[] SBOX = { @@ -41,25 +39,23 @@ public sealed class WhirlpoolDigest 0x16, 0x3a, 0x69, 0x09, 0x70, 0xb6, 0xd0, 0xed, 0xcc, 0x42, 0x98, 0xa4, 0x28, 0x5c, 0xf8, 0x86 }; - private static readonly long[] C0 = new long[256]; - private static readonly long[] C1 = new long[256]; - private static readonly long[] C2 = new long[256]; - private static readonly long[] C3 = new long[256]; - private static readonly long[] C4 = new long[256]; - private static readonly long[] C5 = new long[256]; - private static readonly long[] C6 = new long[256]; - private static readonly long[] C7 = new long[256]; - - private readonly long[] _rc = new long[ROUNDS + 1]; + private static readonly ulong[] C0 = new ulong[256]; + private static readonly ulong[] C1 = new ulong[256]; + private static readonly ulong[] C2 = new ulong[256]; + private static readonly ulong[] C3 = new ulong[256]; + private static readonly ulong[] C4 = new ulong[256]; + private static readonly ulong[] C5 = new ulong[256]; + private static readonly ulong[] C6 = new ulong[256]; + private static readonly ulong[] C7 = new ulong[256]; /* - * increment() can be implemented in this way using 2 arrays or - * by having some temporary variables that are used to set the - * value provided by EIGHT[i] and carry within the loop. - * - * not having done any timing, this seems likely to be faster - * at the slight expense of 32*(sizeof short) bytes - */ + * increment() can be implemented in this way using 2 arrays or + * by having some temporary variables that are used to set the + * value provided by EIGHT[i] and carry within the loop. + * + * not having done any timing, this seems likely to be faster + * at the slight expense of 32*(sizeof short) bytes + */ private static readonly short[] EIGHT = new short[BITCOUNT_ARRAY_SIZE]; static WhirlpoolDigest() @@ -69,88 +65,78 @@ static WhirlpoolDigest() for (int i = 0; i < 256; i++) { int v1 = SBOX[i]; - int v2 = maskWithReductionPolynomial(v1 << 1); - int v4 = maskWithReductionPolynomial(v2 << 1); + int v2 = MulX(v1); + int v4 = MulX(v2); int v5 = v4 ^ v1; - int v8 = maskWithReductionPolynomial(v4 << 1); + int v8 = MulX(v4); int v9 = v8 ^ v1; - C0[i] = packIntoLong(v1, v1, v4, v1, v8, v5, v2, v9); - C1[i] = packIntoLong(v9, v1, v1, v4, v1, v8, v5, v2); - C2[i] = packIntoLong(v2, v9, v1, v1, v4, v1, v8, v5); - C3[i] = packIntoLong(v5, v2, v9, v1, v1, v4, v1, v8); - C4[i] = packIntoLong(v8, v5, v2, v9, v1, v1, v4, v1); - C5[i] = packIntoLong(v1, v8, v5, v2, v9, v1, v1, v4); - C6[i] = packIntoLong(v4, v1, v8, v5, v2, v9, v1, v1); - C7[i] = packIntoLong(v1, v4, v1, v8, v5, v2, v9, v1); + C0[i] = PackIntoUInt64(v1, v1, v4, v1, v8, v5, v2, v9); + C1[i] = PackIntoUInt64(v9, v1, v1, v4, v1, v8, v5, v2); + C2[i] = PackIntoUInt64(v2, v9, v1, v1, v4, v1, v8, v5); + C3[i] = PackIntoUInt64(v5, v2, v9, v1, v1, v4, v1, v8); + C4[i] = PackIntoUInt64(v8, v5, v2, v9, v1, v1, v4, v1); + C5[i] = PackIntoUInt64(v1, v8, v5, v2, v9, v1, v1, v4); + C6[i] = PackIntoUInt64(v4, v1, v8, v5, v2, v9, v1, v1); + C7[i] = PackIntoUInt64(v1, v4, v1, v8, v5, v2, v9, v1); } } - public WhirlpoolDigest() + // int's are used to prevent sign extension. The values that are really being used are actually just 0..255 + private static int MulX(int input) { - _rc[0] = 0L; - for (int r = 1; r <= ROUNDS; r++) - { - int i = 8 * (r - 1); - _rc[r] = (long)((ulong)C0[i] & 0xff00000000000000L) ^ - (C1[i + 1] & (long) 0x00ff000000000000L) ^ - (C2[i + 2] & (long) 0x0000ff0000000000L) ^ - (C3[i + 3] & (long) 0x000000ff00000000L) ^ - (C4[i + 4] & (long) 0x00000000ff000000L) ^ - (C5[i + 5] & (long) 0x0000000000ff0000L) ^ - (C6[i + 6] & (long) 0x000000000000ff00L) ^ - (C7[i + 7] & (long) 0x00000000000000ffL); - } + return (input << 1) ^ (-(input >> 7) & REDUCTION_POLYNOMIAL); } - private static long packIntoLong(int b7, int b6, int b5, int b4, int b3, int b2, int b1, int b0) + private static ulong PackIntoUInt64(int b7, int b6, int b5, int b4, int b3, int b2, int b1, int b0) { - return - ((long)b7 << 56) ^ - ((long)b6 << 48) ^ - ((long)b5 << 40) ^ - ((long)b4 << 32) ^ - ((long)b3 << 24) ^ - ((long)b2 << 16) ^ - ((long)b1 << 8) ^ - b0; + return ((ulong)b7 << 56) ^ + ((ulong)b6 << 48) ^ + ((ulong)b5 << 40) ^ + ((ulong)b4 << 32) ^ + ((ulong)b3 << 24) ^ + ((ulong)b2 << 16) ^ + ((ulong)b1 << 8) ^ + (ulong)b0; } - /* - * int's are used to prevent sign extension. The values that are really being used are - * actually just 0..255 - */ - private static int maskWithReductionPolynomial(int input) + private readonly ulong[] _rc = new ulong[ROUNDS + 1]; + + public WhirlpoolDigest() { - int rv = input; - if (rv >= 0x100L) // high bit set + _rc[0] = 0UL; + for (int r = 1; r <= ROUNDS; r++) { - rv ^= REDUCTION_POLYNOMIAL; // reduced by the polynomial + int i = 8 * (r - 1); + _rc[r] = + (C0[i ] & 0xff00000000000000UL) ^ + (C1[i + 1] & 0x00ff000000000000UL) ^ + (C2[i + 2] & 0x0000ff0000000000UL) ^ + (C3[i + 3] & 0x000000ff00000000UL) ^ + (C4[i + 4] & 0x00000000ff000000UL) ^ + (C5[i + 5] & 0x0000000000ff0000UL) ^ + (C6[i + 6] & 0x000000000000ff00UL) ^ + (C7[i + 7] & 0x00000000000000ffUL); } - return rv; } // --------------------------------------------------------------------------------------// // -- buffer information -- - private const int BITCOUNT_ARRAY_SIZE = 32; private byte[] _buffer = new byte[64]; private int _bufferPos; private short[] _bitCount = new short[BITCOUNT_ARRAY_SIZE]; // -- internal hash state -- - private long[] _hash = new long[8]; - private long[] _K = new long[8]; // the round key - private long[] _L = new long[8]; - private long[] _block = new long[8]; // mu (buffer) - private long[] _state = new long[8]; // the current "cipher" state - - + private ulong[] _hash = new ulong[8]; + private ulong[] _K = new ulong[8]; // the round key + private ulong[] _L = new ulong[8]; + private ulong[] _block = new ulong[8]; // mu (buffer) + private ulong[] _state = new ulong[8]; // the current "cipher" state /** - * Copy constructor. This will copy the state of the provided message - * digest. - */ + * Copy constructor. This will copy the state of the provided message digest. + */ public WhirlpoolDigest(WhirlpoolDigest originalDigest) { Reset(originalDigest); @@ -169,21 +155,32 @@ public int GetDigestSize() public int DoFinal(byte[] output, int outOff) { // sets output[outOff] .. output[outOff+DIGEST_LENGTH_BYTES] - finish(); + Finish(); - for (int i = 0; i < 8; i++) - { - convertLongToByteArray(_hash[i], output, outOff + (i * 8)); - } + Pack.UInt64_To_BE(_hash, output, outOff); + + Reset(); + + return GetDigestSize(); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + // sets output[0..DIGEST_LENGTH_BYTES] + Finish(); + + Pack.UInt64_To_BE(_hash, output); Reset(); return GetDigestSize(); } +#endif /** - * Reset the chaining variables - */ + * Reset the chaining variables + */ public void Reset() { // set variables to null, blank, whatever @@ -198,44 +195,18 @@ public void Reset() } // this takes a buffer of information and fills the block - private void processFilledBuffer() + private void ProcessFilledBuffer() { // copies into the block... - for (int i = 0; i < _state.Length; i++) - { - _block[i] = bytesToLongFromBuffer(_buffer, i * 8); - } - processBlock(); + Pack.BE_To_UInt64(_buffer, 0, _block); + ProcessBlock(); _bufferPos = 0; Array.Clear(_buffer, 0, _buffer.Length); } - private static long bytesToLongFromBuffer(byte[] buffer, int startPos) - { - long rv = (((buffer[startPos + 0] & 0xffL) << 56) | - ((buffer[startPos + 1] & 0xffL) << 48) | - ((buffer[startPos + 2] & 0xffL) << 40) | - ((buffer[startPos + 3] & 0xffL) << 32) | - ((buffer[startPos + 4] & 0xffL) << 24) | - ((buffer[startPos + 5] & 0xffL) << 16) | - ((buffer[startPos + 6] & 0xffL) << 8) | - ((buffer[startPos + 7]) & 0xffL)); - - return rv; - } - - private static void convertLongToByteArray(long inputLong, byte[] outputArray, int offSet) - { - for (int i = 0; i < 8; i++) - { - outputArray[offSet + i] = (byte)((inputLong >> (56 - (i * 8))) & 0xff); - } - } - - private void processBlock() + private void ProcessBlock() { - // buffer contents have been transferred to the _block[] array via - // processFilledBuffer + // buffer contents have been transferred to the _block[] array via ProcessFilledBuffer // compute and apply K^0 for (int i = 0; i < 8; i++) @@ -248,8 +219,7 @@ private void processBlock() { for (int i = 0; i < 8; i++) { - _L[i] = 0; - _L[i] ^= C0[(int)(_K[(i - 0) & 7] >> 56) & 0xff]; + _L[i] = C0[(int)(_K[(i - 0) & 7] >> 56) & 0xff]; _L[i] ^= C1[(int)(_K[(i - 1) & 7] >> 48) & 0xff]; _L[i] ^= C2[(int)(_K[(i - 2) & 7] >> 40) & 0xff]; _L[i] ^= C3[(int)(_K[(i - 3) & 7] >> 32) & 0xff]; @@ -287,26 +257,20 @@ private void processBlock() { _hash[i] ^= _state[i] ^ _block[i]; } - } public void Update(byte input) { _buffer[_bufferPos] = input; - - //Console.WriteLine("adding to buffer = "+_buffer[_bufferPos]); - - ++_bufferPos; - - if (_bufferPos == _buffer.Length) + if (++_bufferPos == _buffer.Length) { - processFilledBuffer(); + ProcessFilledBuffer(); } - increment(); + Increment(); } - private void increment() + private void Increment() { int carry = 0; for (int i = _bitCount.Length - 1; i >= 0; i--) @@ -326,31 +290,39 @@ public void BlockUpdate(byte[] input, int inOff, int length) ++inOff; --length; } + } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + for (int i = 0; i < input.Length; ++i) + { + Update(input[i]); + } } +#endif - private void finish() + private void Finish() { /* - * this makes a copy of the current bit length. at the expense of an - * object creation of 32 bytes rather than providing a _stopCounting - * boolean which was the alternative I could think of. - */ - byte[] bitLength = copyBitLength(); - - _buffer[_bufferPos++] |= 0x80; + * this makes a copy of the current bit length. at the expense of an + * object creation of 32 bytes rather than providing a _stopCounting + * boolean which was the alternative I could think of. + */ + byte[] bitLength = CopyBitLength(); - if (_bufferPos == _buffer.Length) + _buffer[_bufferPos] |= 0x80; + if (++_bufferPos == _buffer.Length) { - processFilledBuffer(); + ProcessFilledBuffer(); } /* - * Final block contains - * [ ... data .... ][0][0][0][ length ] - * - * if [ length ] cannot fit. Need to create a new block. - */ + * Final block contains + * [ ... data .... ][0][0][0][ length ] + * + * if [ length ] cannot fit. Need to create a new block. + */ if (_bufferPos > 32) { while (_bufferPos != 0) @@ -364,14 +336,13 @@ private void finish() Update((byte)0); } - // copy the length information to the final 32 bytes of the - // 64 byte block.... + // copy the length information to the final 32 bytes of the 64 byte block.... Array.Copy(bitLength, 0, _buffer, 32, bitLength.Length); - processFilledBuffer(); + ProcessFilledBuffer(); } - private byte[] copyBitLength() + private byte[] CopyBitLength() { byte[] rv = new byte[BITCOUNT_ARRAY_SIZE]; for (int i = 0; i < rv.Length; i++) @@ -409,8 +380,6 @@ public void Reset(IMemoable other) Array.Copy(originalDigest._block, 0, _block, 0, _block.Length); Array.Copy(originalDigest._state, 0, _state, 0, _state.Length); } - - } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/XofUtils.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/XofUtils.cs index ed81a53..8c7eb28 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/XofUtils.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/digests/XofUtils.cs @@ -30,6 +30,26 @@ internal static byte[] LeftEncode(long strLen) return b; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal static int LeftEncode(long length, Span lengthEncoding) + { + byte n = 1; + + long v = length; + while ((v >>= 8) != 0) + { + n++; + } + + lengthEncoding[0] = n; + for (int i = 1; i <= n; i++) + { + lengthEncoding[i] = (byte)(length >> (8 * (n - i))); + } + return 1 + n; + } +#endif + internal static byte[] RightEncode(long strLen) { byte n = 1; @@ -52,6 +72,26 @@ internal static byte[] RightEncode(long strLen) return b; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal static int RightEncode(long length, Span lengthEncoding) + { + byte n = 1; + + long v = length; + while ((v >>= 8) != 0) + { + n++; + } + + lengthEncoding[n] = n; + for (int i = 0; i < n; i++) + { + lengthEncoding[i] = (byte)(length >> (8 * (n - i - 1))); + } + return n + 1; + } +#endif + internal static byte[] Encode(byte X) { return Arrays.Concatenate(LeftEncode(8), new byte[] { X }); @@ -65,6 +105,16 @@ internal static byte[] Encode(byte[] inBuf, int inOff, int len) } return Arrays.Concatenate(LeftEncode(len * 8), Arrays.CopyOfRange(inBuf, inOff, inOff + len)); } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal static void EncodeTo(IDigest digest, ReadOnlySpan buf) + { + Span lengthEncoding = stackalloc byte[9]; + int count = LeftEncode(buf.Length * 8, lengthEncoding); + digest.BlockUpdate(lengthEncoding[..count]); + digest.BlockUpdate(buf); + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/ec/CustomNamedCurves.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/ec/CustomNamedCurves.cs index 03235d7..1df1d8e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/ec/CustomNamedCurves.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/ec/CustomNamedCurves.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.GM; @@ -9,23 +9,18 @@ using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Djb; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.GM; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Endo; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.EC { - public sealed class CustomNamedCurves + /// Elliptic curve registry for various customized curve implementations. + public static class CustomNamedCurves { - private CustomNamedCurves() - { - } - private static X9ECPoint ConfigureBasepoint(ECCurve curve, string encoding) { X9ECPoint G = new X9ECPoint(curve, Hex.DecodeStrict(encoding)); @@ -43,70 +38,37 @@ private static ECCurve ConfigureCurveGlv(ECCurve c, GlvTypeBParameters p) return c.Configure().SetEndomorphism(new GlvTypeBEndomorphism(c, p)).Create(); } - /* - * curve25519 - */ - internal class Curve25519Holder + internal class SecP128R1Holder : X9ECParametersHolder { - private Curve25519Holder() { } + private SecP128R1Holder() {} - internal static readonly X9ECParametersHolder Instance = new Curve25519Holder(); + internal static readonly X9ECParametersHolder Instance = new SecP128R1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { - byte[] S = null; - ECCurve curve = ConfigureCurve(new Curve25519()); - - /* - * NOTE: Curve25519 was specified in Montgomery form. Rewriting in Weierstrass form - * involves substitution of variables, so the base-point x coordinate is 9 + (486662 / 3). - * - * The Curve25519 paper doesn't say which of the two possible y values the base - * point has. The choice here is guided by language in the Ed25519 paper. - * - * (The other possible y value is 5F51E65E475F794B1FE122D388B72EB36DC2B28192839E4DD6163A5D81312C14) - */ - X9ECPoint G = ConfigureBasepoint(curve, - "042AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD245A20AE19A1B8A086B4E01EDD2C7748D14C923D4D7E6D7C61B229E9C5A27ECED3D9"); - - return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); + return ConfigureCurve(new SecP128R1Curve()); } - } - - /* - * secp128r1 - */ - internal class SecP128R1Holder - : X9ECParametersHolder - { - private SecP128R1Holder() { } - - internal static readonly X9ECParametersHolder Instance = new SecP128R1Holder(); protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("000E0D4D696E6768756151750CC03A4473D03679"); - ECCurve curve = ConfigureCurve(new SecP128R1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "04161FF7528B899B2D0C28607CA52C5B86CF5AC8395BAFEB13C02DA292DDED7A83"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; - /* - * secp160k1 - */ internal class SecP160K1Holder : X9ECParametersHolder { - private SecP160K1Holder() { } + private SecP160K1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecP160K1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { - byte[] S = null; GlvTypeBParameters glv = new GlvTypeBParameters( new BigInteger("9ba48cba5ebcb9b6bd33b92830b2a2e0e192f10a", 16), new BigInteger("c39c6c3b3a36d7701b9c71a1f5804ae5d0003f4", 16), @@ -120,66 +82,72 @@ protected override X9ECParameters CreateParameters() new BigInteger("9162fbe73984472a0a9d0590", 16), new BigInteger("96341f1138933bc2f503fd44", 16), 176)); - ECCurve curve = ConfigureCurveGlv(new SecP160K1Curve(), glv); + return ConfigureCurveGlv(new SecP160K1Curve(), glv); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "043B4C382CE37AA192A4019E763036F4F5DD4D7EBB938CF935318FDCED6BC28286531733C3F03C4FEE"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; - /* - * secp160r1 - */ internal class SecP160R1Holder : X9ECParametersHolder { - private SecP160R1Holder() { } + private SecP160R1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecP160R1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecP160R1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("1053CDE42C14D696E67687561517533BF3F83345"); - ECCurve curve = ConfigureCurve(new SecP160R1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "044A96B5688EF573284664698968C38BB913CBFC8223A628553168947D59DCC912042351377AC5FB32"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; - /* - * secp160r2 - */ internal class SecP160R2Holder : X9ECParametersHolder { - private SecP160R2Holder() { } + private SecP160R2Holder() {} internal static readonly X9ECParametersHolder Instance = new SecP160R2Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecP160R2Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("B99B99B099B323E02709A4D696E6768756151751"); - ECCurve curve = ConfigureCurve(new SecP160R2Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "0452DCB034293A117E1F4FF11B30F7199D3144CE6DFEAFFEF2E331F296E071FA0DF9982CFEA7D43F2E"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; - /* - * secp192k1 - */ internal class SecP192K1Holder : X9ECParametersHolder { - private SecP192K1Holder() { } + private SecP192K1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecP192K1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { - byte[] S = null; GlvTypeBParameters glv = new GlvTypeBParameters( new BigInteger("bb85691939b869c1d087f601554b96b80cb4f55b35f433c2", 16), new BigInteger("3d84f26c12238d7b4f3d516613c1759033b1a5800175d0b1", 16), @@ -193,46 +161,50 @@ protected override X9ECParameters CreateParameters() new BigInteger("71169be7330b3038edb025f1d0f9", 16), new BigInteger("b3fb3400dec5c4adceb8655d4c94", 16), 208)); - ECCurve curve = ConfigureCurveGlv(new SecP192K1Curve(), glv); + return ConfigureCurveGlv(new SecP192K1Curve(), glv); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "04DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } - /* - * secp192r1 - */ internal class SecP192R1Holder : X9ECParametersHolder { - private SecP192R1Holder() { } + private SecP192R1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecP192R1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecP192R1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("3045AE6FC8422F64ED579528D38120EAE12196D5"); - ECCurve curve = ConfigureCurve(new SecP192R1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "04188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF101207192B95FFC8DA78631011ED6B24CDD573F977A11E794811"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } - /* - * secp224k1 - */ internal class SecP224K1Holder : X9ECParametersHolder { - private SecP224K1Holder() { } + private SecP224K1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecP224K1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { - byte[] S = null; GlvTypeBParameters glv = new GlvTypeBParameters( new BigInteger("fe0e87005b4e83761908c5131d552a850b3f58b749c37cf5b84d6768", 16), new BigInteger("60dcd2104c4cbc0be6eeefc2bdd610739ec34e317f9b33046c9e4788", 16), @@ -246,36 +218,41 @@ protected override X9ECParameters CreateParameters() new BigInteger("6b8cf07d4ca75c88957d9d67059037a4", 16), new BigInteger("b8adf1378a6eb73409fa6c9c637ba7f5", 16), 240)); - ECCurve curve = ConfigureCurveGlv(new SecP224K1Curve(), glv); + return ConfigureCurveGlv(new SecP224K1Curve(), glv); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "04A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } - /* - * secp224r1 - */ internal class SecP224R1Holder : X9ECParametersHolder { - private SecP224R1Holder() { } + private SecP224R1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecP224R1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecP224R1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5"); - ECCurve curve = ConfigureCurve(new SecP224R1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "04B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } - /* - * secp256k1 - */ internal class SecP256K1Holder : X9ECParametersHolder { @@ -283,9 +260,8 @@ private SecP256K1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecP256K1Holder(); - protected override X9ECParameters CreateParameters() + protected override ECCurve CreateCurve() { - byte[] S = null; GlvTypeBParameters glv = new GlvTypeBParameters( new BigInteger("7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", 16), new BigInteger("5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", 16), @@ -299,16 +275,19 @@ protected override X9ECParameters CreateParameters() new BigInteger("3086d221a7d46bcde86c90e49284eb153dab", 16), new BigInteger("e4437ed6010e88286f547fa90abfe4c42212", 16), 272)); - ECCurve curve = ConfigureCurveGlv(new SecP256K1Curve(), glv); + return ConfigureCurveGlv(new SecP256K1Curve(), glv); + } + + protected override X9ECParameters CreateParameters() + { + byte[] S = null; + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "0479BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } - /* - * secp256r1 - */ internal class SecP256R1Holder : X9ECParametersHolder { @@ -316,30 +295,37 @@ private SecP256R1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecP256R1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecP256R1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("C49D360886E704936A6678E1139D26B7819F7E90"); - ECCurve curve = ConfigureCurve(new SecP256R1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "046B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C2964FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } - /* - * secp384r1 - */ internal class SecP384R1Holder : X9ECParametersHolder { - private SecP384R1Holder() { } + private SecP384R1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecP384R1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecP384R1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("A335926AA319A27A1D00896A6773A4827ACDAC73"); - ECCurve curve = ConfigureCurve(new SecP384R1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "04" + "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7" + "3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F"); @@ -347,20 +333,22 @@ protected override X9ECParameters CreateParameters() } } - /* - * secp521r1 - */ internal class SecP521R1Holder : X9ECParametersHolder { - private SecP521R1Holder() { } + private SecP521R1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecP521R1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecP521R1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("D09E8800291CB85396CC6717393284AAA0DA64BA"); - ECCurve curve = ConfigureCurve(new SecP521R1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "04" + "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66" + "011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650"); @@ -368,260 +356,286 @@ protected override X9ECParameters CreateParameters() } } - /* - * sect113r1 - */ internal class SecT113R1Holder : X9ECParametersHolder { - private SecT113R1Holder() { } + private SecT113R1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecT113R1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecT113R1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("10E723AB14D696E6768756151756FEBF8FCB49A9"); - ECCurve curve = ConfigureCurve(new SecT113R1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "04009D73616F35F4AB1407D73562C10F00A52830277958EE84D1315ED31886"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; - /* - * sect113r2 - */ internal class SecT113R2Holder : X9ECParametersHolder { - private SecT113R2Holder() { } + private SecT113R2Holder() {} internal static readonly X9ECParametersHolder Instance = new SecT113R2Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecT113R2Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("10C0FB15760860DEF1EEF4D696E676875615175D"); - ECCurve curve = ConfigureCurve(new SecT113R2Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "0401A57A6A7B26CA5EF52FCDB816479700B3ADC94ED1FE674C06E695BABA1D"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; - /* - * sect131r1 - */ internal class SecT131R1Holder : X9ECParametersHolder { - private SecT131R1Holder() { } + private SecT131R1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecT131R1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecT131R1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("4D696E676875615175985BD3ADBADA21B43A97E2"); - ECCurve curve = ConfigureCurve(new SecT131R1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "040081BAF91FDF9833C40F9C181343638399078C6E7EA38C001F73C8134B1B4EF9E150"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; - /* - * sect131r2 - */ internal class SecT131R2Holder : X9ECParametersHolder { - private SecT131R2Holder() { } + private SecT131R2Holder() {} internal static readonly X9ECParametersHolder Instance = new SecT131R2Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecT131R2Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("985BD3ADBAD4D696E676875615175A21B43A97E3"); - ECCurve curve = ConfigureCurve(new SecT131R2Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "040356DCD8F2F95031AD652D23951BB366A80648F06D867940A5366D9E265DE9EB240F"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; - /* - * sect163k1 - */ internal class SecT163K1Holder : X9ECParametersHolder { - private SecT163K1Holder() { } + private SecT163K1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecT163K1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecT163K1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = null; - ECCurve curve = ConfigureCurve(new SecT163K1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "0402FE13C0537BBC11ACAA07D793DE4E6D5E5C94EEE80289070FB05D38FF58321F2E800536D538CCDAA3D9"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; - /* - * sect163r1 - */ internal class SecT163R1Holder : X9ECParametersHolder { - private SecT163R1Holder() { } + private SecT163R1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecT163R1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecT163R1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("24B7B137C8A14D696E6768756151756FD0DA2E5C"); - ECCurve curve = ConfigureCurve(new SecT163R1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "040369979697AB43897789566789567F787A7876A65400435EDB42EFAFB2989D51FEFCE3C80988F41FF883"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; - /* - * sect163r2 - */ internal class SecT163R2Holder : X9ECParametersHolder { - private SecT163R2Holder() { } + private SecT163R2Holder() {} internal static readonly X9ECParametersHolder Instance = new SecT163R2Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecT163R2Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("85E25BFE5C86226CDB12016F7553F9D0E693A268"); - ECCurve curve = ConfigureCurve(new SecT163R2Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "0403F0EBA16286A2D57EA0991168D4994637E8343E3600D51FBC6C71A0094FA2CDD545B11C5C0C797324F1"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; - /* - * sect193r1 - */ internal class SecT193R1Holder : X9ECParametersHolder { - private SecT193R1Holder() { } + private SecT193R1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecT193R1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecT193R1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("103FAEC74D696E676875615175777FC5B191EF30"); - ECCurve curve = ConfigureCurve(new SecT193R1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "0401F481BC5F0FF84A74AD6CDF6FDEF4BF6179625372D8C0C5E10025E399F2903712CCF3EA9E3A1AD17FB0B3201B6AF7CE1B05"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; - /* - * sect193r2 - */ internal class SecT193R2Holder : X9ECParametersHolder { - private SecT193R2Holder() { } + private SecT193R2Holder() {} internal static readonly X9ECParametersHolder Instance = new SecT193R2Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecT193R2Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("10B7B4D696E676875615175137C8A16FD0DA2211"); - ECCurve curve = ConfigureCurve(new SecT193R2Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "0400D9B67D192E0367C803F39E1A7E82CA14A651350AAE617E8F01CE94335607C304AC29E7DEFBD9CA01F596F927224CDECF6C"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; - /* - * sect233k1 - */ internal class SecT233K1Holder : X9ECParametersHolder { - private SecT233K1Holder() { } + private SecT233K1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecT233K1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecT233K1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = null; - ECCurve curve = ConfigureCurve(new SecT233K1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "04017232BA853A7E731AF129F22FF4149563A419C26BF50A4C9D6EEFAD612601DB537DECE819B7F70F555A67C427A8CD9BF18AEB9B56E0C11056FAE6A3"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; - /* - * sect233r1 - */ internal class SecT233R1Holder : X9ECParametersHolder { - private SecT233R1Holder() { } + private SecT233R1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecT233R1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecT233R1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("74D59FF07F6B413D0EA14B344B20A2DB049B50C3"); - ECCurve curve = ConfigureCurve(new SecT233R1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "0400FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; - /* - * sect239k1 - */ internal class SecT239K1Holder : X9ECParametersHolder { - private SecT239K1Holder() { } + private SecT239K1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecT239K1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecT239K1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = null; - ECCurve curve = ConfigureCurve(new SecT239K1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "0429A0B6A887A983E9730988A68727A8B2D126C44CC2CC7B2A6555193035DC76310804F12E549BDB011C103089E73510ACB275FC312A5DC6B76553F0CA"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } }; - /* - * sect283k1 - */ internal class SecT283K1Holder : X9ECParametersHolder { - private SecT283K1Holder() { } + private SecT283K1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecT283K1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecT283K1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = null; - ECCurve curve = ConfigureCurve(new SecT283K1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "04" + "0503213F78CA44883F1A3B8162F188E553CD265F23C1567A16876913B0C2AC2458492836" + "01CCDA380F1C9E318D90F95D07E5426FE87E45C0E8184698E45962364E34116177DD2259"); @@ -629,20 +643,22 @@ protected override X9ECParameters CreateParameters() } }; - /* - * sect283r1 - */ internal class SecT283R1Holder : X9ECParametersHolder { - private SecT283R1Holder() { } + private SecT283R1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecT283R1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecT283R1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("77E2B07370EB0F832A6DD5B62DFC88CD06BB84BE"); - ECCurve curve = ConfigureCurve(new SecT283R1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "04" + "05F939258DB7DD90E1934F8C70B0DFEC2EED25B8557EAC9C80E2E198F8CDBECD86B12053" + "03676854FE24141CB98FE6D4B20D02B4516FF702350EDDB0826779C813F0DF45BE8112F4"); @@ -650,20 +666,22 @@ protected override X9ECParameters CreateParameters() } }; - /* - * sect409k1 - */ internal class SecT409K1Holder : X9ECParametersHolder { - private SecT409K1Holder() { } + private SecT409K1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecT409K1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecT409K1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = null; - ECCurve curve = ConfigureCurve(new SecT409K1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "04" + "0060F05F658F49C1AD3AB1890F7184210EFD0987E307C84C27ACCFB8F9F67CC2C460189EB5AAAA62EE222EB1B35540CFE9023746" + "01E369050B7C4E42ACBA1DACBF04299C3460782F918EA427E6325165E9EA10E3DA5F6C42E9C55215AA9CA27A5863EC48D8E0286B"); @@ -671,20 +689,22 @@ protected override X9ECParameters CreateParameters() } }; - /* - * sect409r1 - */ internal class SecT409R1Holder : X9ECParametersHolder { - private SecT409R1Holder() { } + private SecT409R1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecT409R1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecT409R1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("4099B5A457F9D69F79213D094C4BCD4D4262210B"); - ECCurve curve = ConfigureCurve(new SecT409R1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "04" + "015D4860D088DDB3496B0C6064756260441CDE4AF1771D4DB01FFE5B34E59703DC255A868A1180515603AEAB60794E54BB7996A7" + "0061B1CFAB6BE5F32BBFA78324ED106A7636B9C5A7BD198D0158AA4F5488D08F38514F1FDF4B4F40D2181B3681C364BA0273C706"); @@ -692,20 +712,22 @@ protected override X9ECParameters CreateParameters() } }; - /* - * sect571k1 - */ internal class SecT571K1Holder : X9ECParametersHolder { - private SecT571K1Holder() { } + private SecT571K1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecT571K1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecT571K1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = null; - ECCurve curve = ConfigureCurve(new SecT571K1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "04" + "026EB7A859923FBC82189631F8103FE4AC9CA2970012D5D46024804801841CA44370958493B205E647DA304DB4CEB08CBBD1BA39494776FB988B47174DCA88C7E2945283A01C8972" + "0349DC807F4FBF374F4AEADE3BCA95314DD58CEC9F307A54FFC61EFC006D8A2C9D4979C0AC44AEA74FBEBBB9F772AEDCB620B01A7BA7AF1B320430C8591984F601CD4C143EF1C7A3"); @@ -713,20 +735,22 @@ protected override X9ECParameters CreateParameters() } }; - /* - * sect571r1 - */ internal class SecT571R1Holder : X9ECParametersHolder { - private SecT571R1Holder() { } + private SecT571R1Holder() {} internal static readonly X9ECParametersHolder Instance = new SecT571R1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SecT571R1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = Hex.DecodeStrict("2AA058F73A0E33AB486B0F610410C53A7F132310"); - ECCurve curve = ConfigureCurve(new SecT571R1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "04" + "0303001D34B856296C16C0D40D3CD7750A93D1D2955FA80AA5F40FC8DB7B2ABDBDE53950F4C0D293CDD711A35B67FB1499AE60038614F1394ABFA3B4C850D927E1E7769C8EEC2D19" + "037BF27342DA639B6DCCFFFEB73D69D78C6C27A6009CBBCA1980F8533921E8A684423E43BAB08A576291AF8F461BB2A8B3531D2F0485C19B16E2F1516E23DD3C1A4827AF1B8AC15B"); @@ -734,101 +758,88 @@ protected override X9ECParameters CreateParameters() } }; - /* - * sm2p256v1 - */ internal class SM2P256V1Holder : X9ECParametersHolder { - private SM2P256V1Holder() { } + private SM2P256V1Holder() {} internal static readonly X9ECParametersHolder Instance = new SM2P256V1Holder(); + protected override ECCurve CreateCurve() + { + return ConfigureCurve(new SM2P256V1Curve()); + } + protected override X9ECParameters CreateParameters() { byte[] S = null; - ECCurve curve = ConfigureCurve(new SM2P256V1Curve()); + ECCurve curve = Curve; X9ECPoint G = ConfigureBasepoint(curve, "0432C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0"); return new X9ECParameters(curve, G, curve.Order, curve.Cofactor, S); } } + private static readonly Dictionary objIds = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly Dictionary curves = + new Dictionary(); + private static readonly Dictionary names = + new Dictionary(); - private static readonly IDictionary nameToCurve = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private static readonly IDictionary nameToOid = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private static readonly IDictionary oidToCurve = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private static readonly IDictionary oidToName = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private static readonly IList names = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); - - private static void DefineCurve(string name, X9ECParametersHolder holder) - { - names.Add(name); - name = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(name); - nameToCurve.Add(name, holder); - } - - private static void DefineCurveWithOid(string name, DerObjectIdentifier oid, X9ECParametersHolder holder) + private static void DefineCurve(string name, DerObjectIdentifier oid, X9ECParametersHolder holder) { - names.Add(name); - oidToName.Add(oid, name); - oidToCurve.Add(oid, holder); - name = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(name); - nameToOid.Add(name, oid); - nameToCurve.Add(name, holder); + objIds.Add(name, oid); + names.Add(oid, name); + curves.Add(oid, holder); } private static void DefineCurveAlias(string name, DerObjectIdentifier oid) { - object curve = oidToCurve[oid]; - if (curve == null) + if (!curves.ContainsKey(oid)) throw new InvalidOperationException(); - name = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(name); - nameToOid.Add(name, oid); - nameToCurve.Add(name, curve); + objIds.Add(name, oid); } static CustomNamedCurves() { - DefineCurve("curve25519", Curve25519Holder.Instance); - - //DefineCurveWithOid("secp112r1", SecObjectIdentifiers.SecP112r1, SecP112R1Holder.Instance); - //DefineCurveWithOid("secp112r2", SecObjectIdentifiers.SecP112r2, SecP112R2Holder.Instance); - DefineCurveWithOid("secp128r1", SecObjectIdentifiers.SecP128r1, SecP128R1Holder.Instance); - //DefineCurveWithOid("secp128r2", SecObjectIdentifiers.SecP128r2, SecP128R2Holder.Instance); - DefineCurveWithOid("secp160k1", SecObjectIdentifiers.SecP160k1, SecP160K1Holder.Instance); - DefineCurveWithOid("secp160r1", SecObjectIdentifiers.SecP160r1, SecP160R1Holder.Instance); - DefineCurveWithOid("secp160r2", SecObjectIdentifiers.SecP160r2, SecP160R2Holder.Instance); - DefineCurveWithOid("secp192k1", SecObjectIdentifiers.SecP192k1, SecP192K1Holder.Instance); - DefineCurveWithOid("secp192r1", SecObjectIdentifiers.SecP192r1, SecP192R1Holder.Instance); - DefineCurveWithOid("secp224k1", SecObjectIdentifiers.SecP224k1, SecP224K1Holder.Instance); - DefineCurveWithOid("secp224r1", SecObjectIdentifiers.SecP224r1, SecP224R1Holder.Instance); - DefineCurveWithOid("secp256k1", SecObjectIdentifiers.SecP256k1, SecP256K1Holder.Instance); - DefineCurveWithOid("secp256r1", SecObjectIdentifiers.SecP256r1, SecP256R1Holder.Instance); - DefineCurveWithOid("secp384r1", SecObjectIdentifiers.SecP384r1, SecP384R1Holder.Instance); - DefineCurveWithOid("secp521r1", SecObjectIdentifiers.SecP521r1, SecP521R1Holder.Instance); - - DefineCurveWithOid("sect113r1", SecObjectIdentifiers.SecT113r1, SecT113R1Holder.Instance); - DefineCurveWithOid("sect113r2", SecObjectIdentifiers.SecT113r2, SecT113R2Holder.Instance); - DefineCurveWithOid("sect131r1", SecObjectIdentifiers.SecT131r1, SecT131R1Holder.Instance); - DefineCurveWithOid("sect131r2", SecObjectIdentifiers.SecT131r2, SecT131R2Holder.Instance); - DefineCurveWithOid("sect163k1", SecObjectIdentifiers.SecT163k1, SecT163K1Holder.Instance); - DefineCurveWithOid("sect163r1", SecObjectIdentifiers.SecT163r1, SecT163R1Holder.Instance); - DefineCurveWithOid("sect163r2", SecObjectIdentifiers.SecT163r2, SecT163R2Holder.Instance); - DefineCurveWithOid("sect193r1", SecObjectIdentifiers.SecT193r1, SecT193R1Holder.Instance); - DefineCurveWithOid("sect193r2", SecObjectIdentifiers.SecT193r2, SecT193R2Holder.Instance); - DefineCurveWithOid("sect233k1", SecObjectIdentifiers.SecT233k1, SecT233K1Holder.Instance); - DefineCurveWithOid("sect233r1", SecObjectIdentifiers.SecT233r1, SecT233R1Holder.Instance); - DefineCurveWithOid("sect239k1", SecObjectIdentifiers.SecT239k1, SecT239K1Holder.Instance); - DefineCurveWithOid("sect283k1", SecObjectIdentifiers.SecT283k1, SecT283K1Holder.Instance); - DefineCurveWithOid("sect283r1", SecObjectIdentifiers.SecT283r1, SecT283R1Holder.Instance); - DefineCurveWithOid("sect409k1", SecObjectIdentifiers.SecT409k1, SecT409K1Holder.Instance); - DefineCurveWithOid("sect409r1", SecObjectIdentifiers.SecT409r1, SecT409R1Holder.Instance); - DefineCurveWithOid("sect571k1", SecObjectIdentifiers.SecT571k1, SecT571K1Holder.Instance); - DefineCurveWithOid("sect571r1", SecObjectIdentifiers.SecT571r1, SecT571R1Holder.Instance); - - DefineCurveWithOid("sm2p256v1", GMObjectIdentifiers.sm2p256v1, SM2P256V1Holder.Instance); + //DefineCurve("secp112r1", SecObjectIdentifiers.SecP112r1, SecP112R1Holder.Instance); + //DefineCurve("secp112r2", SecObjectIdentifiers.SecP112r2, SecP112R2Holder.Instance); + DefineCurve("secp128r1", SecObjectIdentifiers.SecP128r1, SecP128R1Holder.Instance); + //DefineCurve("secp128r2", SecObjectIdentifiers.SecP128r2, SecP128R2Holder.Instance); + DefineCurve("secp160k1", SecObjectIdentifiers.SecP160k1, SecP160K1Holder.Instance); + DefineCurve("secp160r1", SecObjectIdentifiers.SecP160r1, SecP160R1Holder.Instance); + DefineCurve("secp160r2", SecObjectIdentifiers.SecP160r2, SecP160R2Holder.Instance); + DefineCurve("secp192k1", SecObjectIdentifiers.SecP192k1, SecP192K1Holder.Instance); + DefineCurve("secp192r1", SecObjectIdentifiers.SecP192r1, SecP192R1Holder.Instance); + DefineCurve("secp224k1", SecObjectIdentifiers.SecP224k1, SecP224K1Holder.Instance); + DefineCurve("secp224r1", SecObjectIdentifiers.SecP224r1, SecP224R1Holder.Instance); + DefineCurve("secp256k1", SecObjectIdentifiers.SecP256k1, SecP256K1Holder.Instance); + DefineCurve("secp256r1", SecObjectIdentifiers.SecP256r1, SecP256R1Holder.Instance); + DefineCurve("secp384r1", SecObjectIdentifiers.SecP384r1, SecP384R1Holder.Instance); + DefineCurve("secp521r1", SecObjectIdentifiers.SecP521r1, SecP521R1Holder.Instance); + + DefineCurve("sect113r1", SecObjectIdentifiers.SecT113r1, SecT113R1Holder.Instance); + DefineCurve("sect113r2", SecObjectIdentifiers.SecT113r2, SecT113R2Holder.Instance); + DefineCurve("sect131r1", SecObjectIdentifiers.SecT131r1, SecT131R1Holder.Instance); + DefineCurve("sect131r2", SecObjectIdentifiers.SecT131r2, SecT131R2Holder.Instance); + DefineCurve("sect163k1", SecObjectIdentifiers.SecT163k1, SecT163K1Holder.Instance); + DefineCurve("sect163r1", SecObjectIdentifiers.SecT163r1, SecT163R1Holder.Instance); + DefineCurve("sect163r2", SecObjectIdentifiers.SecT163r2, SecT163R2Holder.Instance); + DefineCurve("sect193r1", SecObjectIdentifiers.SecT193r1, SecT193R1Holder.Instance); + DefineCurve("sect193r2", SecObjectIdentifiers.SecT193r2, SecT193R2Holder.Instance); + DefineCurve("sect233k1", SecObjectIdentifiers.SecT233k1, SecT233K1Holder.Instance); + DefineCurve("sect233r1", SecObjectIdentifiers.SecT233r1, SecT233R1Holder.Instance); + DefineCurve("sect239k1", SecObjectIdentifiers.SecT239k1, SecT239K1Holder.Instance); + DefineCurve("sect283k1", SecObjectIdentifiers.SecT283k1, SecT283K1Holder.Instance); + DefineCurve("sect283r1", SecObjectIdentifiers.SecT283r1, SecT283R1Holder.Instance); + DefineCurve("sect409k1", SecObjectIdentifiers.SecT409k1, SecT409K1Holder.Instance); + DefineCurve("sect409r1", SecObjectIdentifiers.SecT409r1, SecT409R1Holder.Instance); + DefineCurve("sect571k1", SecObjectIdentifiers.SecT571k1, SecT571K1Holder.Instance); + DefineCurve("sect571r1", SecObjectIdentifiers.SecT571r1, SecT571R1Holder.Instance); + + DefineCurve("sm2p256v1", GMObjectIdentifiers.sm2p256v1, SM2P256V1Holder.Instance); DefineCurveAlias("B-163", SecObjectIdentifiers.SecT163r2); DefineCurveAlias("B-233", SecObjectIdentifiers.SecT233r1); @@ -849,50 +860,64 @@ static CustomNamedCurves() DefineCurveAlias("P-521", SecObjectIdentifiers.SecP521r1); } + /// Look up the for the curve with the given name. + /// The name of the curve. public static X9ECParameters GetByName(string name) { - X9ECParametersHolder holder = (X9ECParametersHolder)nameToCurve[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(name)]; - return holder == null ? null : holder.Parameters; + DerObjectIdentifier oid = GetOid(name); + return oid == null ? null : GetByOid(oid); } - /** - * return the X9ECParameters object for the named curve represented by - * the passed in object identifier. Null if the curve isn't present. - * - * @param oid an object identifier representing a named curve, if present. - */ + /// Look up an for the curve with the given name. + /// + /// Allows accessing the curve without necessarily triggering the creation of the + /// full . + /// + /// The name of the curve. + public static X9ECParametersHolder GetByNameLazy(string name) + { + DerObjectIdentifier oid = GetOid(name); + return oid == null ? null : GetByOidLazy(oid); + } + + /// Look up the for the curve with the given + /// OID. + /// The OID for the curve. public static X9ECParameters GetByOid(DerObjectIdentifier oid) { - X9ECParametersHolder holder = (X9ECParametersHolder)oidToCurve[oid]; - return holder == null ? null : holder.Parameters; + return GetByOidLazy(oid)?.Parameters; } - /** - * return the object identifier signified by the passed in name. Null - * if there is no object identifier associated with name. - * - * @return the object identifier associated with name, if present. - */ - public static DerObjectIdentifier GetOid(string name) + /// Look up an for the curve with the given + /// OID. + /// + /// Allows accessing the curve without necessarily triggering the creation of the + /// full . + /// + /// The OID for the curve. + public static X9ECParametersHolder GetByOidLazy(DerObjectIdentifier oid) { - return (DerObjectIdentifier)nameToOid[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(name)]; + return CollectionUtilities.GetValueOrNull(curves, oid); } - /** - * return the named curve name represented by the given object identifier. - */ + /// Look up the name of the curve with the given OID. + /// The OID for the curve. public static string GetName(DerObjectIdentifier oid) { - return (string)oidToName[oid]; + return CollectionUtilities.GetValueOrNull(names, oid); + } + + /// Look up the OID of the curve with the given name. + /// The name of the curve. + public static DerObjectIdentifier GetOid(string name) + { + return CollectionUtilities.GetValueOrNull(objIds, name); } - /** - * returns an enumeration containing the name strings for curves - * contained in this structure. - */ - public static IEnumerable Names + /// Enumerate the available curve names in this registry. + public static IEnumerable Names { - get { return new EnumerableProxy(names); } + get { return CollectionUtilities.Proxy(objIds.Keys); } } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/encodings/ISO9796d1Encoding.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/encodings/ISO9796d1Encoding.cs index 93e25e7..7c53a9a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/encodings/ISO9796d1Encoding.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/encodings/ISO9796d1Encoding.cs @@ -31,31 +31,21 @@ public class ISO9796d1Encoding private int padBits = 0; private BigInteger modulus; - public ISO9796d1Encoding( - IAsymmetricBlockCipher cipher) + public ISO9796d1Encoding(IAsymmetricBlockCipher cipher) { this.engine = cipher; } - public string AlgorithmName - { - get { return engine.AlgorithmName + "/ISO9796-1Padding"; } - } + public string AlgorithmName => engine.AlgorithmName + "/ISO9796-1Padding"; - public IAsymmetricBlockCipher GetUnderlyingCipher() - { - return engine; - } + public IAsymmetricBlockCipher UnderlyingCipher => engine; - public void Init( - bool forEncryption, - ICipherParameters parameters) - { - RsaKeyParameters kParam; - if (parameters is ParametersWithRandom) + public void Init(bool forEncryption, ICipherParameters parameters) + { + RsaKeyParameters kParam; + if (parameters is ParametersWithRandom withRandom) { - ParametersWithRandom rParam = (ParametersWithRandom)parameters; - kParam = (RsaKeyParameters)rParam.Parameters; + kParam = (RsaKeyParameters)withRandom.Parameters; } else { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/encodings/OaepEncoding.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/encodings/OaepEncoding.cs index ab6353d..32dccc9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/encodings/OaepEncoding.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/encodings/OaepEncoding.cs @@ -64,31 +64,22 @@ public OaepEncoding( hash.DoFinal(defHash, 0); } - public IAsymmetricBlockCipher GetUnderlyingCipher() - { - return engine; - } + public string AlgorithmName => engine.AlgorithmName + "/OAEPPadding"; - public string AlgorithmName - { - get { return engine.AlgorithmName + "/OAEPPadding"; } - } + public IAsymmetricBlockCipher UnderlyingCipher => engine; - public void Init( - bool forEncryption, - ICipherParameters param) + public void Init(bool forEncryption, ICipherParameters parameters) { - if (param is ParametersWithRandom) + if (parameters is ParametersWithRandom withRandom) { - ParametersWithRandom rParam = (ParametersWithRandom)param; - this.random = rParam.Random; + this.random = withRandom.Random; } else { - this.random = new SecureRandom(); + this.random = CryptoServicesRegistrar.GetSecureRandom(); } - engine.Init(forEncryption, param); + engine.Init(forEncryption, parameters); this.forEncryption = forEncryption; } @@ -215,7 +206,8 @@ private byte[] DecodeBlock( // on encryption, we need to make sure our decrypted block comes back // the same size. // - bool wrongData = (block.Length < (2 * defHash.Length) + 1); + // i.e. wrong when block.length < (2 * defHash.length) + 1 + int wrongMask = (block.Length - ((2 * defHash.Length) + 1)) >> 31; if (data.Length <= block.Length) { @@ -224,7 +216,7 @@ private byte[] DecodeBlock( else { Array.Copy(data, 0, block, 0, block.Length); - wrongData = true; + wrongMask |= 1; } // @@ -252,39 +244,38 @@ private byte[] DecodeBlock( // check the hash of the encoding params. // long check to try to avoid this been a source of a timing attack. // - bool defHashWrong = false; - for (int i = 0; i != defHash.Length; i++) { - if (defHash[i] != block[defHash.Length + i]) - { - defHashWrong = true; - } + wrongMask |= defHash[i] ^ block[defHash.Length + i]; } // // find the data block // - int start = block.Length; + int start = -1; for (int index = 2 * defHash.Length; index != block.Length; index++) { - if (block[index] != 0 & start == block.Length) - { - start = index; - } - } + int octet = block[index]; + + // i.e. mask will be 0xFFFFFFFF if octet is non-zero and start is (still) negative, else 0. + int shouldSetMask = (-octet & start) >> 31; - bool dataStartWrong = (start > (block.Length - 1) | block[start] != 1); + start += index & shouldSetMask; + } - start++; + wrongMask |= start >> 31; + ++start; + wrongMask |= block[start] ^ 1; - if (defHashWrong | wrongData | dataStartWrong) + if (wrongMask != 0) { Arrays.Fill(block, 0); throw new InvalidCipherTextException("data wrong"); } + ++start; + // // extract the data block // @@ -306,7 +297,7 @@ private byte[] MaskGeneratorFunction( { byte[] mask = new byte[length]; mgf1Hash.BlockUpdate(Z, zOff, zLen); - ((IXof)mgf1Hash).DoFinal(mask, 0, mask.Length); + ((IXof)mgf1Hash).OutputFinal(mask, 0, mask.Length); return mask; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/encodings/Pkcs1Encoding.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/encodings/Pkcs1Encoding.cs index 8cba8a3..a9a0a7e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/encodings/Pkcs1Encoding.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/encodings/Pkcs1Encoding.cs @@ -41,9 +41,9 @@ public static bool StrictLengthEnabled static Pkcs1Encoding() { - string strictProperty = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetEnvironmentVariable(StrictLengthEnabledProperty); + string strictProperty = Org.BouncyCastle.Utilities.Platform.GetEnvironmentVariable(StrictLengthEnabledProperty); - strictLengthEnabled = new bool[]{ strictProperty == null || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase("true", strictProperty) }; + strictLengthEnabled = new bool[]{ strictProperty == null || Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase("true", strictProperty) }; } @@ -98,29 +98,21 @@ public Pkcs1Encoding(IAsymmetricBlockCipher cipher, byte[] fallback) this.pLen = fallback.Length; } - public IAsymmetricBlockCipher GetUnderlyingCipher() - { - return engine; - } + public string AlgorithmName => engine.AlgorithmName + "/PKCS1Padding"; - public string AlgorithmName - { - get { return engine.AlgorithmName + "/PKCS1Padding"; } - } + public IAsymmetricBlockCipher UnderlyingCipher => engine; public void Init(bool forEncryption, ICipherParameters parameters) { AsymmetricKeyParameter kParam; - if (parameters is ParametersWithRandom) + if (parameters is ParametersWithRandom withRandom) { - ParametersWithRandom rParam = (ParametersWithRandom)parameters; - - this.random = rParam.Random; - kParam = (AsymmetricKeyParameter)rParam.Parameters; + this.random = withRandom.Random; + kParam = (AsymmetricKeyParameter)withRandom.Parameters; } else { - this.random = new SecureRandom(); + this.random = CryptoServicesRegistrar.GetSecureRandom(); kParam = (AsymmetricKeyParameter)parameters; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesEngine.cs index 730f62c..d8232e3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesEngine.cs @@ -33,7 +33,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines * This file contains the middle performance version with 2Kbytes of static tables for round precomputation. *

*/ - public class AesEngine + public sealed class AesEngine : IBlockCipher { // The S box @@ -449,15 +449,11 @@ public AesEngine() * @exception ArgumentException if the parameters argument is * inappropriate. */ - public virtual void Init( - bool forEncryption, - ICipherParameters parameters) + public void Init(bool forEncryption, ICipherParameters parameters) { - KeyParameter keyParameter = parameters as KeyParameter; - - if (keyParameter == null) + if (!(parameters is KeyParameter keyParameter)) throw new ArgumentException("invalid parameter passed to AES init - " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); WorkingKey = GenerateWorkingKey(keyParameter.GetKey(), forEncryption); @@ -465,22 +461,17 @@ public virtual void Init( this.s = Arrays.Clone(forEncryption ? S : Si); } - public virtual string AlgorithmName + public string AlgorithmName { get { return "AES"; } } - public virtual bool IsPartialBlockOkay - { - get { return false; } - } - - public virtual int GetBlockSize() + public int GetBlockSize() { return BLOCK_SIZE; } - public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) + public int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { if (WorkingKey == null) throw new InvalidOperationException("AES engine not initialised"); @@ -488,6 +479,16 @@ public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outO Check.DataLength(input, inOff, 16, "input buffer too short"); Check.OutputLength(output, outOff, 16, "output buffer too short"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + if (forEncryption) + { + EncryptBlock(input.AsSpan(inOff), output.AsSpan(outOff), WorkingKey); + } + else + { + DecryptBlock(input.AsSpan(inOff), output.AsSpan(outOff), WorkingKey); + } +#else if (forEncryption) { EncryptBlock(input, inOff, output, outOff, WorkingKey); @@ -496,14 +497,130 @@ public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outO { DecryptBlock(input, inOff, output, outOff, WorkingKey); } +#endif return BLOCK_SIZE; } - public virtual void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessBlock(ReadOnlySpan input, Span output) { + if (WorkingKey == null) + throw new InvalidOperationException("AES engine not initialised"); + + Check.DataLength(input, 16, "input buffer too short"); + Check.OutputLength(output, 16, "output buffer too short"); + + if (forEncryption) + { + EncryptBlock(input, output, WorkingKey); + } + else + { + DecryptBlock(input, output, WorkingKey); + } + + return BLOCK_SIZE; + } +#endif + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void EncryptBlock(ReadOnlySpan input, Span output, uint[][] KW) + { + uint C0 = Pack.LE_To_UInt32(input); + uint C1 = Pack.LE_To_UInt32(input[4..]); + uint C2 = Pack.LE_To_UInt32(input[8..]); + uint C3 = Pack.LE_To_UInt32(input[12..]); + + uint[] kw = KW[0]; + uint t0 = C0 ^ kw[0]; + uint t1 = C1 ^ kw[1]; + uint t2 = C2 ^ kw[2]; + + uint r0, r1, r2, r3 = C3 ^ kw[3]; + int r = 1; + while (r < ROUNDS - 1) + { + kw = KW[r++]; + r0 = T0[t0 & 255] ^ Shift(T0[(t1 >> 8) & 255], 24) ^ Shift(T0[(t2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0]; + r1 = T0[t1 & 255] ^ Shift(T0[(t2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(t0 >> 24) & 255], 8) ^ kw[1]; + r2 = T0[t2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(t0 >> 16) & 255], 16) ^ Shift(T0[(t1 >> 24) & 255], 8) ^ kw[2]; + r3 = T0[r3 & 255] ^ Shift(T0[(t0 >> 8) & 255], 24) ^ Shift(T0[(t1 >> 16) & 255], 16) ^ Shift(T0[(t2 >> 24) & 255], 8) ^ kw[3]; + kw = KW[r++]; + t0 = T0[r0 & 255] ^ Shift(T0[(r1 >> 8) & 255], 24) ^ Shift(T0[(r2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0]; + t1 = T0[r1 & 255] ^ Shift(T0[(r2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(r0 >> 24) & 255], 8) ^ kw[1]; + t2 = T0[r2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(r0 >> 16) & 255], 16) ^ Shift(T0[(r1 >> 24) & 255], 8) ^ kw[2]; + r3 = T0[r3 & 255] ^ Shift(T0[(r0 >> 8) & 255], 24) ^ Shift(T0[(r1 >> 16) & 255], 16) ^ Shift(T0[(r2 >> 24) & 255], 8) ^ kw[3]; + } + + kw = KW[r++]; + r0 = T0[t0 & 255] ^ Shift(T0[(t1 >> 8) & 255], 24) ^ Shift(T0[(t2 >> 16) & 255], 16) ^ Shift(T0[(r3 >> 24) & 255], 8) ^ kw[0]; + r1 = T0[t1 & 255] ^ Shift(T0[(t2 >> 8) & 255], 24) ^ Shift(T0[(r3 >> 16) & 255], 16) ^ Shift(T0[(t0 >> 24) & 255], 8) ^ kw[1]; + r2 = T0[t2 & 255] ^ Shift(T0[(r3 >> 8) & 255], 24) ^ Shift(T0[(t0 >> 16) & 255], 16) ^ Shift(T0[(t1 >> 24) & 255], 8) ^ kw[2]; + r3 = T0[r3 & 255] ^ Shift(T0[(t0 >> 8) & 255], 24) ^ Shift(T0[(t1 >> 16) & 255], 16) ^ Shift(T0[(t2 >> 24) & 255], 8) ^ kw[3]; + + // the final round's table is a simple function of S so we don't use a whole other four tables for it + + kw = KW[r]; + C0 = (uint)S[r0 & 255] ^ (((uint)S[(r1 >> 8) & 255]) << 8) ^ (((uint)s[(r2 >> 16) & 255]) << 16) ^ (((uint)s[(r3 >> 24) & 255]) << 24) ^ kw[0]; + C1 = (uint)s[r1 & 255] ^ (((uint)S[(r2 >> 8) & 255]) << 8) ^ (((uint)S[(r3 >> 16) & 255]) << 16) ^ (((uint)s[(r0 >> 24) & 255]) << 24) ^ kw[1]; + C2 = (uint)s[r2 & 255] ^ (((uint)S[(r3 >> 8) & 255]) << 8) ^ (((uint)S[(r0 >> 16) & 255]) << 16) ^ (((uint)S[(r1 >> 24) & 255]) << 24) ^ kw[2]; + C3 = (uint)s[r3 & 255] ^ (((uint)s[(r0 >> 8) & 255]) << 8) ^ (((uint)s[(r1 >> 16) & 255]) << 16) ^ (((uint)S[(r2 >> 24) & 255]) << 24) ^ kw[3]; + + Pack.UInt32_To_LE(C0, output); + Pack.UInt32_To_LE(C1, output[4..]); + Pack.UInt32_To_LE(C2, output[8..]); + Pack.UInt32_To_LE(C3, output[12..]); } + private void DecryptBlock(ReadOnlySpan input, Span output, uint[][] KW) + { + uint C0 = Pack.LE_To_UInt32(input); + uint C1 = Pack.LE_To_UInt32(input[4..]); + uint C2 = Pack.LE_To_UInt32(input[8..]); + uint C3 = Pack.LE_To_UInt32(input[12..]); + + uint[] kw = KW[ROUNDS]; + uint t0 = C0 ^ kw[0]; + uint t1 = C1 ^ kw[1]; + uint t2 = C2 ^ kw[2]; + + uint r0, r1, r2, r3 = C3 ^ kw[3]; + int r = ROUNDS - 1; + while (r > 1) + { + kw = KW[r--]; + r0 = Tinv0[t0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(t2 >> 16) & 255], 16) ^ Shift(Tinv0[(t1 >> 24) & 255], 8) ^ kw[0]; + r1 = Tinv0[t1 & 255] ^ Shift(Tinv0[(t0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(t2 >> 24) & 255], 8) ^ kw[1]; + r2 = Tinv0[t2 & 255] ^ Shift(Tinv0[(t1 >> 8) & 255], 24) ^ Shift(Tinv0[(t0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2]; + r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(t2 >> 8) & 255], 24) ^ Shift(Tinv0[(t1 >> 16) & 255], 16) ^ Shift(Tinv0[(t0 >> 24) & 255], 8) ^ kw[3]; + kw = KW[r--]; + t0 = Tinv0[r0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(r2 >> 16) & 255], 16) ^ Shift(Tinv0[(r1 >> 24) & 255], 8) ^ kw[0]; + t1 = Tinv0[r1 & 255] ^ Shift(Tinv0[(r0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(r2 >> 24) & 255], 8) ^ kw[1]; + t2 = Tinv0[r2 & 255] ^ Shift(Tinv0[(r1 >> 8) & 255], 24) ^ Shift(Tinv0[(r0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2]; + r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(r2 >> 8) & 255], 24) ^ Shift(Tinv0[(r1 >> 16) & 255], 16) ^ Shift(Tinv0[(r0 >> 24) & 255], 8) ^ kw[3]; + } + + kw = KW[1]; + r0 = Tinv0[t0 & 255] ^ Shift(Tinv0[(r3 >> 8) & 255], 24) ^ Shift(Tinv0[(t2 >> 16) & 255], 16) ^ Shift(Tinv0[(t1 >> 24) & 255], 8) ^ kw[0]; + r1 = Tinv0[t1 & 255] ^ Shift(Tinv0[(t0 >> 8) & 255], 24) ^ Shift(Tinv0[(r3 >> 16) & 255], 16) ^ Shift(Tinv0[(t2 >> 24) & 255], 8) ^ kw[1]; + r2 = Tinv0[t2 & 255] ^ Shift(Tinv0[(t1 >> 8) & 255], 24) ^ Shift(Tinv0[(t0 >> 16) & 255], 16) ^ Shift(Tinv0[(r3 >> 24) & 255], 8) ^ kw[2]; + r3 = Tinv0[r3 & 255] ^ Shift(Tinv0[(t2 >> 8) & 255], 24) ^ Shift(Tinv0[(t1 >> 16) & 255], 16) ^ Shift(Tinv0[(t0 >> 24) & 255], 8) ^ kw[3]; + + // the final round's table is a simple function of Si so we don't use a whole other four tables for it + + kw = KW[0]; + C0 = (uint)Si[r0 & 255] ^ (((uint)s[(r3 >> 8) & 255]) << 8) ^ (((uint)s[(r2 >> 16) & 255]) << 16) ^ (((uint)Si[(r1 >> 24) & 255]) << 24) ^ kw[0]; + C1 = (uint)s[r1 & 255] ^ (((uint)s[(r0 >> 8) & 255]) << 8) ^ (((uint)Si[(r3 >> 16) & 255]) << 16) ^ (((uint)s[(r2 >> 24) & 255]) << 24) ^ kw[1]; + C2 = (uint)s[r2 & 255] ^ (((uint)Si[(r1 >> 8) & 255]) << 8) ^ (((uint)Si[(r0 >> 16) & 255]) << 16) ^ (((uint)s[(r3 >> 24) & 255]) << 24) ^ kw[2]; + C3 = (uint)Si[r3 & 255] ^ (((uint)s[(r2 >> 8) & 255]) << 8) ^ (((uint)s[(r1 >> 16) & 255]) << 16) ^ (((uint)s[(r0 >> 24) & 255]) << 24) ^ kw[3]; + + Pack.UInt32_To_LE(C0, output); + Pack.UInt32_To_LE(C1, output[4..]); + Pack.UInt32_To_LE(C2, output[8..]); + Pack.UInt32_To_LE(C3, output[12..]); + } +#else private void EncryptBlock(byte[] input, int inOff, byte[] output, int outOff, uint[][] KW) { uint C0 = Pack.LE_To_UInt32(input, inOff + 0); @@ -599,6 +716,7 @@ private void DecryptBlock(byte[] input, int inOff, byte[] output, int outOff, ui Pack.UInt32_To_LE(C2, output, outOff + 8); Pack.UInt32_To_LE(C3, output, outOff + 12); } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesEngine_X86.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesEngine_X86.cs new file mode 100644 index 0000000..ffeb90f --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesEngine_X86.cs @@ -0,0 +1,834 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +#if NETCOREAPP3_0_OR_GREATER +using System; +using System.Buffers.Binary; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; + +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines +{ + using Aes = System.Runtime.Intrinsics.X86.Aes; + using Sse2 = System.Runtime.Intrinsics.X86.Sse2; + + public struct AesEngine_X86 + : IBlockCipher + { + public static bool IsSupported => Aes.IsSupported; + + private static Vector128[] CreateRoundKeys(byte[] key, bool forEncryption) + { + Vector128[] K; + + switch (key.Length) + { + case 16: + { + ReadOnlySpan rcon = stackalloc byte[]{ 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36 }; + + K = new Vector128[11]; + + var s = Load128(key.AsSpan(0, 16)); + K[0] = s; + + for (int round = 0; round < 10;) + { + var t = Aes.KeygenAssist(s, rcon[round++]); + t = Sse2.Shuffle(t.AsInt32(), 0xFF).AsByte(); + s = Sse2.Xor(s, Sse2.ShiftLeftLogical128BitLane(s, 8)); + s = Sse2.Xor(s, Sse2.ShiftLeftLogical128BitLane(s, 4)); + s = Sse2.Xor(s, t); + K[round] = s; + } + + break; + } + case 24: + { + K = new Vector128[13]; + + var s1 = Load128(key.AsSpan(0, 16)); + var s2 = Load64(key.AsSpan(16, 8)).ToVector128(); + K[0] = s1; + + byte rcon = 0x01; + for (int round = 0;;) + { + var t1 = Aes.KeygenAssist(s2, rcon); rcon <<= 1; + t1 = Sse2.Shuffle(t1.AsInt32(), 0x55).AsByte(); + + s1 = Sse2.Xor(s1, Sse2.ShiftLeftLogical128BitLane(s1, 8)); + s1 = Sse2.Xor(s1, Sse2.ShiftLeftLogical128BitLane(s1, 4)); + s1 = Sse2.Xor(s1, t1); + + K[++round] = Sse2.Xor(s2, Sse2.ShiftLeftLogical128BitLane(s1, 8)); + + var s3 = Sse2.Xor(s2, Sse2.ShiftRightLogical128BitLane(s1, 12)); + s3 = Sse2.Xor(s3, Sse2.ShiftLeftLogical128BitLane(s3, 4)); + + K[++round] = Sse2.Xor( + Sse2.ShiftRightLogical128BitLane(s1, 8), + Sse2.ShiftLeftLogical128BitLane(s3, 8)); + + var t2 = Aes.KeygenAssist(s3, rcon); rcon <<= 1; + t2 = Sse2.Shuffle(t2.AsInt32(), 0x55).AsByte(); + + s1 = Sse2.Xor(s1, Sse2.ShiftLeftLogical128BitLane(s1, 8)); + s1 = Sse2.Xor(s1, Sse2.ShiftLeftLogical128BitLane(s1, 4)); + s1 = Sse2.Xor(s1, t2); + + K[++round] = s1; + + if (round == 12) + break; + + s2 = Sse2.Xor(s3, Sse2.ShiftRightLogical128BitLane(s1, 12)); + s2 = Sse2.Xor(s2, Sse2.ShiftLeftLogical128BitLane(s2, 4)); + s2 = s2.WithUpper(Vector64.Zero); + } + + break; + } + case 32: + { + K = new Vector128[15]; + + var s1 = Load128(key.AsSpan(0, 16)); + var s2 = Load128(key.AsSpan(16, 16)); + K[0] = s1; + K[1] = s2; + + byte rcon = 0x01; + for (int round = 1;;) + { + var t1 = Aes.KeygenAssist(s2, rcon); rcon <<= 1; + t1 = Sse2.Shuffle(t1.AsInt32(), 0xFF).AsByte(); + s1 = Sse2.Xor(s1, Sse2.ShiftLeftLogical128BitLane(s1, 8)); + s1 = Sse2.Xor(s1, Sse2.ShiftLeftLogical128BitLane(s1, 4)); + s1 = Sse2.Xor(s1, t1); + K[++round] = s1; + + if (round == 14) + break; + + var t2 = Aes.KeygenAssist(s1, 0x00); + t2 = Sse2.Shuffle(t2.AsInt32(), 0xAA).AsByte(); + s2 = Sse2.Xor(s2, Sse2.ShiftLeftLogical128BitLane(s2, 8)); + s2 = Sse2.Xor(s2, Sse2.ShiftLeftLogical128BitLane(s2, 4)); + s2 = Sse2.Xor(s2, t2); + K[++round] = s2; + } + + break; + } + default: + throw new ArgumentException("Key length not 128/192/256 bits."); + } + + if (!forEncryption) + { + for (int i = 1, last = K.Length - 1; i < last; ++i) + { + K[i] = Aes.InverseMixColumns(K[i]); + } + + Array.Reverse(K); + } + + return K; + } + + private enum Mode { DEC_128, DEC_192, DEC_256, ENC_128, ENC_192, ENC_256, UNINITIALIZED }; + + private Vector128[] m_roundKeys = null; + private Mode m_mode = Mode.UNINITIALIZED; + + public AesEngine_X86() + { + if (!IsSupported) + throw new PlatformNotSupportedException(nameof(AesEngine_X86)); + } + + public string AlgorithmName => "AES"; + + public int GetBlockSize() => 16; + + public void Init(bool forEncryption, ICipherParameters parameters) + { + if (!(parameters is KeyParameter keyParameter)) + { + ArgumentNullException.ThrowIfNull(parameters, nameof(parameters)); + throw new ArgumentException("invalid type: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters), nameof(parameters)); + } + + m_roundKeys = CreateRoundKeys(keyParameter.GetKey(), forEncryption); + + if (m_roundKeys.Length == 11) + { + m_mode = forEncryption ? Mode.ENC_128 : Mode.DEC_128; + } + else if (m_roundKeys.Length == 13) + { + m_mode = forEncryption ? Mode.ENC_192 : Mode.DEC_192; + } + else + { + m_mode = forEncryption ? Mode.ENC_256 : Mode.DEC_256; + } + } + + public int ProcessBlock(byte[] inBuf, int inOff, byte[] outBuf, int outOff) + { + Check.DataLength(inBuf, inOff, 16, "input buffer too short"); + Check.OutputLength(outBuf, outOff, 16, "output buffer too short"); + + var state = Load128(inBuf.AsSpan(inOff, 16)); + ImplRounds(ref state); + Store128(state, outBuf.AsSpan(outOff, 16)); + return 16; + } + + public int ProcessBlock(ReadOnlySpan input, Span output) + { + Check.DataLength(input, 16, "input buffer too short"); + Check.OutputLength(output, 16, "output buffer too short"); + + var state = Load128(input[..16]); + ImplRounds(ref state); + Store128(state, output[..16]); + return 16; + } + + public int ProcessFourBlocks(ReadOnlySpan input, Span output) + { + Check.DataLength(input, 64, "input buffer too short"); + Check.OutputLength(output, 64, "output buffer too short"); + + var s1 = Load128(input[..16]); + var s2 = Load128(input[16..32]); + var s3 = Load128(input[32..48]); + var s4 = Load128(input[48..64]); + ImplRounds(ref s1, ref s2, ref s3, ref s4); + Store128(s1, output[..16]); + Store128(s2, output[16..32]); + Store128(s3, output[32..48]); + Store128(s4, output[48..64]); + return 64; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ImplRounds(ref Vector128 state) + { + switch (m_mode) + { + case Mode.DEC_128: Decrypt128(m_roundKeys, ref state); break; + case Mode.DEC_192: Decrypt192(m_roundKeys, ref state); break; + case Mode.DEC_256: Decrypt256(m_roundKeys, ref state); break; + case Mode.ENC_128: Encrypt128(m_roundKeys, ref state); break; + case Mode.ENC_192: Encrypt192(m_roundKeys, ref state); break; + case Mode.ENC_256: Encrypt256(m_roundKeys, ref state); break; + default: throw new InvalidOperationException(nameof(AesEngine_X86) + " not initialised"); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ImplRounds( + ref Vector128 s1, ref Vector128 s2, ref Vector128 s3, ref Vector128 s4) + { + switch (m_mode) + { + case Mode.DEC_128: DecryptFour128(m_roundKeys, ref s1, ref s2, ref s3, ref s4); break; + case Mode.DEC_192: DecryptFour192(m_roundKeys, ref s1, ref s2, ref s3, ref s4); break; + case Mode.DEC_256: DecryptFour256(m_roundKeys, ref s1, ref s2, ref s3, ref s4); break; + case Mode.ENC_128: EncryptFour128(m_roundKeys, ref s1, ref s2, ref s3, ref s4); break; + case Mode.ENC_192: EncryptFour192(m_roundKeys, ref s1, ref s2, ref s3, ref s4); break; + case Mode.ENC_256: EncryptFour256(m_roundKeys, ref s1, ref s2, ref s3, ref s4); break; + default: throw new InvalidOperationException(nameof(AesEngine_X86) + " not initialised"); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Decrypt128(Vector128[] roundKeys, ref Vector128 state) + { + state = Sse2.Xor(state, roundKeys[0]); + state = Aes.Decrypt(state, roundKeys[1]); + state = Aes.Decrypt(state, roundKeys[2]); + state = Aes.Decrypt(state, roundKeys[3]); + state = Aes.Decrypt(state, roundKeys[4]); + state = Aes.Decrypt(state, roundKeys[5]); + state = Aes.Decrypt(state, roundKeys[6]); + state = Aes.Decrypt(state, roundKeys[7]); + state = Aes.Decrypt(state, roundKeys[8]); + state = Aes.Decrypt(state, roundKeys[9]); + state = Aes.DecryptLast(state, roundKeys[10]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Decrypt192(Vector128[] roundKeys, ref Vector128 state) + { + state = Sse2.Xor(state, roundKeys[0]); + state = Aes.Decrypt(state, roundKeys[1]); + state = Aes.Decrypt(state, roundKeys[2]); + state = Aes.Decrypt(state, roundKeys[3]); + state = Aes.Decrypt(state, roundKeys[4]); + state = Aes.Decrypt(state, roundKeys[5]); + state = Aes.Decrypt(state, roundKeys[6]); + state = Aes.Decrypt(state, roundKeys[7]); + state = Aes.Decrypt(state, roundKeys[8]); + state = Aes.Decrypt(state, roundKeys[9]); + state = Aes.Decrypt(state, roundKeys[10]); + state = Aes.Decrypt(state, roundKeys[11]); + state = Aes.DecryptLast(state, roundKeys[12]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Decrypt256(Vector128[] roundKeys, ref Vector128 state) + { + state = Sse2.Xor(state, roundKeys[0]); + state = Aes.Decrypt(state, roundKeys[1]); + state = Aes.Decrypt(state, roundKeys[2]); + state = Aes.Decrypt(state, roundKeys[3]); + state = Aes.Decrypt(state, roundKeys[4]); + state = Aes.Decrypt(state, roundKeys[5]); + state = Aes.Decrypt(state, roundKeys[6]); + state = Aes.Decrypt(state, roundKeys[7]); + state = Aes.Decrypt(state, roundKeys[8]); + state = Aes.Decrypt(state, roundKeys[9]); + state = Aes.Decrypt(state, roundKeys[10]); + state = Aes.Decrypt(state, roundKeys[11]); + state = Aes.Decrypt(state, roundKeys[12]); + state = Aes.Decrypt(state, roundKeys[13]); + state = Aes.DecryptLast(state, roundKeys[14]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void DecryptFour128(Vector128[] rk, + ref Vector128 s1, ref Vector128 s2, ref Vector128 s3, ref Vector128 s4) + { + s1 = Sse2.Xor(s1, rk[0]); + s2 = Sse2.Xor(s2, rk[0]); + s3 = Sse2.Xor(s3, rk[0]); + s4 = Sse2.Xor(s4, rk[0]); + + s1 = Aes.Decrypt(s1, rk[1]); + s2 = Aes.Decrypt(s2, rk[1]); + s3 = Aes.Decrypt(s3, rk[1]); + s4 = Aes.Decrypt(s4, rk[1]); + + s1 = Aes.Decrypt(s1, rk[2]); + s2 = Aes.Decrypt(s2, rk[2]); + s3 = Aes.Decrypt(s3, rk[2]); + s4 = Aes.Decrypt(s4, rk[2]); + + s1 = Aes.Decrypt(s1, rk[3]); + s2 = Aes.Decrypt(s2, rk[3]); + s3 = Aes.Decrypt(s3, rk[3]); + s4 = Aes.Decrypt(s4, rk[3]); + + s1 = Aes.Decrypt(s1, rk[4]); + s2 = Aes.Decrypt(s2, rk[4]); + s3 = Aes.Decrypt(s3, rk[4]); + s4 = Aes.Decrypt(s4, rk[4]); + + s1 = Aes.Decrypt(s1, rk[5]); + s2 = Aes.Decrypt(s2, rk[5]); + s3 = Aes.Decrypt(s3, rk[5]); + s4 = Aes.Decrypt(s4, rk[5]); + + s1 = Aes.Decrypt(s1, rk[6]); + s2 = Aes.Decrypt(s2, rk[6]); + s3 = Aes.Decrypt(s3, rk[6]); + s4 = Aes.Decrypt(s4, rk[6]); + + s1 = Aes.Decrypt(s1, rk[7]); + s2 = Aes.Decrypt(s2, rk[7]); + s3 = Aes.Decrypt(s3, rk[7]); + s4 = Aes.Decrypt(s4, rk[7]); + + s1 = Aes.Decrypt(s1, rk[8]); + s2 = Aes.Decrypt(s2, rk[8]); + s3 = Aes.Decrypt(s3, rk[8]); + s4 = Aes.Decrypt(s4, rk[8]); + + s1 = Aes.Decrypt(s1, rk[9]); + s2 = Aes.Decrypt(s2, rk[9]); + s3 = Aes.Decrypt(s3, rk[9]); + s4 = Aes.Decrypt(s4, rk[9]); + + s1 = Aes.DecryptLast(s1, rk[10]); + s2 = Aes.DecryptLast(s2, rk[10]); + s3 = Aes.DecryptLast(s3, rk[10]); + s4 = Aes.DecryptLast(s4, rk[10]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void DecryptFour192(Vector128[] rk, + ref Vector128 s1, ref Vector128 s2, ref Vector128 s3, ref Vector128 s4) + { + s1 = Sse2.Xor(s1, rk[0]); + s2 = Sse2.Xor(s2, rk[0]); + s3 = Sse2.Xor(s3, rk[0]); + s4 = Sse2.Xor(s4, rk[0]); + + s1 = Aes.Decrypt(s1, rk[1]); + s2 = Aes.Decrypt(s2, rk[1]); + s3 = Aes.Decrypt(s3, rk[1]); + s4 = Aes.Decrypt(s4, rk[1]); + + s1 = Aes.Decrypt(s1, rk[2]); + s2 = Aes.Decrypt(s2, rk[2]); + s3 = Aes.Decrypt(s3, rk[2]); + s4 = Aes.Decrypt(s4, rk[2]); + + s1 = Aes.Decrypt(s1, rk[3]); + s2 = Aes.Decrypt(s2, rk[3]); + s3 = Aes.Decrypt(s3, rk[3]); + s4 = Aes.Decrypt(s4, rk[3]); + + s1 = Aes.Decrypt(s1, rk[4]); + s2 = Aes.Decrypt(s2, rk[4]); + s3 = Aes.Decrypt(s3, rk[4]); + s4 = Aes.Decrypt(s4, rk[4]); + + s1 = Aes.Decrypt(s1, rk[5]); + s2 = Aes.Decrypt(s2, rk[5]); + s3 = Aes.Decrypt(s3, rk[5]); + s4 = Aes.Decrypt(s4, rk[5]); + + s1 = Aes.Decrypt(s1, rk[6]); + s2 = Aes.Decrypt(s2, rk[6]); + s3 = Aes.Decrypt(s3, rk[6]); + s4 = Aes.Decrypt(s4, rk[6]); + + s1 = Aes.Decrypt(s1, rk[7]); + s2 = Aes.Decrypt(s2, rk[7]); + s3 = Aes.Decrypt(s3, rk[7]); + s4 = Aes.Decrypt(s4, rk[7]); + + s1 = Aes.Decrypt(s1, rk[8]); + s2 = Aes.Decrypt(s2, rk[8]); + s3 = Aes.Decrypt(s3, rk[8]); + s4 = Aes.Decrypt(s4, rk[8]); + + s1 = Aes.Decrypt(s1, rk[9]); + s2 = Aes.Decrypt(s2, rk[9]); + s3 = Aes.Decrypt(s3, rk[9]); + s4 = Aes.Decrypt(s4, rk[9]); + + s1 = Aes.Decrypt(s1, rk[10]); + s2 = Aes.Decrypt(s2, rk[10]); + s3 = Aes.Decrypt(s3, rk[10]); + s4 = Aes.Decrypt(s4, rk[10]); + + s1 = Aes.Decrypt(s1, rk[11]); + s2 = Aes.Decrypt(s2, rk[11]); + s3 = Aes.Decrypt(s3, rk[11]); + s4 = Aes.Decrypt(s4, rk[11]); + + s1 = Aes.DecryptLast(s1, rk[12]); + s2 = Aes.DecryptLast(s2, rk[12]); + s3 = Aes.DecryptLast(s3, rk[12]); + s4 = Aes.DecryptLast(s4, rk[12]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void DecryptFour256(Vector128[] rk, + ref Vector128 s1, ref Vector128 s2, ref Vector128 s3, ref Vector128 s4) + { + s1 = Sse2.Xor(s1, rk[0]); + s2 = Sse2.Xor(s2, rk[0]); + s3 = Sse2.Xor(s3, rk[0]); + s4 = Sse2.Xor(s4, rk[0]); + + s1 = Aes.Decrypt(s1, rk[1]); + s2 = Aes.Decrypt(s2, rk[1]); + s3 = Aes.Decrypt(s3, rk[1]); + s4 = Aes.Decrypt(s4, rk[1]); + + s1 = Aes.Decrypt(s1, rk[2]); + s2 = Aes.Decrypt(s2, rk[2]); + s3 = Aes.Decrypt(s3, rk[2]); + s4 = Aes.Decrypt(s4, rk[2]); + + s1 = Aes.Decrypt(s1, rk[3]); + s2 = Aes.Decrypt(s2, rk[3]); + s3 = Aes.Decrypt(s3, rk[3]); + s4 = Aes.Decrypt(s4, rk[3]); + + s1 = Aes.Decrypt(s1, rk[4]); + s2 = Aes.Decrypt(s2, rk[4]); + s3 = Aes.Decrypt(s3, rk[4]); + s4 = Aes.Decrypt(s4, rk[4]); + + s1 = Aes.Decrypt(s1, rk[5]); + s2 = Aes.Decrypt(s2, rk[5]); + s3 = Aes.Decrypt(s3, rk[5]); + s4 = Aes.Decrypt(s4, rk[5]); + + s1 = Aes.Decrypt(s1, rk[6]); + s2 = Aes.Decrypt(s2, rk[6]); + s3 = Aes.Decrypt(s3, rk[6]); + s4 = Aes.Decrypt(s4, rk[6]); + + s1 = Aes.Decrypt(s1, rk[7]); + s2 = Aes.Decrypt(s2, rk[7]); + s3 = Aes.Decrypt(s3, rk[7]); + s4 = Aes.Decrypt(s4, rk[7]); + + s1 = Aes.Decrypt(s1, rk[8]); + s2 = Aes.Decrypt(s2, rk[8]); + s3 = Aes.Decrypt(s3, rk[8]); + s4 = Aes.Decrypt(s4, rk[8]); + + s1 = Aes.Decrypt(s1, rk[9]); + s2 = Aes.Decrypt(s2, rk[9]); + s3 = Aes.Decrypt(s3, rk[9]); + s4 = Aes.Decrypt(s4, rk[9]); + + s1 = Aes.Decrypt(s1, rk[10]); + s2 = Aes.Decrypt(s2, rk[10]); + s3 = Aes.Decrypt(s3, rk[10]); + s4 = Aes.Decrypt(s4, rk[10]); + + s1 = Aes.Decrypt(s1, rk[11]); + s2 = Aes.Decrypt(s2, rk[11]); + s3 = Aes.Decrypt(s3, rk[11]); + s4 = Aes.Decrypt(s4, rk[11]); + + s1 = Aes.Decrypt(s1, rk[12]); + s2 = Aes.Decrypt(s2, rk[12]); + s3 = Aes.Decrypt(s3, rk[12]); + s4 = Aes.Decrypt(s4, rk[12]); + + s1 = Aes.Decrypt(s1, rk[13]); + s2 = Aes.Decrypt(s2, rk[13]); + s3 = Aes.Decrypt(s3, rk[13]); + s4 = Aes.Decrypt(s4, rk[13]); + + s1 = Aes.DecryptLast(s1, rk[14]); + s2 = Aes.DecryptLast(s2, rk[14]); + s3 = Aes.DecryptLast(s3, rk[14]); + s4 = Aes.DecryptLast(s4, rk[14]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Encrypt128(Vector128[] roundKeys, ref Vector128 state) + { + state = Sse2.Xor(state, roundKeys[0]); + state = Aes.Encrypt(state, roundKeys[1]); + state = Aes.Encrypt(state, roundKeys[2]); + state = Aes.Encrypt(state, roundKeys[3]); + state = Aes.Encrypt(state, roundKeys[4]); + state = Aes.Encrypt(state, roundKeys[5]); + state = Aes.Encrypt(state, roundKeys[6]); + state = Aes.Encrypt(state, roundKeys[7]); + state = Aes.Encrypt(state, roundKeys[8]); + state = Aes.Encrypt(state, roundKeys[9]); + state = Aes.EncryptLast(state, roundKeys[10]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Encrypt192(Vector128[] roundKeys, ref Vector128 state) + { + state = Sse2.Xor(state, roundKeys[0]); + state = Aes.Encrypt(state, roundKeys[1]); + state = Aes.Encrypt(state, roundKeys[2]); + state = Aes.Encrypt(state, roundKeys[3]); + state = Aes.Encrypt(state, roundKeys[4]); + state = Aes.Encrypt(state, roundKeys[5]); + state = Aes.Encrypt(state, roundKeys[6]); + state = Aes.Encrypt(state, roundKeys[7]); + state = Aes.Encrypt(state, roundKeys[8]); + state = Aes.Encrypt(state, roundKeys[9]); + state = Aes.Encrypt(state, roundKeys[10]); + state = Aes.Encrypt(state, roundKeys[11]); + state = Aes.EncryptLast(state, roundKeys[12]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Encrypt256(Vector128[] roundKeys, ref Vector128 state) + { + state = Sse2.Xor(state, roundKeys[0]); + state = Aes.Encrypt(state, roundKeys[1]); + state = Aes.Encrypt(state, roundKeys[2]); + state = Aes.Encrypt(state, roundKeys[3]); + state = Aes.Encrypt(state, roundKeys[4]); + state = Aes.Encrypt(state, roundKeys[5]); + state = Aes.Encrypt(state, roundKeys[6]); + state = Aes.Encrypt(state, roundKeys[7]); + state = Aes.Encrypt(state, roundKeys[8]); + state = Aes.Encrypt(state, roundKeys[9]); + state = Aes.Encrypt(state, roundKeys[10]); + state = Aes.Encrypt(state, roundKeys[11]); + state = Aes.Encrypt(state, roundKeys[12]); + state = Aes.Encrypt(state, roundKeys[13]); + state = Aes.EncryptLast(state, roundKeys[14]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void EncryptFour128(Vector128[] rk, + ref Vector128 s1, ref Vector128 s2, ref Vector128 s3, ref Vector128 s4) + { + s1 = Sse2.Xor(s1, rk[0]); + s2 = Sse2.Xor(s2, rk[0]); + s3 = Sse2.Xor(s3, rk[0]); + s4 = Sse2.Xor(s4, rk[0]); + + s1 = Aes.Encrypt(s1, rk[1]); + s2 = Aes.Encrypt(s2, rk[1]); + s3 = Aes.Encrypt(s3, rk[1]); + s4 = Aes.Encrypt(s4, rk[1]); + + s1 = Aes.Encrypt(s1, rk[2]); + s2 = Aes.Encrypt(s2, rk[2]); + s3 = Aes.Encrypt(s3, rk[2]); + s4 = Aes.Encrypt(s4, rk[2]); + + s1 = Aes.Encrypt(s1, rk[3]); + s2 = Aes.Encrypt(s2, rk[3]); + s3 = Aes.Encrypt(s3, rk[3]); + s4 = Aes.Encrypt(s4, rk[3]); + + s1 = Aes.Encrypt(s1, rk[4]); + s2 = Aes.Encrypt(s2, rk[4]); + s3 = Aes.Encrypt(s3, rk[4]); + s4 = Aes.Encrypt(s4, rk[4]); + + s1 = Aes.Encrypt(s1, rk[5]); + s2 = Aes.Encrypt(s2, rk[5]); + s3 = Aes.Encrypt(s3, rk[5]); + s4 = Aes.Encrypt(s4, rk[5]); + + s1 = Aes.Encrypt(s1, rk[6]); + s2 = Aes.Encrypt(s2, rk[6]); + s3 = Aes.Encrypt(s3, rk[6]); + s4 = Aes.Encrypt(s4, rk[6]); + + s1 = Aes.Encrypt(s1, rk[7]); + s2 = Aes.Encrypt(s2, rk[7]); + s3 = Aes.Encrypt(s3, rk[7]); + s4 = Aes.Encrypt(s4, rk[7]); + + s1 = Aes.Encrypt(s1, rk[8]); + s2 = Aes.Encrypt(s2, rk[8]); + s3 = Aes.Encrypt(s3, rk[8]); + s4 = Aes.Encrypt(s4, rk[8]); + + s1 = Aes.Encrypt(s1, rk[9]); + s2 = Aes.Encrypt(s2, rk[9]); + s3 = Aes.Encrypt(s3, rk[9]); + s4 = Aes.Encrypt(s4, rk[9]); + + s1 = Aes.EncryptLast(s1, rk[10]); + s2 = Aes.EncryptLast(s2, rk[10]); + s3 = Aes.EncryptLast(s3, rk[10]); + s4 = Aes.EncryptLast(s4, rk[10]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void EncryptFour192(Vector128[] rk, + ref Vector128 s1, ref Vector128 s2, ref Vector128 s3, ref Vector128 s4) + { + s1 = Sse2.Xor(s1, rk[0]); + s2 = Sse2.Xor(s2, rk[0]); + s3 = Sse2.Xor(s3, rk[0]); + s4 = Sse2.Xor(s4, rk[0]); + + s1 = Aes.Encrypt(s1, rk[1]); + s2 = Aes.Encrypt(s2, rk[1]); + s3 = Aes.Encrypt(s3, rk[1]); + s4 = Aes.Encrypt(s4, rk[1]); + + s1 = Aes.Encrypt(s1, rk[2]); + s2 = Aes.Encrypt(s2, rk[2]); + s3 = Aes.Encrypt(s3, rk[2]); + s4 = Aes.Encrypt(s4, rk[2]); + + s1 = Aes.Encrypt(s1, rk[3]); + s2 = Aes.Encrypt(s2, rk[3]); + s3 = Aes.Encrypt(s3, rk[3]); + s4 = Aes.Encrypt(s4, rk[3]); + + s1 = Aes.Encrypt(s1, rk[4]); + s2 = Aes.Encrypt(s2, rk[4]); + s3 = Aes.Encrypt(s3, rk[4]); + s4 = Aes.Encrypt(s4, rk[4]); + + s1 = Aes.Encrypt(s1, rk[5]); + s2 = Aes.Encrypt(s2, rk[5]); + s3 = Aes.Encrypt(s3, rk[5]); + s4 = Aes.Encrypt(s4, rk[5]); + + s1 = Aes.Encrypt(s1, rk[6]); + s2 = Aes.Encrypt(s2, rk[6]); + s3 = Aes.Encrypt(s3, rk[6]); + s4 = Aes.Encrypt(s4, rk[6]); + + s1 = Aes.Encrypt(s1, rk[7]); + s2 = Aes.Encrypt(s2, rk[7]); + s3 = Aes.Encrypt(s3, rk[7]); + s4 = Aes.Encrypt(s4, rk[7]); + + s1 = Aes.Encrypt(s1, rk[8]); + s2 = Aes.Encrypt(s2, rk[8]); + s3 = Aes.Encrypt(s3, rk[8]); + s4 = Aes.Encrypt(s4, rk[8]); + + s1 = Aes.Encrypt(s1, rk[9]); + s2 = Aes.Encrypt(s2, rk[9]); + s3 = Aes.Encrypt(s3, rk[9]); + s4 = Aes.Encrypt(s4, rk[9]); + + s1 = Aes.Encrypt(s1, rk[10]); + s2 = Aes.Encrypt(s2, rk[10]); + s3 = Aes.Encrypt(s3, rk[10]); + s4 = Aes.Encrypt(s4, rk[10]); + + s1 = Aes.Encrypt(s1, rk[11]); + s2 = Aes.Encrypt(s2, rk[11]); + s3 = Aes.Encrypt(s3, rk[11]); + s4 = Aes.Encrypt(s4, rk[11]); + + s1 = Aes.EncryptLast(s1, rk[12]); + s2 = Aes.EncryptLast(s2, rk[12]); + s3 = Aes.EncryptLast(s3, rk[12]); + s4 = Aes.EncryptLast(s4, rk[12]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void EncryptFour256(Vector128[] rk, + ref Vector128 s1, ref Vector128 s2, ref Vector128 s3, ref Vector128 s4) + { + s1 = Sse2.Xor(s1, rk[0]); + s2 = Sse2.Xor(s2, rk[0]); + s3 = Sse2.Xor(s3, rk[0]); + s4 = Sse2.Xor(s4, rk[0]); + + s1 = Aes.Encrypt(s1, rk[1]); + s2 = Aes.Encrypt(s2, rk[1]); + s3 = Aes.Encrypt(s3, rk[1]); + s4 = Aes.Encrypt(s4, rk[1]); + + s1 = Aes.Encrypt(s1, rk[2]); + s2 = Aes.Encrypt(s2, rk[2]); + s3 = Aes.Encrypt(s3, rk[2]); + s4 = Aes.Encrypt(s4, rk[2]); + + s1 = Aes.Encrypt(s1, rk[3]); + s2 = Aes.Encrypt(s2, rk[3]); + s3 = Aes.Encrypt(s3, rk[3]); + s4 = Aes.Encrypt(s4, rk[3]); + + s1 = Aes.Encrypt(s1, rk[4]); + s2 = Aes.Encrypt(s2, rk[4]); + s3 = Aes.Encrypt(s3, rk[4]); + s4 = Aes.Encrypt(s4, rk[4]); + + s1 = Aes.Encrypt(s1, rk[5]); + s2 = Aes.Encrypt(s2, rk[5]); + s3 = Aes.Encrypt(s3, rk[5]); + s4 = Aes.Encrypt(s4, rk[5]); + + s1 = Aes.Encrypt(s1, rk[6]); + s2 = Aes.Encrypt(s2, rk[6]); + s3 = Aes.Encrypt(s3, rk[6]); + s4 = Aes.Encrypt(s4, rk[6]); + + s1 = Aes.Encrypt(s1, rk[7]); + s2 = Aes.Encrypt(s2, rk[7]); + s3 = Aes.Encrypt(s3, rk[7]); + s4 = Aes.Encrypt(s4, rk[7]); + + s1 = Aes.Encrypt(s1, rk[8]); + s2 = Aes.Encrypt(s2, rk[8]); + s3 = Aes.Encrypt(s3, rk[8]); + s4 = Aes.Encrypt(s4, rk[8]); + + s1 = Aes.Encrypt(s1, rk[9]); + s2 = Aes.Encrypt(s2, rk[9]); + s3 = Aes.Encrypt(s3, rk[9]); + s4 = Aes.Encrypt(s4, rk[9]); + + s1 = Aes.Encrypt(s1, rk[10]); + s2 = Aes.Encrypt(s2, rk[10]); + s3 = Aes.Encrypt(s3, rk[10]); + s4 = Aes.Encrypt(s4, rk[10]); + + s1 = Aes.Encrypt(s1, rk[11]); + s2 = Aes.Encrypt(s2, rk[11]); + s3 = Aes.Encrypt(s3, rk[11]); + s4 = Aes.Encrypt(s4, rk[11]); + + s1 = Aes.Encrypt(s1, rk[12]); + s2 = Aes.Encrypt(s2, rk[12]); + s3 = Aes.Encrypt(s3, rk[12]); + s4 = Aes.Encrypt(s4, rk[12]); + + s1 = Aes.Encrypt(s1, rk[13]); + s2 = Aes.Encrypt(s2, rk[13]); + s3 = Aes.Encrypt(s3, rk[13]); + s4 = Aes.Encrypt(s4, rk[13]); + + s1 = Aes.EncryptLast(s1, rk[14]); + s2 = Aes.EncryptLast(s2, rk[14]); + s3 = Aes.EncryptLast(s3, rk[14]); + s4 = Aes.EncryptLast(s4, rk[14]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector128 Load128(ReadOnlySpan t) + { +#if NET7_0_OR_GREATER + return Vector128.Create(t); +#else + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 16) + return MemoryMarshal.Read>(t); + + return Vector128.Create( + BinaryPrimitives.ReadUInt64LittleEndian(t[..8]), + BinaryPrimitives.ReadUInt64LittleEndian(t[8..]) + ).AsByte(); +#endif + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector64 Load64(ReadOnlySpan t) + { +#if NET7_0_OR_GREATER + return Vector64.Create(t); +#else + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 8) + return MemoryMarshal.Read>(t); + + return Vector64.Create( + BinaryPrimitives.ReadUInt64LittleEndian(t[..8]) + ).AsByte(); +#endif + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Store128(Vector128 s, Span t) + { +#if NET7_0_OR_GREATER + Vector128.CopyTo(s, t); +#else + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 16) + { + MemoryMarshal.Write(t, ref s); + return; + } + + var u = s.AsUInt64(); + BinaryPrimitives.WriteUInt64LittleEndian(t[..8], u.GetElement(0)); + BinaryPrimitives.WriteUInt64LittleEndian(t[8..], u.GetElement(1)); +#endif + } + } +} +#endif +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesEngine_X86.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesEngine_X86.cs.meta new file mode 100644 index 0000000..c2a1765 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesEngine_X86.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1833d606ace538d4097cfc7ed3d87a28 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesFastEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesFastEngine.cs index 1aefffb..3b1d777 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesFastEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesFastEngine.cs @@ -1,1008 +1,2 @@ #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 fast version with 8Kbytes of static tables for round precomputation - *

- */ - /// - /// Unfortunately this class has a few side channel issues. - /// In an environment where encryption/decryption may be closely observed it should not be used. - /// - - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] - public sealed class AesFastEngine - : IBlockCipher - { - // The S box - private static readonly byte[] S = - { - 99, 124, 119, 123, 242, 107, 111, 197, - 48, 1, 103, 43, 254, 215, 171, 118, - 202, 130, 201, 125, 250, 89, 71, 240, - 173, 212, 162, 175, 156, 164, 114, 192, - 183, 253, 147, 38, 54, 63, 247, 204, - 52, 165, 229, 241, 113, 216, 49, 21, - 4, 199, 35, 195, 24, 150, 5, 154, - 7, 18, 128, 226, 235, 39, 178, 117, - 9, 131, 44, 26, 27, 110, 90, 160, - 82, 59, 214, 179, 41, 227, 47, 132, - 83, 209, 0, 237, 32, 252, 177, 91, - 106, 203, 190, 57, 74, 76, 88, 207, - 208, 239, 170, 251, 67, 77, 51, 133, - 69, 249, 2, 127, 80, 60, 159, 168, - 81, 163, 64, 143, 146, 157, 56, 245, - 188, 182, 218, 33, 16, 255, 243, 210, - 205, 12, 19, 236, 95, 151, 68, 23, - 196, 167, 126, 61, 100, 93, 25, 115, - 96, 129, 79, 220, 34, 42, 144, 136, - 70, 238, 184, 20, 222, 94, 11, 219, - 224, 50, 58, 10, 73, 6, 36, 92, - 194, 211, 172, 98, 145, 149, 228, 121, - 231, 200, 55, 109, 141, 213, 78, 169, - 108, 86, 244, 234, 101, 122, 174, 8, - 186, 120, 37, 46, 28, 166, 180, 198, - 232, 221, 116, 31, 75, 189, 139, 138, - 112, 62, 181, 102, 72, 3, 246, 14, - 97, 53, 87, 185, 134, 193, 29, 158, - 225, 248, 152, 17, 105, 217, 142, 148, - 155, 30, 135, 233, 206, 85, 40, 223, - 140, 161, 137, 13, 191, 230, 66, 104, - 65, 153, 45, 15, 176, 84, 187, 22, - }; - - // The inverse S-box - private static readonly byte[] Si = - { - 82, 9, 106, 213, 48, 54, 165, 56, - 191, 64, 163, 158, 129, 243, 215, 251, - 124, 227, 57, 130, 155, 47, 255, 135, - 52, 142, 67, 68, 196, 222, 233, 203, - 84, 123, 148, 50, 166, 194, 35, 61, - 238, 76, 149, 11, 66, 250, 195, 78, - 8, 46, 161, 102, 40, 217, 36, 178, - 118, 91, 162, 73, 109, 139, 209, 37, - 114, 248, 246, 100, 134, 104, 152, 22, - 212, 164, 92, 204, 93, 101, 182, 146, - 108, 112, 72, 80, 253, 237, 185, 218, - 94, 21, 70, 87, 167, 141, 157, 132, - 144, 216, 171, 0, 140, 188, 211, 10, - 247, 228, 88, 5, 184, 179, 69, 6, - 208, 44, 30, 143, 202, 63, 15, 2, - 193, 175, 189, 3, 1, 19, 138, 107, - 58, 145, 17, 65, 79, 103, 220, 234, - 151, 242, 207, 206, 240, 180, 230, 115, - 150, 172, 116, 34, 231, 173, 53, 133, - 226, 249, 55, 232, 28, 117, 223, 110, - 71, 241, 26, 113, 29, 41, 197, 137, - 111, 183, 98, 14, 170, 24, 190, 27, - 252, 86, 62, 75, 198, 210, 121, 32, - 154, 219, 192, 254, 120, 205, 90, 244, - 31, 221, 168, 51, 136, 7, 199, 49, - 177, 18, 16, 89, 39, 128, 236, 95, - 96, 81, 127, 169, 25, 181, 74, 13, - 45, 229, 122, 159, 147, 201, 156, 239, - 160, 224, 59, 77, 174, 42, 245, 176, - 200, 235, 187, 60, 131, 83, 153, 97, - 23, 43, 4, 126, 186, 119, 214, 38, - 225, 105, 20, 99, 85, 33, 12, 125, - }; - - // vector used in calculating key schedule (powers of x in GF(256)) - private static readonly byte[] rcon = - { - 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, - 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 - }; - - // precomputation tables of calculations for rounds - private static readonly uint[] T0 = - { - 0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff, - 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102, - 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, - 0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, - 0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41, - 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, - 0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d, - 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83, - 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2, - 0x73d8d8ab, 0x53313162, 0x3f15152a, 0x0c040408, 0x52c7c795, - 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a, - 0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, - 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912, - 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, - 0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, - 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, - 0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040, - 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d, - 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, - 0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, - 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a, - 0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, - 0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080, - 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1, - 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, - 0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18, - 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, - 0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, - 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0, - 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, - 0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, - 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, - 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, - 0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd, - 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, - 0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, - 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8, - 0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, - 0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a, - 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, - 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, - 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c, - 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7, - 0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, - 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9, - 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, - 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715, - 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, - 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, - 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929, - 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, - 0x3a16162c - }; - - private static readonly uint[] T1 = - { - 0x6363c6a5, 0x7c7cf884, 0x7777ee99, 0x7b7bf68d, 0xf2f2ff0d, - 0x6b6bd6bd, 0x6f6fdeb1, 0xc5c59154, 0x30306050, 0x01010203, - 0x6767cea9, 0x2b2b567d, 0xfefee719, 0xd7d7b562, 0xabab4de6, - 0x7676ec9a, 0xcaca8f45, 0x82821f9d, 0xc9c98940, 0x7d7dfa87, - 0xfafaef15, 0x5959b2eb, 0x47478ec9, 0xf0f0fb0b, 0xadad41ec, - 0xd4d4b367, 0xa2a25ffd, 0xafaf45ea, 0x9c9c23bf, 0xa4a453f7, - 0x7272e496, 0xc0c09b5b, 0xb7b775c2, 0xfdfde11c, 0x93933dae, - 0x26264c6a, 0x36366c5a, 0x3f3f7e41, 0xf7f7f502, 0xcccc834f, - 0x3434685c, 0xa5a551f4, 0xe5e5d134, 0xf1f1f908, 0x7171e293, - 0xd8d8ab73, 0x31316253, 0x15152a3f, 0x0404080c, 0xc7c79552, - 0x23234665, 0xc3c39d5e, 0x18183028, 0x969637a1, 0x05050a0f, - 0x9a9a2fb5, 0x07070e09, 0x12122436, 0x80801b9b, 0xe2e2df3d, - 0xebebcd26, 0x27274e69, 0xb2b27fcd, 0x7575ea9f, 0x0909121b, - 0x83831d9e, 0x2c2c5874, 0x1a1a342e, 0x1b1b362d, 0x6e6edcb2, - 0x5a5ab4ee, 0xa0a05bfb, 0x5252a4f6, 0x3b3b764d, 0xd6d6b761, - 0xb3b37dce, 0x2929527b, 0xe3e3dd3e, 0x2f2f5e71, 0x84841397, - 0x5353a6f5, 0xd1d1b968, 0x00000000, 0xededc12c, 0x20204060, - 0xfcfce31f, 0xb1b179c8, 0x5b5bb6ed, 0x6a6ad4be, 0xcbcb8d46, - 0xbebe67d9, 0x3939724b, 0x4a4a94de, 0x4c4c98d4, 0x5858b0e8, - 0xcfcf854a, 0xd0d0bb6b, 0xefefc52a, 0xaaaa4fe5, 0xfbfbed16, - 0x434386c5, 0x4d4d9ad7, 0x33336655, 0x85851194, 0x45458acf, - 0xf9f9e910, 0x02020406, 0x7f7ffe81, 0x5050a0f0, 0x3c3c7844, - 0x9f9f25ba, 0xa8a84be3, 0x5151a2f3, 0xa3a35dfe, 0x404080c0, - 0x8f8f058a, 0x92923fad, 0x9d9d21bc, 0x38387048, 0xf5f5f104, - 0xbcbc63df, 0xb6b677c1, 0xdadaaf75, 0x21214263, 0x10102030, - 0xffffe51a, 0xf3f3fd0e, 0xd2d2bf6d, 0xcdcd814c, 0x0c0c1814, - 0x13132635, 0xececc32f, 0x5f5fbee1, 0x979735a2, 0x444488cc, - 0x17172e39, 0xc4c49357, 0xa7a755f2, 0x7e7efc82, 0x3d3d7a47, - 0x6464c8ac, 0x5d5dbae7, 0x1919322b, 0x7373e695, 0x6060c0a0, - 0x81811998, 0x4f4f9ed1, 0xdcdca37f, 0x22224466, 0x2a2a547e, - 0x90903bab, 0x88880b83, 0x46468cca, 0xeeeec729, 0xb8b86bd3, - 0x1414283c, 0xdedea779, 0x5e5ebce2, 0x0b0b161d, 0xdbdbad76, - 0xe0e0db3b, 0x32326456, 0x3a3a744e, 0x0a0a141e, 0x494992db, - 0x06060c0a, 0x2424486c, 0x5c5cb8e4, 0xc2c29f5d, 0xd3d3bd6e, - 0xacac43ef, 0x6262c4a6, 0x919139a8, 0x959531a4, 0xe4e4d337, - 0x7979f28b, 0xe7e7d532, 0xc8c88b43, 0x37376e59, 0x6d6ddab7, - 0x8d8d018c, 0xd5d5b164, 0x4e4e9cd2, 0xa9a949e0, 0x6c6cd8b4, - 0x5656acfa, 0xf4f4f307, 0xeaeacf25, 0x6565caaf, 0x7a7af48e, - 0xaeae47e9, 0x08081018, 0xbaba6fd5, 0x7878f088, 0x25254a6f, - 0x2e2e5c72, 0x1c1c3824, 0xa6a657f1, 0xb4b473c7, 0xc6c69751, - 0xe8e8cb23, 0xdddda17c, 0x7474e89c, 0x1f1f3e21, 0x4b4b96dd, - 0xbdbd61dc, 0x8b8b0d86, 0x8a8a0f85, 0x7070e090, 0x3e3e7c42, - 0xb5b571c4, 0x6666ccaa, 0x484890d8, 0x03030605, 0xf6f6f701, - 0x0e0e1c12, 0x6161c2a3, 0x35356a5f, 0x5757aef9, 0xb9b969d0, - 0x86861791, 0xc1c19958, 0x1d1d3a27, 0x9e9e27b9, 0xe1e1d938, - 0xf8f8eb13, 0x98982bb3, 0x11112233, 0x6969d2bb, 0xd9d9a970, - 0x8e8e0789, 0x949433a7, 0x9b9b2db6, 0x1e1e3c22, 0x87871592, - 0xe9e9c920, 0xcece8749, 0x5555aaff, 0x28285078, 0xdfdfa57a, - 0x8c8c038f, 0xa1a159f8, 0x89890980, 0x0d0d1a17, 0xbfbf65da, - 0xe6e6d731, 0x424284c6, 0x6868d0b8, 0x414182c3, 0x999929b0, - 0x2d2d5a77, 0x0f0f1e11, 0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6, - 0x16162c3a - }; - - private static readonly uint[] T2 = - { - 0x63c6a563, 0x7cf8847c, 0x77ee9977, 0x7bf68d7b, 0xf2ff0df2, - 0x6bd6bd6b, 0x6fdeb16f, 0xc59154c5, 0x30605030, 0x01020301, - 0x67cea967, 0x2b567d2b, 0xfee719fe, 0xd7b562d7, 0xab4de6ab, - 0x76ec9a76, 0xca8f45ca, 0x821f9d82, 0xc98940c9, 0x7dfa877d, - 0xfaef15fa, 0x59b2eb59, 0x478ec947, 0xf0fb0bf0, 0xad41ecad, - 0xd4b367d4, 0xa25ffda2, 0xaf45eaaf, 0x9c23bf9c, 0xa453f7a4, - 0x72e49672, 0xc09b5bc0, 0xb775c2b7, 0xfde11cfd, 0x933dae93, - 0x264c6a26, 0x366c5a36, 0x3f7e413f, 0xf7f502f7, 0xcc834fcc, - 0x34685c34, 0xa551f4a5, 0xe5d134e5, 0xf1f908f1, 0x71e29371, - 0xd8ab73d8, 0x31625331, 0x152a3f15, 0x04080c04, 0xc79552c7, - 0x23466523, 0xc39d5ec3, 0x18302818, 0x9637a196, 0x050a0f05, - 0x9a2fb59a, 0x070e0907, 0x12243612, 0x801b9b80, 0xe2df3de2, - 0xebcd26eb, 0x274e6927, 0xb27fcdb2, 0x75ea9f75, 0x09121b09, - 0x831d9e83, 0x2c58742c, 0x1a342e1a, 0x1b362d1b, 0x6edcb26e, - 0x5ab4ee5a, 0xa05bfba0, 0x52a4f652, 0x3b764d3b, 0xd6b761d6, - 0xb37dceb3, 0x29527b29, 0xe3dd3ee3, 0x2f5e712f, 0x84139784, - 0x53a6f553, 0xd1b968d1, 0x00000000, 0xedc12ced, 0x20406020, - 0xfce31ffc, 0xb179c8b1, 0x5bb6ed5b, 0x6ad4be6a, 0xcb8d46cb, - 0xbe67d9be, 0x39724b39, 0x4a94de4a, 0x4c98d44c, 0x58b0e858, - 0xcf854acf, 0xd0bb6bd0, 0xefc52aef, 0xaa4fe5aa, 0xfbed16fb, - 0x4386c543, 0x4d9ad74d, 0x33665533, 0x85119485, 0x458acf45, - 0xf9e910f9, 0x02040602, 0x7ffe817f, 0x50a0f050, 0x3c78443c, - 0x9f25ba9f, 0xa84be3a8, 0x51a2f351, 0xa35dfea3, 0x4080c040, - 0x8f058a8f, 0x923fad92, 0x9d21bc9d, 0x38704838, 0xf5f104f5, - 0xbc63dfbc, 0xb677c1b6, 0xdaaf75da, 0x21426321, 0x10203010, - 0xffe51aff, 0xf3fd0ef3, 0xd2bf6dd2, 0xcd814ccd, 0x0c18140c, - 0x13263513, 0xecc32fec, 0x5fbee15f, 0x9735a297, 0x4488cc44, - 0x172e3917, 0xc49357c4, 0xa755f2a7, 0x7efc827e, 0x3d7a473d, - 0x64c8ac64, 0x5dbae75d, 0x19322b19, 0x73e69573, 0x60c0a060, - 0x81199881, 0x4f9ed14f, 0xdca37fdc, 0x22446622, 0x2a547e2a, - 0x903bab90, 0x880b8388, 0x468cca46, 0xeec729ee, 0xb86bd3b8, - 0x14283c14, 0xdea779de, 0x5ebce25e, 0x0b161d0b, 0xdbad76db, - 0xe0db3be0, 0x32645632, 0x3a744e3a, 0x0a141e0a, 0x4992db49, - 0x060c0a06, 0x24486c24, 0x5cb8e45c, 0xc29f5dc2, 0xd3bd6ed3, - 0xac43efac, 0x62c4a662, 0x9139a891, 0x9531a495, 0xe4d337e4, - 0x79f28b79, 0xe7d532e7, 0xc88b43c8, 0x376e5937, 0x6ddab76d, - 0x8d018c8d, 0xd5b164d5, 0x4e9cd24e, 0xa949e0a9, 0x6cd8b46c, - 0x56acfa56, 0xf4f307f4, 0xeacf25ea, 0x65caaf65, 0x7af48e7a, - 0xae47e9ae, 0x08101808, 0xba6fd5ba, 0x78f08878, 0x254a6f25, - 0x2e5c722e, 0x1c38241c, 0xa657f1a6, 0xb473c7b4, 0xc69751c6, - 0xe8cb23e8, 0xdda17cdd, 0x74e89c74, 0x1f3e211f, 0x4b96dd4b, - 0xbd61dcbd, 0x8b0d868b, 0x8a0f858a, 0x70e09070, 0x3e7c423e, - 0xb571c4b5, 0x66ccaa66, 0x4890d848, 0x03060503, 0xf6f701f6, - 0x0e1c120e, 0x61c2a361, 0x356a5f35, 0x57aef957, 0xb969d0b9, - 0x86179186, 0xc19958c1, 0x1d3a271d, 0x9e27b99e, 0xe1d938e1, - 0xf8eb13f8, 0x982bb398, 0x11223311, 0x69d2bb69, 0xd9a970d9, - 0x8e07898e, 0x9433a794, 0x9b2db69b, 0x1e3c221e, 0x87159287, - 0xe9c920e9, 0xce8749ce, 0x55aaff55, 0x28507828, 0xdfa57adf, - 0x8c038f8c, 0xa159f8a1, 0x89098089, 0x0d1a170d, 0xbf65dabf, - 0xe6d731e6, 0x4284c642, 0x68d0b868, 0x4182c341, 0x9929b099, - 0x2d5a772d, 0x0f1e110f, 0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb, - 0x162c3a16 - }; - - private static readonly uint[] T3 = - { - 0xc6a56363, 0xf8847c7c, 0xee997777, 0xf68d7b7b, 0xff0df2f2, - 0xd6bd6b6b, 0xdeb16f6f, 0x9154c5c5, 0x60503030, 0x02030101, - 0xcea96767, 0x567d2b2b, 0xe719fefe, 0xb562d7d7, 0x4de6abab, - 0xec9a7676, 0x8f45caca, 0x1f9d8282, 0x8940c9c9, 0xfa877d7d, - 0xef15fafa, 0xb2eb5959, 0x8ec94747, 0xfb0bf0f0, 0x41ecadad, - 0xb367d4d4, 0x5ffda2a2, 0x45eaafaf, 0x23bf9c9c, 0x53f7a4a4, - 0xe4967272, 0x9b5bc0c0, 0x75c2b7b7, 0xe11cfdfd, 0x3dae9393, - 0x4c6a2626, 0x6c5a3636, 0x7e413f3f, 0xf502f7f7, 0x834fcccc, - 0x685c3434, 0x51f4a5a5, 0xd134e5e5, 0xf908f1f1, 0xe2937171, - 0xab73d8d8, 0x62533131, 0x2a3f1515, 0x080c0404, 0x9552c7c7, - 0x46652323, 0x9d5ec3c3, 0x30281818, 0x37a19696, 0x0a0f0505, - 0x2fb59a9a, 0x0e090707, 0x24361212, 0x1b9b8080, 0xdf3de2e2, - 0xcd26ebeb, 0x4e692727, 0x7fcdb2b2, 0xea9f7575, 0x121b0909, - 0x1d9e8383, 0x58742c2c, 0x342e1a1a, 0x362d1b1b, 0xdcb26e6e, - 0xb4ee5a5a, 0x5bfba0a0, 0xa4f65252, 0x764d3b3b, 0xb761d6d6, - 0x7dceb3b3, 0x527b2929, 0xdd3ee3e3, 0x5e712f2f, 0x13978484, - 0xa6f55353, 0xb968d1d1, 0x00000000, 0xc12ceded, 0x40602020, - 0xe31ffcfc, 0x79c8b1b1, 0xb6ed5b5b, 0xd4be6a6a, 0x8d46cbcb, - 0x67d9bebe, 0x724b3939, 0x94de4a4a, 0x98d44c4c, 0xb0e85858, - 0x854acfcf, 0xbb6bd0d0, 0xc52aefef, 0x4fe5aaaa, 0xed16fbfb, - 0x86c54343, 0x9ad74d4d, 0x66553333, 0x11948585, 0x8acf4545, - 0xe910f9f9, 0x04060202, 0xfe817f7f, 0xa0f05050, 0x78443c3c, - 0x25ba9f9f, 0x4be3a8a8, 0xa2f35151, 0x5dfea3a3, 0x80c04040, - 0x058a8f8f, 0x3fad9292, 0x21bc9d9d, 0x70483838, 0xf104f5f5, - 0x63dfbcbc, 0x77c1b6b6, 0xaf75dada, 0x42632121, 0x20301010, - 0xe51affff, 0xfd0ef3f3, 0xbf6dd2d2, 0x814ccdcd, 0x18140c0c, - 0x26351313, 0xc32fecec, 0xbee15f5f, 0x35a29797, 0x88cc4444, - 0x2e391717, 0x9357c4c4, 0x55f2a7a7, 0xfc827e7e, 0x7a473d3d, - 0xc8ac6464, 0xbae75d5d, 0x322b1919, 0xe6957373, 0xc0a06060, - 0x19988181, 0x9ed14f4f, 0xa37fdcdc, 0x44662222, 0x547e2a2a, - 0x3bab9090, 0x0b838888, 0x8cca4646, 0xc729eeee, 0x6bd3b8b8, - 0x283c1414, 0xa779dede, 0xbce25e5e, 0x161d0b0b, 0xad76dbdb, - 0xdb3be0e0, 0x64563232, 0x744e3a3a, 0x141e0a0a, 0x92db4949, - 0x0c0a0606, 0x486c2424, 0xb8e45c5c, 0x9f5dc2c2, 0xbd6ed3d3, - 0x43efacac, 0xc4a66262, 0x39a89191, 0x31a49595, 0xd337e4e4, - 0xf28b7979, 0xd532e7e7, 0x8b43c8c8, 0x6e593737, 0xdab76d6d, - 0x018c8d8d, 0xb164d5d5, 0x9cd24e4e, 0x49e0a9a9, 0xd8b46c6c, - 0xacfa5656, 0xf307f4f4, 0xcf25eaea, 0xcaaf6565, 0xf48e7a7a, - 0x47e9aeae, 0x10180808, 0x6fd5baba, 0xf0887878, 0x4a6f2525, - 0x5c722e2e, 0x38241c1c, 0x57f1a6a6, 0x73c7b4b4, 0x9751c6c6, - 0xcb23e8e8, 0xa17cdddd, 0xe89c7474, 0x3e211f1f, 0x96dd4b4b, - 0x61dcbdbd, 0x0d868b8b, 0x0f858a8a, 0xe0907070, 0x7c423e3e, - 0x71c4b5b5, 0xccaa6666, 0x90d84848, 0x06050303, 0xf701f6f6, - 0x1c120e0e, 0xc2a36161, 0x6a5f3535, 0xaef95757, 0x69d0b9b9, - 0x17918686, 0x9958c1c1, 0x3a271d1d, 0x27b99e9e, 0xd938e1e1, - 0xeb13f8f8, 0x2bb39898, 0x22331111, 0xd2bb6969, 0xa970d9d9, - 0x07898e8e, 0x33a79494, 0x2db69b9b, 0x3c221e1e, 0x15928787, - 0xc920e9e9, 0x8749cece, 0xaaff5555, 0x50782828, 0xa57adfdf, - 0x038f8c8c, 0x59f8a1a1, 0x09808989, 0x1a170d0d, 0x65dabfbf, - 0xd731e6e6, 0x84c64242, 0xd0b86868, 0x82c34141, 0x29b09999, - 0x5a772d2d, 0x1e110f0f, 0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb, - 0x2c3a1616 - }; - - private static readonly uint[] Tinv0 = - { - 0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b, - 0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad, - 0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526, - 0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d, - 0x02752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03, - 0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458, - 0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899, - 0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d, - 0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1, - 0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f, - 0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3, - 0x2aab5566, 0x0728ebb2, 0x03c2b52f, 0x9a7bc586, 0xa50837d3, - 0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a, - 0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506, - 0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05, - 0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x069f715e, 0x51106ebd, - 0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491, - 0x055dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6, - 0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7, - 0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x00000000, - 0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd, - 0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68, - 0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0x0fe75793, 0xd296eeb4, - 0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c, - 0x0aba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0x0b0d090e, - 0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af, - 0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644, - 0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8, - 0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85, - 0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc, - 0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411, - 0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322, - 0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6, - 0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0x0d927850, - 0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e, - 0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf, - 0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x097826cd, - 0xf418596e, 0x01b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa, - 0x08cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea, - 0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235, - 0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1, - 0xf7daec41, 0x0e50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43, - 0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1, - 0x7f516546, 0x04ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb, - 0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a, - 0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7, - 0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418, - 0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478, - 0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16, - 0x0c25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08, - 0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48, - 0x4257b8d0 - }; - - private static readonly uint[] Tinv1 = - { - 0xa7f45150, 0x65417e53, 0xa4171ac3, 0x5e273a96, 0x6bab3bcb, - 0x459d1ff1, 0x58faacab, 0x03e34b93, 0xfa302055, 0x6d76adf6, - 0x76cc8891, 0x4c02f525, 0xd7e54ffc, 0xcb2ac5d7, 0x44352680, - 0xa362b58f, 0x5ab1de49, 0x1bba2567, 0x0eea4598, 0xc0fe5de1, - 0x752fc302, 0xf04c8112, 0x97468da3, 0xf9d36bc6, 0x5f8f03e7, - 0x9c921595, 0x7a6dbfeb, 0x595295da, 0x83bed42d, 0x217458d3, - 0x69e04929, 0xc8c98e44, 0x89c2756a, 0x798ef478, 0x3e58996b, - 0x71b927dd, 0x4fe1beb6, 0xad88f017, 0xac20c966, 0x3ace7db4, - 0x4adf6318, 0x311ae582, 0x33519760, 0x7f536245, 0x7764b1e0, - 0xae6bbb84, 0xa081fe1c, 0x2b08f994, 0x68487058, 0xfd458f19, - 0x6cde9487, 0xf87b52b7, 0xd373ab23, 0x024b72e2, 0x8f1fe357, - 0xab55662a, 0x28ebb207, 0xc2b52f03, 0x7bc5869a, 0x0837d3a5, - 0x872830f2, 0xa5bf23b2, 0x6a0302ba, 0x8216ed5c, 0x1ccf8a2b, - 0xb479a792, 0xf207f3f0, 0xe2694ea1, 0xf4da65cd, 0xbe0506d5, - 0x6234d11f, 0xfea6c48a, 0x532e349d, 0x55f3a2a0, 0xe18a0532, - 0xebf6a475, 0xec830b39, 0xef6040aa, 0x9f715e06, 0x106ebd51, - 0x8a213ef9, 0x06dd963d, 0x053eddae, 0xbde64d46, 0x8d5491b5, - 0x5dc47105, 0xd406046f, 0x155060ff, 0xfb981924, 0xe9bdd697, - 0x434089cc, 0x9ed96777, 0x42e8b0bd, 0x8b890788, 0x5b19e738, - 0xeec879db, 0x0a7ca147, 0x0f427ce9, 0x1e84f8c9, 0x00000000, - 0x86800983, 0xed2b3248, 0x70111eac, 0x725a6c4e, 0xff0efdfb, - 0x38850f56, 0xd5ae3d1e, 0x392d3627, 0xd90f0a64, 0xa65c6821, - 0x545b9bd1, 0x2e36243a, 0x670a0cb1, 0xe757930f, 0x96eeb4d2, - 0x919b1b9e, 0xc5c0804f, 0x20dc61a2, 0x4b775a69, 0x1a121c16, - 0xba93e20a, 0x2aa0c0e5, 0xe0223c43, 0x171b121d, 0x0d090e0b, - 0xc78bf2ad, 0xa8b62db9, 0xa91e14c8, 0x19f15785, 0x0775af4c, - 0xdd99eebb, 0x607fa3fd, 0x2601f79f, 0xf5725cbc, 0x3b6644c5, - 0x7efb5b34, 0x29438b76, 0xc623cbdc, 0xfcedb668, 0xf1e4b863, - 0xdc31d7ca, 0x85634210, 0x22971340, 0x11c68420, 0x244a857d, - 0x3dbbd2f8, 0x32f9ae11, 0xa129c76d, 0x2f9e1d4b, 0x30b2dcf3, - 0x52860dec, 0xe3c177d0, 0x16b32b6c, 0xb970a999, 0x489411fa, - 0x64e94722, 0x8cfca8c4, 0x3ff0a01a, 0x2c7d56d8, 0x903322ef, - 0x4e4987c7, 0xd138d9c1, 0xa2ca8cfe, 0x0bd49836, 0x81f5a6cf, - 0xde7aa528, 0x8eb7da26, 0xbfad3fa4, 0x9d3a2ce4, 0x9278500d, - 0xcc5f6a9b, 0x467e5462, 0x138df6c2, 0xb8d890e8, 0xf7392e5e, - 0xafc382f5, 0x805d9fbe, 0x93d0697c, 0x2dd56fa9, 0x1225cfb3, - 0x99acc83b, 0x7d1810a7, 0x639ce86e, 0xbb3bdb7b, 0x7826cd09, - 0x18596ef4, 0xb79aec01, 0x9a4f83a8, 0x6e95e665, 0xe6ffaa7e, - 0xcfbc2108, 0xe815efe6, 0x9be7bad9, 0x366f4ace, 0x099fead4, - 0x7cb029d6, 0xb2a431af, 0x233f2a31, 0x94a5c630, 0x66a235c0, - 0xbc4e7437, 0xca82fca6, 0xd090e0b0, 0xd8a73315, 0x9804f14a, - 0xdaec41f7, 0x50cd7f0e, 0xf691172f, 0xd64d768d, 0xb0ef434d, - 0x4daacc54, 0x0496e4df, 0xb5d19ee3, 0x886a4c1b, 0x1f2cc1b8, - 0x5165467f, 0xea5e9d04, 0x358c015d, 0x7487fa73, 0x410bfb2e, - 0x1d67b35a, 0xd2db9252, 0x5610e933, 0x47d66d13, 0x61d79a8c, - 0x0ca1377a, 0x14f8598e, 0x3c13eb89, 0x27a9ceee, 0xc961b735, - 0xe51ce1ed, 0xb1477a3c, 0xdfd29c59, 0x73f2553f, 0xce141879, - 0x37c773bf, 0xcdf753ea, 0xaafd5f5b, 0x6f3ddf14, 0xdb447886, - 0xf3afca81, 0xc468b93e, 0x3424382c, 0x40a3c25f, 0xc31d1672, - 0x25e2bc0c, 0x493c288b, 0x950dff41, 0x01a83971, 0xb30c08de, - 0xe4b4d89c, 0xc1566490, 0x84cb7b61, 0xb632d570, 0x5c6c4874, - 0x57b8d042 - }; - - private static readonly uint[] Tinv2 = - { - 0xf45150a7, 0x417e5365, 0x171ac3a4, 0x273a965e, 0xab3bcb6b, - 0x9d1ff145, 0xfaacab58, 0xe34b9303, 0x302055fa, 0x76adf66d, - 0xcc889176, 0x02f5254c, 0xe54ffcd7, 0x2ac5d7cb, 0x35268044, - 0x62b58fa3, 0xb1de495a, 0xba25671b, 0xea45980e, 0xfe5de1c0, - 0x2fc30275, 0x4c8112f0, 0x468da397, 0xd36bc6f9, 0x8f03e75f, - 0x9215959c, 0x6dbfeb7a, 0x5295da59, 0xbed42d83, 0x7458d321, - 0xe0492969, 0xc98e44c8, 0xc2756a89, 0x8ef47879, 0x58996b3e, - 0xb927dd71, 0xe1beb64f, 0x88f017ad, 0x20c966ac, 0xce7db43a, - 0xdf63184a, 0x1ae58231, 0x51976033, 0x5362457f, 0x64b1e077, - 0x6bbb84ae, 0x81fe1ca0, 0x08f9942b, 0x48705868, 0x458f19fd, - 0xde94876c, 0x7b52b7f8, 0x73ab23d3, 0x4b72e202, 0x1fe3578f, - 0x55662aab, 0xebb20728, 0xb52f03c2, 0xc5869a7b, 0x37d3a508, - 0x2830f287, 0xbf23b2a5, 0x0302ba6a, 0x16ed5c82, 0xcf8a2b1c, - 0x79a792b4, 0x07f3f0f2, 0x694ea1e2, 0xda65cdf4, 0x0506d5be, - 0x34d11f62, 0xa6c48afe, 0x2e349d53, 0xf3a2a055, 0x8a0532e1, - 0xf6a475eb, 0x830b39ec, 0x6040aaef, 0x715e069f, 0x6ebd5110, - 0x213ef98a, 0xdd963d06, 0x3eddae05, 0xe64d46bd, 0x5491b58d, - 0xc471055d, 0x06046fd4, 0x5060ff15, 0x981924fb, 0xbdd697e9, - 0x4089cc43, 0xd967779e, 0xe8b0bd42, 0x8907888b, 0x19e7385b, - 0xc879dbee, 0x7ca1470a, 0x427ce90f, 0x84f8c91e, 0x00000000, - 0x80098386, 0x2b3248ed, 0x111eac70, 0x5a6c4e72, 0x0efdfbff, - 0x850f5638, 0xae3d1ed5, 0x2d362739, 0x0f0a64d9, 0x5c6821a6, - 0x5b9bd154, 0x36243a2e, 0x0a0cb167, 0x57930fe7, 0xeeb4d296, - 0x9b1b9e91, 0xc0804fc5, 0xdc61a220, 0x775a694b, 0x121c161a, - 0x93e20aba, 0xa0c0e52a, 0x223c43e0, 0x1b121d17, 0x090e0b0d, - 0x8bf2adc7, 0xb62db9a8, 0x1e14c8a9, 0xf1578519, 0x75af4c07, - 0x99eebbdd, 0x7fa3fd60, 0x01f79f26, 0x725cbcf5, 0x6644c53b, - 0xfb5b347e, 0x438b7629, 0x23cbdcc6, 0xedb668fc, 0xe4b863f1, - 0x31d7cadc, 0x63421085, 0x97134022, 0xc6842011, 0x4a857d24, - 0xbbd2f83d, 0xf9ae1132, 0x29c76da1, 0x9e1d4b2f, 0xb2dcf330, - 0x860dec52, 0xc177d0e3, 0xb32b6c16, 0x70a999b9, 0x9411fa48, - 0xe9472264, 0xfca8c48c, 0xf0a01a3f, 0x7d56d82c, 0x3322ef90, - 0x4987c74e, 0x38d9c1d1, 0xca8cfea2, 0xd498360b, 0xf5a6cf81, - 0x7aa528de, 0xb7da268e, 0xad3fa4bf, 0x3a2ce49d, 0x78500d92, - 0x5f6a9bcc, 0x7e546246, 0x8df6c213, 0xd890e8b8, 0x392e5ef7, - 0xc382f5af, 0x5d9fbe80, 0xd0697c93, 0xd56fa92d, 0x25cfb312, - 0xacc83b99, 0x1810a77d, 0x9ce86e63, 0x3bdb7bbb, 0x26cd0978, - 0x596ef418, 0x9aec01b7, 0x4f83a89a, 0x95e6656e, 0xffaa7ee6, - 0xbc2108cf, 0x15efe6e8, 0xe7bad99b, 0x6f4ace36, 0x9fead409, - 0xb029d67c, 0xa431afb2, 0x3f2a3123, 0xa5c63094, 0xa235c066, - 0x4e7437bc, 0x82fca6ca, 0x90e0b0d0, 0xa73315d8, 0x04f14a98, - 0xec41f7da, 0xcd7f0e50, 0x91172ff6, 0x4d768dd6, 0xef434db0, - 0xaacc544d, 0x96e4df04, 0xd19ee3b5, 0x6a4c1b88, 0x2cc1b81f, - 0x65467f51, 0x5e9d04ea, 0x8c015d35, 0x87fa7374, 0x0bfb2e41, - 0x67b35a1d, 0xdb9252d2, 0x10e93356, 0xd66d1347, 0xd79a8c61, - 0xa1377a0c, 0xf8598e14, 0x13eb893c, 0xa9ceee27, 0x61b735c9, - 0x1ce1ede5, 0x477a3cb1, 0xd29c59df, 0xf2553f73, 0x141879ce, - 0xc773bf37, 0xf753eacd, 0xfd5f5baa, 0x3ddf146f, 0x447886db, - 0xafca81f3, 0x68b93ec4, 0x24382c34, 0xa3c25f40, 0x1d1672c3, - 0xe2bc0c25, 0x3c288b49, 0x0dff4195, 0xa8397101, 0x0c08deb3, - 0xb4d89ce4, 0x566490c1, 0xcb7b6184, 0x32d570b6, 0x6c48745c, - 0xb8d04257 - }; - - private static readonly uint[] Tinv3 = - { - 0x5150a7f4, 0x7e536541, 0x1ac3a417, 0x3a965e27, 0x3bcb6bab, - 0x1ff1459d, 0xacab58fa, 0x4b9303e3, 0x2055fa30, 0xadf66d76, - 0x889176cc, 0xf5254c02, 0x4ffcd7e5, 0xc5d7cb2a, 0x26804435, - 0xb58fa362, 0xde495ab1, 0x25671bba, 0x45980eea, 0x5de1c0fe, - 0xc302752f, 0x8112f04c, 0x8da39746, 0x6bc6f9d3, 0x03e75f8f, - 0x15959c92, 0xbfeb7a6d, 0x95da5952, 0xd42d83be, 0x58d32174, - 0x492969e0, 0x8e44c8c9, 0x756a89c2, 0xf478798e, 0x996b3e58, - 0x27dd71b9, 0xbeb64fe1, 0xf017ad88, 0xc966ac20, 0x7db43ace, - 0x63184adf, 0xe582311a, 0x97603351, 0x62457f53, 0xb1e07764, - 0xbb84ae6b, 0xfe1ca081, 0xf9942b08, 0x70586848, 0x8f19fd45, - 0x94876cde, 0x52b7f87b, 0xab23d373, 0x72e2024b, 0xe3578f1f, - 0x662aab55, 0xb20728eb, 0x2f03c2b5, 0x869a7bc5, 0xd3a50837, - 0x30f28728, 0x23b2a5bf, 0x02ba6a03, 0xed5c8216, 0x8a2b1ccf, - 0xa792b479, 0xf3f0f207, 0x4ea1e269, 0x65cdf4da, 0x06d5be05, - 0xd11f6234, 0xc48afea6, 0x349d532e, 0xa2a055f3, 0x0532e18a, - 0xa475ebf6, 0x0b39ec83, 0x40aaef60, 0x5e069f71, 0xbd51106e, - 0x3ef98a21, 0x963d06dd, 0xddae053e, 0x4d46bde6, 0x91b58d54, - 0x71055dc4, 0x046fd406, 0x60ff1550, 0x1924fb98, 0xd697e9bd, - 0x89cc4340, 0x67779ed9, 0xb0bd42e8, 0x07888b89, 0xe7385b19, - 0x79dbeec8, 0xa1470a7c, 0x7ce90f42, 0xf8c91e84, 0x00000000, - 0x09838680, 0x3248ed2b, 0x1eac7011, 0x6c4e725a, 0xfdfbff0e, - 0x0f563885, 0x3d1ed5ae, 0x3627392d, 0x0a64d90f, 0x6821a65c, - 0x9bd1545b, 0x243a2e36, 0x0cb1670a, 0x930fe757, 0xb4d296ee, - 0x1b9e919b, 0x804fc5c0, 0x61a220dc, 0x5a694b77, 0x1c161a12, - 0xe20aba93, 0xc0e52aa0, 0x3c43e022, 0x121d171b, 0x0e0b0d09, - 0xf2adc78b, 0x2db9a8b6, 0x14c8a91e, 0x578519f1, 0xaf4c0775, - 0xeebbdd99, 0xa3fd607f, 0xf79f2601, 0x5cbcf572, 0x44c53b66, - 0x5b347efb, 0x8b762943, 0xcbdcc623, 0xb668fced, 0xb863f1e4, - 0xd7cadc31, 0x42108563, 0x13402297, 0x842011c6, 0x857d244a, - 0xd2f83dbb, 0xae1132f9, 0xc76da129, 0x1d4b2f9e, 0xdcf330b2, - 0x0dec5286, 0x77d0e3c1, 0x2b6c16b3, 0xa999b970, 0x11fa4894, - 0x472264e9, 0xa8c48cfc, 0xa01a3ff0, 0x56d82c7d, 0x22ef9033, - 0x87c74e49, 0xd9c1d138, 0x8cfea2ca, 0x98360bd4, 0xa6cf81f5, - 0xa528de7a, 0xda268eb7, 0x3fa4bfad, 0x2ce49d3a, 0x500d9278, - 0x6a9bcc5f, 0x5462467e, 0xf6c2138d, 0x90e8b8d8, 0x2e5ef739, - 0x82f5afc3, 0x9fbe805d, 0x697c93d0, 0x6fa92dd5, 0xcfb31225, - 0xc83b99ac, 0x10a77d18, 0xe86e639c, 0xdb7bbb3b, 0xcd097826, - 0x6ef41859, 0xec01b79a, 0x83a89a4f, 0xe6656e95, 0xaa7ee6ff, - 0x2108cfbc, 0xefe6e815, 0xbad99be7, 0x4ace366f, 0xead4099f, - 0x29d67cb0, 0x31afb2a4, 0x2a31233f, 0xc63094a5, 0x35c066a2, - 0x7437bc4e, 0xfca6ca82, 0xe0b0d090, 0x3315d8a7, 0xf14a9804, - 0x41f7daec, 0x7f0e50cd, 0x172ff691, 0x768dd64d, 0x434db0ef, - 0xcc544daa, 0xe4df0496, 0x9ee3b5d1, 0x4c1b886a, 0xc1b81f2c, - 0x467f5165, 0x9d04ea5e, 0x015d358c, 0xfa737487, 0xfb2e410b, - 0xb35a1d67, 0x9252d2db, 0xe9335610, 0x6d1347d6, 0x9a8c61d7, - 0x377a0ca1, 0x598e14f8, 0xeb893c13, 0xceee27a9, 0xb735c961, - 0xe1ede51c, 0x7a3cb147, 0x9c59dfd2, 0x553f73f2, 0x1879ce14, - 0x73bf37c7, 0x53eacdf7, 0x5f5baafd, 0xdf146f3d, 0x7886db44, - 0xca81f3af, 0xb93ec468, 0x382c3424, 0xc25f40a3, 0x1672c31d, - 0xbc0c25e2, 0x288b493c, 0xff41950d, 0x397101a8, 0x08deb30c, - 0xd89ce4b4, 0x6490c156, 0x7b6184cb, 0xd570b632, 0x48745c6c, - 0xd04257b8 - }; - - private static uint Shift(uint r, int shift) - { - return (r >> shift) | (r << (32 - shift)); - } - - /* multiply four bytes in GF(2^8) by 'x' {02} in parallel */ - - private const uint m1 = 0x80808080; - private const uint m2 = 0x7f7f7f7f; - private const uint m3 = 0x0000001b; - private const uint m4 = 0xC0C0C0C0; - private const uint m5 = 0x3f3f3f3f; - - private static uint FFmulX(uint x) - { - return ((x & m2) << 1) ^ (((x & m1) >> 7) * m3); - } - - private static uint FFmulX2(uint x) - { - uint t0 = (x & m5) << 2; - uint t1 = (x & m4); - t1 ^= (t1 >> 1); - return t0 ^ (t1 >> 2) ^ (t1 >> 5); - } - - /* - The following defines provide alternative definitions of FFmulX that might - give improved performance if a fast 32-bit multiply is not available. - - private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) << 1) ^ ((u >>> 3) | (u >>> 6)); } - private static final int m4 = 0x1b1b1b1b; - private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u >>> 7)) & m4); } - - */ - - private static uint Inv_Mcol(uint x) - { - uint t0, t1; - t0 = x; - t1 = t0 ^ Shift(t0, 8); - t0 ^= FFmulX(t1); - t1 ^= FFmulX2(t0); - t0 ^= t1 ^ Shift(t1, 16); - return t0; - } - - private static uint SubWord(uint x) - { - return (uint)S[x&255] - | (((uint)S[(x>>8)&255]) << 8) - | (((uint)S[(x>>16)&255]) << 16) - | (((uint)S[(x>>24)&255]) << 24); - } - - /** - * Calculate the necessary round keys - * The number of calculations depends on key size and block size - * AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits - * This code is written assuming those are the only possible values - */ - private uint[][] GenerateWorkingKey(byte[] key, bool forEncryption) - { - int keyLen = key.Length; - if (keyLen < 16 || keyLen > 32 || (keyLen & 7) != 0) - throw new ArgumentException("Key length not 128/192/256 bits."); - - int KC = keyLen >> 2; - this.ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes - - uint[][] W = new uint[ROUNDS + 1][]; // 4 words in a block - for (int i = 0; i <= ROUNDS; ++i) - { - W[i] = new uint[4]; - } - - switch (KC) - { - case 4: - { - uint t0 = Pack.LE_To_UInt32(key, 0); W[0][0] = t0; - uint t1 = Pack.LE_To_UInt32(key, 4); W[0][1] = t1; - uint t2 = Pack.LE_To_UInt32(key, 8); W[0][2] = t2; - uint t3 = Pack.LE_To_UInt32(key, 12); W[0][3] = t3; - - for (int i = 1; i <= 10; ++i) - { - uint u = SubWord(Shift(t3, 8)) ^ rcon[i - 1]; - t0 ^= u; W[i][0] = t0; - t1 ^= t0; W[i][1] = t1; - t2 ^= t1; W[i][2] = t2; - t3 ^= t2; W[i][3] = t3; - } - - break; - } - case 6: - { - uint t0 = Pack.LE_To_UInt32(key, 0); W[0][0] = t0; - uint t1 = Pack.LE_To_UInt32(key, 4); W[0][1] = t1; - uint t2 = Pack.LE_To_UInt32(key, 8); W[0][2] = t2; - uint t3 = Pack.LE_To_UInt32(key, 12); W[0][3] = t3; - uint t4 = Pack.LE_To_UInt32(key, 16); W[1][0] = t4; - uint t5 = Pack.LE_To_UInt32(key, 20); W[1][1] = t5; - - uint rcon = 1; - uint u = SubWord(Shift(t5, 8)) ^ rcon; rcon <<= 1; - t0 ^= u; W[1][2] = t0; - t1 ^= t0; W[1][3] = t1; - t2 ^= t1; W[2][0] = t2; - t3 ^= t2; W[2][1] = t3; - t4 ^= t3; W[2][2] = t4; - t5 ^= t4; W[2][3] = t5; - - for (int i = 3; i < 12; i += 3) - { - u = SubWord(Shift(t5, 8)) ^ rcon; rcon <<= 1; - t0 ^= u; W[i ][0] = t0; - t1 ^= t0; W[i ][1] = t1; - t2 ^= t1; W[i ][2] = t2; - t3 ^= t2; W[i ][3] = t3; - t4 ^= t3; W[i + 1][0] = t4; - t5 ^= t4; W[i + 1][1] = t5; - u = SubWord(Shift(t5, 8)) ^ rcon; rcon <<= 1; - t0 ^= u; W[i + 1][2] = t0; - t1 ^= t0; W[i + 1][3] = t1; - t2 ^= t1; W[i + 2][0] = t2; - t3 ^= t2; W[i + 2][1] = t3; - t4 ^= t3; W[i + 2][2] = t4; - t5 ^= t4; W[i + 2][3] = t5; - } - - u = SubWord(Shift(t5, 8)) ^ rcon; - t0 ^= u; W[12][0] = t0; - t1 ^= t0; W[12][1] = t1; - t2 ^= t1; W[12][2] = t2; - t3 ^= t2; W[12][3] = t3; - - break; - } - case 8: - { - uint t0 = Pack.LE_To_UInt32(key, 0); W[0][0] = t0; - uint t1 = Pack.LE_To_UInt32(key, 4); W[0][1] = t1; - uint t2 = Pack.LE_To_UInt32(key, 8); W[0][2] = t2; - uint t3 = Pack.LE_To_UInt32(key, 12); W[0][3] = t3; - uint t4 = Pack.LE_To_UInt32(key, 16); W[1][0] = t4; - uint t5 = Pack.LE_To_UInt32(key, 20); W[1][1] = t5; - uint t6 = Pack.LE_To_UInt32(key, 24); W[1][2] = t6; - uint t7 = Pack.LE_To_UInt32(key, 28); W[1][3] = t7; - - uint u, rcon = 1; - - for (int i = 2; i < 14; i += 2) - { - u = SubWord(Shift(t7, 8)) ^ rcon; rcon <<= 1; - t0 ^= u; W[i ][0] = t0; - t1 ^= t0; W[i ][1] = t1; - t2 ^= t1; W[i ][2] = t2; - t3 ^= t2; W[i ][3] = t3; - u = SubWord(t3); - t4 ^= u; W[i + 1][0] = t4; - t5 ^= t4; W[i + 1][1] = t5; - t6 ^= t5; W[i + 1][2] = t6; - t7 ^= t6; W[i + 1][3] = t7; - } - - u = SubWord(Shift(t7, 8)) ^ rcon; - t0 ^= u; W[14][0] = t0; - t1 ^= t0; W[14][1] = t1; - t2 ^= t1; W[14][2] = t2; - t3 ^= t2; W[14][3] = t3; - - break; - } - default: - { - throw new InvalidOperationException("Should never get here"); - } - } - - if (!forEncryption) - { - for (int j = 1; j < ROUNDS; j++) - { - uint[] w = W[j]; - for (int i = 0; i < 4; i++) - { - w[i] = Inv_Mcol(w[i]); - } - } - } - - return W; - } - - private int ROUNDS; - private uint[][] WorkingKey; - private uint C0, C1, C2, C3; - private bool forEncryption; - - private const int BLOCK_SIZE = 16; - - /** - * default constructor - 128 bit block size. - */ - public AesFastEngine() - { - } - - /** - * initialise an AES 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) - { - KeyParameter keyParameter = parameters as KeyParameter; - - if (keyParameter == null) - throw new ArgumentException("invalid parameter passed to AES init - " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); - - WorkingKey = GenerateWorkingKey(keyParameter.GetKey(), forEncryption); - - this.forEncryption = forEncryption; - } - - public /*virtual*/ string AlgorithmName - { - get { return "AES"; } - } - - public /*virtual*/ bool IsPartialBlockOkay - { - get { return false; } - } - - public /*virtual*/ int GetBlockSize() - { - return BLOCK_SIZE; - } - - public unsafe /*virtual*/ int ProcessBlock( - byte[] input, - int inOff, - byte[] output, - int outOff) - { - fixed (byte* pinput = input) - { - uint* puintinput = (uint*)&pinput[inOff]; - - C0 = puintinput[0]; - C1 = puintinput[1]; - C2 = puintinput[2]; - C3 = puintinput[3]; - - inOff += 16; - } - - if (forEncryption) - { - uint[][] KW = WorkingKey; - uint[] kw = KW[0]; - uint t0 = this.C0 ^ kw[0]; - uint t1 = this.C1 ^ kw[1]; - uint t2 = this.C2 ^ kw[2]; - - uint r0, r1, r2, r3 = this.C3 ^ kw[3]; - int r = 1; - fixed (uint* pT0 = T0, pT1 = T1, pT2 = T2, pT3 = T3) - { - while (r < ROUNDS - 1) - { - kw = KW[r++]; - fixed (uint* pkw = kw) - { - r0 = pT0[t0 & 255] ^ pT1[(t1 >> 8) & 255] ^ pT2[(t2 >> 16) & 255] ^ pT3[r3 >> 24] ^ pkw[0]; - r1 = pT0[t1 & 255] ^ pT1[(t2 >> 8) & 255] ^ pT2[(r3 >> 16) & 255] ^ pT3[t0 >> 24] ^ pkw[1]; - r2 = pT0[t2 & 255] ^ pT1[(r3 >> 8) & 255] ^ pT2[(t0 >> 16) & 255] ^ pT3[t1 >> 24] ^ pkw[2]; - r3 = pT0[r3 & 255] ^ pT1[(t0 >> 8) & 255] ^ pT2[(t1 >> 16) & 255] ^ pT3[t2 >> 24] ^ pkw[3]; - } - - kw = KW[r++]; - fixed (uint* pkw = kw) - { - t0 = pT0[r0 & 255] ^ pT1[(r1 >> 8) & 255] ^ pT2[(r2 >> 16) & 255] ^ pT3[r3 >> 24] ^ pkw[0]; - t1 = pT0[r1 & 255] ^ pT1[(r2 >> 8) & 255] ^ pT2[(r3 >> 16) & 255] ^ pT3[r0 >> 24] ^ pkw[1]; - t2 = pT0[r2 & 255] ^ pT1[(r3 >> 8) & 255] ^ pT2[(r0 >> 16) & 255] ^ pT3[r1 >> 24] ^ pkw[2]; - r3 = pT0[r3 & 255] ^ pT1[(r0 >> 8) & 255] ^ pT2[(r1 >> 16) & 255] ^ pT3[r2 >> 24] ^ pkw[3]; - } - } - - kw = KW[r++]; - fixed (uint* pkw = kw) - { - r0 = pT0[t0 & 255] ^ pT1[(t1 >> 8) & 255] ^ pT2[(t2 >> 16) & 255] ^ pT3[r3 >> 24] ^ pkw[0]; - r1 = pT0[t1 & 255] ^ pT1[(t2 >> 8) & 255] ^ pT2[(r3 >> 16) & 255] ^ pT3[t0 >> 24] ^ pkw[1]; - r2 = pT0[t2 & 255] ^ pT1[(r3 >> 8) & 255] ^ pT2[(t0 >> 16) & 255] ^ pT3[t1 >> 24] ^ pkw[2]; - r3 = pT0[r3 & 255] ^ pT1[(t0 >> 8) & 255] ^ pT2[(t1 >> 16) & 255] ^ pT3[t2 >> 24] ^ pkw[3]; - } - - // the final round's table is a simple function of S so we don't use a whole other four tables for it - - kw = KW[r]; - fixed (uint* pkw = kw) - fixed (byte* pS = S) - { - this.C0 = (uint)pS[r0 & 255] ^ (((uint)pS[(r1 >> 8) & 255]) << 8) ^ (((uint)pS[(r2 >> 16) & 255]) << 16) ^ (((uint)pS[r3 >> 24]) << 24) ^ pkw[0]; - this.C1 = (uint)pS[r1 & 255] ^ (((uint)pS[(r2 >> 8) & 255]) << 8) ^ (((uint)pS[(r3 >> 16) & 255]) << 16) ^ (((uint)pS[r0 >> 24]) << 24) ^ pkw[1]; - this.C2 = (uint)pS[r2 & 255] ^ (((uint)pS[(r3 >> 8) & 255]) << 8) ^ (((uint)pS[(r0 >> 16) & 255]) << 16) ^ (((uint)pS[r1 >> 24]) << 24) ^ pkw[2]; - this.C3 = (uint)pS[r3 & 255] ^ (((uint)pS[(r0 >> 8) & 255]) << 8) ^ (((uint)pS[(r1 >> 16) & 255]) << 16) ^ (((uint)pS[r2 >> 24]) << 24) ^ pkw[3]; - } - } - } - else - { - uint[][] KW = WorkingKey; - uint[] kw = KW[ROUNDS]; - uint t0 = this.C0 ^ kw[0]; - uint t1 = this.C1 ^ kw[1]; - uint t2 = this.C2 ^ kw[2]; - - uint r0, r1, r2, r3 = this.C3 ^ kw[3]; - int r = ROUNDS - 1; - fixed (uint* pTinv0 = Tinv0, pTinv1 = Tinv1, pTinv2 = Tinv2, pTinv3 = Tinv3) - { - while (r > 1) - { - kw = KW[r--]; - fixed (uint* pkw = kw) - { - r0 = pTinv0[t0 & 255] ^ pTinv1[(r3 >> 8) & 255] ^ pTinv2[(t2 >> 16) & 255] ^ pTinv3[t1 >> 24] ^ pkw[0]; - r1 = pTinv0[t1 & 255] ^ pTinv1[(t0 >> 8) & 255] ^ pTinv2[(r3 >> 16) & 255] ^ pTinv3[t2 >> 24] ^ pkw[1]; - r2 = pTinv0[t2 & 255] ^ pTinv1[(t1 >> 8) & 255] ^ pTinv2[(t0 >> 16) & 255] ^ pTinv3[r3 >> 24] ^ pkw[2]; - r3 = pTinv0[r3 & 255] ^ pTinv1[(t2 >> 8) & 255] ^ pTinv2[(t1 >> 16) & 255] ^ pTinv3[t0 >> 24] ^ pkw[3]; - } - - kw = KW[r--]; - fixed (uint* pkw = kw) - { - t0 = pTinv0[r0 & 255] ^ pTinv1[(r3 >> 8) & 255] ^ pTinv2[(r2 >> 16) & 255] ^ pTinv3[r1 >> 24] ^ pkw[0]; - t1 = pTinv0[r1 & 255] ^ pTinv1[(r0 >> 8) & 255] ^ pTinv2[(r3 >> 16) & 255] ^ pTinv3[r2 >> 24] ^ pkw[1]; - t2 = pTinv0[r2 & 255] ^ pTinv1[(r1 >> 8) & 255] ^ pTinv2[(r0 >> 16) & 255] ^ pTinv3[r3 >> 24] ^ pkw[2]; - r3 = pTinv0[r3 & 255] ^ pTinv1[(r2 >> 8) & 255] ^ pTinv2[(r1 >> 16) & 255] ^ pTinv3[r0 >> 24] ^ pkw[3]; - } - } - - kw = KW[1]; - fixed (uint* pkw = kw) - { - r0 = pTinv0[t0 & 255] ^ pTinv1[(r3 >> 8) & 255] ^ pTinv2[(t2 >> 16) & 255] ^ pTinv3[t1 >> 24] ^ pkw[0]; - r1 = pTinv0[t1 & 255] ^ pTinv1[(t0 >> 8) & 255] ^ pTinv2[(r3 >> 16) & 255] ^ pTinv3[t2 >> 24] ^ pkw[1]; - r2 = pTinv0[t2 & 255] ^ pTinv1[(t1 >> 8) & 255] ^ pTinv2[(t0 >> 16) & 255] ^ pTinv3[r3 >> 24] ^ pkw[2]; - r3 = pTinv0[r3 & 255] ^ pTinv1[(t2 >> 8) & 255] ^ pTinv2[(t1 >> 16) & 255] ^ pTinv3[t0 >> 24] ^ pkw[3]; - } - - // the final round's table is a simple function of Si so we don't use a whole other four tables for it - - kw = KW[0]; - fixed (uint* pkw = kw) - fixed (byte* pSi = Si) - { - this.C0 = (uint)pSi[r0 & 255] ^ (((uint)pSi[(r3 >> 8) & 255]) << 8) ^ (((uint)pSi[(r2 >> 16) & 255]) << 16) ^ (((uint)pSi[r1 >> 24]) << 24) ^ pkw[0]; - this.C1 = (uint)pSi[r1 & 255] ^ (((uint)pSi[(r0 >> 8) & 255]) << 8) ^ (((uint)pSi[(r3 >> 16) & 255]) << 16) ^ (((uint)pSi[r2 >> 24]) << 24) ^ pkw[1]; - this.C2 = (uint)pSi[r2 & 255] ^ (((uint)pSi[(r1 >> 8) & 255]) << 8) ^ (((uint)pSi[(r0 >> 16) & 255]) << 16) ^ (((uint)pSi[r3 >> 24]) << 24) ^ pkw[2]; - this.C3 = (uint)pSi[r3 & 255] ^ (((uint)pSi[(r2 >> 8) & 255]) << 8) ^ (((uint)pSi[(r1 >> 16) & 255]) << 16) ^ (((uint)pSi[r0 >> 24]) << 24) ^ pkw[3]; - } - } - } - - fixed (byte* poutput = output) - { - uint* puintOutput = (uint*)&poutput[outOff]; - - puintOutput[0] = C0; - puintOutput[1] = C1; - puintOutput[2] = C2; - puintOutput[3] = C3; - } - - return BLOCK_SIZE; - } - - public /*virtual*/ void Reset() - { - } - - private unsafe void UnPackBlock( - byte[] input, - int inOff) - { - fixed (byte* poutput = input) - { - uint* puintoutput = (uint*)&poutput[inOff]; - - C0 = puintoutput[0]; - C1 = puintoutput[1]; - C2 = puintoutput[2]; - C3 = puintoutput[3]; - - inOff += 16; - } - } - - private unsafe void PackBlock( - byte[] output, - int outOff) - { - fixed (byte* poutput = output) - { - uint* puintOutput = (uint*)&poutput[outOff]; - - puintOutput[0] = C0; - puintOutput[1] = C1; - puintOutput[2] = C2; - puintOutput[3] = C3; - - outOff += 16; - } - } - } -} -#pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesFastEngine.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesFastEngine.cs.meta index 091b19f..38e5564 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesFastEngine.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesFastEngine.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 05eb307d46de52e42a911fd8244278df +guid: 68dc51a4fca6eb041bdb766f4e8ca6f4 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesLightEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesLightEngine.cs index 4f01525..7036a9f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesLightEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesLightEngine.cs @@ -35,7 +35,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines * for round precomputation, but it has the smallest foot print. *

*/ - public class AesLightEngine + public sealed class AesLightEngine : IBlockCipher { // The S box @@ -344,37 +344,28 @@ public AesLightEngine() * @exception ArgumentException if the parameters argument is * inappropriate. */ - public virtual void Init( - bool forEncryption, - ICipherParameters parameters) + public void Init(bool forEncryption, ICipherParameters parameters) { - KeyParameter keyParameter = parameters as KeyParameter; - - if (keyParameter == null) + if (!(parameters is KeyParameter keyParameter)) throw new ArgumentException("invalid parameter passed to AES init - " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); WorkingKey = GenerateWorkingKey(keyParameter.GetKey(), forEncryption); this.forEncryption = forEncryption; } - public virtual string AlgorithmName + public string AlgorithmName { get { return "AES"; } } - public virtual bool IsPartialBlockOkay - { - get { return false; } - } - - public virtual int GetBlockSize() + public int GetBlockSize() { return BLOCK_SIZE; } - public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) + public int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { if (WorkingKey == null) throw new InvalidOperationException("AES engine not initialised"); @@ -382,6 +373,16 @@ public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outO Check.DataLength(input, inOff, 16, "input buffer too short"); Check.OutputLength(output, outOff, 16, "output buffer too short"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + if (forEncryption) + { + EncryptBlock(input.AsSpan(inOff), output.AsSpan(outOff), WorkingKey); + } + else + { + DecryptBlock(input.AsSpan(inOff), output.AsSpan(outOff), WorkingKey); + } +#else if (forEncryption) { EncryptBlock(input, inOff, output, outOff, WorkingKey); @@ -390,14 +391,130 @@ public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outO { DecryptBlock(input, inOff, output, outOff, WorkingKey); } +#endif return BLOCK_SIZE; } - public virtual void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessBlock(ReadOnlySpan input, Span output) { + if (WorkingKey == null) + throw new InvalidOperationException("AES engine not initialised"); + + Check.DataLength(input, 16, "input buffer too short"); + Check.OutputLength(output, 16, "output buffer too short"); + + if (forEncryption) + { + EncryptBlock(input, output, WorkingKey); + } + else + { + DecryptBlock(input, output, WorkingKey); + } + + return BLOCK_SIZE; + } +#endif + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void EncryptBlock(ReadOnlySpan input, Span output, uint[][] KW) + { + uint C0 = Pack.LE_To_UInt32(input); + uint C1 = Pack.LE_To_UInt32(input[4..]); + uint C2 = Pack.LE_To_UInt32(input[8..]); + uint C3 = Pack.LE_To_UInt32(input[12..]); + + uint[] kw = KW[0]; + uint t0 = C0 ^ kw[0]; + uint t1 = C1 ^ kw[1]; + uint t2 = C2 ^ kw[2]; + + uint r0, r1, r2, r3 = C3 ^ kw[3]; + int r = 1; + while (r < ROUNDS - 1) + { + kw = KW[r++]; + r0 = Mcol((uint)S[t0 & 255] ^ (((uint)S[(t1 >> 8) & 255]) << 8) ^ (((uint)S[(t2 >> 16) & 255]) << 16) ^ (((uint)S[(r3 >> 24) & 255]) << 24)) ^ kw[0]; + r1 = Mcol((uint)S[t1 & 255] ^ (((uint)S[(t2 >> 8) & 255]) << 8) ^ (((uint)S[(r3 >> 16) & 255]) << 16) ^ (((uint)S[(t0 >> 24) & 255]) << 24)) ^ kw[1]; + r2 = Mcol((uint)S[t2 & 255] ^ (((uint)S[(r3 >> 8) & 255]) << 8) ^ (((uint)S[(t0 >> 16) & 255]) << 16) ^ (((uint)S[(t1 >> 24) & 255]) << 24)) ^ kw[2]; + r3 = Mcol((uint)S[r3 & 255] ^ (((uint)S[(t0 >> 8) & 255]) << 8) ^ (((uint)S[(t1 >> 16) & 255]) << 16) ^ (((uint)S[(t2 >> 24) & 255]) << 24)) ^ kw[3]; + kw = KW[r++]; + t0 = Mcol((uint)S[r0 & 255] ^ (((uint)S[(r1 >> 8) & 255]) << 8) ^ (((uint)S[(r2 >> 16) & 255]) << 16) ^ (((uint)S[(r3 >> 24) & 255]) << 24)) ^ kw[0]; + t1 = Mcol((uint)S[r1 & 255] ^ (((uint)S[(r2 >> 8) & 255]) << 8) ^ (((uint)S[(r3 >> 16) & 255]) << 16) ^ (((uint)S[(r0 >> 24) & 255]) << 24)) ^ kw[1]; + t2 = Mcol((uint)S[r2 & 255] ^ (((uint)S[(r3 >> 8) & 255]) << 8) ^ (((uint)S[(r0 >> 16) & 255]) << 16) ^ (((uint)S[(r1 >> 24) & 255]) << 24)) ^ kw[2]; + r3 = Mcol((uint)S[r3 & 255] ^ (((uint)S[(r0 >> 8) & 255]) << 8) ^ (((uint)S[(r1 >> 16) & 255]) << 16) ^ (((uint)S[(r2 >> 24) & 255]) << 24)) ^ kw[3]; + } + + kw = KW[r++]; + r0 = Mcol((uint)S[t0 & 255] ^ (((uint)S[(t1 >> 8) & 255]) << 8) ^ (((uint)S[(t2 >> 16) & 255]) << 16) ^ (((uint)S[(r3 >> 24) & 255]) << 24)) ^ kw[0]; + r1 = Mcol((uint)S[t1 & 255] ^ (((uint)S[(t2 >> 8) & 255]) << 8) ^ (((uint)S[(r3 >> 16) & 255]) << 16) ^ (((uint)S[(t0 >> 24) & 255]) << 24)) ^ kw[1]; + r2 = Mcol((uint)S[t2 & 255] ^ (((uint)S[(r3 >> 8) & 255]) << 8) ^ (((uint)S[(t0 >> 16) & 255]) << 16) ^ (((uint)S[(t1 >> 24) & 255]) << 24)) ^ kw[2]; + r3 = Mcol((uint)S[r3 & 255] ^ (((uint)S[(t0 >> 8) & 255]) << 8) ^ (((uint)S[(t1 >> 16) & 255]) << 16) ^ (((uint)S[(t2 >> 24) & 255]) << 24)) ^ kw[3]; + + // the final round is a simple function of S + + kw = KW[r]; + C0 = (uint)S[r0 & 255] ^ (((uint)S[(r1 >> 8) & 255]) << 8) ^ (((uint)S[(r2 >> 16) & 255]) << 16) ^ (((uint)S[(r3 >> 24) & 255]) << 24) ^ kw[0]; + C1 = (uint)S[r1 & 255] ^ (((uint)S[(r2 >> 8) & 255]) << 8) ^ (((uint)S[(r3 >> 16) & 255]) << 16) ^ (((uint)S[(r0 >> 24) & 255]) << 24) ^ kw[1]; + C2 = (uint)S[r2 & 255] ^ (((uint)S[(r3 >> 8) & 255]) << 8) ^ (((uint)S[(r0 >> 16) & 255]) << 16) ^ (((uint)S[(r1 >> 24) & 255]) << 24) ^ kw[2]; + C3 = (uint)S[r3 & 255] ^ (((uint)S[(r0 >> 8) & 255]) << 8) ^ (((uint)S[(r1 >> 16) & 255]) << 16) ^ (((uint)S[(r2 >> 24) & 255]) << 24) ^ kw[3]; + + Pack.UInt32_To_LE(C0, output); + Pack.UInt32_To_LE(C1, output[4..]); + Pack.UInt32_To_LE(C2, output[8..]); + Pack.UInt32_To_LE(C3, output[12..]); } + private void DecryptBlock(ReadOnlySpan input, Span output, uint[][] KW) + { + uint C0 = Pack.LE_To_UInt32(input); + uint C1 = Pack.LE_To_UInt32(input[4..]); + uint C2 = Pack.LE_To_UInt32(input[8..]); + uint C3 = Pack.LE_To_UInt32(input[12..]); + + uint[] kw = KW[ROUNDS]; + uint t0 = C0 ^ kw[0]; + uint t1 = C1 ^ kw[1]; + uint t2 = C2 ^ kw[2]; + + uint r0, r1, r2, r3 = C3 ^ kw[3]; + int r = ROUNDS - 1; + while (r > 1) + { + kw = KW[r--]; + r0 = Inv_Mcol((uint)Si[t0 & 255] ^ (((uint)Si[(r3 >> 8) & 255]) << 8) ^ (((uint)Si[(t2 >> 16) & 255]) << 16) ^ ((uint)Si[(t1 >> 24) & 255] << 24)) ^ kw[0]; + r1 = Inv_Mcol((uint)Si[t1 & 255] ^ (((uint)Si[(t0 >> 8) & 255]) << 8) ^ (((uint)Si[(r3 >> 16) & 255]) << 16) ^ ((uint)Si[(t2 >> 24) & 255] << 24)) ^ kw[1]; + r2 = Inv_Mcol((uint)Si[t2 & 255] ^ (((uint)Si[(t1 >> 8) & 255]) << 8) ^ (((uint)Si[(t0 >> 16) & 255]) << 16) ^ ((uint)Si[(r3 >> 24) & 255] << 24)) ^ kw[2]; + r3 = Inv_Mcol((uint)Si[r3 & 255] ^ (((uint)Si[(t2 >> 8) & 255]) << 8) ^ (((uint)Si[(t1 >> 16) & 255]) << 16) ^ ((uint)Si[(t0 >> 24) & 255] << 24)) ^ kw[3]; + kw = KW[r--]; + t0 = Inv_Mcol((uint)Si[r0 & 255] ^ (((uint)Si[(r3 >> 8) & 255]) << 8) ^ (((uint)Si[(r2 >> 16) & 255]) << 16) ^ ((uint)Si[(r1 >> 24) & 255] << 24)) ^ kw[0]; + t1 = Inv_Mcol((uint)Si[r1 & 255] ^ (((uint)Si[(r0 >> 8) & 255]) << 8) ^ (((uint)Si[(r3 >> 16) & 255]) << 16) ^ ((uint)Si[(r2 >> 24) & 255] << 24)) ^ kw[1]; + t2 = Inv_Mcol((uint)Si[r2 & 255] ^ (((uint)Si[(r1 >> 8) & 255]) << 8) ^ (((uint)Si[(r0 >> 16) & 255]) << 16) ^ ((uint)Si[(r3 >> 24) & 255] << 24)) ^ kw[2]; + r3 = Inv_Mcol((uint)Si[r3 & 255] ^ (((uint)Si[(r2 >> 8) & 255]) << 8) ^ (((uint)Si[(r1 >> 16) & 255]) << 16) ^ ((uint)Si[(r0 >> 24) & 255] << 24)) ^ kw[3]; + } + + kw = KW[1]; + r0 = Inv_Mcol((uint)Si[t0 & 255] ^ (((uint)Si[(r3 >> 8) & 255]) << 8) ^ (((uint)Si[(t2 >> 16) & 255]) << 16) ^ ((uint)Si[(t1 >> 24) & 255] << 24)) ^ kw[0]; + r1 = Inv_Mcol((uint)Si[t1 & 255] ^ (((uint)Si[(t0 >> 8) & 255]) << 8) ^ (((uint)Si[(r3 >> 16) & 255]) << 16) ^ ((uint)Si[(t2 >> 24) & 255] << 24)) ^ kw[1]; + r2 = Inv_Mcol((uint)Si[t2 & 255] ^ (((uint)Si[(t1 >> 8) & 255]) << 8) ^ (((uint)Si[(t0 >> 16) & 255]) << 16) ^ ((uint)Si[(r3 >> 24) & 255] << 24)) ^ kw[2]; + r3 = Inv_Mcol((uint)Si[r3 & 255] ^ (((uint)Si[(t2 >> 8) & 255]) << 8) ^ (((uint)Si[(t1 >> 16) & 255]) << 16) ^ ((uint)Si[(t0 >> 24) & 255] << 24)) ^ kw[3]; + + // the final round's table is a simple function of Si + + kw = KW[0]; + C0 = (uint)Si[r0 & 255] ^ (((uint)Si[(r3 >> 8) & 255]) << 8) ^ (((uint)Si[(r2 >> 16) & 255]) << 16) ^ (((uint)Si[(r1 >> 24) & 255]) << 24) ^ kw[0]; + C1 = (uint)Si[r1 & 255] ^ (((uint)Si[(r0 >> 8) & 255]) << 8) ^ (((uint)Si[(r3 >> 16) & 255]) << 16) ^ (((uint)Si[(r2 >> 24) & 255]) << 24) ^ kw[1]; + C2 = (uint)Si[r2 & 255] ^ (((uint)Si[(r1 >> 8) & 255]) << 8) ^ (((uint)Si[(r0 >> 16) & 255]) << 16) ^ (((uint)Si[(r3 >> 24) & 255]) << 24) ^ kw[2]; + C3 = (uint)Si[r3 & 255] ^ (((uint)Si[(r2 >> 8) & 255]) << 8) ^ (((uint)Si[(r1 >> 16) & 255]) << 16) ^ (((uint)Si[(r0 >> 24) & 255]) << 24) ^ kw[3]; + + Pack.UInt32_To_LE(C0, output); + Pack.UInt32_To_LE(C1, output[4..]); + Pack.UInt32_To_LE(C2, output[8..]); + Pack.UInt32_To_LE(C3, output[12..]); + } +#else private void EncryptBlock(byte[] input, int inOff, byte[] output, int outOff, uint[][] KW) { uint C0 = Pack.LE_To_UInt32(input, inOff + 0); @@ -493,6 +610,7 @@ private void DecryptBlock(byte[] input, int inOff, byte[] output, int outOff, ui Pack.UInt32_To_LE(C2, output, outOff + 8); Pack.UInt32_To_LE(C3, output, outOff + 12); } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesWrapEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesWrapEngine.cs index 0129991..40f8209 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesWrapEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AesWrapEngine.cs @@ -11,7 +11,7 @@ public class AesWrapEngine : Rfc3394WrapEngine { public AesWrapEngine() - : base(new AesEngine()) + : base(AesUtilities.CreateEngine()) { } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AriaEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AriaEngine.cs index aaf4320..dfe1427 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AriaEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/AriaEngine.cs @@ -149,7 +149,7 @@ public virtual void Init(bool forEncryption, ICipherParameters parameters) if (keyParameter == null) throw new ArgumentException("invalid parameter passed to ARIA init - " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); this.m_roundKeys = KeySchedule(forEncryption, keyParameter.GetKey()); } @@ -159,11 +159,6 @@ public virtual string AlgorithmName get { return "ARIA"; } } - public virtual bool IsPartialBlockOkay - { - get { return false; } - } - public virtual int GetBlockSize() { return BlockSize; @@ -197,10 +192,35 @@ public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outO return BlockSize; } - public virtual void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) { - // Empty + if (m_roundKeys == null) + throw new InvalidOperationException("ARIA engine not initialised"); + + Check.DataLength(input, BlockSize, "input buffer too short"); + Check.OutputLength(output, BlockSize, "output buffer too short"); + + byte[] z = new byte[BlockSize]; + input[..BlockSize].CopyTo(z); + + int i = 0, rounds = m_roundKeys.Length - 3; + while (i < rounds) + { + FO(z, m_roundKeys[i++]); + FE(z, m_roundKeys[i++]); + } + + FO(z, m_roundKeys[i++]); + Xor(z, m_roundKeys[i++]); + SL2(z); + Xor(z, m_roundKeys[i]); + + z.CopyTo(output); + + return BlockSize; } +#endif protected static void A(byte[] z) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/BlowfishEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/BlowfishEngine.cs index 654bf11..6fbf129 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/BlowfishEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/BlowfishEngine.cs @@ -332,7 +332,7 @@ public void Init( ICipherParameters parameters) { if (!(parameters is KeyParameter)) - throw new ArgumentException("invalid parameter passed to Blowfish init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + throw new ArgumentException("invalid parameter passed to Blowfish init - " + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); this.encrypting = forEncryption; this.workingKey = ((KeyParameter)parameters).GetKey(); @@ -344,16 +344,7 @@ public string AlgorithmName get { return "Blowfish"; } } - public bool IsPartialBlockOkay - { - get { return false; } - } - - public int ProcessBlock( - byte[] input, - int inOff, - byte[] output, - int outOff) + public int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { if (workingKey == null) throw new InvalidOperationException("Blowfish not initialised"); @@ -361,7 +352,17 @@ public int ProcessBlock( Check.DataLength(input, inOff, BLOCK_SIZE, "input buffer too short"); Check.OutputLength(output, outOff, BLOCK_SIZE, "output buffer too short"); - if (encrypting) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + if (encrypting) + { + EncryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); + } + else + { + DecryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); + } +#else + if (encrypting) { EncryptBlock(input, inOff, output, outOff); } @@ -369,13 +370,32 @@ public int ProcessBlock( { DecryptBlock(input, inOff, output, outOff); } +#endif return BLOCK_SIZE; } - public void Reset() - { - } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessBlock(ReadOnlySpan input, Span output) + { + if (workingKey == null) + throw new InvalidOperationException("Blowfish not initialised"); + + Check.DataLength(input, BLOCK_SIZE, "input buffer too short"); + Check.OutputLength(output, BLOCK_SIZE, "output buffer too short"); + + if (encrypting) + { + EncryptBlock(input, output); + } + else + { + DecryptBlock(input, output); + } + + return BLOCK_SIZE; + } +#endif public int GetBlockSize() { @@ -428,7 +448,7 @@ private void SetKey(byte[] key) throw new ArgumentException("key length must be in range 32 to 448 bits"); } - /* + /* * - comments are from _Applied Crypto_, Schneier, p338 * please be careful comparing the two, AC numbers the * arrays from 1, the enclosed code from 0. @@ -437,7 +457,7 @@ private void SetKey(byte[] key) * Initialise the S-boxes and the P-array, with a fixed string * This string contains the hexadecimal digits of pi (3.141...) */ - Array.Copy(KS0, 0, S0, 0, SBOX_SK); + Array.Copy(KS0, 0, S0, 0, SBOX_SK); Array.Copy(KS1, 0, S1, 0, SBOX_SK); Array.Copy(KS2, 0, S2, 0, SBOX_SK); Array.Copy(KS3, 0, S3, 0, SBOX_SK); @@ -501,16 +521,46 @@ private void SetKey(byte[] key) ProcessTable(S2[SBOX_SK - 2], S2[SBOX_SK - 1], S3); } - /** - * Encrypt the given input starting at the given offset and place - * the result in the provided buffer starting at the given offset. - * The input will be an exact multiple of our blocksize. - */ - private void EncryptBlock( - byte[] src, - int srcIndex, - byte[] dst, - int dstIndex) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void EncryptBlock(ReadOnlySpan input, Span output) + { + uint xl = Pack.BE_To_UInt32(input); + uint xr = Pack.BE_To_UInt32(input[4..]); + + xl ^= P[0]; + + for (int i = 1; i < ROUNDS; i += 2) + { + xr ^= F(xl) ^ P[i]; + xl ^= F(xr) ^ P[i + 1]; + } + + xr ^= P[ROUNDS + 1]; + + Pack.UInt32_To_BE(xr, output); + Pack.UInt32_To_BE(xl, output[4..]); + } + + private void DecryptBlock(ReadOnlySpan input, Span output) + { + uint xl = Pack.BE_To_UInt32(input); + uint xr = Pack.BE_To_UInt32(input[4..]); + + xl ^= P[ROUNDS + 1]; + + for (int i = ROUNDS; i > 0; i -= 2) + { + xr ^= F(xl) ^ P[i]; + xl ^= F(xr) ^ P[i - 1]; + } + + xr ^= P[0]; + + Pack.UInt32_To_BE(xr, output); + Pack.UInt32_To_BE(xl, output[4..]); + } +#else + private void EncryptBlock(byte[] src, int srcIndex, byte[] dst, int dstIndex) { uint xl = Pack.BE_To_UInt32(src, srcIndex); uint xr = Pack.BE_To_UInt32(src, srcIndex+4); @@ -529,16 +579,7 @@ private void EncryptBlock( Pack.UInt32_To_BE(xl, dst, dstIndex + 4); } - /** - * Decrypt the given input starting at the given offset and place - * the result in the provided buffer starting at the given offset. - * The input will be an exact multiple of our blocksize. - */ - private void DecryptBlock( - byte[] src, - int srcIndex, - byte[] dst, - int dstIndex) + private void DecryptBlock(byte[] src, int srcIndex, byte[] dst, int dstIndex) { uint xl = Pack.BE_To_UInt32(src, srcIndex); uint xr = Pack.BE_To_UInt32(src, srcIndex + 4); @@ -556,7 +597,8 @@ private void DecryptBlock( Pack.UInt32_To_BE(xr, dst, dstIndex); Pack.UInt32_To_BE(xl, dst, dstIndex + 4); } - } +#endif + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/CamelliaEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/CamelliaEngine.cs index db5613d..633b7a2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/CamelliaEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/CamelliaEngine.cs @@ -3,6 +3,7 @@ using System; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines { @@ -20,7 +21,6 @@ public class CamelliaEngine private uint[] subkey = new uint[24 * 4]; private uint[] kw = new uint[4 * 2]; // for whitening private uint[] ke = new uint[6 * 2]; // for FL and FL^(-1) - private uint[] state = new uint[4]; // for encryption and decryption private static readonly uint[] SIGMA = new uint[]{ 0xa09e667f, 0x3bcc908b, @@ -278,25 +278,6 @@ private static void decroldqo32(int rot, uint[] ki, int ioff, uint[] ko, int oof ki[3 + ioff] = ko[1 + ooff]; } - private static uint bytes2uint(byte[] src, int offset) - { - uint word = 0; - for (int i = 0; i < 4; i++) - { - word = (word << 8) + (uint)src[i + offset]; - } - return word; - } - - private static void uint2bytes(uint word, byte[] dst, int offset) - { - for (int i = 0; i < 4; i++) - { - dst[(3 - i) + offset] = (byte)word; - word >>= 8; - } - } - private static void camelliaF2(uint[] s, uint[] skey, int keyoff) { uint t1, t2, u, v; @@ -349,38 +330,23 @@ private void setKey(bool forEncryption, byte[] key) switch (key.Length) { - case 16: - _keyIs128 = true; - k[0] = bytes2uint(key, 0); - k[1] = bytes2uint(key, 4); - k[2] = bytes2uint(key, 8); - k[3] = bytes2uint(key, 12); - k[4] = k[5] = k[6] = k[7] = 0; - break; - case 24: - k[0] = bytes2uint(key, 0); - k[1] = bytes2uint(key, 4); - k[2] = bytes2uint(key, 8); - k[3] = bytes2uint(key, 12); - k[4] = bytes2uint(key, 16); - k[5] = bytes2uint(key, 20); - k[6] = ~k[4]; - k[7] = ~k[5]; - _keyIs128 = false; - break; - case 32: - k[0] = bytes2uint(key, 0); - k[1] = bytes2uint(key, 4); - k[2] = bytes2uint(key, 8); - k[3] = bytes2uint(key, 12); - k[4] = bytes2uint(key, 16); - k[5] = bytes2uint(key, 20); - k[6] = bytes2uint(key, 24); - k[7] = bytes2uint(key, 28); - _keyIs128 = false; - break; - default: - throw new ArgumentException("key sizes are only 16/24/32 bytes."); + case 16: + _keyIs128 = true; + Pack.BE_To_UInt32(key, 0, k, 0, 4); + k[4] = k[5] = k[6] = k[7] = 0; + break; + case 24: + Pack.BE_To_UInt32(key, 0, k, 0, 6); + k[6] = ~k[4]; + k[7] = ~k[5]; + _keyIs128 = false; + break; + case 32: + Pack.BE_To_UInt32(key, 0, k, 0, 8); + _keyIs128 = false; + break; + default: + throw new ArgumentException("key sizes are only 16/24/32 bytes."); } for (int i = 0; i < 4; i++) @@ -540,12 +506,78 @@ private void setKey(bool forEncryption, byte[] key) } } - private int processBlock128(byte[] input, int inOff, byte[] output, int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int ProcessBlock128(ReadOnlySpan input, Span output) + { + uint[] state = new uint[4]; + Pack.BE_To_UInt32(input, state); + + state[0] ^= kw[0]; + state[1] ^= kw[1]; + state[2] ^= kw[2]; + state[3] ^= kw[3]; + + camelliaF2(state, subkey, 0); + camelliaF2(state, subkey, 4); + camelliaF2(state, subkey, 8); + camelliaFLs(state, ke, 0); + camelliaF2(state, subkey, 12); + camelliaF2(state, subkey, 16); + camelliaF2(state, subkey, 20); + camelliaFLs(state, ke, 4); + camelliaF2(state, subkey, 24); + camelliaF2(state, subkey, 28); + camelliaF2(state, subkey, 32); + + Pack.UInt32_To_BE(state[2] ^ kw[4], output); + Pack.UInt32_To_BE(state[3] ^ kw[5], output[4..]); + Pack.UInt32_To_BE(state[0] ^ kw[6], output[8..]); + Pack.UInt32_To_BE(state[1] ^ kw[7], output[12..]); + + return BLOCK_SIZE; + } + + private int ProcessBlock192or256(ReadOnlySpan input, Span output) { + uint[] state = new uint[4]; + Pack.BE_To_UInt32(input, state); + + state[0] ^= kw[0]; + state[1] ^= kw[1]; + state[2] ^= kw[2]; + state[3] ^= kw[3]; + + camelliaF2(state, subkey, 0); + camelliaF2(state, subkey, 4); + camelliaF2(state, subkey, 8); + camelliaFLs(state, ke, 0); + camelliaF2(state, subkey, 12); + camelliaF2(state, subkey, 16); + camelliaF2(state, subkey, 20); + camelliaFLs(state, ke, 4); + camelliaF2(state, subkey, 24); + camelliaF2(state, subkey, 28); + camelliaF2(state, subkey, 32); + camelliaFLs(state, ke, 8); + camelliaF2(state, subkey, 36); + camelliaF2(state, subkey, 40); + camelliaF2(state, subkey, 44); + + Pack.UInt32_To_BE(state[2] ^ kw[4], output); + Pack.UInt32_To_BE(state[3] ^ kw[5], output[4..]); + Pack.UInt32_To_BE(state[0] ^ kw[6], output[8..]); + Pack.UInt32_To_BE(state[1] ^ kw[7], output[12..]); + + return BLOCK_SIZE; + } +#else + private int ProcessBlock128(byte[] input, int inOff, byte[] output, int outOff) + { + uint[] state = new uint[4]; + for (int i = 0; i < 4; i++) { - state[i] = bytes2uint(input, inOff + (i * 4)); - state[i] ^= kw[i]; + state[i] = Pack.BE_To_UInt32(input, inOff + (i * 4)) ^ kw[i]; } camelliaF2(state, subkey, 0); @@ -560,25 +592,21 @@ private int processBlock128(byte[] input, int inOff, byte[] output, int outOff) camelliaF2(state, subkey, 28); camelliaF2(state, subkey, 32); - state[2] ^= kw[4]; - state[3] ^= kw[5]; - state[0] ^= kw[6]; - state[1] ^= kw[7]; - - uint2bytes(state[2], output, outOff); - uint2bytes(state[3], output, outOff + 4); - uint2bytes(state[0], output, outOff + 8); - uint2bytes(state[1], output, outOff + 12); + Pack.UInt32_To_BE(state[2] ^ kw[4], output, outOff); + Pack.UInt32_To_BE(state[3] ^ kw[5], output, outOff + 4); + Pack.UInt32_To_BE(state[0] ^ kw[6], output, outOff + 8); + Pack.UInt32_To_BE(state[1] ^ kw[7], output, outOff + 12); return BLOCK_SIZE; } - private int processBlock192or256(byte[] input, int inOff, byte[] output, int outOff) + private int ProcessBlock192or256(byte[] input, int inOff, byte[] output, int outOff) { + uint[] state = new uint[4]; + for (int i = 0; i < 4; i++) { - state[i] = bytes2uint(input, inOff + (i * 4)); - state[i] ^= kw[i]; + state[i] = Pack.BE_To_UInt32(input, inOff + (i * 4)) ^ kw[i]; } camelliaF2(state, subkey, 0); @@ -597,17 +625,14 @@ private int processBlock192or256(byte[] input, int inOff, byte[] output, int out camelliaF2(state, subkey, 40); camelliaF2(state, subkey, 44); - state[2] ^= kw[4]; - state[3] ^= kw[5]; - state[0] ^= kw[6]; - state[1] ^= kw[7]; + Pack.UInt32_To_BE(state[2] ^ kw[4], output, outOff); + Pack.UInt32_To_BE(state[3] ^ kw[5], output, outOff + 4); + Pack.UInt32_To_BE(state[0] ^ kw[6], output, outOff + 8); + Pack.UInt32_To_BE(state[1] ^ kw[7], output, outOff + 12); - uint2bytes(state[2], output, outOff); - uint2bytes(state[3], output, outOff + 4); - uint2bytes(state[0], output, outOff + 8); - uint2bytes(state[1], output, outOff + 12); return BLOCK_SIZE; } +#endif public CamelliaEngine() { @@ -630,21 +655,12 @@ public virtual string AlgorithmName get { return "Camellia"; } } - 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) + public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { if (!initialised) throw new InvalidOperationException("Camellia engine not initialised"); @@ -652,20 +668,46 @@ public virtual int ProcessBlock( Check.DataLength(input, inOff, BLOCK_SIZE, "input buffer too short"); Check.OutputLength(output, outOff, BLOCK_SIZE, "output buffer too short"); - if (_keyIs128) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + if (_keyIs128) + { + return ProcessBlock128(input.AsSpan(inOff), output.AsSpan(outOff)); + } + else + { + return ProcessBlock192or256(input.AsSpan(inOff), output.AsSpan(outOff)); + } +#else + if (_keyIs128) { - return processBlock128(input, inOff, output, outOff); + return ProcessBlock128(input, inOff, output, outOff); } else { - return processBlock192or256(input, inOff, output, outOff); + return ProcessBlock192or256(input, inOff, output, outOff); } +#endif } - public virtual void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) { - // nothing + if (!initialised) + throw new InvalidOperationException("Camellia engine not initialised"); + + Check.DataLength(input, BLOCK_SIZE, "input buffer too short"); + Check.OutputLength(output, BLOCK_SIZE, "output buffer too short"); + + if (_keyIs128) + { + return ProcessBlock128(input, output); + } + else + { + return ProcessBlock192or256(input, output); + } } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/CamelliaLightEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/CamelliaLightEngine.cs index d5502c9..3f84723 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/CamelliaLightEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/CamelliaLightEngine.cs @@ -3,6 +3,7 @@ using System; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines { @@ -20,7 +21,6 @@ public class CamelliaLightEngine private uint[] subkey = new uint[24 * 4]; private uint[] kw = new uint[4 * 2]; // for whitening private uint[] ke = new uint[6 * 2]; // for FL and FL^(-1) - private uint[] state = new uint[4]; // for encryption and decryption private static readonly uint[] SIGMA = { 0xa09e667f, 0x3bcc908b, @@ -161,25 +161,6 @@ private static void decroldqo32(int rot, uint[] ki, int ioff, uint[] ko, int oof ki[3 + ioff] = ko[1 + ooff]; } - private static uint bytes2uint(byte[] src, int offset) - { - uint word = 0; - for (int i = 0; i < 4; i++) - { - word = (word << 8) + (uint)src[i + offset]; - } - return word; - } - - private static void uint2bytes(uint word, byte[] dst, int offset) - { - for (int i = 0; i < 4; i++) - { - dst[(3 - i) + offset] = (byte)word; - word >>= 8; - } - } - private byte lRot8(byte v, int rot) { return (byte)(((uint)v << rot) | ((uint)v >> (8 - rot))); @@ -261,38 +242,23 @@ private void setKey(bool forEncryption, byte[] key) switch (key.Length) { - case 16: - _keyis128 = true; - k[0] = bytes2uint(key, 0); - k[1] = bytes2uint(key, 4); - k[2] = bytes2uint(key, 8); - k[3] = bytes2uint(key, 12); - k[4] = k[5] = k[6] = k[7] = 0; - break; - case 24: - k[0] = bytes2uint(key, 0); - k[1] = bytes2uint(key, 4); - k[2] = bytes2uint(key, 8); - k[3] = bytes2uint(key, 12); - k[4] = bytes2uint(key, 16); - k[5] = bytes2uint(key, 20); - k[6] = ~k[4]; - k[7] = ~k[5]; - _keyis128 = false; - break; - case 32: - k[0] = bytes2uint(key, 0); - k[1] = bytes2uint(key, 4); - k[2] = bytes2uint(key, 8); - k[3] = bytes2uint(key, 12); - k[4] = bytes2uint(key, 16); - k[5] = bytes2uint(key, 20); - k[6] = bytes2uint(key, 24); - k[7] = bytes2uint(key, 28); - _keyis128 = false; - break; - default: - throw new ArgumentException("key sizes are only 16/24/32 bytes."); + case 16: + _keyis128 = true; + Pack.BE_To_UInt32(key, 0, k, 0, 4); + k[4] = k[5] = k[6] = k[7] = 0; + break; + case 24: + Pack.BE_To_UInt32(key, 0, k, 0, 6); + k[6] = ~k[4]; + k[7] = ~k[5]; + _keyis128 = false; + break; + case 32: + Pack.BE_To_UInt32(key, 0, k, 0, 8); + _keyis128 = false; + break; + default: + throw new ArgumentException("key sizes are only 16/24/32 bytes."); } for (int i = 0; i < 4; i++) @@ -452,12 +418,78 @@ private void setKey(bool forEncryption, byte[] key) } } - private int processBlock128(byte[] input, int inOff, byte[] output, int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int ProcessBlock128(ReadOnlySpan input, Span output) + { + uint[] state = new uint[4]; + Pack.BE_To_UInt32(input, state); + + state[0] ^= kw[0]; + state[1] ^= kw[1]; + state[2] ^= kw[2]; + state[3] ^= kw[3]; + + camelliaF2(state, subkey, 0); + camelliaF2(state, subkey, 4); + camelliaF2(state, subkey, 8); + camelliaFLs(state, ke, 0); + camelliaF2(state, subkey, 12); + camelliaF2(state, subkey, 16); + camelliaF2(state, subkey, 20); + camelliaFLs(state, ke, 4); + camelliaF2(state, subkey, 24); + camelliaF2(state, subkey, 28); + camelliaF2(state, subkey, 32); + + Pack.UInt32_To_BE(state[2] ^ kw[4], output); + Pack.UInt32_To_BE(state[3] ^ kw[5], output[4..]); + Pack.UInt32_To_BE(state[0] ^ kw[6], output[8..]); + Pack.UInt32_To_BE(state[1] ^ kw[7], output[12..]); + + return BLOCK_SIZE; + } + + private int ProcessBlock192or256(ReadOnlySpan input, Span output) { + uint[] state = new uint[4]; + Pack.BE_To_UInt32(input, state); + + state[0] ^= kw[0]; + state[1] ^= kw[1]; + state[2] ^= kw[2]; + state[3] ^= kw[3]; + + camelliaF2(state, subkey, 0); + camelliaF2(state, subkey, 4); + camelliaF2(state, subkey, 8); + camelliaFLs(state, ke, 0); + camelliaF2(state, subkey, 12); + camelliaF2(state, subkey, 16); + camelliaF2(state, subkey, 20); + camelliaFLs(state, ke, 4); + camelliaF2(state, subkey, 24); + camelliaF2(state, subkey, 28); + camelliaF2(state, subkey, 32); + camelliaFLs(state, ke, 8); + camelliaF2(state, subkey, 36); + camelliaF2(state, subkey, 40); + camelliaF2(state, subkey, 44); + + Pack.UInt32_To_BE(state[2] ^ kw[4], output); + Pack.UInt32_To_BE(state[3] ^ kw[5], output[4..]); + Pack.UInt32_To_BE(state[0] ^ kw[6], output[8..]); + Pack.UInt32_To_BE(state[1] ^ kw[7], output[12..]); + + return BLOCK_SIZE; + } +#else + private int ProcessBlock128(byte[] input, int inOff, byte[] output, int outOff) + { + uint[] state = new uint[4]; + for (int i = 0; i < 4; i++) { - state[i] = bytes2uint(input, inOff + (i * 4)); - state[i] ^= kw[i]; + state[i] = Pack.BE_To_UInt32(input, inOff + (i * 4)) ^ kw[i]; } camelliaF2(state, subkey, 0); @@ -472,25 +504,21 @@ private int processBlock128(byte[] input, int inOff, byte[] output, int outOff) camelliaF2(state, subkey, 28); camelliaF2(state, subkey, 32); - state[2] ^= kw[4]; - state[3] ^= kw[5]; - state[0] ^= kw[6]; - state[1] ^= kw[7]; - - uint2bytes(state[2], output, outOff); - uint2bytes(state[3], output, outOff + 4); - uint2bytes(state[0], output, outOff + 8); - uint2bytes(state[1], output, outOff + 12); + Pack.UInt32_To_BE(state[2] ^ kw[4], output, outOff); + Pack.UInt32_To_BE(state[3] ^ kw[5], output, outOff + 4); + Pack.UInt32_To_BE(state[0] ^ kw[6], output, outOff + 8); + Pack.UInt32_To_BE(state[1] ^ kw[7], output, outOff + 12); return BLOCK_SIZE; } - private int processBlock192or256(byte[] input, int inOff, byte[] output, int outOff) + private int ProcessBlock192or256(byte[] input, int inOff, byte[] output, int outOff) { + uint[] state = new uint[4]; + for (int i = 0; i < 4; i++) { - state[i] = bytes2uint(input, inOff + (i * 4)); - state[i] ^= kw[i]; + state[i] = Pack.BE_To_UInt32(input, inOff + (i * 4)) ^ kw[i]; } camelliaF2(state, subkey, 0); @@ -509,17 +537,14 @@ private int processBlock192or256(byte[] input, int inOff, byte[] output, int out camelliaF2(state, subkey, 40); camelliaF2(state, subkey, 44); - state[2] ^= kw[4]; - state[3] ^= kw[5]; - state[0] ^= kw[6]; - state[1] ^= kw[7]; + Pack.UInt32_To_BE(state[2] ^ kw[4], output, outOff); + Pack.UInt32_To_BE(state[3] ^ kw[5], output, outOff + 4); + Pack.UInt32_To_BE(state[0] ^ kw[6], output, outOff + 8); + Pack.UInt32_To_BE(state[1] ^ kw[7], output, outOff + 12); - uint2bytes(state[2], output, outOff); - uint2bytes(state[3], output, outOff + 4); - uint2bytes(state[0], output, outOff + 8); - uint2bytes(state[1], output, outOff + 12); return BLOCK_SIZE; } +#endif public CamelliaLightEngine() { @@ -531,11 +556,6 @@ public virtual string AlgorithmName get { return "Camellia"; } } - public virtual bool IsPartialBlockOkay - { - get { return false; } - } - public virtual int GetBlockSize() { return BLOCK_SIZE; @@ -553,11 +573,7 @@ public virtual void Init( initialised = true; } - public virtual int ProcessBlock( - byte[] input, - int inOff, - byte[] output, - int outOff) + public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { if (!initialised) throw new InvalidOperationException("Camellia engine not initialised"); @@ -565,19 +581,46 @@ public virtual int ProcessBlock( Check.DataLength(input, inOff, BLOCK_SIZE, "input buffer too short"); Check.OutputLength(output, outOff, BLOCK_SIZE, "output buffer too short"); - if (_keyis128) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + if (_keyis128) + { + return ProcessBlock128(input.AsSpan(inOff), output.AsSpan(outOff)); + } + else + { + return ProcessBlock192or256(input.AsSpan(inOff), output.AsSpan(outOff)); + } +#else + if (_keyis128) { - return processBlock128(input, inOff, output, outOff); + return ProcessBlock128(input, inOff, output, outOff); } else { - return processBlock192or256(input, inOff, output, outOff); + return ProcessBlock192or256(input, inOff, output, outOff); } +#endif } - public virtual void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) { + if (!initialised) + throw new InvalidOperationException("Camellia engine not initialised"); + + Check.DataLength(input, BLOCK_SIZE, "input buffer too short"); + Check.OutputLength(output, BLOCK_SIZE, "output buffer too short"); + + if (_keyis128) + { + return ProcessBlock128(input, output); + } + else + { + return ProcessBlock192or256(input, output); + } } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Cast5Engine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Cast5Engine.cs index 1c5eb9d..c083f02 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Cast5Engine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Cast5Engine.cs @@ -337,7 +337,7 @@ public virtual void Init( ICipherParameters parameters) { if (!(parameters is KeyParameter)) - throw new ArgumentException("Invalid parameter passed to "+ AlgorithmName +" init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + throw new ArgumentException("Invalid parameter passed to "+ AlgorithmName +" init - " + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); _encrypting = forEncryption; _workingKey = ((KeyParameter)parameters).GetKey(); @@ -349,24 +349,25 @@ public virtual string AlgorithmName get { return "CAST5"; } } - public virtual bool IsPartialBlockOkay - { - get { return false; } - } - - public virtual int ProcessBlock( - byte[] input, - int inOff, - byte[] output, - int outOff) + public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { - int blockSize = GetBlockSize(); if (_workingKey == null) throw new InvalidOperationException(AlgorithmName + " not initialised"); + int blockSize = GetBlockSize(); Check.DataLength(input, inOff, blockSize, "input buffer too short"); Check.OutputLength(output, outOff, blockSize, "output buffer too short"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + if (_encrypting) + { + return EncryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); + } + else + { + return DecryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); + } +#else if (_encrypting) { return EncryptBlock(input, inOff, output, outOff); @@ -375,11 +376,29 @@ public virtual int ProcessBlock( { return DecryptBlock(input, inOff, output, outOff); } +#endif } - public virtual void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) { + if (_workingKey == null) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + + int blockSize = GetBlockSize(); + Check.DataLength(input, blockSize, "input buffer too short"); + Check.OutputLength(output, blockSize, "output buffer too short"); + + if (_encrypting) + { + return EncryptBlock(input, output); + } + else + { + return DecryptBlock(input, output); + } } +#endif public virtual int GetBlockSize() { @@ -568,20 +587,45 @@ internal virtual void SetKey(byte[] key) _Kr[16]=(int)((S5[x[0xE]]^S6[x[0xF]]^S7[x[0x1]]^S8[x[0x0]]^S8[x[0xD]])&0x1f); } - /** - * Encrypt the given input starting at the given offset and place - * the result in the provided buffer starting at the given offset. - * - * @param src The plaintext buffer - * @param srcIndex An offset into src - * @param dst The ciphertext buffer - * @param dstIndex An offset into dst - */ - internal virtual int EncryptBlock( - byte[] src, - int srcIndex, - byte[] dst, - int dstIndex) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal virtual int EncryptBlock(ReadOnlySpan input, Span output) + { + // process the input block + // batch the units up into a 32 bit chunk and go for it + // the array is in bytes, the increment is 8x8 bits = 64 + + uint L0 = Pack.BE_To_UInt32(input); + uint R0 = Pack.BE_To_UInt32(input[4..]); + + uint[] result = new uint[2]; + CAST_Encipher(L0, R0, result); + + // now stuff them into the destination block + Pack.UInt32_To_BE(result[0], output); + Pack.UInt32_To_BE(result[1], output[4..]); + + return BLOCK_SIZE; + } + + internal virtual int DecryptBlock(ReadOnlySpan input, Span output) + { + // process the input block + // batch the units up into a 32 bit chunk and go for it + // the array is in bytes, the increment is 8x8 bits = 64 + uint L16 = Pack.BE_To_UInt32(input); + uint R16 = Pack.BE_To_UInt32(input[4..]); + + uint[] result = new uint[2]; + CAST_Decipher(L16, R16, result); + + // now stuff them into the destination block + Pack.UInt32_To_BE(result[0], output); + Pack.UInt32_To_BE(result[1], output[4..]); + + return BLOCK_SIZE; + } +#else + internal virtual int EncryptBlock(byte[] src, int srcIndex, byte[] dst, int dstIndex) { // process the input block // batch the units up into a 32 bit chunk and go for it @@ -600,20 +644,7 @@ internal virtual int EncryptBlock( return BLOCK_SIZE; } - /** - * Decrypt the given input starting at the given offset and place - * the result in the provided buffer starting at the given offset. - * - * @param src The plaintext buffer - * @param srcIndex An offset into src - * @param dst The ciphertext buffer - * @param dstIndex An offset into dst - */ - internal virtual int DecryptBlock( - byte[] src, - int srcIndex, - byte[] dst, - int dstIndex) + internal virtual int DecryptBlock(byte[] src, int srcIndex, byte[] dst, int dstIndex) { // process the input block // batch the units up into a 32 bit chunk and go for it @@ -630,6 +661,7 @@ internal virtual int DecryptBlock( return BLOCK_SIZE; } +#endif /** * The first of the three processing functions for the @@ -704,28 +736,28 @@ internal void CAST_Encipher(uint L0, uint R0, uint[] result) Li = Rp; switch (i) { - case 1: - case 4: - case 7: - case 10: - case 13: - case 16: - Ri = Lp ^ F1(Rp, _Km[i], _Kr[i]); - break; - case 2: - case 5: - case 8: - case 11: - case 14: - Ri = Lp ^ F2(Rp, _Km[i], _Kr[i]); - break; - case 3: - case 6: - case 9: - case 12: - case 15: - Ri = Lp ^ F3(Rp, _Km[i], _Kr[i]); - break; + case 1: + case 4: + case 7: + case 10: + case 13: + case 16: + Ri = Lp ^ F1(Rp, _Km[i], _Kr[i]); + break; + case 2: + case 5: + case 8: + case 11: + case 14: + Ri = Lp ^ F2(Rp, _Km[i], _Kr[i]); + break; + case 3: + case 6: + case 9: + case 12: + case 15: + Ri = Lp ^ F3(Rp, _Km[i], _Kr[i]); + break; } } @@ -754,28 +786,28 @@ internal void CAST_Decipher(uint L16, uint R16, uint[] result) Li = Rp; switch (i) { - case 1: - case 4: - case 7: - case 10: - case 13: - case 16: - Ri = Lp ^ F1(Rp, _Km[i], _Kr[i]); - break; - case 2: - case 5: - case 8: - case 11: - case 14: - Ri = Lp ^ F2(Rp, _Km[i], _Kr[i]); - break; - case 3: - case 6: - case 9: - case 12: - case 15: - Ri = Lp ^ F3(Rp, _Km[i], _Kr[i]); - break; + case 1: + case 4: + case 7: + case 10: + case 13: + case 16: + Ri = Lp ^ F1(Rp, _Km[i], _Kr[i]); + break; + case 2: + case 5: + case 8: + case 11: + case 14: + Ri = Lp ^ F2(Rp, _Km[i], _Kr[i]); + break; + case 3: + case 6: + case 9: + case 12: + case 15: + Ri = Lp ^ F3(Rp, _Km[i], _Kr[i]); + break; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Cast6Engine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Cast6Engine.cs index 028d70c..c389045 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Cast6Engine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Cast6Engine.cs @@ -48,10 +48,6 @@ public override string AlgorithmName get { return "CAST6"; } } - public override void Reset() - { - } - public override int GetBlockSize() { return BLOCK_SIZE; @@ -136,20 +132,44 @@ internal override void SetKey( } } - /** - * Encrypt the given input starting at the given offset and place - * the result in the provided buffer starting at the given offset. - * - * @param src The plaintext buffer - * @param srcIndex An offset into src - * @param dst The ciphertext buffer - * @param dstIndex An offset into dst - */ - internal override int EncryptBlock( - byte[] src, - int srcIndex, - byte[] dst, - int dstIndex) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal override int EncryptBlock(ReadOnlySpan input, Span output) + { + // process the input block + // batch the units up into 4x32 bit chunks and go for it + uint A = Pack.BE_To_UInt32(input); + uint B = Pack.BE_To_UInt32(input[4..]); + uint C = Pack.BE_To_UInt32(input[8..]); + uint D = Pack.BE_To_UInt32(input[12..]); + uint[] result = new uint[4]; + CAST_Encipher(A, B, C, D, result); + // now stuff them into the destination block + Pack.UInt32_To_BE(result[0], output); + Pack.UInt32_To_BE(result[1], output[4..]); + Pack.UInt32_To_BE(result[2], output[8..]); + Pack.UInt32_To_BE(result[3], output[12..]); + return BLOCK_SIZE; + } + + internal override int DecryptBlock(ReadOnlySpan input, Span output) + { + // process the input block + // batch the units up into 4x32 bit chunks and go for it + uint A = Pack.BE_To_UInt32(input); + uint B = Pack.BE_To_UInt32(input[4..]); + uint C = Pack.BE_To_UInt32(input[8..]); + uint D = Pack.BE_To_UInt32(input[12..]); + uint[] result = new uint[4]; + CAST_Decipher(A, B, C, D, result); + // now stuff them into the destination block + Pack.UInt32_To_BE(result[0], output); + Pack.UInt32_To_BE(result[1], output[4..]); + Pack.UInt32_To_BE(result[2], output[8..]); + Pack.UInt32_To_BE(result[3], output[12..]); + return BLOCK_SIZE; + } +#else + internal override int EncryptBlock(byte[] src, int srcIndex, byte[] dst, int dstIndex) { // process the input block // batch the units up into 4x32 bit chunks and go for it @@ -167,20 +187,7 @@ internal override int EncryptBlock( return BLOCK_SIZE; } - /** - * Decrypt the given input starting at the given offset and place - * the result in the provided buffer starting at the given offset. - * - * @param src The plaintext buffer - * @param srcIndex An offset into src - * @param dst The ciphertext buffer - * @param dstIndex An offset into dst - */ - internal override int DecryptBlock( - byte[] src, - int srcIndex, - byte[] dst, - int dstIndex) + internal override int DecryptBlock(byte[] src, int srcIndex, byte[] dst, int dstIndex) { // process the input block // batch the units up into 4x32 bit chunks and go for it @@ -197,8 +204,9 @@ internal override int DecryptBlock( Pack.UInt32_To_BE(result[3], dst, dstIndex + 12); return BLOCK_SIZE; } +#endif - /** + /** * Does the 12 quad rounds rounds to encrypt the block. * * @param A the 00-31 bits of the plaintext block diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ChaCha7539Engine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ChaCha7539Engine.cs index 22536f7..255c837 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ChaCha7539Engine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ChaCha7539Engine.cs @@ -1,6 +1,16 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Diagnostics; +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER +using System.Runtime.CompilerServices; +#endif +#if NETCOREAPP3_0_OR_GREATER +using System.Buffers.Binary; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; @@ -9,10 +19,6 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines /// /// Implementation of Daniel J. Bernstein's ChaCha stream cipher. /// - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] public class ChaCha7539Engine : Salsa20Engine { @@ -64,11 +70,456 @@ protected override void SetKey(byte[] keyBytes, byte[] ivBytes) protected override void GenerateKeyStream(byte[] output) { - ChaChaEngine.ChachaCore(rounds, engineState, x); - Pack.UInt32_To_LE(x, output, 0); + ChaChaEngine.ChachaCore(rounds, engineState, output); } - } -} + internal void DoFinal(byte[] inBuf, int inOff, int inLen, byte[] outBuf, int outOff) + { + if (!initialised) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + if (index != 0) + throw new InvalidOperationException(AlgorithmName + " not in block-aligned state"); + + Check.DataLength(inBuf, inOff, inLen, "input buffer too short"); + Check.OutputLength(outBuf, outOff, inLen, "output buffer too short"); + + while (inLen >= 128) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ProcessBlocks2(inBuf.AsSpan(inOff), outBuf.AsSpan(outOff)); +#else + ProcessBlocks2(inBuf, inOff, outBuf, outOff); +#endif + inOff += 128; + inLen -= 128; + outOff += 128; + } + + if (inLen >= 64) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ImplProcessBlock(inBuf.AsSpan(inOff), outBuf.AsSpan(outOff)); +#else + ImplProcessBlock(inBuf, inOff, outBuf, outOff); +#endif + inOff += 64; + inLen -= 64; + outOff += 64; + } + + if (inLen > 0) + { + GenerateKeyStream(keyStream); + AdvanceCounter(); + + for (int i = 0; i < inLen; ++i) + { + outBuf[outOff + i] = (byte)(inBuf[i + inOff] ^ keyStream[i]); + } + } + + engineState[12] = 0; + + // TODO Prevent re-use if encrypting + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal void ProcessBlock(ReadOnlySpan input, Span output) + { + if (!initialised) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + if (LimitExceeded(64U)) + throw new MaxBytesExceededException("2^38 byte limit per IV would be exceeded; Change IV"); + + Debug.Assert(index == 0); + + ImplProcessBlock(input, output); + } + + internal void ProcessBlocks2(ReadOnlySpan input, Span output) + { + if (!initialised) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + if (LimitExceeded(128U)) + throw new MaxBytesExceededException("2^38 byte limit per IV would be exceeded; Change IV"); + + Debug.Assert(index == 0); + +#if NETCOREAPP3_0_OR_GREATER + if (Avx2.IsSupported) + { + ImplProcessBlocks2_X86_Avx2(rounds, engineState, input, output); + return; + } + + if (Sse2.IsSupported) + { + ImplProcessBlocks2_X86_Sse2(rounds, engineState, input, output); + return; + } +#endif + + { + ImplProcessBlock(input, output); + ImplProcessBlock(input[64..], output[64..]); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void ImplProcessBlock(ReadOnlySpan input, Span output) + { + ChaChaEngine.ChachaCore(rounds, engineState, keyStream); + AdvanceCounter(); + + for (int i = 0; i < 64; ++i) + { + output[i] = (byte)(keyStream[i] ^ input[i]); + } + } +#else + internal void ProcessBlock(byte[] inBytes, int inOff, byte[] outBytes, int outOff) + { + if (!initialised) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + if (LimitExceeded(64U)) + throw new MaxBytesExceededException("2^38 byte limit per IV would be exceeded; Change IV"); + + Debug.Assert(index == 0); + + ImplProcessBlock(inBytes, inOff, outBytes, outOff); + } + + internal void ProcessBlocks2(byte[] inBytes, int inOff, byte[] outBytes, int outOff) + { + if (!initialised) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + if (LimitExceeded(128U)) + throw new MaxBytesExceededException("2^38 byte limit per IV would be exceeded; Change IV"); + + Debug.Assert(index == 0); + + { + ImplProcessBlock(inBytes, inOff, outBytes, outOff); + ImplProcessBlock(inBytes, inOff + 64, outBytes, outOff + 64); + } + } + +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif + internal void ImplProcessBlock(byte[] inBuf, int inOff, byte[] outBuf, int outOff) + { + ChaChaEngine.ChachaCore(rounds, engineState, keyStream); + AdvanceCounter(); + + for (int i = 0; i < 64; ++i) + { + outBuf[outOff + i] = (byte)(keyStream[i] ^ inBuf[inOff + i]); + } + } +#endif + +#if NETCOREAPP3_0_OR_GREATER + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void ImplProcessBlocks2_X86_Avx2(int rounds, uint[] state, ReadOnlySpan input, + Span output) + { + if (!Avx2.IsSupported) + throw new PlatformNotSupportedException(); + + Debug.Assert(rounds % 2 == 0); + Debug.Assert(state.Length >= 16); + Debug.Assert(input.Length >= 128); + Debug.Assert(output.Length >= 128); + + var t0 = Load128_UInt32(state.AsSpan()); + var t1 = Load128_UInt32(state.AsSpan(4)); + var t2 = Load128_UInt32(state.AsSpan(8)); + var t3 = Load128_UInt32(state.AsSpan(12)); + ++state[12]; + var t4 = Load128_UInt32(state.AsSpan(12)); + ++state[12]; + + var x0 = Vector256.Create(t0, t0); + var x1 = Vector256.Create(t1, t1); + var x2 = Vector256.Create(t2, t2); + var x3 = Vector256.Create(t3, t4); + + var v0 = x0; + var v1 = x1; + var v2 = x2; + var v3 = x3; + + for (int i = rounds; i > 0; i -= 2) + { + v0 = Avx2.Add(v0, v1); + v3 = Avx2.Xor(v3, v0); + v3 = Avx2.Xor(Avx2.ShiftLeftLogical(v3, 16), Avx2.ShiftRightLogical(v3, 16)); + v2 = Avx2.Add(v2, v3); + v1 = Avx2.Xor(v1, v2); + v1 = Avx2.Xor(Avx2.ShiftLeftLogical(v1, 12), Avx2.ShiftRightLogical(v1, 20)); + v0 = Avx2.Add(v0, v1); + v3 = Avx2.Xor(v3, v0); + v3 = Avx2.Xor(Avx2.ShiftLeftLogical(v3, 8), Avx2.ShiftRightLogical(v3, 24)); + v2 = Avx2.Add(v2, v3); + v1 = Avx2.Xor(v1, v2); + v1 = Avx2.Xor(Avx2.ShiftLeftLogical(v1, 7), Avx2.ShiftRightLogical(v1, 25)); + + v1 = Avx2.Shuffle(v1, 0x39); + v2 = Avx2.Shuffle(v2, 0x4E); + v3 = Avx2.Shuffle(v3, 0x93); + + v0 = Avx2.Add(v0, v1); + v3 = Avx2.Xor(v3, v0); + v3 = Avx2.Xor(Avx2.ShiftLeftLogical(v3, 16), Avx2.ShiftRightLogical(v3, 16)); + v2 = Avx2.Add(v2, v3); + v1 = Avx2.Xor(v1, v2); + v1 = Avx2.Xor(Avx2.ShiftLeftLogical(v1, 12), Avx2.ShiftRightLogical(v1, 20)); + v0 = Avx2.Add(v0, v1); + v3 = Avx2.Xor(v3, v0); + v3 = Avx2.Xor(Avx2.ShiftLeftLogical(v3, 8), Avx2.ShiftRightLogical(v3, 24)); + v2 = Avx2.Add(v2, v3); + v1 = Avx2.Xor(v1, v2); + v1 = Avx2.Xor(Avx2.ShiftLeftLogical(v1, 7), Avx2.ShiftRightLogical(v1, 25)); + + v1 = Avx2.Shuffle(v1, 0x93); + v2 = Avx2.Shuffle(v2, 0x4E); + v3 = Avx2.Shuffle(v3, 0x39); + } + + v0 = Avx2.Add(v0, x0); + v1 = Avx2.Add(v1, x1); + v2 = Avx2.Add(v2, x2); + v3 = Avx2.Add(v3, x3); + + var n0 = Avx2.Permute2x128(v0, v1, 0x20).AsByte(); + var n1 = Avx2.Permute2x128(v2, v3, 0x20).AsByte(); + var n2 = Avx2.Permute2x128(v0, v1, 0x31).AsByte(); + var n3 = Avx2.Permute2x128(v2, v3, 0x31).AsByte(); + + n0 = Avx2.Xor(n0, Load256_Byte(input)); + n1 = Avx2.Xor(n1, Load256_Byte(input[0x20..])); + n2 = Avx2.Xor(n2, Load256_Byte(input[0x40..])); + n3 = Avx2.Xor(n3, Load256_Byte(input[0x60..])); + + Store256_Byte(n0, output); + Store256_Byte(n1, output[0x20..]); + Store256_Byte(n2, output[0x40..]); + Store256_Byte(n3, output[0x60..]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void ImplProcessBlocks2_X86_Sse2(int rounds, uint[] state, ReadOnlySpan input, + Span output) + { + if (!Sse2.IsSupported) + throw new PlatformNotSupportedException(); + + Debug.Assert(rounds % 2 == 0); + Debug.Assert(state.Length >= 16); + Debug.Assert(input.Length >= 128); + Debug.Assert(output.Length >= 128); + + var x0 = Load128_UInt32(state.AsSpan()); + var x1 = Load128_UInt32(state.AsSpan(4)); + var x2 = Load128_UInt32(state.AsSpan(8)); + var x3 = Load128_UInt32(state.AsSpan(12)); + ++state[12]; + + var v0 = x0; + var v1 = x1; + var v2 = x2; + var v3 = x3; + + for (int i = rounds; i > 0; i -= 2) + { + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 16), Sse2.ShiftRightLogical(v3, 16)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 12), Sse2.ShiftRightLogical(v1, 20)); + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 8), Sse2.ShiftRightLogical(v3, 24)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 7), Sse2.ShiftRightLogical(v1, 25)); + + v1 = Sse2.Shuffle(v1, 0x39); + v2 = Sse2.Shuffle(v2, 0x4E); + v3 = Sse2.Shuffle(v3, 0x93); + + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 16), Sse2.ShiftRightLogical(v3, 16)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 12), Sse2.ShiftRightLogical(v1, 20)); + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 8), Sse2.ShiftRightLogical(v3, 24)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 7), Sse2.ShiftRightLogical(v1, 25)); + + v1 = Sse2.Shuffle(v1, 0x93); + v2 = Sse2.Shuffle(v2, 0x4E); + v3 = Sse2.Shuffle(v3, 0x39); + } + + v0 = Sse2.Add(v0, x0); + v1 = Sse2.Add(v1, x1); + v2 = Sse2.Add(v2, x2); + v3 = Sse2.Add(v3, x3); + + var n0 = Load128_Byte(input); + var n1 = Load128_Byte(input[0x10..]); + var n2 = Load128_Byte(input[0x20..]); + var n3 = Load128_Byte(input[0x30..]); + + n0 = Sse2.Xor(n0, v0.AsByte()); + n1 = Sse2.Xor(n1, v1.AsByte()); + n2 = Sse2.Xor(n2, v2.AsByte()); + n3 = Sse2.Xor(n3, v3.AsByte()); + + Store128_Byte(n0, output); + Store128_Byte(n1, output[0x10..]); + Store128_Byte(n2, output[0x20..]); + Store128_Byte(n3, output[0x30..]); + + x3 = Load128_UInt32(state.AsSpan(12)); + ++state[12]; + + v0 = x0; + v1 = x1; + v2 = x2; + v3 = x3; + + for (int i = rounds; i > 0; i -= 2) + { + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 16), Sse2.ShiftRightLogical(v3, 16)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 12), Sse2.ShiftRightLogical(v1, 20)); + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 8), Sse2.ShiftRightLogical(v3, 24)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 7), Sse2.ShiftRightLogical(v1, 25)); + + v1 = Sse2.Shuffle(v1, 0x39); + v2 = Sse2.Shuffle(v2, 0x4E); + v3 = Sse2.Shuffle(v3, 0x93); + + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 16), Sse2.ShiftRightLogical(v3, 16)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 12), Sse2.ShiftRightLogical(v1, 20)); + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 8), Sse2.ShiftRightLogical(v3, 24)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 7), Sse2.ShiftRightLogical(v1, 25)); + + v1 = Sse2.Shuffle(v1, 0x93); + v2 = Sse2.Shuffle(v2, 0x4E); + v3 = Sse2.Shuffle(v3, 0x39); + } + + v0 = Sse2.Add(v0, x0); + v1 = Sse2.Add(v1, x1); + v2 = Sse2.Add(v2, x2); + v3 = Sse2.Add(v3, x3); + + n0 = Load128_Byte(input[0x40..]); + n1 = Load128_Byte(input[0x50..]); + n2 = Load128_Byte(input[0x60..]); + n3 = Load128_Byte(input[0x70..]); + + n0 = Sse2.Xor(n0, v0.AsByte()); + n1 = Sse2.Xor(n1, v1.AsByte()); + n2 = Sse2.Xor(n2, v2.AsByte()); + n3 = Sse2.Xor(n3, v3.AsByte()); + + Store128_Byte(n0, output[0x40..]); + Store128_Byte(n1, output[0x50..]); + Store128_Byte(n2, output[0x60..]); + Store128_Byte(n3, output[0x70..]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector128 Load128_Byte(ReadOnlySpan t) + { + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 16) + return MemoryMarshal.Read>(t); + + return Vector128.Create( + BinaryPrimitives.ReadUInt64LittleEndian(t[..8]), + BinaryPrimitives.ReadUInt64LittleEndian(t[8..]) + ).AsByte(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector128 Load128_UInt32(ReadOnlySpan t) + { + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 16) + return MemoryMarshal.Read>(MemoryMarshal.AsBytes(t)); + + return Vector128.Create(t[0], t[1], t[2], t[3]); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector256 Load256_Byte(ReadOnlySpan t) + { + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 32) + return MemoryMarshal.Read>(t); + + return Vector256.Create( + BinaryPrimitives.ReadUInt64LittleEndian(t[ 0.. 8]), + BinaryPrimitives.ReadUInt64LittleEndian(t[ 8..16]), + BinaryPrimitives.ReadUInt64LittleEndian(t[16..24]), + BinaryPrimitives.ReadUInt64LittleEndian(t[24..32]) + ).AsByte(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Store128_Byte(Vector128 s, Span t) + { + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 16) + { + MemoryMarshal.Write(t, ref s); + return; + } + + var u = s.AsUInt64(); + BinaryPrimitives.WriteUInt64LittleEndian(t[..8], u.GetElement(0)); + BinaryPrimitives.WriteUInt64LittleEndian(t[8..], u.GetElement(1)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Store256_Byte(Vector256 s, Span t) + { + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 32) + { + MemoryMarshal.Write(t, ref s); + return; + } + + var u = s.AsUInt64(); + BinaryPrimitives.WriteUInt64LittleEndian(t[ 0.. 8], u.GetElement(0)); + BinaryPrimitives.WriteUInt64LittleEndian(t[ 8..16], u.GetElement(1)); + BinaryPrimitives.WriteUInt64LittleEndian(t[16..24], u.GetElement(2)); + BinaryPrimitives.WriteUInt64LittleEndian(t[24..32], u.GetElement(3)); + } +#endif + } +} #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ChaChaEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ChaChaEngine.cs index 03bf59d..160d03c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ChaChaEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ChaChaEngine.cs @@ -1,6 +1,14 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Diagnostics; +#if NETCOREAPP3_0_OR_GREATER +using System.Buffers.Binary; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -10,11 +18,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines /// /// Implementation of Daniel J. Bernstein's ChaCha stream cipher. /// - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] - public sealed class ChaChaEngine + public class ChaChaEngine : Salsa20Engine { /// @@ -71,95 +75,170 @@ protected override void SetKey(byte[] keyBytes, byte[] ivBytes) protected override void GenerateKeyStream(byte[] output) { - ChachaCore(rounds, engineState, x); - Pack.UInt32_To_LE(x, output, 0); - } + ChachaCore(rounds, engineState, output); + } - /// - /// ChaCha function. - /// - /// The number of ChaCha rounds to execute - /// The input words. - /// The ChaCha state to modify. - internal static void ChachaCore(int rounds, uint[] input, uint[] x) + internal static void ChachaCore(int rounds, uint[] input, byte[] output) + { + Debug.Assert(rounds % 2 == 0); + Debug.Assert(input.Length >= 16); + Debug.Assert(output.Length >= 64); + +#if NETCOREAPP3_0_OR_GREATER + if (Sse2.IsSupported) + { + var x0 = Load128_UInt32(input.AsSpan()); + var x1 = Load128_UInt32(input.AsSpan(4)); + var x2 = Load128_UInt32(input.AsSpan(8)); + var x3 = Load128_UInt32(input.AsSpan(12)); + + var v0 = x0; + var v1 = x1; + var v2 = x2; + var v3 = x3; + + for (int i = rounds; i > 0; i -= 2) + { + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 16), Sse2.ShiftRightLogical(v3, 16)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 12), Sse2.ShiftRightLogical(v1, 20)); + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 8), Sse2.ShiftRightLogical(v3, 24)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 7), Sse2.ShiftRightLogical(v1, 25)); + + v1 = Sse2.Shuffle(v1, 0x39); + v2 = Sse2.Shuffle(v2, 0x4E); + v3 = Sse2.Shuffle(v3, 0x93); + + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 16), Sse2.ShiftRightLogical(v3, 16)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 12), Sse2.ShiftRightLogical(v1, 20)); + v0 = Sse2.Add(v0, v1); + v3 = Sse2.Xor(v3, v0); + v3 = Sse2.Xor(Sse2.ShiftLeftLogical(v3, 8), Sse2.ShiftRightLogical(v3, 24)); + v2 = Sse2.Add(v2, v3); + v1 = Sse2.Xor(v1, v2); + v1 = Sse2.Xor(Sse2.ShiftLeftLogical(v1, 7), Sse2.ShiftRightLogical(v1, 25)); + + v1 = Sse2.Shuffle(v1, 0x93); + v2 = Sse2.Shuffle(v2, 0x4E); + v3 = Sse2.Shuffle(v3, 0x39); + } + + v0 = Sse2.Add(v0, x0); + v1 = Sse2.Add(v1, x1); + v2 = Sse2.Add(v2, x2); + v3 = Sse2.Add(v3, x3); + + Store128_UInt32(v0, output.AsSpan()); + Store128_UInt32(v1, output.AsSpan(0x10)); + Store128_UInt32(v2, output.AsSpan(0x20)); + Store128_UInt32(v3, output.AsSpan(0x30)); + return; + } +#endif + + { + uint x00 = input[ 0], x01 = input[ 1], x02 = input[ 2], x03 = input[ 3]; + uint x04 = input[ 4], x05 = input[ 5], x06 = input[ 6], x07 = input[ 7]; + uint x08 = input[ 8], x09 = input[ 9], x10 = input[10], x11 = input[11]; + uint x12 = input[12], x13 = input[13], x14 = input[14], x15 = input[15]; + + for (int i = rounds; i > 0; i -= 2) + { + x00 += x04; x12 = Integers.RotateLeft(x12 ^ x00, 16); + x01 += x05; x13 = Integers.RotateLeft(x13 ^ x01, 16); + x02 += x06; x14 = Integers.RotateLeft(x14 ^ x02, 16); + x03 += x07; x15 = Integers.RotateLeft(x15 ^ x03, 16); + + x08 += x12; x04 = Integers.RotateLeft(x04 ^ x08, 12); + x09 += x13; x05 = Integers.RotateLeft(x05 ^ x09, 12); + x10 += x14; x06 = Integers.RotateLeft(x06 ^ x10, 12); + x11 += x15; x07 = Integers.RotateLeft(x07 ^ x11, 12); + + x00 += x04; x12 = Integers.RotateLeft(x12 ^ x00, 8); + x01 += x05; x13 = Integers.RotateLeft(x13 ^ x01, 8); + x02 += x06; x14 = Integers.RotateLeft(x14 ^ x02, 8); + x03 += x07; x15 = Integers.RotateLeft(x15 ^ x03, 8); + + x08 += x12; x04 = Integers.RotateLeft(x04 ^ x08, 7); + x09 += x13; x05 = Integers.RotateLeft(x05 ^ x09, 7); + x10 += x14; x06 = Integers.RotateLeft(x06 ^ x10, 7); + x11 += x15; x07 = Integers.RotateLeft(x07 ^ x11, 7); + + x00 += x05; x15 = Integers.RotateLeft(x15 ^ x00, 16); + x01 += x06; x12 = Integers.RotateLeft(x12 ^ x01, 16); + x02 += x07; x13 = Integers.RotateLeft(x13 ^ x02, 16); + x03 += x04; x14 = Integers.RotateLeft(x14 ^ x03, 16); + + x10 += x15; x05 = Integers.RotateLeft(x05 ^ x10, 12); + x11 += x12; x06 = Integers.RotateLeft(x06 ^ x11, 12); + x08 += x13; x07 = Integers.RotateLeft(x07 ^ x08, 12); + x09 += x14; x04 = Integers.RotateLeft(x04 ^ x09, 12); + + x00 += x05; x15 = Integers.RotateLeft(x15 ^ x00, 8); + x01 += x06; x12 = Integers.RotateLeft(x12 ^ x01, 8); + x02 += x07; x13 = Integers.RotateLeft(x13 ^ x02, 8); + x03 += x04; x14 = Integers.RotateLeft(x14 ^ x03, 8); + + x10 += x15; x05 = Integers.RotateLeft(x05 ^ x10, 7); + x11 += x12; x06 = Integers.RotateLeft(x06 ^ x11, 7); + x08 += x13; x07 = Integers.RotateLeft(x07 ^ x08, 7); + x09 += x14; x04 = Integers.RotateLeft(x04 ^ x09, 7); + } + + Pack.UInt32_To_LE(x00 + input[ 0], output, 0); + Pack.UInt32_To_LE(x01 + input[ 1], output, 4); + Pack.UInt32_To_LE(x02 + input[ 2], output, 8); + Pack.UInt32_To_LE(x03 + input[ 3], output, 12); + Pack.UInt32_To_LE(x04 + input[ 4], output, 16); + Pack.UInt32_To_LE(x05 + input[ 5], output, 20); + Pack.UInt32_To_LE(x06 + input[ 6], output, 24); + Pack.UInt32_To_LE(x07 + input[ 7], output, 28); + Pack.UInt32_To_LE(x08 + input[ 8], output, 32); + Pack.UInt32_To_LE(x09 + input[ 9], output, 36); + Pack.UInt32_To_LE(x10 + input[10], output, 40); + Pack.UInt32_To_LE(x11 + input[11], output, 44); + Pack.UInt32_To_LE(x12 + input[12], output, 48); + Pack.UInt32_To_LE(x13 + input[13], output, 52); + Pack.UInt32_To_LE(x14 + input[14], output, 56); + Pack.UInt32_To_LE(x15 + input[15], output, 60); + } + } + +#if NETCOREAPP3_0_OR_GREATER + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector128 Load128_UInt32(ReadOnlySpan t) { - if (input.Length != 16) - throw new ArgumentException(); - if (x.Length != 16) - throw new ArgumentException(); - if (rounds % 2 != 0) - throw new ArgumentException("Number of rounds must be even"); - - uint x00 = input[ 0]; - uint x01 = input[ 1]; - uint x02 = input[ 2]; - uint x03 = input[ 3]; - uint x04 = input[ 4]; - uint x05 = input[ 5]; - uint x06 = input[ 6]; - uint x07 = input[ 7]; - uint x08 = input[ 8]; - uint x09 = input[ 9]; - uint x10 = input[10]; - uint x11 = input[11]; - uint x12 = input[12]; - uint x13 = input[13]; - uint x14 = input[14]; - uint x15 = input[15]; - - for (int i = rounds; i > 0; i -= 2) - { - x00 += x04; x12 = Integers.RotateLeft(x12 ^ x00, 16); - x08 += x12; x04 = Integers.RotateLeft(x04 ^ x08, 12); - x00 += x04; x12 = Integers.RotateLeft(x12 ^ x00, 8); - x08 += x12; x04 = Integers.RotateLeft(x04 ^ x08, 7); - x01 += x05; x13 = Integers.RotateLeft(x13 ^ x01, 16); - x09 += x13; x05 = Integers.RotateLeft(x05 ^ x09, 12); - x01 += x05; x13 = Integers.RotateLeft(x13 ^ x01, 8); - x09 += x13; x05 = Integers.RotateLeft(x05 ^ x09, 7); - x02 += x06; x14 = Integers.RotateLeft(x14 ^ x02, 16); - x10 += x14; x06 = Integers.RotateLeft(x06 ^ x10, 12); - x02 += x06; x14 = Integers.RotateLeft(x14 ^ x02, 8); - x10 += x14; x06 = Integers.RotateLeft(x06 ^ x10, 7); - x03 += x07; x15 = Integers.RotateLeft(x15 ^ x03, 16); - x11 += x15; x07 = Integers.RotateLeft(x07 ^ x11, 12); - x03 += x07; x15 = Integers.RotateLeft(x15 ^ x03, 8); - x11 += x15; x07 = Integers.RotateLeft(x07 ^ x11, 7); - x00 += x05; x15 = Integers.RotateLeft(x15 ^ x00, 16); - x10 += x15; x05 = Integers.RotateLeft(x05 ^ x10, 12); - x00 += x05; x15 = Integers.RotateLeft(x15 ^ x00, 8); - x10 += x15; x05 = Integers.RotateLeft(x05 ^ x10, 7); - x01 += x06; x12 = Integers.RotateLeft(x12 ^ x01, 16); - x11 += x12; x06 = Integers.RotateLeft(x06 ^ x11, 12); - x01 += x06; x12 = Integers.RotateLeft(x12 ^ x01, 8); - x11 += x12; x06 = Integers.RotateLeft(x06 ^ x11, 7); - x02 += x07; x13 = Integers.RotateLeft(x13 ^ x02, 16); - x08 += x13; x07 = Integers.RotateLeft(x07 ^ x08, 12); - x02 += x07; x13 = Integers.RotateLeft(x13 ^ x02, 8); - x08 += x13; x07 = Integers.RotateLeft(x07 ^ x08, 7); - x03 += x04; x14 = Integers.RotateLeft(x14 ^ x03, 16); - x09 += x14; x04 = Integers.RotateLeft(x04 ^ x09, 12); - x03 += x04; x14 = Integers.RotateLeft(x14 ^ x03, 8); - x09 += x14; x04 = Integers.RotateLeft(x04 ^ x09, 7); - } - - x[ 0] = x00 + input[ 0]; - x[ 1] = x01 + input[ 1]; - x[ 2] = x02 + input[ 2]; - x[ 3] = x03 + input[ 3]; - x[ 4] = x04 + input[ 4]; - x[ 5] = x05 + input[ 5]; - x[ 6] = x06 + input[ 6]; - x[ 7] = x07 + input[ 7]; - x[ 8] = x08 + input[ 8]; - x[ 9] = x09 + input[ 9]; - x[10] = x10 + input[10]; - x[11] = x11 + input[11]; - x[12] = x12 + input[12]; - x[13] = x13 + input[13]; - x[14] = x14 + input[14]; - x[15] = x15 + input[15]; + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 16) + return MemoryMarshal.Read>(MemoryMarshal.AsBytes(t)); + + return Vector128.Create(t[0], t[1], t[2], t[3]); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Store128_UInt32(Vector128 s, Span t) + { + if (BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 16) + { + MemoryMarshal.Write(t, ref s); + return; + } + + var u = s.AsUInt64(); + BinaryPrimitives.WriteUInt64LittleEndian(t[..8], u.GetElement(0)); + BinaryPrimitives.WriteUInt64LittleEndian(t[8..], u.GetElement(1)); + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/DesEdeEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/DesEdeEngine.cs index 7c13e48..c4636d4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/DesEdeEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/DesEdeEngine.cs @@ -3,6 +3,7 @@ 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 @@ -27,7 +28,7 @@ public override void Init( ICipherParameters parameters) { if (!(parameters is KeyParameter)) - throw new ArgumentException("invalid parameter passed to DESede init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + throw new ArgumentException("invalid parameter passed to DESede init - " + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); byte[] keyMaster = ((KeyParameter)parameters).GetKey(); if (keyMaster.Length != 24 && keyMaster.Length != 16) @@ -65,11 +66,7 @@ public override int GetBlockSize() return BLOCK_SIZE; } - public override int ProcessBlock( - byte[] input, - int inOff, - byte[] output, - int outOff) + public override int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { if (workingKey1 == null) throw new InvalidOperationException("DESede engine not initialised"); @@ -77,27 +74,59 @@ public override int ProcessBlock( Check.DataLength(input, inOff, BLOCK_SIZE, "input buffer too short"); Check.OutputLength(output, outOff, BLOCK_SIZE, "output buffer too short"); - byte[] temp = new byte[BLOCK_SIZE]; + uint hi32 = Pack.BE_To_UInt32(input, inOff); + uint lo32 = Pack.BE_To_UInt32(input, inOff + 4); if (forEncryption) { - DesFunc(workingKey1, input, inOff, temp, 0); - DesFunc(workingKey2, temp, 0, temp, 0); - DesFunc(workingKey3, temp, 0, output, outOff); + DesFunc(workingKey1, ref hi32, ref lo32); + DesFunc(workingKey2, ref hi32, ref lo32); + DesFunc(workingKey3, ref hi32, ref lo32); } else { - DesFunc(workingKey3, input, inOff, temp, 0); - DesFunc(workingKey2, temp, 0, temp, 0); - DesFunc(workingKey1, temp, 0, output, outOff); + DesFunc(workingKey3, ref hi32, ref lo32); + DesFunc(workingKey2, ref hi32, ref lo32); + DesFunc(workingKey1, ref hi32, ref lo32); } + Pack.UInt32_To_BE(hi32, output, outOff); + Pack.UInt32_To_BE(lo32, output, outOff + 4); + return BLOCK_SIZE; } - public override void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int ProcessBlock(ReadOnlySpan input, Span output) { + if (workingKey1 == null) + throw new InvalidOperationException("DESede engine not initialised"); + + Check.DataLength(input, BLOCK_SIZE, "input buffer too short"); + Check.OutputLength(output, BLOCK_SIZE, "output buffer too short"); + + uint hi32 = Pack.BE_To_UInt32(input); + uint lo32 = Pack.BE_To_UInt32(input[4..]); + + if (forEncryption) + { + DesFunc(workingKey1, ref hi32, ref lo32); + DesFunc(workingKey2, ref hi32, ref lo32); + DesFunc(workingKey3, ref hi32, ref lo32); + } + else + { + DesFunc(workingKey3, ref hi32, ref lo32); + DesFunc(workingKey2, ref hi32, ref lo32); + DesFunc(workingKey1, ref hi32, ref lo32); + } + + Pack.UInt32_To_BE(hi32, output); + Pack.UInt32_To_BE(lo32, output[4..]); + + return BLOCK_SIZE; } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/DesEdeWrapEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/DesEdeWrapEngine.cs index 4757408..b7b9c50 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/DesEdeWrapEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/DesEdeWrapEngine.cs @@ -62,15 +62,14 @@ public virtual void Init( this.engine = new CbcBlockCipher(new DesEdeEngine()); SecureRandom sr; - if (parameters is ParametersWithRandom) + if (parameters is ParametersWithRandom pr) { - ParametersWithRandom pr = (ParametersWithRandom) parameters; parameters = pr.Parameters; sr = pr.Random; } else { - sr = new SecureRandom(); + sr = CryptoServicesRegistrar.GetSecureRandom(); } if (parameters is KeyParameter) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/DesEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/DesEngine.cs index cf9255c..9842c4e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/DesEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/DesEngine.cs @@ -33,10 +33,10 @@ public virtual void Init( bool forEncryption, ICipherParameters parameters) { - if (!(parameters is KeyParameter)) - throw new ArgumentException("invalid parameter passed to DES init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + if (!(parameters is KeyParameter keyParameter)) + throw new ArgumentException("invalid parameter passed to DES init - " + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); - workingKey = GenerateWorkingKey(forEncryption, ((KeyParameter)parameters).GetKey()); + workingKey = GenerateWorkingKey(forEncryption, keyParameter.GetKey()); } public virtual string AlgorithmName @@ -44,21 +44,12 @@ public virtual string AlgorithmName get { return "DES"; } } - 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) + public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { if (workingKey == null) throw new InvalidOperationException("DES engine not initialised"); @@ -66,14 +57,37 @@ public virtual int ProcessBlock( Check.DataLength(input, inOff, BLOCK_SIZE, "input buffer too short"); Check.OutputLength(output, outOff, BLOCK_SIZE, "output buffer too short"); - DesFunc(workingKey, input, inOff, output, outOff); + uint hi32 = Pack.BE_To_UInt32(input, inOff); + uint lo32 = Pack.BE_To_UInt32(input, inOff + 4); + + DesFunc(workingKey, ref hi32, ref lo32); + + Pack.UInt32_To_BE(hi32, output, outOff); + Pack.UInt32_To_BE(lo32, output, outOff + 4); return BLOCK_SIZE; } - public virtual void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) { + if (workingKey == null) + throw new InvalidOperationException("DES engine not initialised"); + + Check.DataLength(input, BLOCK_SIZE, "input buffer too short"); + Check.OutputLength(output, BLOCK_SIZE, "output buffer too short"); + + uint hi32 = Pack.BE_To_UInt32(input); + uint lo32 = Pack.BE_To_UInt32(input[4..]); + + DesFunc(workingKey, ref hi32, ref lo32); + + Pack.UInt32_To_BE(hi32, output); + Pack.UInt32_To_BE(lo32, output[4..]); + + return BLOCK_SIZE; } +#endif /** * what follows is mainly taken from "Applied Cryptography", by @@ -390,19 +404,11 @@ protected static int[] GenerateWorkingKey( return newKey; } - /** - * the DES engine. - */ - internal static void DesFunc( - int[] wKey, - byte[] input, - int inOff, - byte[] outBytes, - int outOff) + internal static void DesFunc(int[] wKey, ref uint hi32, ref uint lo32) { - uint left = Pack.BE_To_UInt32(input, inOff); - uint right = Pack.BE_To_UInt32(input, inOff + 4); - uint work; + uint left = hi32; + uint right = lo32; + uint work; work = ((left >> 4) ^ right) & 0x0f0f0f0f; right ^= work; @@ -470,8 +476,8 @@ internal static void DesFunc( left ^= work; right ^= (work << 4); - Pack.UInt32_To_BE(right, outBytes, outOff); - Pack.UInt32_To_BE(left, outBytes, outOff + 4); + hi32 = right; + lo32 = left; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Dstu7624Engine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Dstu7624Engine.cs index 4f0452c..270ec26 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Dstu7624Engine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Dstu7624Engine.cs @@ -1,11 +1,9 @@ #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.Crypto.Utilities; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines { @@ -272,7 +270,11 @@ public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outO { case 2: { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + EncryptBlock_128(input.AsSpan(inOff), output.AsSpan(outOff)); +#else EncryptBlock_128(input, inOff, output, outOff); +#endif break; } default: @@ -292,6 +294,7 @@ public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outO } AddRoundKey(roundsAmount); Pack.UInt64_To_LE(internalState, output, outOff); + Array.Clear(internalState, 0, internalState.Length); break; } } @@ -303,7 +306,11 @@ public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outO { case 2: { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + DecryptBlock_128(input.AsSpan(inOff), output.AsSpan(outOff)); +#else DecryptBlock_128(input, inOff, output, outOff); +#endif break; } default: @@ -323,6 +330,7 @@ public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outO } SubRoundKey(0); Pack.UInt64_To_LE(internalState, output, outOff); + Array.Clear(internalState, 0, internalState.Length); break; } } @@ -331,6 +339,84 @@ public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outO return GetBlockSize(); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) + { + if (workingKey == null) + throw new InvalidOperationException("Dstu7624Engine not initialised"); + + Check.DataLength(input, GetBlockSize(), "input buffer too short"); + Check.OutputLength(output, GetBlockSize(), "output buffer too short"); + + if (forEncryption) + { + /* Encrypt */ + switch (wordsInBlock) + { + case 2: + { + EncryptBlock_128(input, output); + break; + } + default: + { + Pack.LE_To_UInt64(input, internalState); + AddRoundKey(0); + for (int round = 0;;) + { + EncryptionRound(); + + if (++round == roundsAmount) + { + break; + } + + XorRoundKey(round); + } + AddRoundKey(roundsAmount); + Pack.UInt64_To_LE(internalState, output); + Array.Clear(internalState, 0, internalState.Length); + break; + } + } + } + else + { + /* Decrypt */ + switch (wordsInBlock) + { + case 2: + { + DecryptBlock_128(input, output); + break; + } + default: + { + Pack.LE_To_UInt64(input, internalState); + SubRoundKey(roundsAmount); + for (int round = roundsAmount;;) + { + DecryptionRound(); + + if (--round == 0) + { + break; + } + + XorRoundKey(round); + } + SubRoundKey(0); + Pack.UInt64_To_LE(internalState, output); + Array.Clear(internalState, 0, internalState.Length); + break; + } + } + } + + return GetBlockSize(); + } +#endif + private void EncryptionRound() { SubBytes(); @@ -345,6 +431,133 @@ private void DecryptionRound() InvSubBytes(); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void DecryptBlock_128(ReadOnlySpan input, Span output) + { + ulong c0 = Pack.LE_To_UInt64(input); + ulong c1 = Pack.LE_To_UInt64(input[8..]); + + ulong[] roundKey = roundKeys[roundsAmount]; + c0 -= roundKey[0]; + c1 -= roundKey[1]; + + for (int round = roundsAmount; ;) + { + c0 = MixColumnInv(c0); + c1 = MixColumnInv(c1); + + uint lo0 = (uint)c0, hi0 = (uint)(c0 >> 32); + uint lo1 = (uint)c1, hi1 = (uint)(c1 >> 32); + + { + byte t0 = T0[lo0 & 0xFF]; + byte t1 = T1[(lo0 >> 8) & 0xFF]; + byte t2 = T2[(lo0 >> 16) & 0xFF]; + byte t3 = T3[lo0 >> 24]; + lo0 = (uint)t0 | ((uint)t1 << 8) | ((uint)t2 << 16) | ((uint)t3 << 24); + byte t4 = T0[hi1 & 0xFF]; + byte t5 = T1[(hi1 >> 8) & 0xFF]; + byte t6 = T2[(hi1 >> 16) & 0xFF]; + byte t7 = T3[hi1 >> 24]; + hi1 = (uint)t4 | ((uint)t5 << 8) | ((uint)t6 << 16) | ((uint)t7 << 24); + c0 = (ulong)lo0 | ((ulong)hi1 << 32); + } + + { + byte t0 = T0[lo1 & 0xFF]; + byte t1 = T1[(lo1 >> 8) & 0xFF]; + byte t2 = T2[(lo1 >> 16) & 0xFF]; + byte t3 = T3[lo1 >> 24]; + lo1 = (uint)t0 | ((uint)t1 << 8) | ((uint)t2 << 16) | ((uint)t3 << 24); + byte t4 = T0[hi0 & 0xFF]; + byte t5 = T1[(hi0 >> 8) & 0xFF]; + byte t6 = T2[(hi0 >> 16) & 0xFF]; + byte t7 = T3[hi0 >> 24]; + hi0 = (uint)t4 | ((uint)t5 << 8) | ((uint)t6 << 16) | ((uint)t7 << 24); + c1 = (ulong)lo1 | ((ulong)hi0 << 32); + } + + if (--round == 0) + { + break; + } + + roundKey = roundKeys[round]; + c0 ^= roundKey[0]; + c1 ^= roundKey[1]; + } + + roundKey = roundKeys[0]; + c0 -= roundKey[0]; + c1 -= roundKey[1]; + + Pack.UInt64_To_LE(c0, output); + Pack.UInt64_To_LE(c1, output[8..]); + } + + private void EncryptBlock_128(ReadOnlySpan input, Span output) + { + ulong c0 = Pack.LE_To_UInt64(input); + ulong c1 = Pack.LE_To_UInt64(input[8..]); + + ulong[] roundKey = roundKeys[0]; + c0 += roundKey[0]; + c1 += roundKey[1]; + + for (int round = 0; ;) + { + uint lo0 = (uint)c0, hi0 = (uint)(c0 >> 32); + uint lo1 = (uint)c1, hi1 = (uint)(c1 >> 32); + + { + byte t0 = S0[lo0 & 0xFF]; + byte t1 = S1[(lo0 >> 8) & 0xFF]; + byte t2 = S2[(lo0 >> 16) & 0xFF]; + byte t3 = S3[lo0 >> 24]; + lo0 = (uint)t0 | ((uint)t1 << 8) | ((uint)t2 << 16) | ((uint)t3 << 24); + byte t4 = S0[hi1 & 0xFF]; + byte t5 = S1[(hi1 >> 8) & 0xFF]; + byte t6 = S2[(hi1 >> 16) & 0xFF]; + byte t7 = S3[hi1 >> 24]; + hi1 = (uint)t4 | ((uint)t5 << 8) | ((uint)t6 << 16) | ((uint)t7 << 24); + c0 = (ulong)lo0 | ((ulong)hi1 << 32); + } + + { + byte t0 = S0[lo1 & 0xFF]; + byte t1 = S1[(lo1 >> 8) & 0xFF]; + byte t2 = S2[(lo1 >> 16) & 0xFF]; + byte t3 = S3[lo1 >> 24]; + lo1 = (uint)t0 | ((uint)t1 << 8) | ((uint)t2 << 16) | ((uint)t3 << 24); + byte t4 = S0[hi0 & 0xFF]; + byte t5 = S1[(hi0 >> 8) & 0xFF]; + byte t6 = S2[(hi0 >> 16) & 0xFF]; + byte t7 = S3[hi0 >> 24]; + hi0 = (uint)t4 | ((uint)t5 << 8) | ((uint)t6 << 16) | ((uint)t7 << 24); + c1 = (ulong)lo1 | ((ulong)hi0 << 32); + } + + c0 = MixColumn(c0); + c1 = MixColumn(c1); + + if (++round == roundsAmount) + { + break; + } + + roundKey = roundKeys[round]; + c0 ^= roundKey[0]; + c1 ^= roundKey[1]; + } + + roundKey = roundKeys[roundsAmount]; + c0 += roundKey[0]; + c1 += roundKey[1]; + + Pack.UInt64_To_LE(c0, output); + Pack.UInt64_To_LE(c1, output[8..]); + } +#else private void DecryptBlock_128(byte[] input, int inOff, byte[] output, int outOff) { ulong c0 = Pack.LE_To_UInt64(input, inOff); @@ -470,6 +683,7 @@ private void EncryptBlock_128(byte[] input, int inOff, byte[] output, int outOff Pack.UInt64_To_LE(c0, output, outOff); Pack.UInt64_To_LE(c1, output, outOff + 8); } +#endif private void SubBytes() { @@ -904,7 +1118,7 @@ private void RotateLeft(ulong[] x, ulong[] z) } } - #region TABLES AND S-BOXES +#region TABLES AND S-BOXES private const ulong mdsMatrix = 0x0407060801050101UL; private const ulong mdsInvMatrix = 0xCAD7492FA87695ADUL; @@ -1061,7 +1275,7 @@ private void RotateLeft(ulong[] x, ulong[] z) 0xf3, 0x83, 0x28, 0x32, 0x45, 0x1e, 0xa4, 0xd3, 0xa2, 0x46, 0x6e, 0x9c, 0xdd, 0x63, 0xd4, 0x9d }; - #endregion +#endregion public virtual string AlgorithmName { @@ -1072,16 +1286,6 @@ public virtual int GetBlockSize() { return wordsInBlock << 3; } - - public virtual bool IsPartialBlockOkay - { - get { return false; } - } - - public virtual void Reset() - { - Array.Clear(internalState, 0, internalState.Length); - } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Dstu7624WrapEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Dstu7624WrapEngine.cs index 7ab1bd0..36d8c08 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Dstu7624WrapEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Dstu7624WrapEngine.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; @@ -65,7 +65,7 @@ public byte[] Wrap(byte[] input, int inOff, int length) Array.Copy(buffer, 0, B, 0, blockSize / 2); //Console.WriteLine("B0: "+ BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders.Hex.ToHexString(B)); - IList bTemp = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var bTemp = new List(); int bHalfBlocksLen = buffer.Length - blockSize / 2; int bufOff = blockSize / 2; while (bHalfBlocksLen != 0) @@ -85,7 +85,7 @@ public byte[] Wrap(byte[] input, int inOff, int length) for (int j = 0; j < V; j++) { Array.Copy(B, 0, buffer, 0, blockSize / 2); - Array.Copy((byte[])bTemp[0], 0, buffer, blockSize / 2, blockSize / 2); + Array.Copy(bTemp[0], 0, buffer, blockSize / 2, blockSize / 2); engine.ProcessBlock(buffer, 0, buffer, 0); @@ -99,10 +99,10 @@ public byte[] Wrap(byte[] input, int inOff, int length) for (int i = 2; i < n; i++) { - Array.Copy((byte[])bTemp[i - 1], 0, (byte[])bTemp[i - 2], 0, blockSize / 2); + Array.Copy(bTemp[i - 1], 0, bTemp[i - 2], 0, blockSize / 2); } - Array.Copy(buffer, 0, (byte[])bTemp[n - 2], 0, blockSize / 2); + Array.Copy(buffer, 0, bTemp[n - 2], 0, blockSize / 2); //Console.WriteLine("B" + j.ToString() + ": " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders.Hex.ToHexString(B)); //Console.WriteLine("b: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders.Hex.ToHexString(bTemp[0])); @@ -142,7 +142,7 @@ public byte[] Unwrap(byte[] input, int inOff, int length) Array.Copy(buffer, 0, B, 0, blockSize / 2); //Console.WriteLine("B18: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders.Hex.ToHexString(B)); - IList bTemp = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var bTemp = new List(); int bHalfBlocksLen = buffer.Length - blockSize / 2; int bufOff = blockSize / 2; @@ -162,7 +162,7 @@ public byte[] Unwrap(byte[] input, int inOff, int length) for (int j = 0; j < V; j++) { - Array.Copy((byte[])bTemp[n - 2], 0, buffer, 0, blockSize / 2); + Array.Copy(bTemp[n - 2], 0, buffer, 0, blockSize / 2); Array.Copy(B, 0, buffer, blockSize / 2, blockSize / 2); byte[] intArray = Pack.UInt32_To_LE((uint)(V - j)); @@ -181,10 +181,10 @@ public byte[] Unwrap(byte[] input, int inOff, int length) for (int i = 2; i < n; i++) { - Array.Copy((byte[])bTemp[n - i - 1], 0, (byte[])bTemp[n - i], 0, blockSize / 2); + Array.Copy(bTemp[n - i - 1], 0, bTemp[n - i], 0, blockSize / 2); } - Array.Copy(buffer, blockSize / 2, (byte[])bTemp[0], 0, blockSize / 2); + Array.Copy(buffer, blockSize / 2, bTemp[0], 0, blockSize / 2); //Console.WriteLine("B" + (V - j - 1).ToString() + ": " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders.Hex.ToHexString(B)); //Console.WriteLine("b: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders.Hex.ToHexString(bTemp[0])); @@ -199,7 +199,7 @@ public byte[] Unwrap(byte[] input, int inOff, int length) for (int i = 0; i < n - 1; i++) { - Array.Copy((byte[])bTemp[i], 0, buffer, bufOff, blockSize / 2); + Array.Copy(bTemp[i], 0, buffer, bufOff, blockSize / 2); bufOff += blockSize / 2; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ElGamalEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ElGamalEngine.cs index e948dee..01490dd 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ElGamalEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ElGamalEngine.cs @@ -30,22 +30,18 @@ public virtual string AlgorithmName * @param forEncryption true if we are encrypting, false otherwise. * @param param the necessary ElGamal key parameters. */ - public virtual void Init( - bool forEncryption, - ICipherParameters parameters) + public virtual void Init(bool forEncryption, ICipherParameters parameters) { - if (parameters is ParametersWithRandom) + if (parameters is ParametersWithRandom withRandom) { - ParametersWithRandom p = (ParametersWithRandom) parameters; - - this.key = (ElGamalKeyParameters) p.Parameters; - this.random = p.Random; + this.key = (ElGamalKeyParameters)withRandom.Parameters; + this.random = withRandom.Random; } else { - this.key = (ElGamalKeyParameters) parameters; - this.random = new SecureRandom(); - } + this.key = (ElGamalKeyParameters)parameters; + this.random = CryptoServicesRegistrar.GetSecureRandom(); + } this.forEncryption = forEncryption; this.bitSize = key.Parameters.P.BitLength; @@ -53,16 +49,12 @@ public virtual void Init( if (forEncryption) { if (!(key is ElGamalPublicKeyParameters)) - { throw new ArgumentException("ElGamalPublicKeyParameters are required for encryption."); - } } else { if (!(key is ElGamalPrivateKeyParameters)) - { throw new ArgumentException("ElGamalPrivateKeyParameters are required for decryption."); - } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/GOST28147Engine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/GOST28147Engine.cs index c308cef..219be7a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/GOST28147Engine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/GOST28147Engine.cs @@ -1,9 +1,10 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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 @@ -119,7 +120,8 @@ public class Gost28147Engine // // pre-defined sbox table // - private static readonly IDictionary sBoxes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + private static readonly Dictionary m_sBoxes = + new Dictionary(StringComparer.OrdinalIgnoreCase); static Gost28147Engine() { @@ -135,7 +137,7 @@ static Gost28147Engine() private static void AddSBox(string sBoxName, byte[] sBox) { - sBoxes.Add(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(sBoxName), sBox); + m_sBoxes.Add(sBoxName, sBox); } /** @@ -152,14 +154,10 @@ public Gost28147Engine() * @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) + public virtual void Init(bool forEncryption, ICipherParameters parameters) { - if (parameters is ParametersWithSBox) + if (parameters is ParametersWithSBox param) { - ParametersWithSBox param = (ParametersWithSBox)parameters; - // // Set the S-Box // @@ -174,19 +172,17 @@ public virtual void Init( // if (param.Parameters != null) { - workingKey = generateWorkingKey(forEncryption, - ((KeyParameter)param.Parameters).GetKey()); + workingKey = GenerateWorkingKey(forEncryption, ((KeyParameter)param.Parameters).GetKey()); } } - else if (parameters is KeyParameter) + else if (parameters is KeyParameter keyParameter) { - workingKey = generateWorkingKey(forEncryption, - ((KeyParameter)parameters).GetKey()); + workingKey = GenerateWorkingKey(forEncryption, keyParameter.GetKey()); } else if (parameters != null) { throw new ArgumentException("invalid parameter passed to Gost28147 init - " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); } } @@ -195,21 +191,12 @@ public virtual string AlgorithmName get { return "Gost28147"; } } - public virtual bool IsPartialBlockOkay - { - get { return false; } - } - public virtual int GetBlockSize() { return BlockSize; } - public virtual int ProcessBlock( - byte[] input, - int inOff, - byte[] output, - int outOff) + public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { if (workingKey == null) throw new InvalidOperationException("Gost28147 engine not initialised"); @@ -217,30 +204,41 @@ public virtual int ProcessBlock( Check.DataLength(input, inOff, BlockSize, "input buffer too short"); Check.OutputLength(output, outOff, BlockSize, "output buffer too short"); - Gost28147Func(workingKey, input, inOff, output, outOff); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Gost28147Func(workingKey, input.AsSpan(inOff), output.AsSpan(outOff)); +#else + Gost28147Func(workingKey, input, inOff, output, outOff); +#endif return BlockSize; } - public virtual void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) { + if (workingKey == null) + throw new InvalidOperationException("Gost28147 engine not initialised"); + + Check.DataLength(input, BlockSize, "input buffer too short"); + Check.OutputLength(output, BlockSize, "output buffer too short"); + + Gost28147Func(workingKey, input, output); + + return BlockSize; } +#endif - private int[] generateWorkingKey( - bool forEncryption, - byte[] userKey) + private int[] GenerateWorkingKey(bool forEncryption, byte[] userKey) { this.forEncryption = forEncryption; 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++) + for(int i=0; i != 8; i++) { - key[i] = bytesToint(userKey,i*4); + key[i] = (int)Pack.LE_To_UInt32(userKey, i * 4); } return key; @@ -268,16 +266,12 @@ private int Gost28147_mainStep(int n1, int key) return omLeft | omRight; } - private void Gost28147Func( - int[] workingKey, - byte[] inBytes, - int inOff, - byte[] outBytes, - int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void Gost28147Func(int[] workingKey, ReadOnlySpan input, Span output) { - int N1, N2, tmp; //tmp -> for saving N1 - N1 = bytesToint(inBytes, inOff); - N2 = bytesToint(inBytes, inOff + 4); + int N1 = (int)Pack.LE_To_UInt32(input); + int N2 = (int)Pack.LE_To_UInt32(input[4..]); + int tmp; //tmp -> for saving N1 if (this.forEncryption) { @@ -323,42 +317,73 @@ private void Gost28147Func( N2 = N2 ^ Gost28147_mainStep(N1, workingKey[0]); // 32 step (N1=N1) - intTobytes(N1, outBytes, outOff); - intTobytes(N2, outBytes, outOff + 4); + Pack.UInt32_To_LE((uint)N1, output); + Pack.UInt32_To_LE((uint)N2, output[4..]); } - - //array of bytes to type int - private static int bytesToint( - byte[] inBytes, - int inOff) +#else + private void Gost28147Func(int[] workingKey, byte[] inBytes, int inOff, byte[] outBytes, int outOff) { - return (int)((inBytes[inOff + 3] << 24) & 0xff000000) + ((inBytes[inOff + 2] << 16) & 0xff0000) + - ((inBytes[inOff + 1] << 8) & 0xff00) + (inBytes[inOff] & 0xff); - } + int N1 = (int)Pack.LE_To_UInt32(inBytes, inOff); + int N2 = (int)Pack.LE_To_UInt32(inBytes, inOff + 4); + int tmp; //tmp -> for saving N1 - //int to array of bytes - private static 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; + if (this.forEncryption) + { + for(int k = 0; k < 3; k++) // 1-24 steps + { + for(int j = 0; j < 8; j++) + { + tmp = N1; + int step = Gost28147_mainStep(N1, workingKey[j]); + N1 = N2 ^ step; // CM2 + N2 = tmp; + } + } + for(int j = 7; j > 0; j--) // 25-31 steps + { + tmp = N1; + N1 = N2 ^ Gost28147_mainStep(N1, workingKey[j]); // CM2 + N2 = tmp; + } + } + else //decrypt + { + for(int j = 0; j < 8; j++) // 1-8 steps + { + tmp = N1; + N1 = N2 ^ Gost28147_mainStep(N1, workingKey[j]); // CM2 + N2 = tmp; + } + for(int k = 0; k < 3; k++) //9-31 steps + { + for(int j = 7; j >= 0; j--) + { + if ((k == 2) && (j==0)) + { + break; // break 32 step + } + tmp = N1; + N1 = N2 ^ Gost28147_mainStep(N1, workingKey[j]); // CM2 + N2 = tmp; + } + } + } + + N2 = N2 ^ Gost28147_mainStep(N1, workingKey[0]); // 32 step (N1=N1) + + Pack.UInt32_To_LE((uint)N1, outBytes, outOff); + Pack.UInt32_To_LE((uint)N2, outBytes, outOff + 4); } +#endif /** * Return the S-Box associated with SBoxName * @param sBoxName name of the S-Box * @return byte array representing the S-Box */ - public static byte[] GetSBox( - string sBoxName) + public static byte[] GetSBox(string sBoxName) { - byte[] sBox = (byte[])sBoxes[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(sBoxName)]; - - if (sBox == null) + if (!m_sBoxes.TryGetValue(sBoxName, out var sBox)) { throw new ArgumentException("Unknown S-Box - possible types: " + "\"Default\", \"E-Test\", \"E-A\", \"E-B\", \"E-C\", \"E-D\", \"D-Test\", \"D-A\"."); @@ -369,13 +394,10 @@ public static byte[] GetSBox( public static string GetSBoxName(byte[] sBox) { - foreach (string name in sBoxes.Keys) + foreach (var entry in m_sBoxes) { - byte[] sb = (byte[])sBoxes[name]; - if (Arrays.AreEqual(sb, sBox)) - { - return name; - } + if (Arrays.AreEqual(entry.Value, sBox)) + return entry.Key; } throw new ArgumentException("SBOX provided did not map to a known one"); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Grain128AEADEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Grain128AEADEngine.cs new file mode 100644 index 0000000..68078f2 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Grain128AEADEngine.cs @@ -0,0 +1,568 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.IO; + +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines +{ + public sealed class Grain128AeadEngine + : IAeadCipher + { + /** + * Constants + */ + private static readonly int STATE_SIZE = 4; + + /** + * Variables to hold the state of the engine during encryption and + * decryption + */ + private byte[] workingKey; + private byte[] workingIV; + private uint[] lfsr; + private uint[] nfsr; + private uint[] authAcc; + private uint[] authSr; + + private bool initialised = false; + private bool aadFinished = false; + private MemoryStream aadData = new MemoryStream(); + + private byte[] mac; + + public string AlgorithmName => "Grain-128AEAD"; + + /** + * Initialize a Grain-128AEAD cipher. + * + * @param forEncryption Whether or not we are for encryption. + * @param param The parameters required to set up the cipher. + * @throws ArgumentException If the params argument is inappropriate. + */ + public void Init(bool forEncryption, ICipherParameters param) + { + /* + * Grain encryption and decryption is completely symmetrical, so the + * 'forEncryption' is irrelevant. + */ + if (!(param is ParametersWithIV ivParams)) + throw new ArgumentException("Grain-128AEAD Init parameters must include an IV"); + + byte[] iv = ivParams.GetIV(); + + if (iv == null || iv.Length != 12) + throw new ArgumentException("Grain-128AEAD requires exactly 12 bytes of IV"); + + if (!(ivParams.Parameters is KeyParameter key)) + throw new ArgumentException("Grain-128AEAD Init parameters must include a key"); + + byte[] keyBytes = key.GetKey(); + if (keyBytes.Length != 16) + throw new ArgumentException("Grain-128AEAD key must be 128 bits long"); + + /* + * Initialize variables. + */ + workingIV = new byte[keyBytes.Length]; + workingKey = keyBytes; + lfsr = new uint[STATE_SIZE]; + nfsr = new uint[STATE_SIZE]; + authAcc = new uint[2]; + authSr = new uint[2]; + + Array.Copy(iv, 0, workingIV, 0, iv.Length); + + Reset(); + } + + /** + * 320 clocks initialization phase. + */ + private void InitGrain() + { + for (int i = 0; i < 320; ++i) + { + uint outputZ = GetOutput(); + nfsr = Shift(nfsr, (GetOutputNFSR() ^ lfsr[0] ^ outputZ) & 1); + lfsr = Shift(lfsr, (GetOutputLFSR() ^ outputZ) & 1); + } + for (int quotient = 0; quotient < 8; ++quotient) + { + for (int remainder = 0; remainder < 8; ++remainder) + { + uint outputZ = GetOutput(); + nfsr = Shift(nfsr, (GetOutputNFSR() ^ lfsr[0] ^ outputZ ^ (uint)((workingKey[quotient]) >> remainder)) & 1); + lfsr = Shift(lfsr, (GetOutputLFSR() ^ outputZ ^ (uint)((workingKey[quotient + 8]) >> remainder)) & 1); + } + } + for (int quotient = 0; quotient < 2; ++quotient) + { + for (int remainder = 0; remainder < 32; ++remainder) + { + uint outputZ = GetOutput(); + nfsr = Shift(nfsr, (GetOutputNFSR() ^ lfsr[0]) & 1); + lfsr = Shift(lfsr, (GetOutputLFSR()) & 1); + authAcc[quotient] |= outputZ << remainder; + } + } + for (int quotient = 0; quotient < 2; ++quotient) + { + for (int remainder = 0; remainder < 32; ++remainder) + { + uint outputZ = GetOutput(); + nfsr = Shift(nfsr, (GetOutputNFSR() ^ lfsr[0]) & 1); + lfsr = Shift(lfsr, (GetOutputLFSR()) & 1); + authSr[quotient] |= outputZ << remainder; + } + } + initialised = true; + } + + /** + * Get output from non-linear function g(x). + * + * @return Output from NFSR. + */ + private uint GetOutputNFSR() + { + uint b0 = nfsr[0]; + uint b3 = nfsr[0] >> 3; + uint b11 = nfsr[0] >> 11; + uint b13 = nfsr[0] >> 13; + uint b17 = nfsr[0] >> 17; + uint b18 = nfsr[0] >> 18; + uint b22 = nfsr[0] >> 22; + uint b24 = nfsr[0] >> 24; + uint b25 = nfsr[0] >> 25; + uint b26 = nfsr[0] >> 26; + uint b27 = nfsr[0] >> 27; + uint b40 = nfsr[1] >> 8; + uint b48 = nfsr[1] >> 16; + uint b56 = nfsr[1] >> 24; + uint b59 = nfsr[1] >> 27; + uint b61 = nfsr[1] >> 29; + uint b65 = nfsr[2] >> 1; + uint b67 = nfsr[2] >> 3; + uint b68 = nfsr[2] >> 4; + uint b70 = nfsr[2] >> 6; + uint b78 = nfsr[2] >> 14; + uint b82 = nfsr[2] >> 18; + uint b84 = nfsr[2] >> 20; + uint b88 = nfsr[2] >> 24; + uint b91 = nfsr[2] >> 27; + uint b92 = nfsr[2] >> 28; + uint b93 = nfsr[2] >> 29; + uint b95 = nfsr[2] >> 31; + uint b96 = nfsr[3]; + + return (b0 ^ b26 ^ b56 ^ b91 ^ b96 ^ b3 & b67 ^ b11 & b13 ^ b17 & b18 + ^ b27 & b59 ^ b40 & b48 ^ b61 & b65 ^ b68 & b84 ^ b22 & b24 & b25 ^ b70 & b78 & b82 ^ b88 & b92 & b93 & b95) & 1; + } + + /** + * Get output from linear function f(x). + * + * @return Output from LFSR. + */ + private uint GetOutputLFSR() + { + uint s0 = lfsr[0]; + uint s7 = lfsr[0] >> 7; + uint s38 = lfsr[1] >> 6; + uint s70 = lfsr[2] >> 6; + uint s81 = lfsr[2] >> 17; + uint s96 = lfsr[3]; + + return (s0 ^ s7 ^ s38 ^ s70 ^ s81 ^ s96) & 1; + } + + /** + * Get output from output function h(x). + * + * @return y_t. + */ + private uint GetOutput() + { + uint b2 = nfsr[0] >> 2; + uint b12 = nfsr[0] >> 12; + uint b15 = nfsr[0] >> 15; + uint b36 = nfsr[1] >> 4; + uint b45 = nfsr[1] >> 13; + uint b64 = nfsr[2]; + uint b73 = nfsr[2] >> 9; + uint b89 = nfsr[2] >> 25; + uint b95 = nfsr[2] >> 31; + uint s8 = lfsr[0] >> 8; + uint s13 = lfsr[0] >> 13; + uint s20 = lfsr[0] >> 20; + uint s42 = lfsr[1] >> 10; + uint s60 = lfsr[1] >> 28; + uint s79 = lfsr[2] >> 15; + uint s93 = lfsr[2] >> 29; + uint s94 = lfsr[2] >> 30; + + return ((b12 & s8) ^ (s13 & s20) ^ (b95 & s42) ^ (s60 & s79) ^ (b12 & b95 & s94) ^ s93 + ^ b2 ^ b15 ^ b36 ^ b45 ^ b64 ^ b73 ^ b89) & 1; + } + + /** + * Shift array 1 bit and add val to index.Length - 1. + * + * @param array The array to shift. + * @param val The value to shift in. + * @return The shifted array with val added to index.Length - 1. + */ + private uint[] Shift(uint[] array, uint val) + { + array[0] = (array[0] >> 1) | (array[1] << 31); + array[1] = (array[1] >> 1) | (array[2] << 31); + array[2] = (array[2] >> 1) | (array[3] << 31); + array[3] = (array[3] >> 1) | (val << 31); + return array; + } + + /** + * Set keys, reset cipher. + * + * @param keyBytes The key. + * @param ivBytes The IV. + */ + private void SetKey(byte[] keyBytes, byte[] ivBytes) + { + ivBytes[12] = 0xFF; + ivBytes[13] = 0xFF; + ivBytes[14] = 0xFF; + ivBytes[15] = 0x7F; + workingKey = keyBytes; + workingIV = ivBytes; + + /* + * Load NFSR and LFSR + */ + Pack.LE_To_UInt32(workingKey, 0, nfsr); + Pack.LE_To_UInt32(workingIV, 0, lfsr); + } + + public int 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"); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ProcessBytes(input.AsSpan(inOff, len), output.AsSpan(outOff)); +#else + if (!initialised) + throw new ArgumentException(AlgorithmName + " not initialised"); + + if (!aadFinished) + { + DoProcessAADBytes(aadData.GetBuffer(), 0, (int)aadData.Length); + aadFinished = true; + } + + GetKeyStream(input, inOff, len, output, outOff); + return len; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessBytes(ReadOnlySpan input, Span output) + { + Check.OutputLength(output, input.Length, "output buffer too short"); + + if (!initialised) + throw new ArgumentException(AlgorithmName + " not initialised"); + + if (!aadFinished) + { + DoProcessAADBytes(aadData.GetBuffer(), 0, (int)aadData.Length); + aadFinished = true; + } + + GetKeyStream(input, output); + return input.Length; + } +#endif + + public void Reset() + { + Reset(true); + } + + private void Reset(bool clearMac) + { + if (clearMac) + { + this.mac = null; + } + this.aadData.SetLength(0); + this.aadFinished = false; + + SetKey(workingKey, workingIV); + InitGrain(); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void GetKeyStream(ReadOnlySpan input, Span output) + { + int len = input.Length; + for (int i = 0; i < len; ++i) + { + uint cc = 0, input_i = input[i]; + for (int j = 0; j < 8; ++j) + { + uint outputZ = GetOutput(); + nfsr = Shift(nfsr, (GetOutputNFSR() ^ lfsr[0]) & 1); + lfsr = Shift(lfsr, (GetOutputLFSR()) & 1); + + uint input_i_j = (input_i >> j) & 1U; + cc |= (input_i_j ^ outputZ) << j; + + //if (input_i_j != 0) + //{ + // Accumulate(); + //} + uint mask = 0U - input_i_j; + authAcc[0] ^= authSr[0] & mask; + authAcc[1] ^= authSr[1] & mask; + + AuthShift(GetOutput()); + nfsr = Shift(nfsr, (GetOutputNFSR() ^ lfsr[0]) & 1); + lfsr = Shift(lfsr, (GetOutputLFSR()) & 1); + } + output[i] = (byte)cc; + } + } +#else + private void GetKeyStream(byte[] input, int inOff, int len, byte[] ciphertext, int outOff) + { + for (int i = 0; i < len; ++i) + { + uint cc = 0, input_i = input[inOff + i]; + for (int j = 0; j < 8; ++j) + { + uint outputZ = GetOutput(); + nfsr = Shift(nfsr, (GetOutputNFSR() ^ lfsr[0]) & 1); + lfsr = Shift(lfsr, (GetOutputLFSR()) & 1); + + uint input_i_j = (input_i >> j) & 1U; + cc |= (input_i_j ^ outputZ) << j; + + //if (input_i_j != 0) + //{ + // Accumulate(); + //} + uint mask = 0U - input_i_j; + authAcc[0] ^= authSr[0] & mask; + authAcc[1] ^= authSr[1] & mask; + + AuthShift(GetOutput()); + nfsr = Shift(nfsr, (GetOutputNFSR() ^ lfsr[0]) & 1); + lfsr = Shift(lfsr, (GetOutputLFSR()) & 1); + } + ciphertext[outOff + i] = (byte)cc; + } + } +#endif + + public byte ReturnByte(byte input) + { + if (!initialised) + throw new ArgumentException(AlgorithmName + " not initialised"); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span plaintext = stackalloc byte[1]{ input }; + Span ciphertext = stackalloc byte[1]; + GetKeyStream(plaintext, ciphertext); + return ciphertext[0]; +#else + byte[] plaintext = new byte[1]{ input }; + byte[] ciphertext = new byte[1]; + GetKeyStream(plaintext, 0, 1, ciphertext, 0); + return ciphertext[0]; +#endif + } + + public void ProcessAadByte(byte input) + { + if (aadFinished) + throw new ArgumentException("associated data must be added before plaintext/ciphertext"); + + aadData.WriteByte(input); + } + + public void ProcessAadBytes(byte[] input, int inOff, int len) + { + if (aadFinished) + throw new ArgumentException("associated data must be added before plaintext/ciphertext"); + + aadData.Write(input, inOff, len); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void ProcessAadBytes(ReadOnlySpan input) + { + if (aadFinished) + throw new ArgumentException("associated data must be added before plaintext/ciphertext"); + + aadData.Write(input); + } +#endif + + private void Accumulate() + { + authAcc[0] ^= authSr[0]; + authAcc[1] ^= authSr[1]; + } + + private void AuthShift(uint val) + { + authSr[0] = (authSr[0] >> 1) | (authSr[1] << 31); + authSr[1] = (authSr[1] >> 1) | (val << 31); + } + + public int ProcessByte(byte input, byte[] output, int outOff) + { + return ProcessBytes(new byte[]{ input }, 0, 1, output, outOff); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessByte(byte input, Span output) + { + return ProcessBytes(stackalloc byte[1]{ input }, output); + } +#endif + + private void DoProcessAADBytes(byte[] input, int inOff, int len) + { + byte[] ader; + int aderlen; + //encodeDer + if (len < 128) + { + ader = new byte[1 + len]; + ader[0] = (byte)len; + aderlen = 0; + } + else + { + // aderlen is the highest bit position divided by 8 + aderlen = LenLength(len); + ader = new byte[aderlen + 1 + len]; + ader[0] = (byte)(0x80 | (uint)aderlen); + uint tmp = (uint)len; + for (int i = 0; i < aderlen; ++i) + { + ader[1 + i] = (byte)tmp; + tmp >>= 8; + } + } + for (int i = 0; i < len; ++i) + { + ader[1 + aderlen + i] = input[inOff + i]; + } + + for (int i = 0; i < ader.Length; ++i) + { + uint ader_i = ader[i]; + for (int j = 0; j < 8; ++j) + { + nfsr = Shift(nfsr, (GetOutputNFSR() ^ lfsr[0]) & 1); + lfsr = Shift(lfsr, (GetOutputLFSR()) & 1); + + uint ader_i_j = (ader_i >> j) & 1U; + //if (ader_i_j != 0) + //{ + // Accumulate(); + //} + uint mask = 0U - ader_i_j; + authAcc[0] ^= authSr[0] & mask; + authAcc[1] ^= authSr[1] & mask; + + AuthShift(GetOutput()); + nfsr = Shift(nfsr, (GetOutputNFSR() ^ lfsr[0]) & 1); + lfsr = Shift(lfsr, (GetOutputLFSR()) & 1); + } + } + } + + public int DoFinal(byte[] output, int outOff) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(output.AsSpan(outOff)); +#else + if (!aadFinished) + { + DoProcessAADBytes(aadData.GetBuffer(), 0, (int)aadData.Length); + aadFinished = true; + } + + Accumulate(); + + this.mac = Pack.UInt32_To_LE(authAcc); + + Array.Copy(mac, 0, output, outOff, mac.Length); + + Reset(false); + + return mac.Length; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + if (!aadFinished) + { + DoProcessAADBytes(aadData.GetBuffer(), 0, (int)aadData.Length); + aadFinished = true; + } + + Accumulate(); + + this.mac = Pack.UInt32_To_LE(authAcc); + + mac.CopyTo(output); + + Reset(false); + + return mac.Length; + } +#endif + + public byte[] GetMac() + { + return mac; + } + + public int GetUpdateOutputSize(int len) + { + return len; + } + + public int GetOutputSize(int len) + { + return len + 8; + } + + private static int LenLength(int v) + { + if ((v & 0xff) == v) + return 1; + + if ((v & 0xffff) == v) + return 2; + + if ((v & 0xffffff) == v) + return 3; + + return 4; + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Grain128AEADEngine.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Grain128AEADEngine.cs.meta new file mode 100644 index 0000000..ca9c434 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Grain128AEADEngine.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d88344f3dc885a643b132a3fae2adebb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/HC128Engine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/HC128Engine.cs index 8955fff..b8ce44a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/HC128Engine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/HC128Engine.cs @@ -184,7 +184,7 @@ public virtual void Init( else { throw new ArgumentException( - "Invalid parameter passed to HC128 init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters), + "Invalid parameter passed to HC128 init - " + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters), "parameters"); } @@ -224,6 +224,21 @@ public virtual void ProcessBytes( } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void ProcessBytes(ReadOnlySpan input, Span output) + { + if (!initialised) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + + Check.OutputLength(output, input.Length, "output buffer too short"); + + for (int i = 0; i < input.Length; i++) + { + output[i] = (byte)(input[i] ^ GetByte()); + } + } +#endif + public virtual void Reset() { Init(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/HC256Engine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/HC256Engine.cs index bd70973..65f33af 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/HC256Engine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/HC256Engine.cs @@ -168,7 +168,7 @@ public virtual void Init( else { throw new ArgumentException( - "Invalid parameter passed to HC256 init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters), + "Invalid parameter passed to HC256 init - " + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters), "parameters"); } @@ -208,6 +208,21 @@ public virtual void ProcessBytes( } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void ProcessBytes(ReadOnlySpan input, Span output) + { + if (!initialised) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + + Check.OutputLength(output, input.Length, "output buffer too short"); + + for (int i = 0; i < input.Length; i++) + { + output[i] = (byte)(input[i] ^ GetByte()); + } + } +#endif + public virtual void Reset() { Init(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ISAACEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ISAACEngine.cs index 261318f..ff6c56b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ISAACEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ISAACEngine.cs @@ -44,7 +44,7 @@ public virtual void Init( { if (!(parameters is KeyParameter)) throw new ArgumentException( - "invalid parameter passed to ISAAC Init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters), + "invalid parameter passed to ISAAC Init - " + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters), "parameters"); /* @@ -96,6 +96,27 @@ public virtual void ProcessBytes( } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void ProcessBytes(ReadOnlySpan input, Span output) + { + if (!initialised) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + + Check.OutputLength(output, input.Length, "output buffer too short"); + + for (int i = 0; i < input.Length; i++) + { + if (index == 0) + { + isaac(); + keyStream = Pack.UInt32_To_BE(results); + } + output[i] = (byte)(keyStream[index++] ^ input[i]); + index &= 1023; + } + } +#endif + public virtual string AlgorithmName { get { return "ISAAC"; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/IdeaEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/IdeaEngine.cs index 1cf9708..4ee7907 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/IdeaEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/IdeaEngine.cs @@ -45,7 +45,7 @@ public virtual void Init( ICipherParameters parameters) { if (!(parameters is KeyParameter)) - throw new ArgumentException("invalid parameter passed to IDEA init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + throw new ArgumentException("invalid parameter passed to IDEA init - " + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); workingKey = GenerateWorkingKey(forEncryption, ((KeyParameter)parameters).GetKey()); @@ -56,21 +56,12 @@ 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) + public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { if (workingKey == null) throw new InvalidOperationException("IDEA engine not initialised"); @@ -78,28 +69,55 @@ public virtual int ProcessBlock( Check.DataLength(input, inOff, BLOCK_SIZE, "input buffer too short"); Check.OutputLength(output, outOff, BLOCK_SIZE, "output buffer too short"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + IdeaFunc(workingKey, input.AsSpan(inOff), output.AsSpan(outOff)); +#else IdeaFunc(workingKey, input, inOff, output, outOff); +#endif return BLOCK_SIZE; } - public virtual void Reset() + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) + { + if (workingKey == null) + throw new InvalidOperationException("IDEA engine not initialised"); + + Check.DataLength(input, BLOCK_SIZE, "input buffer too short"); + Check.OutputLength(output, BLOCK_SIZE, "output buffer too short"); + + IdeaFunc(workingKey, input, output); + return BLOCK_SIZE; + } +#endif + + private static readonly int MASK = 0xffff; + private static readonly int BASE = 0x10001; + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int BytesToWord(ReadOnlySpan input) + { + return ((input[0] << 8) & 0xff00) + (input[1] & 0xff); + } + + private void WordToBytes(int word, Span output) { + output[0] = (byte)((uint)word >> 8); + output[1] = (byte)word; } - private static readonly int MASK = 0xffff; - private static readonly int BASE = 0x10001; - private int BytesToWord( - byte[] input, - int inOff) +#else + 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) + + private void WordToBytes(int word, byte[] outBytes, int outOff) { outBytes[outOff] = (byte)((uint) word >> 8); outBytes[outOff + 1] = (byte)word; } +#endif + /** * return x = x * y where the multiplication is done modulo * 65537 (0x10001) (as defined in the IDEA specification) and @@ -130,19 +148,51 @@ private int Mul( } return x & MASK; } - private void IdeaFunc( - int[] workingKey, - byte[] input, - int inOff, - byte[] outBytes, - int outOff) + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void IdeaFunc(int[] workingKey, ReadOnlySpan input, Span output) { - 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); + int x0 = BytesToWord(input); + int x1 = BytesToWord(input[2..]); + int x2 = BytesToWord(input[4..]); + int x3 = BytesToWord(input[6..]); + int keyOff = 0, t0, t1; + 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++]), output); + WordToBytes(x2 + workingKey[keyOff++], output[2..]); /* NB: Order */ + WordToBytes(x1 + workingKey[keyOff++], output[4..]); + WordToBytes(Mul(x3, workingKey[keyOff]), output[6..]); + } +#else + private void IdeaFunc(int[] workingKey, byte[] input, int inOff, byte[] outBytes, int outOff) + { + int x0 = BytesToWord(input, inOff); + int x1 = BytesToWord(input, inOff + 2); + int x2 = BytesToWord(input, inOff + 4); + int x3 = BytesToWord(input, inOff + 6); + int keyOff = 0, t0, t1; for (int round = 0; round < 8; round++) { x0 = Mul(x0, workingKey[keyOff++]); @@ -171,16 +221,17 @@ private void IdeaFunc( WordToBytes(x1 + workingKey[keyOff++], outBytes, outOff + 4); WordToBytes(Mul(x3, workingKey[keyOff]), outBytes, outOff + 6); } +#endif + /** * 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) + private int[] ExpandKey(byte[] uKey) { - int[] key = new int[52]; + int[] key = new int[52]; if (uKey.Length < 16) { byte[] tmp = new byte[16]; @@ -189,7 +240,11 @@ private int[] ExpandKey( } for (int i = 0; i < 8; i++) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + key[i] = BytesToWord(uKey[(i * 2)..]); +#else key[i] = BytesToWord(uKey, i * 2); +#endif } for (int i = 8; i < 52; i++) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/NaccacheSternEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/NaccacheSternEngine.cs index a424922..c8d1b56 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/NaccacheSternEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/NaccacheSternEngine.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; @@ -20,9 +20,9 @@ public class NaccacheSternEngine private NaccacheSternKeyParameters key; - private IList[] lookup = null; + private IList[] lookup = null; - public string AlgorithmName + public string AlgorithmName { get { return "NaccacheStern"; } } @@ -50,22 +50,19 @@ public virtual void Init( if (!this.forEncryption) { NaccacheSternPrivateKeyParameters priv = (NaccacheSternPrivateKeyParameters)key; - IList primes = priv.SmallPrimesList; - lookup = new IList[primes.Count]; + var primes = priv.SmallPrimesList; + lookup = new IList[primes.Count]; for (int i = 0; i < primes.Count; i++) { - BigInteger actualPrime = (BigInteger) primes[i]; + BigInteger actualPrime = primes[i]; int actualPrimeValue = actualPrime.IntValue; - lookup[i] = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(actualPrimeValue); + lookup[i] = new List(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)); @@ -74,13 +71,7 @@ public virtual void Init( } } - - public virtual bool Debug - { - set {} - } - - /** + /** * Returns the input block size of this algorithm. * * @see org.bouncycastle.crypto.AsymmetricBlockCipher#GetInputBlockSize() @@ -155,31 +146,30 @@ public virtual byte[] ProcessBlock( } else { - IList plain = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var plain = new List(); NaccacheSternPrivateKeyParameters priv = (NaccacheSternPrivateKeyParameters)key; - IList primes = priv.SmallPrimesList; + var 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) + var al = lookup[i]; + if (lookup[i].Count != primes[i].IntValue) { throw new InvalidCipherTextException("Error in lookup Array for " - + ((BigInteger)primes[i]).IntValue + + primes[i].IntValue + ": Size mismatch. Expected ArrayList with length " - + ((BigInteger)primes[i]).IntValue + " but found ArrayList of length " + + 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); + BigInteger test = ChineseRemainder(plain, primes); // Should not be used as an oracle, so reencrypt output to see // if it corresponds to input @@ -263,7 +253,7 @@ public virtual byte[] AddCryptedBlocks( BigInteger m1m2Crypt = m1Crypt.Multiply(m2Crypt); m1m2Crypt = m1m2Crypt.Mod(key.Modulus); - //byte[] output = key.Modulus.ToByteArray(); + //byte[] output = key.Modulus.ToByteArray(); //Array.Clear(output, 0, output.Length); byte[] output = new byte[key.Modulus.BitLength / 8 + 1]; @@ -336,21 +326,21 @@ public virtual byte[] ProcessData( * the primes p_i * @return an integer x for that x % p_i == c_i */ - private static BigInteger chineseRemainder(IList congruences, IList primes) + 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]); + all = all.Multiply(primes[i]); } for (int i = 0; i < primes.Count; i++) { - BigInteger a = (BigInteger)primes[i]; + BigInteger a = primes[i]; BigInteger b = all.Divide(a); BigInteger b2 = b.ModInverse(a); BigInteger tmp = b.Multiply(b2); - tmp = tmp.Multiply((BigInteger)congruences[i]); + tmp = tmp.Multiply(congruences[i]); retval = retval.Add(tmp); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/NoekeonEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/NoekeonEngine.cs index 3b7433a..78fefd6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/NoekeonEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/NoekeonEngine.cs @@ -38,11 +38,6 @@ public virtual string AlgorithmName get { return "Noekeon"; } } - public virtual bool IsPartialBlockOkay - { - get { return false; } - } - public virtual int GetBlockSize() { return Size; @@ -60,7 +55,7 @@ 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"); + + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters), "parameters"); KeyParameter p = (KeyParameter) parameters; byte[] key = p.GetKey(); @@ -94,11 +89,7 @@ public virtual void Init(bool forEncryption, ICipherParameters parameters) this._initialised = true; } - public virtual int ProcessBlock( - byte[] input, - int inOff, - byte[] output, - int outOff) + public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { if (!_initialised) throw new InvalidOperationException(AlgorithmName + " not initialised"); @@ -106,15 +97,175 @@ public virtual int ProcessBlock( Check.DataLength(input, inOff, Size, "input buffer too short"); Check.OutputLength(output, outOff, Size, "output buffer too short"); - return _forEncryption - ? EncryptBlock(input, inOff, output, outOff) - : DecryptBlock(input, inOff, output, outOff); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return _forEncryption + ? EncryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)) + : DecryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); +#else + return _forEncryption + ? EncryptBlock(input, inOff, output, outOff) + : DecryptBlock(input, inOff, output, outOff); +#endif } - public virtual void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) { + if (!_initialised) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + + Check.DataLength(input, Size, "input buffer too short"); + Check.OutputLength(output, Size, "output buffer too short"); + + return _forEncryption + ? EncryptBlock(input, output) + : DecryptBlock(input, output); } +#endif + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int EncryptBlock(ReadOnlySpan input, Span output) + { + uint a0 = Pack.BE_To_UInt32(input); + uint a1 = Pack.BE_To_UInt32(input[4..]); + uint a2 = Pack.BE_To_UInt32(input[8..]); + uint a3 = Pack.BE_To_UInt32(input[12..]); + + uint k0 = k[0], k1 = k[1], k2 = k[2], k3 = k[3]; + + int round = 0; + for (;;) + { + a0 ^= RoundConstants[round]; + + // theta(a, k); + { + uint t02 = a0 ^ a2; + t02 ^= Integers.RotateLeft(t02, 8) ^ Integers.RotateLeft(t02, 24); + + a0 ^= k0; + a1 ^= k1; + a2 ^= k2; + a3 ^= k3; + + uint t13 = a1 ^ a3; + t13 ^= Integers.RotateLeft(t13, 8) ^ Integers.RotateLeft(t13, 24); + + a0 ^= t13; + a1 ^= t02; + a2 ^= t13; + a3 ^= t02; + } + + if (++round > Size) + break; + + // pi1(a); + { + a1 = Integers.RotateLeft(a1, 1); + a2 = Integers.RotateLeft(a2, 5); + a3 = Integers.RotateLeft(a3, 2); + } + + // gamma(a); + { + uint t = a3; + a1 ^= a3 | a2; + a3 = a0 ^ (a2 & ~a1); + + a2 = t ^ ~a1 ^ a2 ^ a3; + + a1 ^= a3 | a2; + a0 = t ^ (a2 & a1); + } + + // pi2(a); + { + a1 = Integers.RotateLeft(a1, 31); + a2 = Integers.RotateLeft(a2, 27); + a3 = Integers.RotateLeft(a3, 30); + } + } + Pack.UInt32_To_BE(a0, output); + Pack.UInt32_To_BE(a1, output[4..]); + Pack.UInt32_To_BE(a2, output[8..]); + Pack.UInt32_To_BE(a3, output[12..]); + + return Size; + } + + private int DecryptBlock(ReadOnlySpan input, Span output) + { + uint a0 = Pack.BE_To_UInt32(input); + uint a1 = Pack.BE_To_UInt32(input[4..]); + uint a2 = Pack.BE_To_UInt32(input[8..]); + uint a3 = Pack.BE_To_UInt32(input[12..]); + + uint k0 = k[0], k1 = k[1], k2 = k[2], k3 = k[3]; + + int round = Size; + for (;;) + { + // theta(a, k); + { + uint t02 = a0 ^ a2; + t02 ^= Integers.RotateLeft(t02, 8) ^ Integers.RotateLeft(t02, 24); + + a0 ^= k0; + a1 ^= k1; + a2 ^= k2; + a3 ^= k3; + + uint t13 = a1 ^ a3; + t13 ^= Integers.RotateLeft(t13, 8) ^ Integers.RotateLeft(t13, 24); + + a0 ^= t13; + a1 ^= t02; + a2 ^= t13; + a3 ^= t02; + } + + a0 ^= RoundConstants[round]; + + if (--round < 0) + break; + + // pi1(a); + { + a1 = Integers.RotateLeft(a1, 1); + a2 = Integers.RotateLeft(a2, 5); + a3 = Integers.RotateLeft(a3, 2); + } + + // gamma(a); + { + uint t = a3; + a1 ^= a3 | a2; + a3 = a0 ^ (a2 & ~a1); + + a2 = t ^ ~a1 ^ a2 ^ a3; + + a1 ^= a3 | a2; + a0 = t ^ (a2 & a1); + } + + // pi2(a); + { + a1 = Integers.RotateLeft(a1, 31); + a2 = Integers.RotateLeft(a2, 27); + a3 = Integers.RotateLeft(a3, 30); + } + } + + Pack.UInt32_To_BE(a0, output); + Pack.UInt32_To_BE(a1, output[4..]); + Pack.UInt32_To_BE(a2, output[8..]); + Pack.UInt32_To_BE(a3, output[12..]); + + return Size; + } +#else private int EncryptBlock(byte[] input, int inOff, byte[] output, int outOff) { uint a0 = Pack.BE_To_UInt32(input, inOff); @@ -256,6 +407,7 @@ private int DecryptBlock(byte[] input, int inOff, byte[] output, int outOff) return Size; } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/NullEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/NullEngine.cs index 8611c19..3b1d777 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/NullEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/NullEngine.cs @@ -1,73 +1,2 @@ #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/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/NullEngine.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/NullEngine.cs.meta index 82f177c..d4f1fa2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/NullEngine.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/NullEngine.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: e8ef7c09573c15a4aa37a145bd617daf +guid: 149fe63ae461c054ea71ccbdac969ac8 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC2Engine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC2Engine.cs index 19b850e..7095da7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC2Engine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC2Engine.cs @@ -138,34 +138,21 @@ public virtual void Init( } else { - throw new ArgumentException("invalid parameter passed to RC2 init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + throw new ArgumentException("invalid parameter passed to RC2 init - " + 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) + public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { if (workingKey == null) throw new InvalidOperationException("RC2 engine not initialised"); @@ -173,6 +160,16 @@ public virtual int ProcessBlock( Check.DataLength(input, inOff, BLOCK_SIZE, "input buffer too short"); Check.OutputLength(output, outOff, BLOCK_SIZE, "output buffer too short"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + if (encrypting) + { + EncryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); + } + else + { + DecryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); + } +#else if (encrypting) { EncryptBlock(input, inOff, output, outOff); @@ -181,26 +178,150 @@ public virtual int ProcessBlock( { DecryptBlock(input, inOff, output, outOff); } +#endif + + return BLOCK_SIZE; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) + { + if (workingKey == null) + throw new InvalidOperationException("RC2 engine not initialised"); + + Check.DataLength(input, BLOCK_SIZE, "input buffer too short"); + Check.OutputLength(output, BLOCK_SIZE, "output buffer too short"); + + if (encrypting) + { + EncryptBlock(input, output); + } + else + { + DecryptBlock(input, output); + } return BLOCK_SIZE; } +#endif /** * return the result rotating the 16 bit number in x left by y */ - private int RotateWordLeft( - int x, - int y) + private static 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) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void EncryptBlock(ReadOnlySpan input, Span output) + { + int x76, x54, x32, x10; + + x76 = ((input[7] & 0xff) << 8) + (input[6] & 0xff); + x54 = ((input[5] & 0xff) << 8) + (input[4] & 0xff); + x32 = ((input[3] & 0xff) << 8) + (input[2] & 0xff); + x10 = ((input[1] & 0xff) << 8) + (input[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); + } + + output[0] = (byte)x10; + output[1] = (byte)(x10 >> 8); + output[2] = (byte)x32; + output[3] = (byte)(x32 >> 8); + output[4] = (byte)x54; + output[5] = (byte)(x54 >> 8); + output[6] = (byte)x76; + output[7] = (byte)(x76 >> 8); + } + + private void DecryptBlock(ReadOnlySpan input, Span output) + { + int x76, x54, x32, x10; + + x76 = ((input[7] & 0xff) << 8) + (input[6] & 0xff); + x54 = ((input[5] & 0xff) << 8) + (input[4] & 0xff); + x32 = ((input[3] & 0xff) << 8) + (input[2] & 0xff); + x10 = ((input[1] & 0xff) << 8) + (input[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]); + } + + output[0] = (byte)x10; + output[1] = (byte)(x10 >> 8); + output[2] = (byte)x32; + output[3] = (byte)(x32 >> 8); + output[4] = (byte)x54; + output[5] = (byte)(x54 >> 8); + output[6] = (byte)x76; + output[7] = (byte)(x76 >> 8); + } +#else + private void EncryptBlock(byte[] input, int inOff, byte[] outBytes, int outOff) { int x76, x54, x32, x10; @@ -211,10 +332,10 @@ private void EncryptBlock( 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 = 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]; @@ -224,10 +345,10 @@ private void EncryptBlock( 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 = 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]; @@ -237,10 +358,10 @@ private void EncryptBlock( 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); + 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; @@ -253,11 +374,7 @@ private void EncryptBlock( outBytes[outOff + 7] = (byte)(x76 >> 8); } - private void DecryptBlock( - byte[] input, - int inOff, - byte[] outBytes, - int outOff) + private void DecryptBlock(byte[] input, int inOff, byte[] outBytes, int outOff) { int x76, x54, x32, x10; @@ -309,6 +426,7 @@ private void DecryptBlock( outBytes[outOff + 6] = (byte)x76; outBytes[outOff + 7] = (byte)(x76 >> 8); } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC2WrapEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC2WrapEngine.cs index ad9ddf3..1e2770c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC2WrapEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC2WrapEngine.cs @@ -44,8 +44,8 @@ public class RC2WrapEngine // // checksum digest // - IDigest sha1 = new Sha1Digest(); - byte[] digest = new byte[20]; + private readonly IDigest sha1 = new Sha1Digest(); + private readonly byte[] digest = new byte[20]; /** * Method init @@ -53,22 +53,19 @@ public class RC2WrapEngine * @param forWrapping * @param param */ - public virtual void Init( - bool forWrapping, - ICipherParameters parameters) + public virtual void Init(bool forWrapping, ICipherParameters parameters) { this.forWrapping = forWrapping; this.engine = new CbcBlockCipher(new RC2Engine()); - if (parameters is ParametersWithRandom) + if (parameters is ParametersWithRandom pWithR) { - ParametersWithRandom pWithR = (ParametersWithRandom)parameters; sr = pWithR.Random; parameters = pWithR.Parameters; } else { - sr = new SecureRandom(); + sr = CryptoServicesRegistrar.GetSecureRandom(); } if (parameters is ParametersWithIV) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC4Engine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC4Engine.cs index 8f6214a..665b9d5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC4Engine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC4Engine.cs @@ -47,7 +47,7 @@ public virtual void Init( return; } - throw new ArgumentException("invalid parameter passed to RC4 init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + throw new ArgumentException("invalid parameter passed to RC4 init - " + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); } public virtual string AlgorithmName @@ -85,17 +85,41 @@ public virtual void ProcessBytes( x = (x + 1) & 0xff; y = (engineState[x] + y) & 0xff; + byte sx = engineState[x]; + byte sy = engineState[y]; + // swap - byte tmp = engineState[x]; - engineState[x] = engineState[y]; - engineState[y] = tmp; + engineState[x] = sy; + engineState[y] = sx; // xor - output[i+outOff] = (byte)(input[i + inOff] - ^ engineState[(engineState[x] + engineState[y]) & 0xff]); + output[i+outOff] = (byte)(input[i + inOff] ^ engineState[(sx + sy) & 0xff]); } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void ProcessBytes(ReadOnlySpan input, Span output) + { + Check.OutputLength(output, input.Length, "output buffer too short"); + + for (int i = 0; i < input.Length; i++) + { + x = (x + 1) & 0xff; + y = (engineState[x] + y) & 0xff; + + byte sx = engineState[x]; + byte sy = engineState[y]; + + // swap + engineState[x] = sy; + engineState[y] = sx; + + // xor + output[i] = (byte)(input[i] ^ engineState[(sx + sy) & 0xff]); + } + } +#endif + public virtual void Reset() { SetKey(workingKey); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC532Engine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC532Engine.cs index b240a0e..0ed24d7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC532Engine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC532Engine.cs @@ -2,10 +2,8 @@ #pragma warning disable using System; -#if UNITY_WSA && !UNITY_EDITOR && !ENABLE_IL2CPP -using System.TypeFix; -#endif 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 @@ -51,7 +49,6 @@ public class RC532Engine public RC532Engine() { _noRounds = 12; // the default -// _S = null; } public virtual string AlgorithmName @@ -59,11 +56,6 @@ public virtual string AlgorithmName get { return "RC5-32"; } } - public virtual bool IsPartialBlockOkay - { - get { return false; } - } - public virtual int GetBlockSize() { return 2 * 4; @@ -77,54 +69,54 @@ public virtual int GetBlockSize() * @exception ArgumentException if the parameters argument is * inappropriate. */ - public virtual void Init( - bool forEncryption, - ICipherParameters parameters) + public virtual void Init(bool forEncryption, ICipherParameters parameters) { - if (typeof(RC5Parameters).IsInstanceOfType(parameters)) + if (parameters is RC5Parameters rc5Parameters) { - RC5Parameters p = (RC5Parameters)parameters; + _noRounds = rc5Parameters.Rounds; - _noRounds = p.Rounds; - - SetKey(p.GetKey()); + SetKey(rc5Parameters.GetKey()); } - else if (typeof(KeyParameter).IsInstanceOfType(parameters)) + else if (parameters is KeyParameter keyParameter) { - KeyParameter p = (KeyParameter)parameters; - - SetKey(p.GetKey()); + SetKey(keyParameter.GetKey()); } else { - throw new ArgumentException("invalid parameter passed to RC532 init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + throw new ArgumentException("invalid parameter passed to RC532 init - " + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); } this.forEncryption = forEncryption; } - public virtual int ProcessBlock( - byte[] input, - int inOff, - byte[] output, - int outOff) + public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { - return (forEncryption) - ? EncryptBlock(input, inOff, output, outOff) - : DecryptBlock(input, inOff, output, outOff); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return forEncryption + ? EncryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)) + : DecryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); +#else + return forEncryption + ? EncryptBlock(input, inOff, output, outOff) + : DecryptBlock(input, inOff, output, outOff); +#endif } - public virtual void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) { + return forEncryption + ? EncryptBlock(input, output) + : DecryptBlock(input, output); } +#endif /** * Re-key the cipher. * * @param key the key to be used */ - private void SetKey( - byte[] key) + private void SetKey(byte[] key) { // // KEY EXPANSION: @@ -138,7 +130,7 @@ private void SetKey( // 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]; + int[] L = new int[(key.Length + 3) / 4]; for (int i = 0; i != key.Length; i++) { @@ -180,121 +172,82 @@ private void SetKey( 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); + A = _S[ii] = Integers.RotateLeft(_S[ii] + A + B, 3); + B = L[jj] = Integers.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) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int EncryptBlock(ReadOnlySpan input, Span output) { - int A = BytesToWord(input, inOff) + _S[0]; - int B = BytesToWord(input, inOff + 4) + _S[1]; + int A = (int)Pack.LE_To_UInt32(input) + _S[0]; + int B = (int)Pack.LE_To_UInt32(input[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]; + A = Integers.RotateLeft(A ^ B, B) + _S[2*i]; + B = Integers.RotateLeft(B ^ A, A) + _S[2*i+1]; } - WordToBytes(A, outBytes, outOff); - WordToBytes(B, outBytes, outOff + 4); + Pack.UInt32_To_LE((uint)A, output); + Pack.UInt32_To_LE((uint)B, output[4..]); - return 2 * 4; + return 8; } - private int DecryptBlock( - byte[] input, - int inOff, - byte[] outBytes, - int outOff) + private int DecryptBlock(ReadOnlySpan input, Span output) { - int A = BytesToWord(input, inOff); - int B = BytesToWord(input, inOff + 4); + int A = (int)Pack.LE_To_UInt32(input); + int B = (int)Pack.LE_To_UInt32(input[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; + B = Integers.RotateRight(B - _S[2*i+1], A) ^ A; + A = Integers.RotateRight(A - _S[2*i], B) ^ B; } - WordToBytes(A - _S[0], outBytes, outOff); - WordToBytes(B - _S[1], outBytes, outOff + 4); + Pack.UInt32_To_LE((uint)(A - _S[0]), output); + Pack.UInt32_To_LE((uint)(B - _S[1]), output[4..]); - return 2 * 4; + return 8; } +#else + private int EncryptBlock(byte[] input, int inOff, byte[] outBytes, int outOff) + { + int A = (int)Pack.LE_To_UInt32(input, inOff) + _S[0]; + int B = (int)Pack.LE_To_UInt32(input, inOff + 4) + _S[1]; + for (int i = 1; i <= _noRounds; i++) + { + A = Integers.RotateLeft(A ^ B, B) + _S[2*i]; + B = Integers.RotateLeft(B ^ A, A) + _S[2*i+1]; + } - ////////////////////////////////////////////////////////////// - // - // PRIVATE Helper Methods - // - ////////////////////////////////////////////////////////////// + Pack.UInt32_To_LE((uint)A, outBytes, outOff); + Pack.UInt32_To_LE((uint)B, outBytes, outOff + 4); - /** - * 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)))) ) - ); + return 8; } - private int BytesToWord( - byte[] src, - int srcOff) + private int DecryptBlock(byte[] input, int inOff, byte[] outBytes, int outOff) { - return (src[srcOff] & 0xff) | ((src[srcOff + 1] & 0xff) << 8) - | ((src[srcOff + 2] & 0xff) << 16) | ((src[srcOff + 3] & 0xff) << 24); - } + int A = (int)Pack.LE_To_UInt32(input, inOff); + int B = (int)Pack.LE_To_UInt32(input, inOff + 4); - 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); + for (int i = _noRounds; i >= 1; i--) + { + B = Integers.RotateRight(B - _S[2*i+1], A) ^ A; + A = Integers.RotateRight(A - _S[2*i], B) ^ B; + } + + Pack.UInt32_To_LE((uint)(A - _S[0]), outBytes, outOff); + Pack.UInt32_To_LE((uint)(B - _S[1]), outBytes, outOff + 4); + + return 8; } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC564Engine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC564Engine.cs index ce7bd28..ac84dab 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC564Engine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC564Engine.cs @@ -2,10 +2,8 @@ #pragma warning disable using System; -#if UNITY_WSA && !UNITY_EDITOR && !ENABLE_IL2CPP -using System.TypeFix; -#endif 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 @@ -20,9 +18,6 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines public class RC564Engine : IBlockCipher { - private static readonly int wordSize = 64; - private static readonly int bytesPerWord = wordSize / 8; - /* * the number of rounds to perform */ @@ -62,14 +57,9 @@ public virtual string AlgorithmName get { return "RC5-64"; } } - public virtual bool IsPartialBlockOkay - { - get { return false; } - } - public virtual int GetBlockSize() { - return 2 * bytesPerWord; + return 16; } /** @@ -80,45 +70,46 @@ public virtual int GetBlockSize() * @exception ArgumentException if the parameters argument is * inappropriate. */ - public virtual void Init( - bool forEncryption, - ICipherParameters parameters) + 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; + if (!(parameters is RC5Parameters rc5Parameters)) + throw new ArgumentException("invalid parameter passed to RC564 init - " + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); this.forEncryption = forEncryption; - _noRounds = p.Rounds; + _noRounds = rc5Parameters.Rounds; - SetKey(p.GetKey()); + SetKey(rc5Parameters.GetKey()); } - public virtual int ProcessBlock( - byte[] input, - int inOff, - byte[] output, - int outOff) + public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { - return (forEncryption) ? EncryptBlock(input, inOff, output, outOff) - : DecryptBlock(input, inOff, output, outOff); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return forEncryption + ? EncryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)) + : DecryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); +#else + return forEncryption + ? EncryptBlock(input, inOff, output, outOff) + : DecryptBlock(input, inOff, output, outOff); +#endif } - public virtual void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) { + return forEncryption + ? EncryptBlock(input, output) + : DecryptBlock(input, output); } +#endif /** * Re-key the cipher. * * @param key the key to be used */ - private void SetKey( - byte[] key) + private void SetKey(byte[] key) { // // KEY EXPANSION: @@ -132,11 +123,11 @@ private void SetKey( // 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]; + long[] L = new long[(key.Length + 7) / 8]; for (int i = 0; i != key.Length; i++) { - L[i / bytesPerWord] += (long)(key[i] & 0xff) << (8 * (i % bytesPerWord)); + L[i / 8] += (long)(key[i] & 0xff) << (8 * (i % 8)); } // @@ -174,128 +165,82 @@ private void SetKey( 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); + A = _S[ii] = Longs.RotateLeft(_S[ii] + A + B, 3); + B = L[jj] = Longs.RotateLeft(L[jj] + A + B, (int)(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) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int EncryptBlock(ReadOnlySpan input, Span output) { - long A = BytesToWord(input, inOff) + _S[0]; - long B = BytesToWord(input, inOff + bytesPerWord) + _S[1]; + long A = (long)Pack.LE_To_UInt64(input) + _S[0]; + long B = (long)Pack.LE_To_UInt64(input[8..]) + _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]; + A = Longs.RotateLeft(A ^ B, (int)B) + _S[2*i]; + B = Longs.RotateLeft(B ^ A, (int)A) + _S[2*i+1]; } - WordToBytes(A, outBytes, outOff); - WordToBytes(B, outBytes, outOff + bytesPerWord); + Pack.UInt64_To_LE((ulong)A, output); + Pack.UInt64_To_LE((ulong)B, output[8..]); - return 2 * bytesPerWord; + return 16; } - private int DecryptBlock( - byte[] input, - int inOff, - byte[] outBytes, - int outOff) + private int DecryptBlock(ReadOnlySpan input, Span output) { - long A = BytesToWord(input, inOff); - long B = BytesToWord(input, inOff + bytesPerWord); + long A = (long)Pack.LE_To_UInt64(input); + long B = (long)Pack.LE_To_UInt64(input[8..]); for (int i = _noRounds; i >= 1; i--) { - B = RotateRight(B - _S[2*i+1], A) ^ A; - A = RotateRight(A - _S[2*i], B) ^ B; + B = Longs.RotateRight(B - _S[2*i+1], (int)A) ^ A; + A = Longs.RotateRight(A - _S[2*i], (int)B) ^ B; } - WordToBytes(A - _S[0], outBytes, outOff); - WordToBytes(B - _S[1], outBytes, outOff + bytesPerWord); + Pack.UInt64_To_LE((ulong)(A - _S[0]), output); + Pack.UInt64_To_LE((ulong)(B - _S[1]), output[8..]); - return 2 * bytesPerWord; + return 16; } +#else + private int EncryptBlock(byte[] input, int inOff, byte[] outBytes, int outOff) + { + long A = (long)Pack.LE_To_UInt64(input, inOff) + _S[0]; + long B = (long)Pack.LE_To_UInt64(input, inOff + 8) + _S[1]; + for (int i = 1; i <= _noRounds; i++) + { + A = Longs.RotateLeft(A ^ B, (int)B) + _S[2*i]; + B = Longs.RotateLeft(B ^ A, (int)A) + _S[2*i+1]; + } - ////////////////////////////////////////////////////////////// - // - // 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))))) - ); - } + Pack.UInt64_To_LE((ulong)A, outBytes, outOff); + Pack.UInt64_To_LE((ulong)B, outBytes, outOff + 8); - /** - * 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))))) - ); + return 16; } - private long BytesToWord( - byte[] src, - int srcOff) + private int DecryptBlock(byte[] input, int inOff, byte[] outBytes, int outOff) { - long word = 0; + long A = (long)Pack.LE_To_UInt64(input, inOff); + long B = (long)Pack.LE_To_UInt64(input, inOff + 8); - for (int i = bytesPerWord - 1; i >= 0; i--) + for (int i = _noRounds; i >= 1; i--) { - word = (word << 8) + (src[i + srcOff] & 0xff); + B = Longs.RotateRight(B - _S[2*i+1], (int)A) ^ A; + A = Longs.RotateRight(A - _S[2*i], (int)B) ^ B; } - return word; - } + Pack.UInt64_To_LE((ulong)(A - _S[0]), outBytes, outOff); + Pack.UInt64_To_LE((ulong)(B - _S[1]), outBytes, outOff + 8); - 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); - } + return 16; } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC6Engine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC6Engine.cs index e1ca2d7..d24c30f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC6Engine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RC6Engine.cs @@ -3,6 +3,7 @@ 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 @@ -13,9 +14,6 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines public class RC6Engine : IBlockCipher { - private static readonly int wordSize = 32; - private static readonly int bytesPerWord = wordSize / 8; - /* * the number of rounds to perform */ @@ -48,7 +46,6 @@ public class RC6Engine */ public RC6Engine() { -// _S = null; } public virtual string AlgorithmName @@ -56,14 +53,9 @@ public virtual string AlgorithmName get { return "RC6"; } } - public virtual bool IsPartialBlockOkay - { - get { return false; } - } - public virtual int GetBlockSize() { - return 4 * bytesPerWord; + return 16; } /** @@ -74,40 +66,51 @@ public virtual int GetBlockSize() * @exception ArgumentException if the parameters argument is * inappropriate. */ - public virtual void Init( - bool forEncryption, - ICipherParameters parameters) + 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)); + if (!(parameters is KeyParameter keyParameter)) + throw new ArgumentException("invalid parameter passed to RC6 init - " + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); this.forEncryption = forEncryption; - KeyParameter p = (KeyParameter)parameters; - SetKey(p.GetKey()); + SetKey(keyParameter.GetKey()); } - public virtual int ProcessBlock( - byte[] input, - int inOff, - byte[] output, - int outOff) + 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"); + int blockSize = GetBlockSize(); 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); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return forEncryption + ? EncryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)) + : DecryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); +#else + return forEncryption + ? EncryptBlock(input, inOff, output, outOff) + : DecryptBlock(input, inOff, output, outOff); +#endif } - public virtual void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) { + if (_S == null) + throw new InvalidOperationException("RC6 engine not initialised"); + + int blockSize = GetBlockSize(); + Check.DataLength(input, blockSize, "input buffer too short"); + Check.OutputLength(output, blockSize, "output buffer too short"); + + return forEncryption + ? EncryptBlock(input, output) + : DecryptBlock(input, output); } +#endif /** * Re-key the cipher. @@ -130,17 +133,17 @@ private void SetKey( // case that b = c = 0, set c = 1 and L[0] = 0. // // compute number of dwords - int c = (key.Length + (bytesPerWord - 1)) / bytesPerWord; + int c = (key.Length + 3) / 4; if (c == 0) { c = 1; } - int[] L = new int[(key.Length + bytesPerWord - 1) / bytesPerWord]; + int[] L = new int[(key.Length + 3) / 4]; // 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); + L[i / 4] = (L[i / 4] << 8) + (key[i] & 0xff); } // @@ -180,24 +183,21 @@ private void SetKey( 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); + A = _S[ii] = Integers.RotateLeft(_S[ii] + A + B, 3); + B = L[jj] = Integers.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) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int EncryptBlock(ReadOnlySpan input, Span output) { // 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); + int A = (int)Pack.LE_To_UInt32(input); + int B = (int)Pack.LE_To_UInt32(input[4..]); + int C = (int)Pack.LE_To_UInt32(input[8..]); + int D = (int)Pack.LE_To_UInt32(input[12..]); // Do pseudo-round #0: pre-whitening of B and D B += _S[0]; @@ -206,21 +206,21 @@ private int EncryptBlock( // perform round #1,#2 ... #ROUNDS of encryption for (int i = 1; i <= _noRounds; i++) { - int t = 0,u = 0; + int t = 0, u = 0; - t = B*(2*B+1); - t = RotateLeft(t,5); + t = B * (2 * B + 1); + t = Integers.RotateLeft(t, 5); - u = D*(2*D+1); - u = RotateLeft(u,5); + u = D * (2 * D + 1); + u = Integers.RotateLeft(u, 5); A ^= t; - A = RotateLeft(A,u); - A += _S[2*i]; + A = Integers.RotateLeft(A, u); + A += _S[2 * i]; C ^= u; - C = RotateLeft(C,t); - C += _S[2*i+1]; + C = Integers.RotateLeft(C, t); + C += _S[2 * i + 1]; int temp = A; A = B; @@ -228,39 +228,36 @@ private int EncryptBlock( 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]; + 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); + Pack.UInt32_To_LE((uint)A, output); + Pack.UInt32_To_LE((uint)B, output[4..]); + Pack.UInt32_To_LE((uint)C, output[8..]); + Pack.UInt32_To_LE((uint)D, output[12..]); - return 4 * bytesPerWord; + return 16; } - private int DecryptBlock( - byte[] input, - int inOff, - byte[] outBytes, - int outOff) + private int DecryptBlock(ReadOnlySpan input, Span output) { // 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); + int A = (int)Pack.LE_To_UInt32(input); + int B = (int)Pack.LE_To_UInt32(input[4..]); + int C = (int)Pack.LE_To_UInt32(input[8..]); + int D = (int)Pack.LE_To_UInt32(input[12..]); // Undo pseudo-round #(ROUNDS+1) : post whitening of A and C - C -= _S[2*_noRounds+3]; - A -= _S[2*_noRounds+2]; + 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 t = 0, u = 0; int temp = D; D = C; @@ -268,97 +265,134 @@ private int DecryptBlock( B = A; A = temp; - t = B*(2*B+1); - t = RotateLeft(t, LGW); + t = B * (2 * B + 1); + t = Integers.RotateLeft(t, LGW); - u = D*(2*D+1); - u = RotateLeft(u, LGW); + u = D * (2 * D + 1); + u = Integers.RotateLeft(u, LGW); - C -= _S[2*i+1]; - C = RotateRight(C,t); + C -= _S[2 * i + 1]; + C = Integers.RotateRight(C, t); C ^= u; - A -= _S[2*i]; - A = RotateRight(A,u); + A -= _S[2 * i]; + A = Integers.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); + Pack.UInt32_To_LE((uint)A, output); + Pack.UInt32_To_LE((uint)B, output[4..]); + Pack.UInt32_To_LE((uint)C, output[8..]); + Pack.UInt32_To_LE((uint)D, output[12..]); - return 4 * bytesPerWord; + return 16; } +#else + private int EncryptBlock(byte[] input, int inOff, byte[] outBytes, int outOff) + { + // load A,B,C and D registers from in. + int A = (int)Pack.LE_To_UInt32(input, inOff); + int B = (int)Pack.LE_To_UInt32(input, inOff + 4); + int C = (int)Pack.LE_To_UInt32(input, inOff + 8); + int D = (int)Pack.LE_To_UInt32(input, inOff + 12); + // Do pseudo-round #0: pre-whitening of B and D + B += _S[0]; + D += _S[1]; - ////////////////////////////////////////////////////////////// - // - // PRIVATE Helper Methods - // - ////////////////////////////////////////////////////////////// + // perform round #1,#2 ... #ROUNDS of encryption + for (int i = 1; i <= _noRounds; i++) + { + int t = 0,u = 0; - /** - * 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)))))); - } + t = B*(2*B+1); + t = Integers.RotateLeft(t,5); - /** - * 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)))))); - } + u = D*(2*D+1); + u = Integers.RotateLeft(u,5); - private int BytesToWord( - byte[] src, - int srcOff) - { - int word = 0; + A ^= t; + A = Integers.RotateLeft(A,u); + A += _S[2*i]; - for (int i = bytesPerWord - 1; i >= 0; i--) - { - word = (word << 8) + (src[i + srcOff] & 0xff); + C ^= u; + C = Integers.RotateLeft(C,t); + C += _S[2*i+1]; + + int temp = A; + A = B; + B = C; + C = D; + D = temp; } - return word; + // 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 + Pack.UInt32_To_LE((uint)A, outBytes, outOff); + Pack.UInt32_To_LE((uint)B, outBytes, outOff + 4); + Pack.UInt32_To_LE((uint)C, outBytes, outOff + 8); + Pack.UInt32_To_LE((uint)D, outBytes, outOff + 12); + + return 16; } - private void WordToBytes( - int word, - byte[] dst, - int dstOff) + private int DecryptBlock(byte[] input, int inOff, byte[] outBytes, int outOff) { - for (int i = 0; i < bytesPerWord; i++) + // load A,B,C and D registers from out. + int A = (int)Pack.LE_To_UInt32(input, inOff); + int B = (int)Pack.LE_To_UInt32(input, inOff + 4); + int C = (int)Pack.LE_To_UInt32(input, inOff + 8); + int D = (int)Pack.LE_To_UInt32(input, inOff + 12); + + // 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--) { - dst[i + dstOff] = (byte)word; - word = (int) ((uint) word >> 8); + int t=0,u = 0; + + int temp = D; + D = C; + C = B; + B = A; + A = temp; + + t = B*(2*B+1); + t = Integers.RotateLeft(t, LGW); + + u = D*(2*D+1); + u = Integers.RotateLeft(u, LGW); + + C -= _S[2*i+1]; + C = Integers.RotateRight(C,t); + C ^= u; + + A -= _S[2*i]; + A = Integers.RotateRight(A,u); + A ^= t; } + + // Undo pseudo-round #0: pre-whitening of B and D + D -= _S[1]; + B -= _S[0]; + + Pack.UInt32_To_LE((uint)A, outBytes, outOff); + Pack.UInt32_To_LE((uint)B, outBytes, outOff + 4); + Pack.UInt32_To_LE((uint)C, outBytes, outOff + 8); + Pack.UInt32_To_LE((uint)D, outBytes, outOff + 12); + + return 16; } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RFC3211WrapEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RFC3211WrapEngine.cs index 69bf4e6..7e777ae 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RFC3211WrapEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RFC3211WrapEngine.cs @@ -26,24 +26,20 @@ public Rfc3211WrapEngine( this.engine = new CbcBlockCipher(engine); } - public virtual void Init( - bool forWrapping, - ICipherParameters param) + public virtual void Init(bool forWrapping, ICipherParameters param) { this.forWrapping = forWrapping; - if (param is ParametersWithRandom) + if (param is ParametersWithRandom withRandom) { - ParametersWithRandom p = (ParametersWithRandom)param; - - this.rand = p.Random; - this.param = p.Parameters as ParametersWithIV; + this.rand = withRandom.Random; + this.param = withRandom.Parameters as ParametersWithIV; } else { if (forWrapping) { - rand = new SecureRandom(); + rand = CryptoServicesRegistrar.GetSecureRandom(); } this.param = param as ParametersWithIV; @@ -55,7 +51,7 @@ public virtual void Init( public virtual string AlgorithmName { - get { return engine.GetUnderlyingCipher().AlgorithmName + "/RFC3211Wrap"; } + get { return engine.UnderlyingCipher.AlgorithmName + "/RFC3211Wrap"; } } public virtual byte[] Wrap( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RSABlindedEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RSABlindedEngine.cs index 8368f47..19a75e8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RSABlindedEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RSABlindedEngine.cs @@ -41,16 +41,12 @@ public virtual string AlgorithmName * @param forEncryption true if we are encrypting, false otherwise. * @param param the necessary RSA key parameters. */ - public virtual void Init( - bool forEncryption, - ICipherParameters param) + public virtual void Init(bool forEncryption, ICipherParameters param) { core.Init(forEncryption, param); - if (param is ParametersWithRandom) + if (param is ParametersWithRandom rParam) { - ParametersWithRandom rParam = (ParametersWithRandom)param; - this.key = (RsaKeyParameters)rParam.Parameters; if (key is RsaPrivateCrtKeyParameters) @@ -68,7 +64,7 @@ public virtual void Init( if (key is RsaPrivateCrtKeyParameters) { - this.random = new SecureRandom(); + this.random = CryptoServicesRegistrar.GetSecureRandom(); } else { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RSACoreEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RSACoreEngine.cs index 112536b..b1c7024 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RSACoreEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RSACoreEngine.cs @@ -5,6 +5,7 @@ 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 { @@ -105,28 +106,13 @@ public virtual BigInteger ConvertInput( return input; } - public virtual byte[] ConvertOutput( - BigInteger result) + 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; + return forEncryption + ? BigIntegers.AsUnsignedByteArray(GetOutputBlockSize(), result) + : BigIntegers.AsUnsignedByteArray(result); } public virtual BigInteger ProcessBlock( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RijndaelEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RijndaelEngine.cs index 9235ed8..9d303e4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RijndaelEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/RijndaelEngine.cs @@ -588,7 +588,7 @@ public virtual void Init( return; } - throw new ArgumentException("invalid parameter passed to Rijndael init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + throw new ArgumentException("invalid parameter passed to Rijndael init - " + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); } public virtual string AlgorithmName @@ -596,21 +596,12 @@ public virtual string AlgorithmName get { return "Rijndael"; } } - public virtual bool IsPartialBlockOkay - { - get { return false; } - } - public virtual int GetBlockSize() { return BC / 2; } - public virtual int ProcessBlock( - byte[] input, - int inOff, - byte[] output, - int outOff) + public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { if (workingKey == null) throw new InvalidOperationException("Rijndael engine not initialised"); @@ -618,7 +609,11 @@ public virtual int ProcessBlock( Check.DataLength(input, inOff, (BC / 2), "input buffer too short"); Check.OutputLength(output, outOff, (BC / 2), "output buffer too short"); - UnPackBlock(input, inOff); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + UnPackBlock(input.AsSpan(inOff)); +#else + UnPackBlock(input, inOff); +#endif if (forEncryption) { @@ -629,20 +624,76 @@ public virtual int ProcessBlock( DecryptBlock(workingKey); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + PackBlock(output.AsSpan(outOff)); +#else PackBlock(output, outOff); +#endif return BC / 2; } - public virtual void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) { + if (workingKey == null) + throw new InvalidOperationException("Rijndael engine not initialised"); + + Check.DataLength(input, (BC / 2), "input buffer too short"); + Check.OutputLength(output, (BC / 2), "output buffer too short"); + + UnPackBlock(input); + + if (forEncryption) + { + EncryptBlock(workingKey); + } + else + { + DecryptBlock(workingKey); + } + + PackBlock(output); + + return BC / 2; } +#endif - private void UnPackBlock( - byte[] bytes, - int off) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void UnPackBlock(ReadOnlySpan input) { - int index = off; + int index = 0; + + A0 = (long)(input[index++] & 0xff); + A1 = (long)(input[index++] & 0xff); + A2 = (long)(input[index++] & 0xff); + A3 = (long)(input[index++] & 0xff); + + for (int j = 8; j != BC; j += 8) + { + A0 |= (long)(input[index++] & 0xff) << j; + A1 |= (long)(input[index++] & 0xff) << j; + A2 |= (long)(input[index++] & 0xff) << j; + A3 |= (long)(input[index++] & 0xff) << j; + } + } + + private void PackBlock(Span output) + { + int index = 0; + + for (int j = 0; j != BC; j += 8) + { + output[index++] = (byte)(A0 >> j); + output[index++] = (byte)(A1 >> j); + output[index++] = (byte)(A2 >> j); + output[index++] = (byte)(A3 >> j); + } + } +#else + private void UnPackBlock(byte[] bytes, int off) + { + int index = off; A0 = (long)(bytes[index++] & 0xff); A1 = (long)(bytes[index++] & 0xff); @@ -658,11 +709,9 @@ private void UnPackBlock( } } - private void PackBlock( - byte[] bytes, - int off) + private void PackBlock(byte[] bytes, int off) { - int index = off; + int index = off; for (int j = 0; j != BC; j += 8) { @@ -672,8 +721,9 @@ private void PackBlock( bytes[index++] = (byte)(A3 >> j); } } +#endif - private void EncryptBlock( + private void EncryptBlock( long[][] rk) { int r; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SEEDEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SEEDEngine.cs index 66a3921..b099f2d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SEEDEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SEEDEngine.cs @@ -1,7 +1,9 @@ #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 { @@ -170,12 +172,10 @@ public class SeedEngine private int[] wKey; private bool forEncryption; - public virtual void Init( - bool forEncryption, - ICipherParameters parameters) + public virtual void Init(bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; - wKey = createWorkingKey(((KeyParameter)parameters).GetKey()); + wKey = CreateWorkingKey(((KeyParameter)parameters).GetKey()); } public virtual string AlgorithmName @@ -183,21 +183,12 @@ public virtual string AlgorithmName get { return "SEED"; } } - public virtual bool IsPartialBlockOkay - { - get { return false; } - } - public virtual int GetBlockSize() { return BlockSize; } - public virtual int ProcessBlock( - byte[] inBuf, - int inOff, - byte[] outBuf, - int outOff) + public virtual int ProcessBlock(byte[] inBuf, int inOff, byte[] outBuf, int outOff) { if (wKey == null) throw new InvalidOperationException("SEED engine not initialised"); @@ -205,8 +196,8 @@ public virtual int ProcessBlock( Check.DataLength(inBuf, inOff, BlockSize, "input buffer too short"); Check.OutputLength(outBuf, outOff, BlockSize, "output buffer too short"); - long l = bytesToLong(inBuf, inOff + 0); - long r = bytesToLong(inBuf, inOff + 8); + long l = (long)Pack.BE_To_UInt64(inBuf, inOff + 0); + long r = (long)Pack.BE_To_UInt64(inBuf, inOff + 8); if (forEncryption) { @@ -229,22 +220,60 @@ public virtual int ProcessBlock( } } - longToBytes(outBuf, outOff + 0, r); - longToBytes(outBuf, outOff + 8, l); + Pack.UInt64_To_BE((ulong)r, outBuf, outOff + 0); + Pack.UInt64_To_BE((ulong)l, outBuf, outOff + 8); return BlockSize; } - public virtual void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) { + if (wKey == null) + throw new InvalidOperationException("SEED engine not initialised"); + + Check.DataLength(input, BlockSize, "input buffer too short"); + Check.OutputLength(output, BlockSize, "output buffer too short"); + + long l = (long)Pack.BE_To_UInt64(input); + long r = (long)Pack.BE_To_UInt64(input[8..]); + + if (forEncryption) + { + for (int i = 0; i < 16; i++) + { + long nl = r; + + r = l ^ F(wKey[2 * i], wKey[(2 * i) + 1], r); + l = nl; + } + } + else + { + for (int i = 15; i >= 0; i--) + { + long nl = r; + + r = l ^ F(wKey[2 * i], wKey[(2 * i) + 1], r); + l = nl; + } + } + + Pack.UInt64_To_BE((ulong)r, output); + Pack.UInt64_To_BE((ulong)l, output[8..]); + + return BlockSize; } +#endif - private int[] createWorkingKey( - byte[] inKey) + private int[] CreateWorkingKey(byte[] inKey) { + if (inKey.Length != 16) + throw new ArgumentException("key size must be 128 bits"); + int[] key = new int[32]; - long lower = bytesToLong(inKey, 0); - long upper = bytesToLong(inKey, 8); + long lower = (long)Pack.BE_To_UInt64(inKey, 0); + long upper = (long)Pack.BE_To_UInt64(inKey, 8); int key0 = extractW0(lower); int key1 = extractW1(lower); @@ -297,31 +326,6 @@ private long rotateRight8( return ((long)((ulong) x >> 8)) | (x << 56); } - private long bytesToLong( - byte[] src, - int srcOff) - { - long word = 0; - - for (int i = 0; i <= 7; i++) - { - word = (word << 8) + (src[i + srcOff] & 0xff); - } - - return word; - } - - private void longToBytes( - byte[] dest, - int destOff, - long value) - { - for (int i = 0; i < 8; i++) - { - dest[i + destOff] = (byte)(value >> ((7 - i) * 8)); - } - } - private int G( int x) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SM2Engine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SM2Engine.cs index a361996..74ad44b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SM2Engine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SM2Engine.cs @@ -18,7 +18,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines /// public class SM2Engine { + public enum Mode + { + C1C2C3, C1C3C2 + } + private readonly IDigest mDigest; + private readonly Mode mMode; private bool mForEncryption; private ECKeyParameters mECKey; @@ -31,9 +37,20 @@ public SM2Engine() { } + public SM2Engine(Mode mode) + : this(new SM3Digest(), mode) + { + } + public SM2Engine(IDigest digest) + : this(digest, Mode.C1C2C3) + { + } + + public SM2Engine(IDigest digest, Mode mode) { - this.mDigest = digest; + mDigest = digest; + mMode = mode; } public virtual void Init(bool forEncryption, ICipherParameters param) @@ -64,6 +81,12 @@ public virtual void Init(bool forEncryption, ICipherParameters param) public virtual byte[] ProcessBlock(byte[] input, int inOff, int inLen) { + if ((inOff + inLen) > input.Length || inLen == 0) + throw new DataLengthException("input buffer too short"); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ProcessBlock(input.AsSpan(inOff, inLen)); +#else if (mForEncryption) { return Encrypt(input, inOff, inLen); @@ -72,13 +95,149 @@ public virtual byte[] ProcessBlock(byte[] input, int inOff, int inLen) { return Decrypt(input, inOff, inLen); } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual byte[] ProcessBlock(ReadOnlySpan input) + { + if (input.Length == 0) + throw new DataLengthException("input buffer too short"); + + if (mForEncryption) + { + return Encrypt(input); + } + else + { + return Decrypt(input); + } } +#endif protected virtual ECMultiplier CreateBasePointMultiplier() { return new FixedPointCombMultiplier(); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private byte[] Encrypt(ReadOnlySpan input) + { + byte[] c2 = input.ToArray(); + + ECMultiplier multiplier = CreateBasePointMultiplier(); + + BigInteger k; + ECPoint kPB; + do + { + k = NextK(); + kPB = ((ECPublicKeyParameters)mECKey).Q.Multiply(k).Normalize(); + + Kdf(mDigest, kPB, c2); + } + while (NotEncrypted(c2, input)); + + ECPoint c1P = multiplier.Multiply(mECParams.G, k).Normalize(); + + int c1PEncodedLength = c1P.GetEncodedLength(false); + Span c1 = c1PEncodedLength <= 512 + ? stackalloc byte[c1PEncodedLength] + : new byte[c1PEncodedLength]; + c1P.EncodeTo(false, c1); + + AddFieldElement(mDigest, kPB.AffineXCoord); + mDigest.BlockUpdate(input); + AddFieldElement(mDigest, kPB.AffineYCoord); + + int digestSize = mDigest.GetDigestSize(); + Span c3 = digestSize <= 128 + ? stackalloc byte[digestSize] + : new byte[digestSize]; + mDigest.DoFinal(c3); + + switch (mMode) + { + case Mode.C1C3C2: + return Arrays.Concatenate(c1, c3, c2); + default: + return Arrays.Concatenate(c1, c2, c3); + } + } + + private byte[] Decrypt(ReadOnlySpan input) + { + int c1Length = mCurveLength * 2 + 1; + ECPoint c1P = mECParams.Curve.DecodePoint(input[..c1Length]); + + ECPoint s = c1P.Multiply(mECParams.H); + if (s.IsInfinity) + throw new InvalidCipherTextException("[h]C1 at infinity"); + + c1P = c1P.Multiply(((ECPrivateKeyParameters)mECKey).D).Normalize(); + + int digestSize = mDigest.GetDigestSize(); + int c2Length = input.Length - c1Length - digestSize; + byte[] c2 = new byte[c2Length]; + + if (mMode == Mode.C1C3C2) + { + input[(c1Length + digestSize)..].CopyTo(c2); + } + else + { + input[c1Length..(c1Length + c2Length)].CopyTo(c2); + } + + Kdf(mDigest, c1P, c2); + + AddFieldElement(mDigest, c1P.AffineXCoord); + mDigest.BlockUpdate(c2); + AddFieldElement(mDigest, c1P.AffineYCoord); + + Span c3 = digestSize <= 128 + ? stackalloc byte[digestSize] + : new byte[digestSize]; + mDigest.DoFinal(c3); + + int check = 0; + if (mMode == Mode.C1C3C2) + { + for (int i = 0; i != c3.Length; i++) + { + check |= c3[i] ^ input[c1Length + i]; + } + } + else + { + for (int i = 0; i != c3.Length; i++) + { + check |= c3[i] ^ input[c1Length + c2.Length + i]; + } + } + + c3.Fill(0); + + if (check != 0) + { + Arrays.Fill(c2, 0); + throw new InvalidCipherTextException("invalid cipher text"); + } + + return c2; + } + + private bool NotEncrypted(ReadOnlySpan encData, ReadOnlySpan input) + { + for (int i = 0; i != encData.Length; i++) + { + if (encData[i] != input[i]) + return false; + } + + return true; + } +#else private byte[] Encrypt(byte[] input, int inOff, int inLen) { byte[] c2 = new byte[inLen]; @@ -87,29 +246,34 @@ private byte[] Encrypt(byte[] input, int inOff, int inLen) ECMultiplier multiplier = CreateBasePointMultiplier(); - byte[] c1; + BigInteger k; ECPoint kPB; do { - BigInteger k = NextK(); - - ECPoint c1P = multiplier.Multiply(mECParams.G, k).Normalize(); - - c1 = c1P.GetEncoded(false); - + k = NextK(); kPB = ((ECPublicKeyParameters)mECKey).Q.Multiply(k).Normalize(); Kdf(mDigest, kPB, c2); } while (NotEncrypted(c2, input, inOff)); + ECPoint c1P = multiplier.Multiply(mECParams.G, k).Normalize(); + + byte[] c1 = c1P.GetEncoded(false); + AddFieldElement(mDigest, kPB.AffineXCoord); mDigest.BlockUpdate(input, inOff, inLen); AddFieldElement(mDigest, kPB.AffineYCoord); byte[] c3 = DigestUtilities.DoFinal(mDigest); - return Arrays.ConcatenateAll(c1, c2, c3); + switch (mMode) + { + case Mode.C1C3C2: + return Arrays.ConcatenateAll(c1, c3, c2); + default: + return Arrays.ConcatenateAll(c1, c2, c3); + } } private byte[] Decrypt(byte[] input, int inOff, int inLen) @@ -126,9 +290,17 @@ private byte[] Decrypt(byte[] input, int inOff, int inLen) c1P = c1P.Multiply(((ECPrivateKeyParameters)mECKey).D).Normalize(); - byte[] c2 = new byte[inLen - c1.Length - mDigest.GetDigestSize()]; + int digestSize = mDigest.GetDigestSize(); + byte[] c2 = new byte[inLen - c1.Length - digestSize]; - Array.Copy(input, inOff + c1.Length, c2, 0, c2.Length); + if (mMode == Mode.C1C3C2) + { + Array.Copy(input, inOff + c1.Length + digestSize, c2, 0, c2.Length); + } + else + { + Array.Copy(input, inOff + c1.Length, c2, 0, c2.Length); + } Kdf(mDigest, c1P, c2); @@ -139,9 +311,19 @@ private byte[] Decrypt(byte[] input, int inOff, int inLen) byte[] c3 = DigestUtilities.DoFinal(mDigest); int check = 0; - for (int i = 0; i != c3.Length; i++) + if (mMode == Mode.C1C3C2) + { + for (int i = 0; i != c3.Length; i++) + { + check |= c3[i] ^ input[inOff + c1.Length + i]; + } + } + else { - check |= c3[i] ^ input[inOff + c1.Length + c2.Length + i]; + for (int i = 0; i != c3.Length; i++) + { + check |= c3[i] ^ input[inOff + c1.Length + c2.Length + i]; + } } Arrays.Fill(c1, 0); @@ -161,18 +343,24 @@ private bool NotEncrypted(byte[] encData, byte[] input, int inOff) for (int i = 0; i != encData.Length; i++) { if (encData[i] != input[inOff + i]) - { return false; - } } return true; } +#endif private void Kdf(IDigest digest, ECPoint c1, byte[] encData) { int digestSize = digest.GetDigestSize(); - byte[] buf = new byte[System.Math.Max(4, digestSize)]; + int bufSize = System.Math.Max(4, digestSize); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span buf = bufSize <= 128 + ? stackalloc byte[bufSize] + : new byte[bufSize]; +#else + byte[] buf = new byte[bufSize]; +#endif int off = 0; IMemoable memo = digest as IMemoable; @@ -199,16 +387,32 @@ private void Kdf(IDigest digest, ECPoint c1, byte[] encData) AddFieldElement(digest, c1.AffineYCoord); } + int xorLen = System.Math.Min(digestSize, encData.Length - off); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Pack.UInt32_To_BE(++ct, buf); + digest.BlockUpdate(buf[..4]); + digest.DoFinal(buf); + Xor(encData.AsSpan(off, xorLen), buf); +#else Pack.UInt32_To_BE(++ct, buf, 0); digest.BlockUpdate(buf, 0, 4); digest.DoFinal(buf, 0); - - int xorLen = System.Math.Min(digestSize, encData.Length - off); Xor(encData, buf, off, xorLen); +#endif off += xorLen; } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void Xor(Span data, ReadOnlySpan kdfOut) + { + for (int i = 0; i != data.Length; i++) + { + data[i] ^= kdfOut[i]; + } + } +#else private void Xor(byte[] data, byte[] kdfOut, int dOff, int dRemaining) { for (int i = 0; i != dRemaining; i++) @@ -216,6 +420,7 @@ private void Xor(byte[] data, byte[] kdfOut, int dOff, int dRemaining) data[dOff + i] ^= kdfOut[i]; } } +#endif private BigInteger NextK() { @@ -233,8 +438,17 @@ private BigInteger NextK() private void AddFieldElement(IDigest digest, ECFieldElement v) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int encodedLength = v.GetEncodedLength(); + Span p = encodedLength <= 128 + ? stackalloc byte[encodedLength] + : new byte[encodedLength]; + v.EncodeTo(p); + digest.BlockUpdate(p); +#else byte[] p = v.GetEncoded(); digest.BlockUpdate(p, 0, p.Length); +#endif } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SM4Engine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SM4Engine.cs index 0855877..0ad8bdf 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SM4Engine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SM4Engine.cs @@ -126,7 +126,7 @@ public virtual void Init(bool forEncryption, ICipherParameters parameters) { KeyParameter keyParameter = parameters as KeyParameter; if (null == keyParameter) - throw new ArgumentException("invalid parameter passed to SM4 init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters), "parameters"); + throw new ArgumentException("invalid parameter passed to SM4 init - " + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters), "parameters"); byte[] key = keyParameter.GetKey(); if (key.Length != 16) @@ -145,11 +145,6 @@ public virtual string AlgorithmName get { return "SM4"; } } - public virtual bool IsPartialBlockOkay - { - get { return false; } - } - public virtual int GetBlockSize() { return BlockSize; @@ -184,9 +179,36 @@ public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outO return BlockSize; } - public virtual void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) { + if (null == rk) + throw new InvalidOperationException("SM4 not initialised"); + + Check.DataLength(input, BlockSize, "input buffer too short"); + Check.OutputLength(output, BlockSize, "output buffer too short"); + + uint X0 = Pack.BE_To_UInt32(input); + uint X1 = Pack.BE_To_UInt32(input[4..]); + uint X2 = Pack.BE_To_UInt32(input[8..]); + uint X3 = Pack.BE_To_UInt32(input[12..]); + + for (int i = 0; i < 32; i += 4) + { + X0 ^= T(X1 ^ X2 ^ X3 ^ rk[i ]); // F0 + X1 ^= T(X2 ^ X3 ^ X0 ^ rk[i + 1]); // F1 + X2 ^= T(X3 ^ X0 ^ X1 ^ rk[i + 2]); // F2 + X3 ^= T(X0 ^ X1 ^ X2 ^ rk[i + 3]); // F3 + } + + Pack.UInt32_To_BE(X3, output); + Pack.UInt32_To_BE(X2, output[4..]); + Pack.UInt32_To_BE(X1, output[8..]); + Pack.UInt32_To_BE(X0, output[12..]); + + return BlockSize; } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Salsa20Engine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Salsa20Engine.cs index 238a96a..19fe935 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Salsa20Engine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/Salsa20Engine.cs @@ -1,7 +1,14 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Text; +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER +using System.Runtime.CompilerServices; +#endif +#if NETCOREAPP3_0_OR_GREATER +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; @@ -9,14 +16,10 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines { - /// - /// Implementation of Daniel J. Bernstein's Salsa20 stream cipher, Snuffle 2005 - /// - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] - public class Salsa20Engine + /// + /// Implementation of Daniel J. Bernstein's Salsa20 stream cipher, Snuffle 2005 + /// + public class Salsa20Engine : IStreamCipher { public static readonly int DEFAULT_ROUNDS = 20; @@ -35,22 +38,17 @@ internal void PackTauOrSigma(int keyLength, uint[] state, int stateOffset) state[stateOffset + 3] = TAU_SIGMA[tsOff + 3]; } - [Obsolete] - protected readonly static byte[] - sigma = Strings.ToAsciiByteArray("expand 32-byte k"), - tau = Strings.ToAsciiByteArray("expand 16-byte k"); - protected int rounds; /* * variables to hold the state of the engine * during encryption and decryption */ - private int index = 0; + internal int index = 0; internal uint[] engineState = new uint[StateSize]; // state internal uint[] x = new uint[StateSize]; // internal buffer - private byte[] keyStream = new byte[StateSize * 4]; // expanded state, 64 bytes - private bool initialised = false; + internal byte[] keyStream = new byte[StateSize * 4]; // expanded state, 64 bytes + internal bool initialised = false; /* * internal counter @@ -181,16 +179,40 @@ public virtual void ProcessBytes( throw new MaxBytesExceededException("2^70 byte limit per IV would be exceeded; Change IV"); for (int i = 0; i < len; i++) - { - if (index == 0) - { - GenerateKeyStream(keyStream); - AdvanceCounter(); - } + { + if (index == 0) + { + GenerateKeyStream(keyStream); + AdvanceCounter(); + } outBytes[i+outOff] = (byte)(keyStream[index]^inBytes[i+inOff]); - index = (index + 1) & 63; + index = (index + 1) & 63; + } + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void ProcessBytes(ReadOnlySpan input, Span output) + { + if (!initialised) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + + Check.OutputLength(output, input.Length, "output buffer too short"); + + if (LimitExceeded((uint)input.Length)) + throw new MaxBytesExceededException("2^70 byte limit per IV would be exceeded; Change IV"); + + for (int i = 0; i < input.Length; i++) + { + if (index == 0) + { + GenerateKeyStream(keyStream); + AdvanceCounter(); } + output[i] = (byte)(keyStream[index++] ^ input[i]); + index &= 63; } + } +#endif public virtual void Reset() { @@ -232,16 +254,81 @@ protected virtual void GenerateKeyStream(byte[] output) Pack.UInt32_To_LE(x, output, 0); } - internal static void SalsaCore(int rounds, uint[] input, uint[] x) - { - if (input.Length != 16) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal static void SalsaCore(int rounds, ReadOnlySpan input, Span output) + { + if (input.Length < 16) throw new ArgumentException(); - if (x.Length != 16) + if (output.Length < 16) throw new ArgumentException(); if (rounds % 2 != 0) throw new ArgumentException("Number of rounds must be even"); - uint x00 = input[ 0]; +#if NETCOREAPP3_0_OR_GREATER + if (Sse41.IsSupported && BitConverter.IsLittleEndian && Unsafe.SizeOf>() == 16) + { + Vector128 b0, b1, b2, b3; + { + var I = MemoryMarshal.AsBytes(input[..16]); + var t0 = MemoryMarshal.Read>(I[0x00..0x10]); + var t1 = MemoryMarshal.Read>(I[0x10..0x20]); + var t2 = MemoryMarshal.Read>(I[0x20..0x30]); + var t3 = MemoryMarshal.Read>(I[0x30..0x40]); + + var u0 = Sse41.Blend(t0, t2, 0xF0); + var u1 = Sse41.Blend(t1, t3, 0xC3); + var u2 = Sse41.Blend(t0, t2, 0x0F); + var u3 = Sse41.Blend(t1, t3, 0x3C); + + b0 = Sse41.Blend(u0, u1, 0xCC).AsUInt32(); + b1 = Sse41.Blend(u0, u1, 0x33).AsUInt32(); + b2 = Sse41.Blend(u2, u3, 0xCC).AsUInt32(); + b3 = Sse41.Blend(u2, u3, 0x33).AsUInt32(); + } + + var c0 = b0; + var c1 = b1; + var c2 = b2; + var c3 = b3; + + for (int i = rounds; i > 0; i -= 2) + { + QuarterRound_Sse2(ref c0, ref c3, ref c2, ref c1); + QuarterRound_Sse2(ref c0, ref c1, ref c2, ref c3); + } + + b0 = Sse2.Add(b0, c0); + b1 = Sse2.Add(b1, c1); + b2 = Sse2.Add(b2, c2); + b3 = Sse2.Add(b3, c3); + + { + var t0 = b0.AsUInt16(); + var t1 = b1.AsUInt16(); + var t2 = b2.AsUInt16(); + var t3 = b3.AsUInt16(); + + var u0 = Sse41.Blend(t0, t1, 0xCC); + var u1 = Sse41.Blend(t0, t1, 0x33); + var u2 = Sse41.Blend(t2, t3, 0xCC); + var u3 = Sse41.Blend(t2, t3, 0x33); + + var v0 = Sse41.Blend(u0, u2, 0xF0); + var v1 = Sse41.Blend(u1, u3, 0xC3); + var v2 = Sse41.Blend(u0, u2, 0x0F); + var v3 = Sse41.Blend(u1, u3, 0x3C); + + var X = MemoryMarshal.AsBytes(output[..16]); + MemoryMarshal.Write(X[0x00..0x10], ref v0); + MemoryMarshal.Write(X[0x10..0x20], ref v1); + MemoryMarshal.Write(X[0x20..0x30], ref v2); + MemoryMarshal.Write(X[0x30..0x40], ref v3); + } + return; + } +#endif + + uint x00 = input[ 0]; uint x01 = input[ 1]; uint x02 = input[ 2]; uint x03 = input[ 3]; @@ -258,69 +345,103 @@ internal static void SalsaCore(int rounds, uint[] input, uint[] x) uint x14 = input[14]; uint x15 = input[15]; - for (int i = rounds; i > 0; i -= 2) - { - x04 ^= Integers.RotateLeft((x00+x12), 7); - x08 ^= Integers.RotateLeft((x04+x00), 9); - x12 ^= Integers.RotateLeft((x08+x04),13); - x00 ^= Integers.RotateLeft((x12+x08),18); - x09 ^= Integers.RotateLeft((x05+x01), 7); - x13 ^= Integers.RotateLeft((x09+x05), 9); - x01 ^= Integers.RotateLeft((x13+x09),13); - x05 ^= Integers.RotateLeft((x01+x13),18); - x14 ^= Integers.RotateLeft((x10+x06), 7); - x02 ^= Integers.RotateLeft((x14+x10), 9); - x06 ^= Integers.RotateLeft((x02+x14),13); - x10 ^= Integers.RotateLeft((x06+x02),18); - x03 ^= Integers.RotateLeft((x15+x11), 7); - x07 ^= Integers.RotateLeft((x03+x15), 9); - x11 ^= Integers.RotateLeft((x07+x03),13); - x15 ^= Integers.RotateLeft((x11+x07),18); - - x01 ^= Integers.RotateLeft((x00+x03), 7); - x02 ^= Integers.RotateLeft((x01+x00), 9); - x03 ^= Integers.RotateLeft((x02+x01),13); - x00 ^= Integers.RotateLeft((x03+x02),18); - x06 ^= Integers.RotateLeft((x05+x04), 7); - x07 ^= Integers.RotateLeft((x06+x05), 9); - x04 ^= Integers.RotateLeft((x07+x06),13); - x05 ^= Integers.RotateLeft((x04+x07),18); - x11 ^= Integers.RotateLeft((x10+x09), 7); - x08 ^= Integers.RotateLeft((x11+x10), 9); - x09 ^= Integers.RotateLeft((x08+x11),13); - x10 ^= Integers.RotateLeft((x09+x08),18); - x12 ^= Integers.RotateLeft((x15+x14), 7); - x13 ^= Integers.RotateLeft((x12+x15), 9); - x14 ^= Integers.RotateLeft((x13+x12),13); - x15 ^= Integers.RotateLeft((x14+x13),18); + for (int i = rounds; i > 0; i -= 2) + { + QuarterRound(ref x00, ref x04, ref x08, ref x12); + QuarterRound(ref x05, ref x09, ref x13, ref x01); + QuarterRound(ref x10, ref x14, ref x02, ref x06); + QuarterRound(ref x15, ref x03, ref x07, ref x11); + + QuarterRound(ref x00, ref x01, ref x02, ref x03); + QuarterRound(ref x05, ref x06, ref x07, ref x04); + QuarterRound(ref x10, ref x11, ref x08, ref x09); + QuarterRound(ref x15, ref x12, ref x13, ref x14); } - x[ 0] = x00 + input[ 0]; - x[ 1] = x01 + input[ 1]; - x[ 2] = x02 + input[ 2]; - x[ 3] = x03 + input[ 3]; - x[ 4] = x04 + input[ 4]; - x[ 5] = x05 + input[ 5]; - x[ 6] = x06 + input[ 6]; - x[ 7] = x07 + input[ 7]; - x[ 8] = x08 + input[ 8]; - x[ 9] = x09 + input[ 9]; - x[10] = x10 + input[10]; - x[11] = x11 + input[11]; - x[12] = x12 + input[12]; - x[13] = x13 + input[13]; - x[14] = x14 + input[14]; - x[15] = x15 + input[15]; - } + output[ 0] = x00 + input[ 0]; + output[ 1] = x01 + input[ 1]; + output[ 2] = x02 + input[ 2]; + output[ 3] = x03 + input[ 3]; + output[ 4] = x04 + input[ 4]; + output[ 5] = x05 + input[ 5]; + output[ 6] = x06 + input[ 6]; + output[ 7] = x07 + input[ 7]; + output[ 8] = x08 + input[ 8]; + output[ 9] = x09 + input[ 9]; + output[10] = x10 + input[10]; + output[11] = x11 + input[11]; + output[12] = x12 + input[12]; + output[13] = x13 + input[13]; + output[14] = x14 + input[14]; + output[15] = x15 + input[15]; + } +#else + internal static void SalsaCore(int rounds, uint[] input, uint[] output) + { + if (input.Length < 16) + throw new ArgumentException(); + if (output.Length < 16) + throw new ArgumentException(); + if (rounds % 2 != 0) + throw new ArgumentException("Number of rounds must be even"); - private void ResetLimitCounter() + uint x00 = input[ 0]; + uint x01 = input[ 1]; + uint x02 = input[ 2]; + uint x03 = input[ 3]; + uint x04 = input[ 4]; + uint x05 = input[ 5]; + uint x06 = input[ 6]; + uint x07 = input[ 7]; + uint x08 = input[ 8]; + uint x09 = input[ 9]; + uint x10 = input[10]; + uint x11 = input[11]; + uint x12 = input[12]; + uint x13 = input[13]; + uint x14 = input[14]; + uint x15 = input[15]; + + for (int i = rounds; i > 0; i -= 2) + { + QuarterRound(ref x00, ref x04, ref x08, ref x12); + QuarterRound(ref x05, ref x09, ref x13, ref x01); + QuarterRound(ref x10, ref x14, ref x02, ref x06); + QuarterRound(ref x15, ref x03, ref x07, ref x11); + + QuarterRound(ref x00, ref x01, ref x02, ref x03); + QuarterRound(ref x05, ref x06, ref x07, ref x04); + QuarterRound(ref x10, ref x11, ref x08, ref x09); + QuarterRound(ref x15, ref x12, ref x13, ref x14); + } + + output[ 0] = x00 + input[ 0]; + output[ 1] = x01 + input[ 1]; + output[ 2] = x02 + input[ 2]; + output[ 3] = x03 + input[ 3]; + output[ 4] = x04 + input[ 4]; + output[ 5] = x05 + input[ 5]; + output[ 6] = x06 + input[ 6]; + output[ 7] = x07 + input[ 7]; + output[ 8] = x08 + input[ 8]; + output[ 9] = x09 + input[ 9]; + output[10] = x10 + input[10]; + output[11] = x11 + input[11]; + output[12] = x12 + input[12]; + output[13] = x13 + input[13]; + output[14] = x14 + input[14]; + output[15] = x15 + input[15]; + } +#endif + + internal void ResetLimitCounter() { cW0 = 0; cW1 = 0; cW2 = 0; } - private bool LimitExceeded() + internal bool LimitExceeded() { if (++cW0 == 0) { @@ -336,7 +457,7 @@ private bool LimitExceeded() /* * this relies on the fact len will always be positive. */ - private bool LimitExceeded( + internal bool LimitExceeded( uint len) { uint old = cW0; @@ -351,7 +472,41 @@ private bool LimitExceeded( return false; } - } + +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif + private static void QuarterRound(ref uint a, ref uint b, ref uint c, ref uint d) + { + b ^= Integers.RotateLeft(a + d, 7); + c ^= Integers.RotateLeft(b + a, 9); + d ^= Integers.RotateLeft(c + b, 13); + a ^= Integers.RotateLeft(d + c, 18); + } + +#if NETCOREAPP3_0_OR_GREATER + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void QuarterRound_Sse2(ref Vector128 a, ref Vector128 b, ref Vector128 c, + ref Vector128 d) + { + b = Sse2.Xor(b, Rotate_Sse2(Sse2.Add(a, d), 7)); + c = Sse2.Xor(c, Rotate_Sse2(Sse2.Add(b, a), 9)); + d = Sse2.Xor(d, Rotate_Sse2(Sse2.Add(c, b), 13)); + a = Sse2.Xor(a, Rotate_Sse2(Sse2.Add(d, c), 18)); + + b = Sse2.Shuffle(b, 0x93); + c = Sse2.Shuffle(c, 0x4E); + d = Sse2.Shuffle(d, 0x39); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static Vector128 Rotate_Sse2(Vector128 x, byte sl) + { + byte sr = (byte)(32 - sl); + return Sse2.Xor(Sse2.ShiftLeftLogical(x, sl), Sse2.ShiftRightLogical(x, sr)); + } +#endif + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SerpentEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SerpentEngine.cs index 9c458ee..bf62104 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SerpentEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SerpentEngine.cs @@ -2,8 +2,8 @@ #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 { @@ -28,7 +28,7 @@ public sealed class SerpentEngine * @param key The user-key bytes (multiples of 4) to use. * @exception ArgumentException */ - protected override int[] MakeWorkingKey(byte[] key) + internal override int[] MakeWorkingKey(byte[] key) { // // pad key to 256 bits @@ -66,7 +66,7 @@ protected override int[] MakeWorkingKey(byte[] key) // for (int i = 8; i < 16; i++) { - kPad[i] = RotateLeft(kPad[i - 8] ^ kPad[i - 5] ^ kPad[i - 3] ^ kPad[i - 1] ^ PHI ^ (i - 8), 11); + kPad[i] = Integers.RotateLeft(kPad[i - 8] ^ kPad[i - 5] ^ kPad[i - 3] ^ kPad[i - 1] ^ PHI ^ (i - 8), 11); } Array.Copy(kPad, 8, w, 0, 8); @@ -76,7 +76,7 @@ protected override int[] MakeWorkingKey(byte[] key) // for (int i = 8; i < amount; i++) { - w[i] = RotateLeft(w[i - 8] ^ w[i - 5] ^ w[i - 3] ^ w[i - 1] ^ PHI ^ i, 11); + w[i] = Integers.RotateLeft(w[i - 8] ^ w[i - 5] ^ w[i - 3] ^ w[i - 1] ^ PHI ^ i, 11); } // @@ -152,15 +152,131 @@ protected override int[] MakeWorkingKey(byte[] key) return w; } - /** - * Encrypt one block of plaintext. - * - * @param input the array containing the input data. - * @param inOff offset into the in array the data starts at. - * @param output the array the output data will be copied into. - * @param outOff the offset into the out array the output will start at. - */ - protected override void EncryptBlock(byte[] input, int inOff, byte[] output, int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal override void EncryptBlock(ReadOnlySpan input, Span output) + { + X0 = (int)Pack.LE_To_UInt32(input); + X1 = (int)Pack.LE_To_UInt32(input[4..]); + X2 = (int)Pack.LE_To_UInt32(input[8..]); + X3 = (int)Pack.LE_To_UInt32(input[12..]); + + Sb0(wKey[0] ^ X0, wKey[1] ^ X1, wKey[2] ^ X2, wKey[3] ^ X3); LT(); + Sb1(wKey[4] ^ X0, wKey[5] ^ X1, wKey[6] ^ X2, wKey[7] ^ X3); LT(); + Sb2(wKey[8] ^ X0, wKey[9] ^ X1, wKey[10] ^ X2, wKey[11] ^ X3); LT(); + Sb3(wKey[12] ^ X0, wKey[13] ^ X1, wKey[14] ^ X2, wKey[15] ^ X3); LT(); + Sb4(wKey[16] ^ X0, wKey[17] ^ X1, wKey[18] ^ X2, wKey[19] ^ X3); LT(); + Sb5(wKey[20] ^ X0, wKey[21] ^ X1, wKey[22] ^ X2, wKey[23] ^ X3); LT(); + Sb6(wKey[24] ^ X0, wKey[25] ^ X1, wKey[26] ^ X2, wKey[27] ^ X3); LT(); + Sb7(wKey[28] ^ X0, wKey[29] ^ X1, wKey[30] ^ X2, wKey[31] ^ X3); LT(); + Sb0(wKey[32] ^ X0, wKey[33] ^ X1, wKey[34] ^ X2, wKey[35] ^ X3); LT(); + Sb1(wKey[36] ^ X0, wKey[37] ^ X1, wKey[38] ^ X2, wKey[39] ^ X3); LT(); + Sb2(wKey[40] ^ X0, wKey[41] ^ X1, wKey[42] ^ X2, wKey[43] ^ X3); LT(); + Sb3(wKey[44] ^ X0, wKey[45] ^ X1, wKey[46] ^ X2, wKey[47] ^ X3); LT(); + Sb4(wKey[48] ^ X0, wKey[49] ^ X1, wKey[50] ^ X2, wKey[51] ^ X3); LT(); + Sb5(wKey[52] ^ X0, wKey[53] ^ X1, wKey[54] ^ X2, wKey[55] ^ X3); LT(); + Sb6(wKey[56] ^ X0, wKey[57] ^ X1, wKey[58] ^ X2, wKey[59] ^ X3); LT(); + Sb7(wKey[60] ^ X0, wKey[61] ^ X1, wKey[62] ^ X2, wKey[63] ^ X3); LT(); + Sb0(wKey[64] ^ X0, wKey[65] ^ X1, wKey[66] ^ X2, wKey[67] ^ X3); LT(); + Sb1(wKey[68] ^ X0, wKey[69] ^ X1, wKey[70] ^ X2, wKey[71] ^ X3); LT(); + Sb2(wKey[72] ^ X0, wKey[73] ^ X1, wKey[74] ^ X2, wKey[75] ^ X3); LT(); + Sb3(wKey[76] ^ X0, wKey[77] ^ X1, wKey[78] ^ X2, wKey[79] ^ X3); LT(); + Sb4(wKey[80] ^ X0, wKey[81] ^ X1, wKey[82] ^ X2, wKey[83] ^ X3); LT(); + Sb5(wKey[84] ^ X0, wKey[85] ^ X1, wKey[86] ^ X2, wKey[87] ^ X3); LT(); + Sb6(wKey[88] ^ X0, wKey[89] ^ X1, wKey[90] ^ X2, wKey[91] ^ X3); LT(); + Sb7(wKey[92] ^ X0, wKey[93] ^ X1, wKey[94] ^ X2, wKey[95] ^ X3); LT(); + Sb0(wKey[96] ^ X0, wKey[97] ^ X1, wKey[98] ^ X2, wKey[99] ^ X3); LT(); + Sb1(wKey[100] ^ X0, wKey[101] ^ X1, wKey[102] ^ X2, wKey[103] ^ X3); LT(); + Sb2(wKey[104] ^ X0, wKey[105] ^ X1, wKey[106] ^ X2, wKey[107] ^ X3); LT(); + Sb3(wKey[108] ^ X0, wKey[109] ^ X1, wKey[110] ^ X2, wKey[111] ^ X3); LT(); + Sb4(wKey[112] ^ X0, wKey[113] ^ X1, wKey[114] ^ X2, wKey[115] ^ X3); LT(); + Sb5(wKey[116] ^ X0, wKey[117] ^ X1, wKey[118] ^ X2, wKey[119] ^ X3); LT(); + Sb6(wKey[120] ^ X0, wKey[121] ^ X1, wKey[122] ^ X2, wKey[123] ^ X3); LT(); + Sb7(wKey[124] ^ X0, wKey[125] ^ X1, wKey[126] ^ X2, wKey[127] ^ X3); + + Pack.UInt32_To_LE((uint)(wKey[128] ^ X0), output); + Pack.UInt32_To_LE((uint)(wKey[129] ^ X1), output[4..]); + Pack.UInt32_To_LE((uint)(wKey[130] ^ X2), output[8..]); + Pack.UInt32_To_LE((uint)(wKey[131] ^ X3), output[12..]); + } + + internal override void DecryptBlock(ReadOnlySpan input, Span output) + { + X0 = wKey[128] ^ (int)Pack.LE_To_UInt32(input); + X1 = wKey[129] ^ (int)Pack.LE_To_UInt32(input[4..]); + X2 = wKey[130] ^ (int)Pack.LE_To_UInt32(input[8..]); + X3 = wKey[131] ^ (int)Pack.LE_To_UInt32(input[12..]); + + Ib7(X0, X1, X2, X3); + X0 ^= wKey[124]; X1 ^= wKey[125]; X2 ^= wKey[126]; X3 ^= wKey[127]; + InverseLT(); Ib6(X0, X1, X2, X3); + X0 ^= wKey[120]; X1 ^= wKey[121]; X2 ^= wKey[122]; X3 ^= wKey[123]; + InverseLT(); Ib5(X0, X1, X2, X3); + X0 ^= wKey[116]; X1 ^= wKey[117]; X2 ^= wKey[118]; X3 ^= wKey[119]; + InverseLT(); Ib4(X0, X1, X2, X3); + X0 ^= wKey[112]; X1 ^= wKey[113]; X2 ^= wKey[114]; X3 ^= wKey[115]; + InverseLT(); Ib3(X0, X1, X2, X3); + X0 ^= wKey[108]; X1 ^= wKey[109]; X2 ^= wKey[110]; X3 ^= wKey[111]; + InverseLT(); Ib2(X0, X1, X2, X3); + X0 ^= wKey[104]; X1 ^= wKey[105]; X2 ^= wKey[106]; X3 ^= wKey[107]; + InverseLT(); Ib1(X0, X1, X2, X3); + X0 ^= wKey[100]; X1 ^= wKey[101]; X2 ^= wKey[102]; X3 ^= wKey[103]; + InverseLT(); Ib0(X0, X1, X2, X3); + X0 ^= wKey[96]; X1 ^= wKey[97]; X2 ^= wKey[98]; X3 ^= wKey[99]; + InverseLT(); Ib7(X0, X1, X2, X3); + X0 ^= wKey[92]; X1 ^= wKey[93]; X2 ^= wKey[94]; X3 ^= wKey[95]; + InverseLT(); Ib6(X0, X1, X2, X3); + X0 ^= wKey[88]; X1 ^= wKey[89]; X2 ^= wKey[90]; X3 ^= wKey[91]; + InverseLT(); Ib5(X0, X1, X2, X3); + X0 ^= wKey[84]; X1 ^= wKey[85]; X2 ^= wKey[86]; X3 ^= wKey[87]; + InverseLT(); Ib4(X0, X1, X2, X3); + X0 ^= wKey[80]; X1 ^= wKey[81]; X2 ^= wKey[82]; X3 ^= wKey[83]; + InverseLT(); Ib3(X0, X1, X2, X3); + X0 ^= wKey[76]; X1 ^= wKey[77]; X2 ^= wKey[78]; X3 ^= wKey[79]; + InverseLT(); Ib2(X0, X1, X2, X3); + X0 ^= wKey[72]; X1 ^= wKey[73]; X2 ^= wKey[74]; X3 ^= wKey[75]; + InverseLT(); Ib1(X0, X1, X2, X3); + X0 ^= wKey[68]; X1 ^= wKey[69]; X2 ^= wKey[70]; X3 ^= wKey[71]; + InverseLT(); Ib0(X0, X1, X2, X3); + X0 ^= wKey[64]; X1 ^= wKey[65]; X2 ^= wKey[66]; X3 ^= wKey[67]; + InverseLT(); Ib7(X0, X1, X2, X3); + X0 ^= wKey[60]; X1 ^= wKey[61]; X2 ^= wKey[62]; X3 ^= wKey[63]; + InverseLT(); Ib6(X0, X1, X2, X3); + X0 ^= wKey[56]; X1 ^= wKey[57]; X2 ^= wKey[58]; X3 ^= wKey[59]; + InverseLT(); Ib5(X0, X1, X2, X3); + X0 ^= wKey[52]; X1 ^= wKey[53]; X2 ^= wKey[54]; X3 ^= wKey[55]; + InverseLT(); Ib4(X0, X1, X2, X3); + X0 ^= wKey[48]; X1 ^= wKey[49]; X2 ^= wKey[50]; X3 ^= wKey[51]; + InverseLT(); Ib3(X0, X1, X2, X3); + X0 ^= wKey[44]; X1 ^= wKey[45]; X2 ^= wKey[46]; X3 ^= wKey[47]; + InverseLT(); Ib2(X0, X1, X2, X3); + X0 ^= wKey[40]; X1 ^= wKey[41]; X2 ^= wKey[42]; X3 ^= wKey[43]; + InverseLT(); Ib1(X0, X1, X2, X3); + X0 ^= wKey[36]; X1 ^= wKey[37]; X2 ^= wKey[38]; X3 ^= wKey[39]; + InverseLT(); Ib0(X0, X1, X2, X3); + X0 ^= wKey[32]; X1 ^= wKey[33]; X2 ^= wKey[34]; X3 ^= wKey[35]; + InverseLT(); Ib7(X0, X1, X2, X3); + X0 ^= wKey[28]; X1 ^= wKey[29]; X2 ^= wKey[30]; X3 ^= wKey[31]; + InverseLT(); Ib6(X0, X1, X2, X3); + X0 ^= wKey[24]; X1 ^= wKey[25]; X2 ^= wKey[26]; X3 ^= wKey[27]; + InverseLT(); Ib5(X0, X1, X2, X3); + X0 ^= wKey[20]; X1 ^= wKey[21]; X2 ^= wKey[22]; X3 ^= wKey[23]; + InverseLT(); Ib4(X0, X1, X2, X3); + X0 ^= wKey[16]; X1 ^= wKey[17]; X2 ^= wKey[18]; X3 ^= wKey[19]; + InverseLT(); Ib3(X0, X1, X2, X3); + X0 ^= wKey[12]; X1 ^= wKey[13]; X2 ^= wKey[14]; X3 ^= wKey[15]; + InverseLT(); Ib2(X0, X1, X2, X3); + X0 ^= wKey[8]; X1 ^= wKey[9]; X2 ^= wKey[10]; X3 ^= wKey[11]; + InverseLT(); Ib1(X0, X1, X2, X3); + X0 ^= wKey[4]; X1 ^= wKey[5]; X2 ^= wKey[6]; X3 ^= wKey[7]; + InverseLT(); Ib0(X0, X1, X2, X3); + + Pack.UInt32_To_LE((uint)(X0 ^ wKey[0]), output); + Pack.UInt32_To_LE((uint)(X1 ^ wKey[1]), output[4..]); + Pack.UInt32_To_LE((uint)(X2 ^ wKey[2]), output[8..]); + Pack.UInt32_To_LE((uint)(X3 ^ wKey[3]), output[12..]); + } +#else + internal override void EncryptBlock(byte[] input, int inOff, byte[] output, int outOff) { X0 = (int)Pack.LE_To_UInt32(input, inOff); X1 = (int)Pack.LE_To_UInt32(input, inOff + 4); @@ -206,15 +322,7 @@ protected override void EncryptBlock(byte[] input, int inOff, byte[] output, int Pack.UInt32_To_LE((uint)(wKey[131] ^ X3), output, outOff + 12); } - /** - * Decrypt one block of ciphertext. - * - * @param input the array containing the input data. - * @param inOff offset into the in array the data starts at. - * @param output the array the output data will be copied into. - * @param outOff the offset into the out array the output will start at. - */ - protected override void DecryptBlock(byte[] input, int inOff, byte[] output, int outOff) + internal override void DecryptBlock(byte[] input, int inOff, byte[] output, int outOff) { X0 = wKey[128] ^ (int)Pack.LE_To_UInt32(input, inOff); X1 = wKey[129] ^ (int)Pack.LE_To_UInt32(input, inOff + 4); @@ -290,6 +398,7 @@ protected override void DecryptBlock(byte[] input, int inOff, byte[] output, int Pack.UInt32_To_LE((uint)(X2 ^ wKey[2]), output, outOff + 8); Pack.UInt32_To_LE((uint)(X3 ^ wKey[3]), output, outOff + 12); } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SerpentEngineBase.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SerpentEngineBase.cs index 35fe66e..8602a38 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SerpentEngineBase.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SerpentEngineBase.cs @@ -20,7 +20,7 @@ public abstract class SerpentEngineBase protected int X0, X1, X2, X3; // registers - protected SerpentEngineBase() + internal SerpentEngineBase() { } @@ -35,7 +35,7 @@ protected SerpentEngineBase() public virtual void Init(bool encrypting, ICipherParameters parameters) { if (!(parameters is KeyParameter)) - throw new ArgumentException("invalid parameter passed to " + AlgorithmName + " init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + throw new ArgumentException("invalid parameter passed to " + AlgorithmName + " init - " + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); this.encrypting = encrypting; this.wKey = MakeWorkingKey(((KeyParameter)parameters).GetKey()); @@ -46,11 +46,6 @@ public virtual string AlgorithmName get { return "Serpent"; } } - public virtual bool IsPartialBlockOkay - { - get { return false; } - } - public virtual int GetBlockSize() { return BlockSize; @@ -77,6 +72,16 @@ public int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) Check.DataLength(input, inOff, BlockSize, "input buffer too short"); Check.OutputLength(output, outOff, BlockSize, "output buffer too short"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + if (encrypting) + { + EncryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); + } + else + { + DecryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); + } +#else if (encrypting) { EncryptBlock(input, inOff, output, outOff); @@ -85,23 +90,32 @@ public int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { DecryptBlock(input, inOff, output, outOff); } +#endif return BlockSize; } - public virtual void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessBlock(ReadOnlySpan input, Span output) { - } + if (wKey == null) + throw new InvalidOperationException(AlgorithmName + " not initialised"); - protected static int RotateLeft(int x, int bits) - { - return ((x << bits) | (int) ((uint)x >> (32 - bits))); - } + Check.DataLength(input, BlockSize, "input buffer too short"); + Check.OutputLength(output, BlockSize, "output buffer too short"); - private static int RotateRight(int x, int bits) - { - return ( (int)((uint)x >> bits) | (x << (32 - bits))); + if (encrypting) + { + EncryptBlock(input, output); + } + else + { + DecryptBlock(input, output); + } + + return BlockSize; } +#endif /* * The sboxes below are based on the work of Brian Gladman and @@ -436,15 +450,15 @@ protected void Ib7(int a, int b, int c, int d) */ protected void LT() { - int x0 = RotateLeft(X0, 13); - int x2 = RotateLeft(X2, 3); + int x0 = Integers.RotateLeft(X0, 13); + int x2 = Integers.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); + X1 = Integers.RotateLeft(x1, 1); + X3 = Integers.RotateLeft(x3, 7); + X0 = Integers.RotateLeft(x0 ^ X1 ^ X3, 5); + X2 = Integers.RotateLeft(x2 ^ X3 ^ (X1 << 7), 22); } /** @@ -452,21 +466,25 @@ protected void LT() */ 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); + int x2 = Integers.RotateRight(X2, 22) ^ X3 ^ (X1 << 7); + int x0 = Integers.RotateRight(X0, 5) ^ X1 ^ X3; + int x3 = Integers.RotateRight(X3, 7); + int x1 = Integers.RotateRight(X1, 1); X3 = x3 ^ x2 ^ x0 << 3; X1 = x1 ^ x0 ^ x2; - X2 = RotateRight(x2, 3); - X0 = RotateRight(x0, 13); + X2 = Integers.RotateRight(x2, 3); + X0 = Integers.RotateRight(x0, 13); } - protected abstract int[] MakeWorkingKey(byte[] key); - - protected abstract void EncryptBlock(byte[] input, int inOff, byte[] output, int outOff); + internal abstract int[] MakeWorkingKey(byte[] key); - protected abstract void DecryptBlock(byte[] input, int inOff, byte[] output, int outOff); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal abstract void EncryptBlock(ReadOnlySpan input, Span output); + internal abstract void DecryptBlock(ReadOnlySpan input, Span output); +#else + internal abstract void EncryptBlock(byte[] input, int inOff, byte[] output, int outOff); + internal abstract void DecryptBlock(byte[] input, int inOff, byte[] output, int outOff); +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SkipjackEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SkipjackEngine.cs index 000161d..f8e6551 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SkipjackEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/SkipjackEngine.cs @@ -10,12 +10,12 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines /** * a class that provides a basic SKIPJACK engine. */ - public class SkipjackEngine + public sealed class SkipjackEngine : IBlockCipher { - const int BLOCK_SIZE = 8; + private const int BLOCK_SIZE = 8; - static readonly short [] ftable = + private 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, @@ -46,14 +46,12 @@ public class SkipjackEngine * @exception ArgumentException if the parameters argument is * inappropriate. */ - public virtual void Init( - bool forEncryption, - ICipherParameters parameters) + public 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)); + if (!(parameters is KeyParameter keyParameter)) + throw new ArgumentException("invalid parameter passed to SKIPJACK init - " + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); - byte[] keyBytes = ((KeyParameter)parameters).GetKey(); + byte[] keyBytes = keyParameter.GetKey(); this.encrypting = forEncryption; this.key0 = new int[32]; @@ -65,35 +63,26 @@ public virtual void Init( // expand the key to 128 bytes in 4 parts (saving us a modulo, multiply // and an addition). // - for (int i = 0; i < 32; i ++) + 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; + key0[i] = keyBytes[(i * 4 + 0) % 10]; + key1[i] = keyBytes[(i * 4 + 1) % 10]; + key2[i] = keyBytes[(i * 4 + 2) % 10]; + key3[i] = keyBytes[(i * 4 + 3) % 10]; } } - public virtual string AlgorithmName + public string AlgorithmName { get { return "SKIPJACK"; } } - public virtual bool IsPartialBlockOkay - { - get { return false; } - } - - public virtual int GetBlockSize() + public int GetBlockSize() { return BLOCK_SIZE; } - public virtual int ProcessBlock( - byte[] input, - int inOff, - byte[] output, - int outOff) + public int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { if (key1 == null) throw new InvalidOperationException("SKIPJACK engine not initialised"); @@ -101,6 +90,16 @@ public virtual int ProcessBlock( Check.DataLength(input, inOff, BLOCK_SIZE, "input buffer too short"); Check.OutputLength(output, outOff, BLOCK_SIZE, "output buffer too short"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + if (encrypting) + { + EncryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); + } + else + { + DecryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); + } +#else if (encrypting) { EncryptBlock(input, inOff, output, outOff); @@ -109,13 +108,32 @@ public virtual int ProcessBlock( { DecryptBlock(input, inOff, output, outOff); } +#endif return BLOCK_SIZE; } - public virtual void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessBlock(ReadOnlySpan input, Span output) { + if (key1 == null) + throw new InvalidOperationException("SKIPJACK engine not initialised"); + + Check.DataLength(input, BLOCK_SIZE, "input buffer too short"); + Check.OutputLength(output, BLOCK_SIZE, "output buffer too short"); + + if (encrypting) + { + EncryptBlock(input, output); + } + else + { + DecryptBlock(input, output); + } + + return BLOCK_SIZE; } +#endif /** * The G permutation @@ -137,11 +155,97 @@ private int G( return ((g5 << 8) + g6); } - public virtual int EncryptBlock( - byte[] input, - int inOff, - byte[] outBytes, - int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int EncryptBlock(ReadOnlySpan input, Span output) + { + int w1 = (input[0] << 8) + (input[1] & 0xff); + int w2 = (input[2] << 8) + (input[3] & 0xff); + int w3 = (input[4] << 8) + (input[5] & 0xff); + int w4 = (input[6] << 8) + (input[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++; + } + } + + output[0] = (byte)((w1 >> 8)); + output[1] = (byte)(w1); + output[2] = (byte)((w2 >> 8)); + output[3] = (byte)(w2); + output[4] = (byte)((w3 >> 8)); + output[5] = (byte)(w3); + output[6] = (byte)((w4 >> 8)); + output[7] = (byte)(w4); + + return BLOCK_SIZE; + } + + private int DecryptBlock(ReadOnlySpan input, Span output) + { + int w2 = (input[0] << 8) + (input[1] & 0xff); + int w1 = (input[2] << 8) + (input[3] & 0xff); + int w4 = (input[4] << 8) + (input[5] & 0xff); + int w3 = (input[6] << 8) + (input[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--; + } + } + + output[0] = (byte)((w2 >> 8)); + output[1] = (byte)(w2); + output[2] = (byte)((w1 >> 8)); + output[3] = (byte)(w1); + output[4] = (byte)((w4 >> 8)); + output[5] = (byte)(w4); + output[6] = (byte)((w3 >> 8)); + output[7] = (byte)(w3); + + return BLOCK_SIZE; + } + +#else + private 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); @@ -185,31 +289,7 @@ public virtual int EncryptBlock( 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) + private 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); @@ -220,7 +300,7 @@ public virtual int DecryptBlock( for (int t = 0; t < 2; t++) { - for(int i = 0; i < 8; i++) + for (int i = 0; i < 8; i++) { int tmp = w4; w4 = w3; @@ -230,7 +310,7 @@ public virtual int DecryptBlock( k--; } - for(int i = 0; i < 8; i++) + for (int i = 0; i < 8; i++) { int tmp = w4; w4 = w3; @@ -252,6 +332,23 @@ public virtual int DecryptBlock( return BLOCK_SIZE; } +#endif + + /** + * the inverse of the G permutation. + */ + private int H(int k, int w) + { + int h1 = w & 0xff; + int h2 = (w >> 8) & 0xff; + + int h3 = ftable[h2 ^ key3[k]] ^ h1; + int h4 = ftable[h3 ^ key2[k]] ^ h2; + int h5 = ftable[h4 ^ key1[k]] ^ h3; + int h6 = ftable[h5 ^ key0[k]] ^ h4; + + return (h6 << 8) + h5; + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/TEAEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/TEAEngine.cs index 71081ae..6becb19 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/TEAEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/TEAEngine.cs @@ -44,11 +44,6 @@ public virtual string AlgorithmName get { return "TEA"; } } - public virtual bool IsPartialBlockOkay - { - get { return false; } - } - public virtual int GetBlockSize() { return block_size; @@ -62,29 +57,21 @@ public virtual int GetBlockSize() * @exception ArgumentException if the params argument is * inappropriate. */ - public virtual void Init( - bool forEncryption, - ICipherParameters parameters) + public virtual void Init(bool forEncryption, ICipherParameters parameters) { - if (!(parameters is KeyParameter)) + if (!(parameters is KeyParameter keyParameter)) { throw new ArgumentException("invalid parameter passed to TEA init - " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); } _forEncryption = forEncryption; _initialised = true; - KeyParameter p = (KeyParameter) parameters; - - setKey(p.GetKey()); + SetKey(keyParameter.GetKey()); } - public virtual int ProcessBlock( - byte[] inBytes, - int inOff, - byte[] outBytes, - int outOff) + public virtual int ProcessBlock(byte[] inBytes, int inOff, byte[] outBytes, int outOff) { if (!_initialised) throw new InvalidOperationException(AlgorithmName + " not initialised"); @@ -92,22 +79,38 @@ public virtual int ProcessBlock( 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); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return _forEncryption + ? EncryptBlock(inBytes.AsSpan(inOff), outBytes.AsSpan(outOff)) + : DecryptBlock(inBytes.AsSpan(inOff), outBytes.AsSpan(outOff)); +#else + return _forEncryption + ? EncryptBlock(inBytes, inOff, outBytes, outOff) + : DecryptBlock(inBytes, inOff, outBytes, outOff); +#endif } - public virtual void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) { + if (!_initialised) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + + Check.DataLength(input, block_size, "input buffer too short"); + Check.OutputLength(output, block_size, "output buffer too short"); + + return _forEncryption + ? EncryptBlock(input, output) + : DecryptBlock(input, output); } +#endif /** * Re-key the cipher. * * @param key the key to be used */ - private void setKey( - byte[] key) + private void SetKey(byte[] key) { _a = Pack.BE_To_UInt32(key, 0); _b = Pack.BE_To_UInt32(key, 4); @@ -115,18 +118,57 @@ private void setKey( _d = Pack.BE_To_UInt32(key, 12); } - private int encryptBlock( - byte[] inBytes, - int inOff, - byte[] outBytes, - int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int EncryptBlock(ReadOnlySpan input, Span output) + { + // Pack bytes into integers + uint v0 = Pack.BE_To_UInt32(input); + uint v1 = Pack.BE_To_UInt32(input[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, output); + Pack.UInt32_To_BE(v1, output[4..]); + + return block_size; + } + + private int DecryptBlock(ReadOnlySpan input, Span output) + { + // Pack bytes into integers + uint v0 = Pack.BE_To_UInt32(input); + uint v1 = Pack.BE_To_UInt32(input[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, output); + Pack.UInt32_To_BE(v1, output[4..]); + + return block_size; + } +#else + 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; @@ -140,11 +182,7 @@ private int encryptBlock( return block_size; } - private int decryptBlock( - byte[] inBytes, - int inOff, - byte[] outBytes, - int outOff) + private int DecryptBlock(byte[] inBytes, int inOff, byte[] outBytes, int outOff) { // Pack bytes into integers uint v0 = Pack.BE_To_UInt32(inBytes, inOff); @@ -164,6 +202,7 @@ private int decryptBlock( return block_size; } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ThreefishEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ThreefishEngine.cs index 9a672ae..d6d66e7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ThreefishEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/ThreefishEngine.cs @@ -137,18 +137,17 @@ public ThreefishEngine(int blocksizeBits) switch (blocksizeBits) { - case BLOCKSIZE_256: + case BLOCKSIZE_256: cipher = new Threefish256Cipher(kw, t); break; - case BLOCKSIZE_512: + case BLOCKSIZE_512: cipher = new Threefish512Cipher(kw, t); break; - case BLOCKSIZE_1024: + 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"); + default: + throw new ArgumentException("Invalid blocksize - Threefish is defined with block size of 256, 512, or 1024 bits"); } } @@ -177,7 +176,7 @@ public virtual void Init(bool forEncryption, ICipherParameters parameters) else { throw new ArgumentException("Invalid parameter passed to Threefish init - " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); } ulong[] keyWords = null; @@ -191,10 +190,7 @@ public virtual void Init(bool forEncryption, ICipherParameters parameters) + " bytes)"); } keyWords = new ulong[blocksizeWords]; - for (int i = 0; i < keyWords.Length; i++) - { - keyWords[i] = BytesToWord(keyBytes, i * 8); - } + Pack.LE_To_UInt64(keyBytes, 0, keyWords); } if (tweakBytes != null) { @@ -202,7 +198,8 @@ public virtual void Init(bool forEncryption, ICipherParameters parameters) { throw new ArgumentException("Threefish tweak must be " + TWEAK_SIZE_BYTES + " bytes"); } - tweakWords = new ulong[]{BytesToWord(tweakBytes, 0), BytesToWord(tweakBytes, 8)}; + tweakWords = new ulong[2]; + Pack.LE_To_UInt64(tweakBytes, 0, tweakWords); } Init(forEncryption, keyWords, tweakWords); } @@ -274,44 +271,34 @@ 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) { + Check.DataLength(inBytes, inOff, blocksizeBytes, "input buffer too short"); + Check.OutputLength(outBytes, outOff, blocksizeBytes, "output buffer too short"); + + Pack.LE_To_UInt64(inBytes, inOff, currentBlock); + ProcessBlock(this.currentBlock, this.currentBlock); + Pack.UInt64_To_LE(currentBlock, outBytes, outOff); + return blocksizeBytes; } - public virtual int ProcessBlock(byte[] inBytes, int inOff, byte[] outBytes, int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) { - if ((outOff + blocksizeBytes) > outBytes.Length) - { - throw new DataLengthException("Output buffer too short"); - } + Check.DataLength(input, blocksizeBytes, "input buffer too short"); + Check.OutputLength(output, blocksizeBytes, "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); - } + Pack.LE_To_UInt64(input, currentBlock); ProcessBlock(this.currentBlock, this.currentBlock); - for (int i = 0; i < blocksizeBytes; i += 8) - { - WordToBytes(this.currentBlock[i >> 3], outBytes, outOff + i); - } - + Pack.UInt64_To_LE(currentBlock, output); return blocksizeBytes; } +#endif /// /// Process a block of data represented as 64 bit words. @@ -329,13 +316,9 @@ internal int ProcessBlock(ulong[] inWords, ulong[] outWords) } if (inWords.Length != blocksizeWords) - { - throw new DataLengthException("Input buffer too short"); - } + throw new DataLengthException("input buffer too short"); if (outWords.Length != blocksizeWords) - { - throw new DataLengthException("Output buffer too short"); - } + throw new OutputLengthException("output buffer too short"); if (forEncryption) { @@ -349,54 +332,6 @@ internal int ProcessBlock(ulong[] inWords, ulong[] 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. */ diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/TnepresEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/TnepresEngine.cs index fc3c2e6..342fe58 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/TnepresEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/TnepresEngine.cs @@ -2,8 +2,8 @@ #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 { @@ -35,7 +35,7 @@ public override string AlgorithmName * @param key The user-key bytes (multiples of 4) to use. * @exception ArgumentException */ - protected override int[] MakeWorkingKey(byte[] key) + internal override int[] MakeWorkingKey(byte[] key) { // // pad key to 256 bits @@ -73,7 +73,7 @@ protected override int[] MakeWorkingKey(byte[] key) // for (int i = 8; i < 16; i++) { - kPad[i] = RotateLeft(kPad[i - 8] ^ kPad[i - 5] ^ kPad[i - 3] ^ kPad[i - 1] ^ PHI ^ (i - 8), 11); + kPad[i] = Integers.RotateLeft(kPad[i - 8] ^ kPad[i - 5] ^ kPad[i - 3] ^ kPad[i - 1] ^ PHI ^ (i - 8), 11); } Array.Copy(kPad, 8, w, 0, 8); @@ -83,7 +83,7 @@ protected override int[] MakeWorkingKey(byte[] key) // for (int i = 8; i < amount; i++) { - w[i] = RotateLeft(w[i - 8] ^ w[i - 5] ^ w[i - 3] ^ w[i - 1] ^ PHI ^ i, 11); + w[i] = Integers.RotateLeft(w[i - 8] ^ w[i - 5] ^ w[i - 3] ^ w[i - 1] ^ PHI ^ i, 11); } // @@ -159,15 +159,131 @@ protected override int[] MakeWorkingKey(byte[] key) return w; } - /** - * Encrypt one block of plaintext. - * - * @param input the array containing the input data. - * @param inOff offset into the in array the data starts at. - * @param output the array the output data will be copied into. - * @param outOff the offset into the out array the output will start at. - */ - protected override void EncryptBlock(byte[] input, int inOff, byte[] output, int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal override void EncryptBlock(ReadOnlySpan input, Span output) + { + X3 = (int)Pack.BE_To_UInt32(input); + X2 = (int)Pack.BE_To_UInt32(input[4..]); + X1 = (int)Pack.BE_To_UInt32(input[8..]); + X0 = (int)Pack.BE_To_UInt32(input[12..]); + + Sb0(wKey[0] ^ X0, wKey[1] ^ X1, wKey[2] ^ X2, wKey[3] ^ X3); LT(); + Sb1(wKey[4] ^ X0, wKey[5] ^ X1, wKey[6] ^ X2, wKey[7] ^ X3); LT(); + Sb2(wKey[8] ^ X0, wKey[9] ^ X1, wKey[10] ^ X2, wKey[11] ^ X3); LT(); + Sb3(wKey[12] ^ X0, wKey[13] ^ X1, wKey[14] ^ X2, wKey[15] ^ X3); LT(); + Sb4(wKey[16] ^ X0, wKey[17] ^ X1, wKey[18] ^ X2, wKey[19] ^ X3); LT(); + Sb5(wKey[20] ^ X0, wKey[21] ^ X1, wKey[22] ^ X2, wKey[23] ^ X3); LT(); + Sb6(wKey[24] ^ X0, wKey[25] ^ X1, wKey[26] ^ X2, wKey[27] ^ X3); LT(); + Sb7(wKey[28] ^ X0, wKey[29] ^ X1, wKey[30] ^ X2, wKey[31] ^ X3); LT(); + Sb0(wKey[32] ^ X0, wKey[33] ^ X1, wKey[34] ^ X2, wKey[35] ^ X3); LT(); + Sb1(wKey[36] ^ X0, wKey[37] ^ X1, wKey[38] ^ X2, wKey[39] ^ X3); LT(); + Sb2(wKey[40] ^ X0, wKey[41] ^ X1, wKey[42] ^ X2, wKey[43] ^ X3); LT(); + Sb3(wKey[44] ^ X0, wKey[45] ^ X1, wKey[46] ^ X2, wKey[47] ^ X3); LT(); + Sb4(wKey[48] ^ X0, wKey[49] ^ X1, wKey[50] ^ X2, wKey[51] ^ X3); LT(); + Sb5(wKey[52] ^ X0, wKey[53] ^ X1, wKey[54] ^ X2, wKey[55] ^ X3); LT(); + Sb6(wKey[56] ^ X0, wKey[57] ^ X1, wKey[58] ^ X2, wKey[59] ^ X3); LT(); + Sb7(wKey[60] ^ X0, wKey[61] ^ X1, wKey[62] ^ X2, wKey[63] ^ X3); LT(); + Sb0(wKey[64] ^ X0, wKey[65] ^ X1, wKey[66] ^ X2, wKey[67] ^ X3); LT(); + Sb1(wKey[68] ^ X0, wKey[69] ^ X1, wKey[70] ^ X2, wKey[71] ^ X3); LT(); + Sb2(wKey[72] ^ X0, wKey[73] ^ X1, wKey[74] ^ X2, wKey[75] ^ X3); LT(); + Sb3(wKey[76] ^ X0, wKey[77] ^ X1, wKey[78] ^ X2, wKey[79] ^ X3); LT(); + Sb4(wKey[80] ^ X0, wKey[81] ^ X1, wKey[82] ^ X2, wKey[83] ^ X3); LT(); + Sb5(wKey[84] ^ X0, wKey[85] ^ X1, wKey[86] ^ X2, wKey[87] ^ X3); LT(); + Sb6(wKey[88] ^ X0, wKey[89] ^ X1, wKey[90] ^ X2, wKey[91] ^ X3); LT(); + Sb7(wKey[92] ^ X0, wKey[93] ^ X1, wKey[94] ^ X2, wKey[95] ^ X3); LT(); + Sb0(wKey[96] ^ X0, wKey[97] ^ X1, wKey[98] ^ X2, wKey[99] ^ X3); LT(); + Sb1(wKey[100] ^ X0, wKey[101] ^ X1, wKey[102] ^ X2, wKey[103] ^ X3); LT(); + Sb2(wKey[104] ^ X0, wKey[105] ^ X1, wKey[106] ^ X2, wKey[107] ^ X3); LT(); + Sb3(wKey[108] ^ X0, wKey[109] ^ X1, wKey[110] ^ X2, wKey[111] ^ X3); LT(); + Sb4(wKey[112] ^ X0, wKey[113] ^ X1, wKey[114] ^ X2, wKey[115] ^ X3); LT(); + Sb5(wKey[116] ^ X0, wKey[117] ^ X1, wKey[118] ^ X2, wKey[119] ^ X3); LT(); + Sb6(wKey[120] ^ X0, wKey[121] ^ X1, wKey[122] ^ X2, wKey[123] ^ X3); LT(); + Sb7(wKey[124] ^ X0, wKey[125] ^ X1, wKey[126] ^ X2, wKey[127] ^ X3); + + Pack.UInt32_To_BE((uint)(wKey[131] ^ X3), output); + Pack.UInt32_To_BE((uint)(wKey[130] ^ X2), output[4..]); + Pack.UInt32_To_BE((uint)(wKey[129] ^ X1), output[8..]); + Pack.UInt32_To_BE((uint)(wKey[128] ^ X0), output[12..]); + } + + internal override void DecryptBlock(ReadOnlySpan input, Span output) + { + X3 = wKey[131] ^ (int)Pack.BE_To_UInt32(input); + X2 = wKey[130] ^ (int)Pack.BE_To_UInt32(input[4..]); + X1 = wKey[129] ^ (int)Pack.BE_To_UInt32(input[8..]); + X0 = wKey[128] ^ (int)Pack.BE_To_UInt32(input[12..]); + + Ib7(X0, X1, X2, X3); + X0 ^= wKey[124]; X1 ^= wKey[125]; X2 ^= wKey[126]; X3 ^= wKey[127]; + InverseLT(); Ib6(X0, X1, X2, X3); + X0 ^= wKey[120]; X1 ^= wKey[121]; X2 ^= wKey[122]; X3 ^= wKey[123]; + InverseLT(); Ib5(X0, X1, X2, X3); + X0 ^= wKey[116]; X1 ^= wKey[117]; X2 ^= wKey[118]; X3 ^= wKey[119]; + InverseLT(); Ib4(X0, X1, X2, X3); + X0 ^= wKey[112]; X1 ^= wKey[113]; X2 ^= wKey[114]; X3 ^= wKey[115]; + InverseLT(); Ib3(X0, X1, X2, X3); + X0 ^= wKey[108]; X1 ^= wKey[109]; X2 ^= wKey[110]; X3 ^= wKey[111]; + InverseLT(); Ib2(X0, X1, X2, X3); + X0 ^= wKey[104]; X1 ^= wKey[105]; X2 ^= wKey[106]; X3 ^= wKey[107]; + InverseLT(); Ib1(X0, X1, X2, X3); + X0 ^= wKey[100]; X1 ^= wKey[101]; X2 ^= wKey[102]; X3 ^= wKey[103]; + InverseLT(); Ib0(X0, X1, X2, X3); + X0 ^= wKey[96]; X1 ^= wKey[97]; X2 ^= wKey[98]; X3 ^= wKey[99]; + InverseLT(); Ib7(X0, X1, X2, X3); + X0 ^= wKey[92]; X1 ^= wKey[93]; X2 ^= wKey[94]; X3 ^= wKey[95]; + InverseLT(); Ib6(X0, X1, X2, X3); + X0 ^= wKey[88]; X1 ^= wKey[89]; X2 ^= wKey[90]; X3 ^= wKey[91]; + InverseLT(); Ib5(X0, X1, X2, X3); + X0 ^= wKey[84]; X1 ^= wKey[85]; X2 ^= wKey[86]; X3 ^= wKey[87]; + InverseLT(); Ib4(X0, X1, X2, X3); + X0 ^= wKey[80]; X1 ^= wKey[81]; X2 ^= wKey[82]; X3 ^= wKey[83]; + InverseLT(); Ib3(X0, X1, X2, X3); + X0 ^= wKey[76]; X1 ^= wKey[77]; X2 ^= wKey[78]; X3 ^= wKey[79]; + InverseLT(); Ib2(X0, X1, X2, X3); + X0 ^= wKey[72]; X1 ^= wKey[73]; X2 ^= wKey[74]; X3 ^= wKey[75]; + InverseLT(); Ib1(X0, X1, X2, X3); + X0 ^= wKey[68]; X1 ^= wKey[69]; X2 ^= wKey[70]; X3 ^= wKey[71]; + InverseLT(); Ib0(X0, X1, X2, X3); + X0 ^= wKey[64]; X1 ^= wKey[65]; X2 ^= wKey[66]; X3 ^= wKey[67]; + InverseLT(); Ib7(X0, X1, X2, X3); + X0 ^= wKey[60]; X1 ^= wKey[61]; X2 ^= wKey[62]; X3 ^= wKey[63]; + InverseLT(); Ib6(X0, X1, X2, X3); + X0 ^= wKey[56]; X1 ^= wKey[57]; X2 ^= wKey[58]; X3 ^= wKey[59]; + InverseLT(); Ib5(X0, X1, X2, X3); + X0 ^= wKey[52]; X1 ^= wKey[53]; X2 ^= wKey[54]; X3 ^= wKey[55]; + InverseLT(); Ib4(X0, X1, X2, X3); + X0 ^= wKey[48]; X1 ^= wKey[49]; X2 ^= wKey[50]; X3 ^= wKey[51]; + InverseLT(); Ib3(X0, X1, X2, X3); + X0 ^= wKey[44]; X1 ^= wKey[45]; X2 ^= wKey[46]; X3 ^= wKey[47]; + InverseLT(); Ib2(X0, X1, X2, X3); + X0 ^= wKey[40]; X1 ^= wKey[41]; X2 ^= wKey[42]; X3 ^= wKey[43]; + InverseLT(); Ib1(X0, X1, X2, X3); + X0 ^= wKey[36]; X1 ^= wKey[37]; X2 ^= wKey[38]; X3 ^= wKey[39]; + InverseLT(); Ib0(X0, X1, X2, X3); + X0 ^= wKey[32]; X1 ^= wKey[33]; X2 ^= wKey[34]; X3 ^= wKey[35]; + InverseLT(); Ib7(X0, X1, X2, X3); + X0 ^= wKey[28]; X1 ^= wKey[29]; X2 ^= wKey[30]; X3 ^= wKey[31]; + InverseLT(); Ib6(X0, X1, X2, X3); + X0 ^= wKey[24]; X1 ^= wKey[25]; X2 ^= wKey[26]; X3 ^= wKey[27]; + InverseLT(); Ib5(X0, X1, X2, X3); + X0 ^= wKey[20]; X1 ^= wKey[21]; X2 ^= wKey[22]; X3 ^= wKey[23]; + InverseLT(); Ib4(X0, X1, X2, X3); + X0 ^= wKey[16]; X1 ^= wKey[17]; X2 ^= wKey[18]; X3 ^= wKey[19]; + InverseLT(); Ib3(X0, X1, X2, X3); + X0 ^= wKey[12]; X1 ^= wKey[13]; X2 ^= wKey[14]; X3 ^= wKey[15]; + InverseLT(); Ib2(X0, X1, X2, X3); + X0 ^= wKey[8]; X1 ^= wKey[9]; X2 ^= wKey[10]; X3 ^= wKey[11]; + InverseLT(); Ib1(X0, X1, X2, X3); + X0 ^= wKey[4]; X1 ^= wKey[5]; X2 ^= wKey[6]; X3 ^= wKey[7]; + InverseLT(); Ib0(X0, X1, X2, X3); + + Pack.UInt32_To_BE((uint)(X3 ^ wKey[3]), output); + Pack.UInt32_To_BE((uint)(X2 ^ wKey[2]), output[4..]); + Pack.UInt32_To_BE((uint)(X1 ^ wKey[1]), output[8..]); + Pack.UInt32_To_BE((uint)(X0 ^ wKey[0]), output[12..]); + } +#else + internal override void EncryptBlock(byte[] input, int inOff, byte[] output, int outOff) { X3 = (int)Pack.BE_To_UInt32(input, inOff); X2 = (int)Pack.BE_To_UInt32(input, inOff + 4); @@ -213,15 +329,7 @@ protected override void EncryptBlock(byte[] input, int inOff, byte[] output, int Pack.UInt32_To_BE((uint)(wKey[128] ^ X0), output, outOff + 12); } - /** - * Decrypt one block of ciphertext. - * - * @param input the array containing the input data. - * @param inOff offset into the in array the data starts at. - * @param output the array the output data will be copied into. - * @param outOff the offset into the out array the output will start at. - */ - protected override void DecryptBlock(byte[] input, int inOff, byte[] output, int outOff) + internal override void DecryptBlock(byte[] input, int inOff, byte[] output, int outOff) { X3 = wKey[131] ^ (int)Pack.BE_To_UInt32(input, inOff); X2 = wKey[130] ^ (int)Pack.BE_To_UInt32(input, inOff + 4); @@ -297,6 +405,7 @@ protected override void DecryptBlock(byte[] input, int inOff, byte[] output, int Pack.UInt32_To_BE((uint)(X1 ^ wKey[1]), output, outOff + 8); Pack.UInt32_To_BE((uint)(X0 ^ wKey[0]), output, outOff + 12); } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/TwofishEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/TwofishEngine.cs index 685de60..231fd1f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/TwofishEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/TwofishEngine.cs @@ -271,7 +271,7 @@ public void Init( ICipherParameters parameters) { if (!(parameters is KeyParameter)) - throw new ArgumentException("invalid parameter passed to Twofish init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + throw new ArgumentException("invalid parameter passed to Twofish init - " + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); this.encrypting = forEncryption; this.workingKey = ((KeyParameter)parameters).GetKey(); @@ -296,16 +296,7 @@ public string AlgorithmName get { return "Twofish"; } } - public bool IsPartialBlockOkay - { - get { return false; } - } - - public int ProcessBlock( - byte[] input, - int inOff, - byte[] output, - int outOff) + public int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { if (workingKey == null) throw new InvalidOperationException("Twofish not initialised"); @@ -313,6 +304,16 @@ public int ProcessBlock( Check.DataLength(input, inOff, BLOCK_SIZE, "input buffer too short"); Check.OutputLength(output, outOff, BLOCK_SIZE, "output buffer too short"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + if (encrypting) + { + EncryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); + } + else + { + DecryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); + } +#else if (encrypting) { EncryptBlock(input, inOff, output, outOff); @@ -321,17 +322,32 @@ public int ProcessBlock( { DecryptBlock(input, inOff, output, outOff); } +#endif return BLOCK_SIZE; } - public void Reset() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessBlock(ReadOnlySpan input, Span output) { - if (this.workingKey != null) + if (workingKey == null) + throw new InvalidOperationException("Twofish not initialised"); + + Check.DataLength(input, BLOCK_SIZE, "input buffer too short"); + Check.OutputLength(output, BLOCK_SIZE, "output buffer too short"); + + if (encrypting) + { + EncryptBlock(input, output); + } + else { - SetKey(this.workingKey); + DecryptBlock(input, output); } + + return BLOCK_SIZE; } +#endif public int GetBlockSize() { @@ -353,7 +369,7 @@ private void SetKey(byte[] key) /* * k64Cnt is the number of 8 byte blocks (64 chunks) that are in the input key. * The input key is 16, 24 or 32 bytes, so the range for k64Cnt is 2..4 - */ + */ for (int i = 0; i < k64Cnt; i++) { int p = i * 8; @@ -426,6 +442,7 @@ private void SetKey(byte[] key) */ } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ /** * Encrypt the given input starting at the given offset and place * the result in the provided buffer starting at the given offset. @@ -434,11 +451,80 @@ private void SetKey(byte[] key) * encryptBlock uses the pre-calculated gSBox[] and subKey[] * arrays. */ - private void EncryptBlock( - byte[] src, - int srcIndex, - byte[] dst, - int dstIndex) + private void EncryptBlock(ReadOnlySpan input, Span output) + { + int x0 = (int)Pack.LE_To_UInt32(input) ^ gSubKeys[INPUT_WHITEN]; + int x1 = (int)Pack.LE_To_UInt32(input[4..]) ^ gSubKeys[INPUT_WHITEN + 1]; + int x2 = (int)Pack.LE_To_UInt32(input[8..]) ^ gSubKeys[INPUT_WHITEN + 2]; + int x3 = (int)Pack.LE_To_UInt32(input[12..]) ^ gSubKeys[INPUT_WHITEN + 3]; + + int k = ROUND_SUBKEYS; + int t0, t1; + for (int r = 0; r < ROUNDS; r +=2) + { + t0 = Fe32_0(x0); + t1 = Fe32_3(x1); + x2 ^= t0 + t1 + gSubKeys[k++]; + x2 = Integers.RotateRight(x2, 1); + x3 = Integers.RotateLeft(x3, 1) ^ (t0 + 2*t1 + gSubKeys[k++]); + + t0 = Fe32_0(x2); + t1 = Fe32_3(x3); + x0 ^= t0 + t1 + gSubKeys[k++]; + x0 = Integers.RotateRight(x0, 1); + x1 = Integers.RotateLeft(x1, 1) ^ (t0 + 2*t1 + gSubKeys[k++]); + } + + Pack.UInt32_To_LE((uint)(x2 ^ gSubKeys[OUTPUT_WHITEN]), output); + Pack.UInt32_To_LE((uint)(x3 ^ gSubKeys[OUTPUT_WHITEN + 1]), output[4..]); + Pack.UInt32_To_LE((uint)(x0 ^ gSubKeys[OUTPUT_WHITEN + 2]), output[8..]); + Pack.UInt32_To_LE((uint)(x1 ^ gSubKeys[OUTPUT_WHITEN + 3]), output[12..]); + } + + /** + * Decrypt the given input starting at the given offset and place + * the result in the provided buffer starting at the given offset. + * The input will be an exact multiple of our blocksize. + */ + private void DecryptBlock(ReadOnlySpan input, Span output) + { + int x2 = (int)Pack.LE_To_UInt32(input) ^ gSubKeys[OUTPUT_WHITEN]; + int x3 = (int)Pack.LE_To_UInt32(input[4..]) ^ gSubKeys[OUTPUT_WHITEN + 1]; + int x0 = (int)Pack.LE_To_UInt32(input[8..]) ^ gSubKeys[OUTPUT_WHITEN + 2]; + int x1 = (int)Pack.LE_To_UInt32(input[12..]) ^ gSubKeys[OUTPUT_WHITEN + 3]; + + int k = ROUND_SUBKEYS + 2 * ROUNDS -1 ; + int t0, t1; + for (int r = 0; r< ROUNDS ; r +=2) + { + t0 = Fe32_0(x2); + t1 = Fe32_3(x3); + x1 ^= t0 + 2*t1 + gSubKeys[k--]; + x0 = Integers.RotateLeft(x0, 1) ^ (t0 + t1 + gSubKeys[k--]); + x1 = Integers.RotateRight(x1, 1); + + t0 = Fe32_0(x0); + t1 = Fe32_3(x1); + x3 ^= t0 + 2*t1 + gSubKeys[k--]; + x2 = Integers.RotateLeft(x2, 1) ^ (t0 + t1 + gSubKeys[k--]); + x3 = Integers.RotateRight(x3, 1); + } + + Pack.UInt32_To_LE((uint)(x0 ^ gSubKeys[INPUT_WHITEN]), output); + Pack.UInt32_To_LE((uint)(x1 ^ gSubKeys[INPUT_WHITEN + 1]), output[4..]); + Pack.UInt32_To_LE((uint)(x2 ^ gSubKeys[INPUT_WHITEN + 2]), output[8..]); + Pack.UInt32_To_LE((uint)(x3 ^ gSubKeys[INPUT_WHITEN + 3]), output[12..]); + } +#else + /** + * Encrypt the given input starting at the given offset and place + * the result in the provided buffer starting at the given offset. + * The input will be an exact multiple of our blocksize. + * + * encryptBlock uses the pre-calculated gSBox[] and subKey[] + * arrays. + */ + private void EncryptBlock(byte[] src, int srcIndex, byte[] dst, int dstIndex) { int x0 = (int)Pack.LE_To_UInt32(src, srcIndex) ^ gSubKeys[INPUT_WHITEN]; int x1 = (int)Pack.LE_To_UInt32(src, srcIndex + 4) ^ gSubKeys[INPUT_WHITEN + 1]; @@ -473,11 +559,7 @@ private void EncryptBlock( * the result in the provided buffer starting at the given offset. * The input will be an exact multiple of our blocksize. */ - private void DecryptBlock( - byte[] src, - int srcIndex, - byte[] dst, - int dstIndex) + private void DecryptBlock(byte[] src, int srcIndex, byte[] dst, int dstIndex) { int x2 = (int)Pack.LE_To_UInt32(src, srcIndex) ^ gSubKeys[OUTPUT_WHITEN]; int x3 = (int)Pack.LE_To_UInt32(src, srcIndex + 4) ^ gSubKeys[OUTPUT_WHITEN + 1]; @@ -486,7 +568,7 @@ private void DecryptBlock( int k = ROUND_SUBKEYS + 2 * ROUNDS -1 ; int t0, t1; - for (int r = 0; r< ROUNDS ; r +=2) + for (int r = 0; r < ROUNDS ; r += 2) { t0 = Fe32_0(x2); t1 = Fe32_3(x3); @@ -506,6 +588,7 @@ private void DecryptBlock( Pack.UInt32_To_LE((uint)(x2 ^ gSubKeys[INPUT_WHITEN + 2]), dst, dstIndex + 8); Pack.UInt32_To_LE((uint)(x3 ^ gSubKeys[INPUT_WHITEN + 3]), dst, dstIndex + 12); } +#endif /* * TODO: This can be optimised and made cleaner by combining @@ -657,7 +740,7 @@ private int Fe32_3(int x) gSBox[ 0x200 + 2*((int)((uint)x >> 8) & 0xff) ] ^ gSBox[ 0x201 + 2*((int)((uint)x >> 16) & 0xff) ]; } - } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/VMPCEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/VMPCEngine.cs index c1da4ca..ecb20df 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/VMPCEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/VMPCEngine.cs @@ -99,19 +99,42 @@ public virtual void ProcessBytes( for (int i = 0; i < len; i++) { - s = P[(s + P[n & 0xff]) & 0xff]; - byte z = P[(P[(P[s & 0xff]) & 0xff] + 1) & 0xff]; + byte pn = P[n]; + s = P[(s + pn) & 0xff]; + byte ps = P[s]; + byte z = P[(P[ps] + 1) & 0xff]; // encryption - byte temp = P[n & 0xff]; - P[n & 0xff] = P[s & 0xff]; - P[s & 0xff] = temp; - n = (byte) ((n + 1) & 0xff); + P[n] = ps; + P[s] = pn; + n = (byte)(n + 1); // xor - output[i + outOff] = (byte) (input[i + inOff] ^ z); + output[i + outOff] = (byte)(input[i + inOff] ^ z); } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void ProcessBytes(ReadOnlySpan input, Span output) + { + Check.OutputLength(output, input.Length, "output buffer too short"); + + for (int i = 0; i < input.Length; i++) + { + byte pn = P[n]; + s = P[(s + pn) & 0xff]; + byte ps = P[s]; + byte z = P[(P[ps] + 1) & 0xff]; + // encryption + P[n] = ps; + P[s] = pn; + n = (byte)(n + 1); + + // xor + output[i] = (byte)(input[i] ^ z); + } + } +#endif + public virtual void Reset() { InitKey(this.workingKey, this.workingIV); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/XTEAEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/XTEAEngine.cs index b2fdaad..b6b7371 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/XTEAEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/engines/XTEAEngine.cs @@ -42,11 +42,6 @@ public virtual string AlgorithmName get { return "XTEA"; } } - public virtual bool IsPartialBlockOkay - { - get { return false; } - } - public virtual int GetBlockSize() { return block_size; @@ -67,7 +62,7 @@ public virtual void Init( if (!(parameters is KeyParameter)) { throw new ArgumentException("invalid parameter passed to TEA init - " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); } _forEncryption = forEncryption; @@ -78,11 +73,7 @@ public virtual void Init( setKey(p.GetKey()); } - public virtual int ProcessBlock( - byte[] inBytes, - int inOff, - byte[] outBytes, - int outOff) + public virtual int ProcessBlock(byte[] inBytes, int inOff, byte[] outBytes, int outOff) { if (!_initialised) throw new InvalidOperationException(AlgorithmName + " not initialised"); @@ -90,14 +81,31 @@ public virtual int ProcessBlock( 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); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return _forEncryption + ? EncryptBlock(inBytes.AsSpan(inOff), outBytes.AsSpan(outOff)) + : DecryptBlock(inBytes.AsSpan(inOff), outBytes.AsSpan(outOff)); +#else + return _forEncryption + ? EncryptBlock(inBytes, inOff, outBytes, outOff) + : DecryptBlock(inBytes, inOff, outBytes, outOff); +#endif } - public virtual void Reset() - { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) + { + if (!_initialised) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + + Check.DataLength(input, block_size, "input buffer too short"); + Check.OutputLength(output, block_size, "output buffer too short"); + + return _forEncryption + ? EncryptBlock(input, output) + : DecryptBlock(input, output); } +#endif /** * Re-key the cipher. @@ -121,13 +129,45 @@ private void setKey( } } - private int encryptBlock( - byte[] inBytes, - int inOff, - byte[] outBytes, - int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int EncryptBlock(ReadOnlySpan input, Span output) + { + // Pack bytes into integers + uint v0 = Pack.BE_To_UInt32(input); + uint v1 = Pack.BE_To_UInt32(input[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, output); + Pack.UInt32_To_BE(v1, output[4..]); + + return block_size; + } + + private int DecryptBlock(ReadOnlySpan input, Span output) { // Pack bytes into integers + uint v0 = Pack.BE_To_UInt32(input); + uint v1 = Pack.BE_To_UInt32(input[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, output); + Pack.UInt32_To_BE(v1, output[4..]); + + return block_size; + } +#else + private int EncryptBlock(byte[] inBytes, int inOff, byte[] outBytes, int outOff) + { uint v0 = Pack.BE_To_UInt32(inBytes, inOff); uint v1 = Pack.BE_To_UInt32(inBytes, inOff + 4); @@ -143,11 +183,7 @@ private int encryptBlock( return block_size; } - private int decryptBlock( - byte[] inBytes, - int inOff, - byte[] outBytes, - int outOff) + private int DecryptBlock(byte[] inBytes, int inOff, byte[] outBytes, int outOff) { // Pack bytes into integers uint v0 = Pack.BE_To_UInt32(inBytes, inOff); @@ -164,6 +200,7 @@ private int decryptBlock( return block_size; } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/fpe/FpeEngine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/fpe/FpeEngine.cs index e908004..b5a5b29 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/fpe/FpeEngine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/fpe/FpeEngine.cs @@ -55,9 +55,9 @@ public virtual int ProcessBlock(byte[] inBuf, int inOff, int length, byte[] outB protected static bool IsOverrideSet(string propName) { - string propValue = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetEnvironmentVariable(propName); + string propValue = Org.BouncyCastle.Utilities.Platform.GetEnvironmentVariable(propName); - return propValue != null && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase("true", propValue); + return propValue != null && Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase("true", propValue); } /// diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/fpe/FpeFf1Engine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/fpe/FpeFf1Engine.cs index 551254e..4592e8d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/fpe/FpeFf1Engine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/fpe/FpeFf1Engine.cs @@ -2,7 +2,6 @@ #pragma warning disable using System; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; @@ -12,7 +11,7 @@ public class FpeFf1Engine : FpeEngine { public FpeFf1Engine() - : this(new AesEngine()) + : this(AesUtilities.CreateEngine()) { } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/fpe/FpeFf3_1Engine.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/fpe/FpeFf3_1Engine.cs index 17519a6..d1e6788 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/fpe/FpeFf3_1Engine.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/fpe/FpeFf3_1Engine.cs @@ -13,7 +13,7 @@ public class FpeFf3_1Engine : FpeEngine { public FpeFf3_1Engine() - : this(new AesEngine()) + : this(AesUtilities.CreateEngine()) { } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/fpe/SP80038G.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/fpe/SP80038G.cs index 2089e99..bf71662 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/fpe/SP80038G.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/fpe/SP80038G.cs @@ -303,14 +303,13 @@ protected static BigInteger calculateY_FF1(IBlockCipher cipher, BigInteger bigRa int t = T.Length; // i. - BigInteger numAB = num(bigRadix, AB); - byte[] bytesAB = BigIntegers.AsUnsignedByteArray(numAB); - int zeroes = -(t + b + 1) & 15; byte[] Q = new byte[t + zeroes + 1 + b]; Array.Copy(T, 0, Q, 0, t); Q[t + zeroes] = (byte)round; - Array.Copy(bytesAB, 0, Q, Q.Length - bytesAB.Length, bytesAB.Length); + + BigInteger numAB = num(bigRadix, AB); + BigIntegers.AsUnsignedByteArray(numAB, Q, Q.Length - b, b); // ii. byte[] R = prf(cipher, Arrays.Concatenate(P, Q)); @@ -321,47 +320,43 @@ protected static BigInteger calculateY_FF1(IBlockCipher cipher, BigInteger bigRa { int sBlocksLen = (d + BLOCK_SIZE - 1) / BLOCK_SIZE; sBlocks = new byte[sBlocksLen * BLOCK_SIZE]; + + uint j0 = Pack.BE_To_UInt32(R, BLOCK_SIZE - 4); Array.Copy(R, 0, sBlocks, 0, BLOCK_SIZE); - byte[] uint32 = new byte[4]; for (uint j = 1; j < sBlocksLen; ++j) { int sOff = (int)(j * BLOCK_SIZE); - Array.Copy(R, 0, sBlocks, sOff, BLOCK_SIZE); - Pack.UInt32_To_BE(j, uint32, 0); - xor(uint32, 0, sBlocks, sOff + BLOCK_SIZE - 4, 4); + + Array.Copy(R, 0, sBlocks, sOff, BLOCK_SIZE - 4); + Pack.UInt32_To_BE(j0 ^ j, sBlocks, sOff + BLOCK_SIZE - 4); + cipher.ProcessBlock(sBlocks, sOff, sBlocks, sOff); } } // iv. - return num(sBlocks, 0, d); + return new BigInteger(1, sBlocks, 0, d); } - protected static BigInteger calculateY_FF3(IBlockCipher cipher, BigInteger bigRadix, byte[] T, int wOff, uint round, ushort[] AB) + protected static BigInteger calculateY_FF3(IBlockCipher cipher, BigInteger bigRadix, byte[] T, int wOff, + uint round, ushort[] AB) { // ii. byte[] P = new byte[BLOCK_SIZE]; - Pack.UInt32_To_BE(round, P, 0); - xor(T, wOff, P, 0, 4); - BigInteger numAB = num(bigRadix, AB); - - byte[] bytesAB = BigIntegers.AsUnsignedByteArray(numAB); + Pack.UInt32_To_BE(Pack.BE_To_UInt32(T, wOff) ^ round, P, 0); - if ((P.Length - bytesAB.Length) < 4) // to be sure... - { - throw new InvalidOperationException("input out of range"); - } - Array.Copy(bytesAB, 0, P, P.Length - bytesAB.Length, bytesAB.Length); + BigInteger numAB = num(bigRadix, AB); + BigIntegers.AsUnsignedByteArray(numAB, P, 4, BLOCK_SIZE - 4); // iii. - rev(P); + Array.Reverse(P); cipher.ProcessBlock(P, 0, P, 0); - rev(P); + Array.Reverse(P); byte[] S = P; // iv. - return num(S, 0, S.Length); + return new BigInteger(1, S); } protected static void checkArgs(IBlockCipher cipher, bool isFF1, int radix, ushort[] buf, int off, int len) @@ -473,8 +468,8 @@ private static ushort[] decFF3_1(IBlockCipher cipher, int radix, byte[] T, int n int m = u; // Note we keep A, B in reverse order throughout - rev(A); - rev(B); + Array.Reverse(A); + Array.Reverse(B); for (int i = 7; i >= 0; --i) { @@ -496,8 +491,8 @@ private static ushort[] decFF3_1(IBlockCipher cipher, int radix, byte[] T, int n str(bigRadix, c, m, C, 0); } - rev(A); - rev(B); + Array.Reverse(A); + Array.Reverse(B); return Arrays.Concatenate(A, B); } @@ -541,8 +536,8 @@ private static ushort[] encFF3_1(IBlockCipher cipher, int radix, byte[] t, int n int m = v; // Note we keep A, B in reverse order throughout - rev(a); - rev(b); + Array.Reverse(a); + Array.Reverse(b); for (uint i = 0; i < 8; ++i) { @@ -564,17 +559,12 @@ private static ushort[] encFF3_1(IBlockCipher cipher, int radix, byte[] t, int n str(bigRadix, c, m, C, 0); } - rev(a); - rev(b); + Array.Reverse(a); + Array.Reverse(b); return Arrays.Concatenate(a, b); } - protected static BigInteger num(byte[] buf, int off, int len) - { - return new BigInteger(1, Arrays.CopyOfRange(buf, off, off + len)); - } - protected static BigInteger num(BigInteger R, ushort[] x) { BigInteger result = BigInteger.Zero; @@ -588,9 +578,7 @@ protected static BigInteger num(BigInteger R, ushort[] x) protected static byte[] prf(IBlockCipher c, byte[] x) { if ((x.Length % BLOCK_SIZE) != 0) - { throw new ArgumentException(); - } int m = x.Length / BLOCK_SIZE; byte[] y = new byte[BLOCK_SIZE]; @@ -604,42 +592,11 @@ protected static byte[] prf(IBlockCipher c, byte[] x) return y; } - // protected static void rev(byte[] x, int xOff, byte[] y, int yOff, int len) - // { - // for (int i = 1; i <= len; ++i) - // { - // y[yOff + len - i] = x[xOff + i - 1]; - // } - // } - - protected static void rev(byte[] x) - { - int half = x.Length / 2, end = x.Length - 1; - for (int i = 0; i < half; ++i) - { - byte tmp = x[i]; - x[i] = x[end - i]; - x[end - i] = tmp; - } - } - - protected static void rev(ushort[] x) - { - int half = x.Length / 2, end = x.Length - 1; - for (int i = 0; i < half; ++i) - { - ushort tmp = x[i]; - x[i] = x[end - i]; - x[end - i] = tmp; - } - } - protected static void str(BigInteger R, BigInteger x, int m, ushort[] output, int off) { if (x.SignValue < 0) - { throw new ArgumentException(); - } + for (int i = 1; i <= m; ++i) { BigInteger[] qr = x.DivideAndRemainder(R); @@ -647,9 +604,7 @@ protected static void str(BigInteger R, BigInteger x, int m, ushort[] output, in x = qr[0]; } if (x.SignValue != 0) - { throw new ArgumentException(); - } } protected static void xor(byte[] x, int xOff, byte[] y, int yOff, int len) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/BaseKdfBytesGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/BaseKdfBytesGenerator.cs index ecc20b2..1a34a9a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/BaseKdfBytesGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/BaseKdfBytesGenerator.cs @@ -13,7 +13,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators *
* This implementation is based on ISO 18033/P1363a. */ - public class BaseKdfBytesGenerator + public abstract class BaseKdfBytesGenerator : IDerivationFunction { private int counterStart; @@ -27,26 +27,22 @@ public class BaseKdfBytesGenerator * @param counterStart value of counter. * @param digest the digest to be used as the source of derived keys. */ - public BaseKdfBytesGenerator(int counterStart, IDigest digest) + protected BaseKdfBytesGenerator(int counterStart, IDigest digest) { this.counterStart = counterStart; this.digest = digest; } - public virtual void Init(IDerivationParameters parameters) + public void Init(IDerivationParameters parameters) { - if (parameters is KdfParameters) + if (parameters is KdfParameters kdfParameters) { - KdfParameters p = (KdfParameters)parameters; - - shared = p.GetSharedSecret(); - iv = p.GetIV(); + shared = kdfParameters.GetSharedSecret(); + iv = kdfParameters.GetIV(); } - else if (parameters is Iso18033KdfParameters) + else if (parameters is Iso18033KdfParameters iso18033KdfParameters) { - Iso18033KdfParameters p = (Iso18033KdfParameters)parameters; - - shared = p.GetSeed(); + shared = iso18033KdfParameters.GetSeed(); iv = null; } else @@ -58,10 +54,7 @@ public virtual void Init(IDerivationParameters parameters) /** * return the underlying digest. */ - public virtual IDigest Digest - { - get { return digest; } - } + public IDigest Digest => digest; /** * fill len bytes of the output buffer with bytes generated from @@ -70,13 +63,15 @@ public virtual IDigest Digest * @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) + public int GenerateBytes(byte[] output, int outOff, int length) { - if ((output.Length - length) < outOff) - throw new DataLengthException("output buffer too small"); + Check.OutputLength(output, outOff, length, "output buffer too small"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return GenerateBytes(output.AsSpan(outOff, length)); +#else long oBytes = length; - int outLen = digest.GetDigestSize(); + int digestSize = digest.GetDigestSize(); // // this is at odds with the standard implementation, the @@ -87,9 +82,9 @@ public virtual int GenerateBytes(byte[] output, int outOff, int length) if (oBytes > ((2L << 32) - 1)) throw new ArgumentException("Output length too large"); - int cThreshold = (int)((oBytes + outLen - 1) / outLen); + int cThreshold = (int)((oBytes + digestSize - 1) / digestSize); - byte[] dig = new byte[digest.GetDigestSize()]; + byte[] dig = new byte[digestSize]; byte[] C = new byte[4]; Pack.UInt32_To_BE((uint)counterStart, C, 0); @@ -108,11 +103,11 @@ public virtual int GenerateBytes(byte[] output, int outOff, int length) digest.DoFinal(dig, 0); - if (length > outLen) + if (length > digestSize) { - Array.Copy(dig, 0, output, outOff, outLen); - outOff += outLen; - length -= outLen; + Array.Copy(dig, 0, output, outOff, digestSize); + outOff += digestSize; + length -= digestSize; } else { @@ -129,7 +124,70 @@ public virtual int GenerateBytes(byte[] output, int outOff, int length) digest.Reset(); return (int)oBytes; +#endif } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int GenerateBytes(Span output) + { + long oBytes = output.Length; + int digestSize = 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 + digestSize - 1) / digestSize); + + Span dig = digestSize <= 128 + ? stackalloc byte[digestSize] + : new byte[digestSize]; + + Span C = stackalloc byte[4]; + Pack.UInt32_To_BE((uint)counterStart, C); + + uint counterBase = (uint)(counterStart & ~0xFF); + + for (int i = 0; i < cThreshold; i++) + { + digest.BlockUpdate(shared); + digest.BlockUpdate(C); + + if (iv != null) + { + digest.BlockUpdate(iv); + } + + digest.DoFinal(dig); + + int remaining = output.Length; + if (remaining > digestSize) + { + dig.CopyTo(output); + output = output[digestSize..]; + } + else + { + dig[..remaining].CopyTo(output); + } + + if (++C[3] == 0) + { + counterBase += 0x100; + Pack.UInt32_To_BE(counterBase, C); + } + } + + digest.Reset(); + + return (int)oBytes; + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/DesEdeKeyGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/DesEdeKeyGenerator.cs index f559805..b8f411f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/DesEdeKeyGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/DesEdeKeyGenerator.cs @@ -28,8 +28,7 @@ internal DesEdeKeyGenerator( * * @param param the parameters to be used for key generation */ - protected override void engineInit( - KeyGenerationParameters parameters) + protected override void EngineInit(KeyGenerationParameters parameters) { this.random = parameters.Random; this.strength = (parameters.Strength + 7) / 8; @@ -52,7 +51,7 @@ protected override void engineInit( } } - protected override byte[] engineGenerateKey() + protected override byte[] EngineGenerateKey() { byte[] newKey = new byte[strength]; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/DesKeyGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/DesKeyGenerator.cs index 845583f..a37fef6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/DesKeyGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/DesKeyGenerator.cs @@ -26,10 +26,9 @@ internal DesKeyGenerator( * * @param param the parameters to be used for key generation */ - protected override void engineInit( - KeyGenerationParameters parameters) + protected override void EngineInit(KeyGenerationParameters parameters) { - base.engineInit(parameters); + base.EngineInit(parameters); if (strength == 0 || strength == (56 / 8)) { @@ -42,7 +41,7 @@ protected override void engineInit( } } - protected override byte[] engineGenerateKey() + protected override byte[] EngineGenerateKey() { byte[] newKey = new byte[DesParameters.DesKeyLength]; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/ECKeyPairGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/ECKeyPairGenerator.cs index 7fa9498..9aa4719 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/ECKeyPairGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/ECKeyPairGenerator.cs @@ -3,18 +3,14 @@ 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 { @@ -89,7 +85,7 @@ public void Init( if (this.random == null) { - this.random = new SecureRandom(); + this.random = CryptoServicesRegistrar.GetSecureRandom(); } } @@ -135,10 +131,28 @@ protected virtual ECMultiplier CreateBasePointMultiplier() return new FixedPointCombMultiplier(); } - internal static X9ECParameters FindECCurveByOid(DerObjectIdentifier oid) + internal static X9ECParameters FindECCurveByName(string name) { - // TODO ECGost3410NamedCurves support (returns ECDomainParameters though) + X9ECParameters ecP = CustomNamedCurves.GetByName(name); + if (ecP == null) + { + ecP = ECNamedCurveTable.GetByName(name); + } + return ecP; + } + + internal static X9ECParametersHolder FindECCurveByNameLazy(string name) + { + X9ECParametersHolder holder = CustomNamedCurves.GetByNameLazy(name); + if (holder == null) + { + holder = ECNamedCurveTable.GetByNameLazy(name); + } + return holder; + } + internal static X9ECParameters FindECCurveByOid(DerObjectIdentifier oid) + { X9ECParameters ecP = CustomNamedCurves.GetByOid(oid); if (ecP == null) { @@ -147,6 +161,16 @@ internal static X9ECParameters FindECCurveByOid(DerObjectIdentifier oid) return ecP; } + internal static X9ECParametersHolder FindECCurveByOidLazy(DerObjectIdentifier oid) + { + X9ECParametersHolder holder = CustomNamedCurves.GetByOidLazy(oid); + if (holder == null) + { + holder = ECNamedCurveTable.GetByOidLazy(oid); + } + return holder; + } + internal static ECPublicKeyParameters GetCorrespondingPublicKey( ECPrivateKeyParameters privKey) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/HKDFBytesGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/HKDFBytesGenerator.cs index 99b4e5a..eb14aff 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/HKDFBytesGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/HKDFBytesGenerator.cs @@ -15,7 +15,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators * (output keying material) and is likely to have better security properties * than KDF's based on just a hash function. */ - public class HkdfBytesGenerator + public sealed class HkdfBytesGenerator : IDerivationFunction { private HMac hMacHash; @@ -37,12 +37,11 @@ public HkdfBytesGenerator(IDigest hash) this.hashLen = hash.GetDigestSize(); } - public virtual void Init(IDerivationParameters parameters) + public void Init(IDerivationParameters parameters) { - if (!(parameters is HkdfParameters)) + if (!(parameters is HkdfParameters hkdfParameters)) throw new ArgumentException("HKDF parameters required for HkdfBytesGenerator", "parameters"); - HkdfParameters hkdfParameters = (HkdfParameters)parameters; if (hkdfParameters.SkipExtract) { // use IKM directly as PRK @@ -110,46 +109,71 @@ private void ExpandNext() hMacHash.DoFinal(currentT, 0); } - public virtual IDigest Digest - { - get { return hMacHash.GetUnderlyingDigest(); } - } + public IDigest Digest => hMacHash.GetUnderlyingDigest(); - public virtual int GenerateBytes(byte[] output, int outOff, int len) + public int GenerateBytes(byte[] output, int outOff, int length) { - if (generatedBytes + len > 255 * hashLen) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return GenerateBytes(output.AsSpan(outOff, length)); +#else + if (generatedBytes > 255 * hashLen - length) + throw new DataLengthException("HKDF may only be used for 255 * HashLen bytes of output"); + + int toGenerate = length; + int posInT = generatedBytes % hashLen; + if (posInT != 0) { - throw new DataLengthException( - "HKDF may only be used for 255 * HashLen bytes of output"); + // copy what is left in the currentT (1..hash + int toCopy = System.Math.Min(hashLen - posInT, toGenerate); + Array.Copy(currentT, posInT, output, outOff, toCopy); + generatedBytes += toCopy; + toGenerate -= toCopy; + outOff += toCopy; } - if (generatedBytes % hashLen == 0) + while (toGenerate > 0) { ExpandNext(); + int toCopy = System.Math.Min(hashLen, toGenerate); + Array.Copy(currentT, 0, output, outOff, toCopy); + generatedBytes += toCopy; + toGenerate -= toCopy; + outOff += toCopy; } - // copy what is left in the currentT (1..hash - int toGenerate = len; + return length; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int GenerateBytes(Span output) + { + int length = output.Length; + if (generatedBytes > 255 * hashLen - length) + throw new DataLengthException("HKDF may only be used for 255 * HashLen bytes of output"); + 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; + if (posInT != 0) + { + // copy what is left in the currentT (1..hash + int toCopy = System.Math.Min(hashLen - posInT, output.Length); + currentT.AsSpan(posInT, toCopy).CopyTo(output); + generatedBytes += toCopy; + output = output[toCopy..]; + } - while (toGenerate > 0) + while (!output.IsEmpty) { ExpandNext(); - toCopy = System.Math.Min(hashLen, toGenerate); - Array.Copy(currentT, 0, output, outOff, toCopy); + int toCopy = System.Math.Min(hashLen, output.Length); + currentT.AsSpan(0, toCopy).CopyTo(output); generatedBytes += toCopy; - toGenerate -= toCopy; - outOff += toCopy; + output = output[toCopy..]; } - return len; + return length; } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/KDFCounterBytesGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/KDFCounterBytesGenerator.cs index 329229d..d5e98a2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/KDFCounterBytesGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/KDFCounterBytesGenerator.cs @@ -5,17 +5,12 @@ 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.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators { - public class KdfCounterBytesGenerator : IMacDerivationFunction + public sealed class KdfCounterBytesGenerator + : IMacDerivationFunction { - - private static readonly BigInteger IntegerMax = BigInteger.ValueOf(0x7fffffff); - private static readonly BigInteger Two = BigInteger.Two; - - private readonly IMac prf; private readonly int h; @@ -39,13 +34,8 @@ public KdfCounterBytesGenerator(IMac prf) public void Init(IDerivationParameters param) { - KdfCounterParameters kdfParams = param as KdfCounterParameters; - if (kdfParams == null) - { + if (!(param is KdfCounterParameters kdfParams)) throw new ArgumentException("Wrong type of arguments given"); - } - - // --- init mac based PRF --- @@ -59,54 +49,45 @@ public void Init(IDerivationParameters param) int r = kdfParams.R; this.ios = new byte[r / 8]; - BigInteger maxSize = Two.Pow(r).Multiply(BigInteger.ValueOf(h)); - this.maxSizeExcl = maxSize.CompareTo(IntegerMax) == 1 ? - Int32.MaxValue : maxSize.IntValue; + BigInteger maxSize = BigInteger.One.ShiftLeft(r).Multiply(BigInteger.ValueOf(h)); + this.maxSizeExcl = maxSize.BitLength > 31 ? int.MaxValue : maxSize.IntValueExact; // --- set operational state --- generatedBytes = 0; } - - public IMac GetMac() - { - return prf; - } + public IMac Mac => prf; public IDigest Digest { - get { return prf is HMac ? ((HMac)prf).GetUnderlyingDigest() : null; } + get { return (prf as HMac)?.GetUnderlyingDigest(); } } public int GenerateBytes(byte[] output, int outOff, int length) { - int generatedBytesAfter = generatedBytes + length; - if (generatedBytesAfter < 0 || generatedBytesAfter >= maxSizeExcl) - { - throw new DataLengthException( - "Current KDFCTR may only be used for " + maxSizeExcl + " bytes"); - } - - if (generatedBytes % h == 0) - { - generateNext(); - } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return GenerateBytes(output.AsSpan(outOff, length)); +#else + if (generatedBytes >= maxSizeExcl - length) + throw new DataLengthException("Current KDFCTR may only be used for " + maxSizeExcl + " bytes"); - // copy what is left in the currentT (1..hash int toGenerate = length; int posInK = generatedBytes % h; - int leftInK = h - generatedBytes % h; - int toCopy = System.Math.Min(leftInK, toGenerate); - Array.Copy(k, posInK, output, outOff, toCopy); - generatedBytes += toCopy; - toGenerate -= toCopy; - outOff += toCopy; + if (posInK != 0) + { + // copy what is left in the currentT (1..hash + int toCopy = System.Math.Min(h - posInK, toGenerate); + Array.Copy(k, posInK, output, outOff, toCopy); + generatedBytes += toCopy; + toGenerate -= toCopy; + outOff += toCopy; + } while (toGenerate > 0) { - generateNext(); - toCopy = System.Math.Min(h, toGenerate); + GenerateNext(); + int toCopy = System.Math.Min(h, toGenerate); Array.Copy(k, 0, output, outOff, toCopy); generatedBytes += toCopy; toGenerate -= toCopy; @@ -114,38 +95,65 @@ public int GenerateBytes(byte[] output, int outOff, int length) } return length; - +#endif } - private void generateNext() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int GenerateBytes(Span output) { + int length = output.Length; + if (generatedBytes >= maxSizeExcl - length) + throw new DataLengthException("Current KDFCTR may only be used for " + maxSizeExcl + " bytes"); + + int posInK = generatedBytes % h; + if (posInK != 0) + { + // copy what is left in the currentT (1..hash + int toCopy = System.Math.Min(h - posInK, output.Length); + k.AsSpan(posInK, toCopy).CopyTo(output); + generatedBytes += toCopy; + output = output[toCopy..]; + } + + while (!output.IsEmpty) + { + GenerateNext(); + int toCopy = System.Math.Min(h, output.Length); + k.AsSpan(0, toCopy).CopyTo(output); + generatedBytes += toCopy; + output = output[toCopy..]; + } + + return length; + } +#endif + private void GenerateNext() + { int i = generatedBytes / h + 1; // encode i into counter buffer switch (ios.Length) { - case 4: - ios[0] = (byte)(i >> 24); - goto case 3; + case 4: + ios[0] = (byte)(i >> 24); + // fall through + goto case 3; + case 3: + ios[ios.Length - 3] = (byte)(i >> 16); + // fall through + goto case 2; + case 2: + ios[ios.Length - 2] = (byte)(i >> 8); // fall through - case 3: - ios[ios.Length - 3] = (byte)(i >> 16); - // fall through - goto case 2; - case 2: - ios[ios.Length - 2] = (byte)(i >> 8); - // fall through - goto case 1; - case 1: - ios[ios.Length - 1] = (byte)i; - break; - default: - throw new InvalidOperationException("Unsupported size of counter i"); + goto case 1; + case 1: + ios[ios.Length - 1] = (byte)i; + break; + default: + throw new InvalidOperationException("Unsupported size of counter i"); } - - // special case for K(0): K(0) is empty, so no update prf.BlockUpdate(fixedInputDataCtrPrefix, 0, fixedInputDataCtrPrefix.Length); prf.BlockUpdate(ios, 0, ios.Length); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/KDFDoublePipelineIterationBytesGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/KDFDoublePipelineIterationBytesGenerator.cs index 7586460..2841d8a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/KDFDoublePipelineIterationBytesGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/KDFDoublePipelineIterationBytesGenerator.cs @@ -8,11 +8,9 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators { - public class KdfDoublePipelineIterationBytesGenerator : IMacDerivationFunction + public sealed class KdfDoublePipelineIterationBytesGenerator + : IMacDerivationFunction { - private static readonly BigInteger IntegerMax = BigInteger.ValueOf(0x7fffffff); - private static readonly BigInteger Two = BigInteger.Two; - // fields set by the constructor private readonly IMac prf; private readonly int h; @@ -30,7 +28,6 @@ public class KdfDoublePipelineIterationBytesGenerator : IMacDerivationFunction private byte[] a; private byte[] k; - public KdfDoublePipelineIterationBytesGenerator(IMac prf) { this.prf = prf; @@ -39,16 +36,10 @@ public KdfDoublePipelineIterationBytesGenerator(IMac prf) this.k = new byte[h]; } - public void Init(IDerivationParameters parameters) { - KdfDoublePipelineIterationParameters dpiParams = parameters as KdfDoublePipelineIterationParameters; - if (dpiParams == null) - { + if (!(parameters is KdfDoublePipelineIterationParameters dpiParams)) throw new ArgumentException("Wrong type of arguments given"); - } - - // --- init mac based PRF --- @@ -64,13 +55,12 @@ public void Init(IDerivationParameters parameters) if (dpiParams.UseCounter) { // this is more conservative than the spec - BigInteger maxSize = Two.Pow(r).Multiply(BigInteger.ValueOf(h)); - this.maxSizeExcl = maxSize.CompareTo(IntegerMax) == 1 ? - Int32.MaxValue : maxSize.IntValue; + BigInteger maxSize = BigInteger.One.ShiftLeft(r).Multiply(BigInteger.ValueOf(h)); + this.maxSizeExcl = maxSize.BitLength > 31 ? int.MaxValue : maxSize.IntValueExact; } else { - this.maxSizeExcl = IntegerMax.IntValue; + this.maxSizeExcl = int.MaxValue; } this.useCounter = dpiParams.UseCounter; @@ -80,12 +70,8 @@ public void Init(IDerivationParameters parameters) generatedBytes = 0; } - - - - private void generateNext() + private void GenerateNext() { - if (generatedBytes == 0) { // --- step 4 --- @@ -109,23 +95,23 @@ private void generateNext() // encode i into counter buffer switch (ios.Length) { - case 4: - ios[0] = (byte)(i >> 24); - // fall through - goto case 3; - case 3: - ios[ios.Length - 3] = (byte)(i >> 16); - // fall through - goto case 2; - case 2: - ios[ios.Length - 2] = (byte)(i >> 8); - // fall through - goto case 1; - case 1: - ios[ios.Length - 1] = (byte)i; - break; - default: - throw new InvalidOperationException("Unsupported size of counter i"); + case 4: + ios[0] = (byte)(i >> 24); + // fall through + goto case 3; + case 3: + ios[ios.Length - 3] = (byte)(i >> 16); + // fall through + goto case 2; + case 2: + ios[ios.Length - 2] = (byte)(i >> 8); + // fall through + goto case 1; + case 1: + ios[ios.Length - 1] = (byte)i; + break; + default: + throw new InvalidOperationException("Unsupported size of counter i"); } prf.BlockUpdate(ios, 0, ios.Length); } @@ -136,37 +122,33 @@ private void generateNext() public IDigest Digest { - get { return prf is HMac ? ((HMac)prf).GetUnderlyingDigest() : null; } + get { return (prf as HMac)?.GetUnderlyingDigest(); } } public int GenerateBytes(byte[] output, int outOff, int length) { - int generatedBytesAfter = generatedBytes + length; - if (generatedBytesAfter < 0 || generatedBytesAfter >= maxSizeExcl) - { - throw new DataLengthException( - "Current KDFCTR may only be used for " + maxSizeExcl + " bytes"); - } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return GenerateBytes(output.AsSpan(outOff, length)); +#else + if (generatedBytes >= maxSizeExcl - length) + throw new DataLengthException("Current KDFCTR may only be used for " + maxSizeExcl + " bytes"); - if (generatedBytes % h == 0) - { - generateNext(); - } - - // copy what is left in the currentT (1..hash int toGenerate = length; int posInK = generatedBytes % h; - int leftInK = h - generatedBytes % h; - int toCopy = System.Math.Min(leftInK, toGenerate); - Array.Copy(k, posInK, output, outOff, toCopy); - generatedBytes += toCopy; - toGenerate -= toCopy; - outOff += toCopy; + if (posInK != 0) + { + // copy what is left in the currentT (1..hash + int toCopy = System.Math.Min(h - posInK, toGenerate); + Array.Copy(k, posInK, output, outOff, toCopy); + generatedBytes += toCopy; + toGenerate -= toCopy; + outOff += toCopy; + } while (toGenerate > 0) { - generateNext(); - toCopy = System.Math.Min(h, toGenerate); + GenerateNext(); + int toCopy = System.Math.Min(h, toGenerate); Array.Copy(k, 0, output, outOff, toCopy); generatedBytes += toCopy; toGenerate -= toCopy; @@ -174,12 +156,41 @@ public int GenerateBytes(byte[] output, int outOff, int length) } return length; +#endif } - public IMac GetMac() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int GenerateBytes(Span output) { - return prf; + int length = output.Length; + if (generatedBytes >= maxSizeExcl - length) + throw new DataLengthException("Current KDFCTR may only be used for " + maxSizeExcl + " bytes"); + + int posInK = generatedBytes % h; + if (posInK != 0) + { + // copy what is left in the currentT (1..hash + GenerateNext(); + int toCopy = System.Math.Min(h - posInK, output.Length); + k.AsSpan(posInK, toCopy).CopyTo(output); + generatedBytes += toCopy; + output = output[toCopy..]; + } + + while (!output.IsEmpty) + { + GenerateNext(); + int toCopy = System.Math.Min(h, output.Length); + k.AsSpan(0, toCopy).CopyTo(output); + generatedBytes += toCopy; + output = output[toCopy..]; + } + + return length; } +#endif + + public IMac Mac => prf; } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/KDFFeedbackBytesGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/KDFFeedbackBytesGenerator.cs index eb70087..e8580cd 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/KDFFeedbackBytesGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/KDFFeedbackBytesGenerator.cs @@ -8,11 +8,9 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators { - public class KdfFeedbackBytesGenerator : IMacDerivationFunction + public sealed class KdfFeedbackBytesGenerator + : IMacDerivationFunction { - private static readonly BigInteger IntegerMax = BigInteger.ValueOf(0x7fffffff); - private static readonly BigInteger Two = BigInteger.Two; - // please refer to the standard for the meaning of the variable names // all field lengths are in bytes, not in bits as specified by the standard @@ -40,15 +38,10 @@ public KdfFeedbackBytesGenerator(IMac prf) this.k = new byte[h]; } - public void Init(IDerivationParameters parameters) { - KdfFeedbackParameters feedbackParams = parameters as KdfFeedbackParameters; - if (feedbackParams == null) - { + if (!(parameters is KdfFeedbackParameters feedbackParams)) throw new ArgumentException("Wrong type of arguments given"); - } - // --- init mac based PRF --- @@ -64,13 +57,12 @@ public void Init(IDerivationParameters parameters) if (feedbackParams.UseCounter) { // this is more conservative than the spec - BigInteger maxSize = Two.Pow(r).Multiply(BigInteger.ValueOf(h)); - this.maxSizeExcl = maxSize.CompareTo(IntegerMax) == 1 ? - Int32.MaxValue : maxSize.IntValue; + BigInteger maxSize = BigInteger.One.ShiftLeft(r).Multiply(BigInteger.ValueOf(h)); + this.maxSizeExcl = maxSize.BitLength > 31 ? int.MaxValue : maxSize.IntValueExact; } else { - this.maxSizeExcl = Int32.MaxValue; + this.maxSizeExcl = int.MaxValue; } this.iv = feedbackParams.Iv; @@ -83,40 +75,33 @@ public void Init(IDerivationParameters parameters) public IDigest Digest { - get { return prf is HMac ? ((HMac)prf).GetUnderlyingDigest() : null; } + get { return (prf as HMac)?.GetUnderlyingDigest(); } } public int GenerateBytes(byte[] output, int outOff, int length) { - int generatedBytesAfter = generatedBytes + length; - if (generatedBytesAfter < 0 || generatedBytesAfter >= maxSizeExcl) - { - throw new DataLengthException( - "Current KDFCTR may only be used for " + maxSizeExcl + " bytes"); - } - - if (generatedBytes % h == 0) - { - generateNext(); - } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return GenerateBytes(output.AsSpan(outOff, length)); +#else + if (generatedBytes >= maxSizeExcl - length) + throw new DataLengthException("Current KDFCTR may only be used for " + maxSizeExcl + " bytes"); - // copy what is left in the currentT (1..hash int toGenerate = length; int posInK = generatedBytes % h; - int leftInK = h - generatedBytes % h; - - - int toCopy = System.Math.Min(leftInK, toGenerate); - Array.Copy(k, posInK, output, outOff, toCopy); - - generatedBytes += toCopy; - toGenerate -= toCopy; - outOff += toCopy; + if (posInK != 0) + { + // copy what is left in the currentT (1..hash + int toCopy = System.Math.Min(h - posInK, toGenerate); + Array.Copy(k, posInK, output, outOff, toCopy); + generatedBytes += toCopy; + toGenerate -= toCopy; + outOff += toCopy; + } while (toGenerate > 0) { - generateNext(); - toCopy = System.Math.Min(h, toGenerate); + GenerateNext(); + int toCopy = System.Math.Min(h, toGenerate); Array.Copy(k, 0, output, outOff, toCopy); generatedBytes += toCopy; toGenerate -= toCopy; @@ -124,11 +109,41 @@ public int GenerateBytes(byte[] output, int outOff, int length) } return length; +#endif } - private void generateNext() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int GenerateBytes(Span output) { + int length = output.Length; + if (generatedBytes >= maxSizeExcl - length) + throw new DataLengthException("Current KDFCTR may only be used for " + maxSizeExcl + " bytes"); + int posInK = generatedBytes % h; + if (posInK != 0) + { + // copy what is left in the currentT (1..hash + int toCopy = System.Math.Min(h - posInK, output.Length); + k.AsSpan(posInK, toCopy).CopyTo(output); + generatedBytes += toCopy; + output = output[toCopy..]; + } + + while (!output.IsEmpty) + { + GenerateNext(); + int toCopy = System.Math.Min(h, output.Length); + k.AsSpan(0, toCopy).CopyTo(output); + generatedBytes += toCopy; + output = output[toCopy..]; + } + + return length; + } +#endif + + private void GenerateNext() + { // TODO enable IV if (generatedBytes == 0) { @@ -146,23 +161,23 @@ private void generateNext() // encode i into counter buffer switch (ios.Length) { - case 4: - ios[0] = (byte)(i >> 24); - goto case 3; + case 4: + ios[0] = (byte)(i >> 24); // fall through - case 3: - ios[ios.Length - 3] = (byte)(i >> 16); - // fall through - goto case 2; - case 2: - ios[ios.Length - 2] = (byte)(i >> 8); - // fall through - goto case 1; - case 1: - ios[ios.Length - 1] = (byte)i; - break; - default: - throw new InvalidOperationException("Unsupported size of counter i"); + goto case 3; + case 3: + ios[ios.Length - 3] = (byte)(i >> 16); + // fall through + goto case 2; + case 2: + ios[ios.Length - 2] = (byte)(i >> 8); + // fall through + goto case 1; + case 1: + ios[ios.Length - 1] = (byte)i; + break; + default: + throw new InvalidOperationException("Unsupported size of counter i"); } prf.BlockUpdate(ios, 0, ios.Length); } @@ -171,10 +186,7 @@ private void generateNext() prf.DoFinal(k, 0); } - public IMac GetMac() - { - return prf; - } + public IMac Mac => prf; } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Kdf1BytesGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Kdf1BytesGenerator.cs index b99e4e7..dbe0ffe 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Kdf1BytesGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Kdf1BytesGenerator.cs @@ -1,18 +1,13 @@ #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 + * KFD1 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 + public sealed class Kdf1BytesGenerator : BaseKdfBytesGenerator { /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Kdf2BytesGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Kdf2BytesGenerator.cs index 39683b7..cd80c63 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Kdf2BytesGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Kdf2BytesGenerator.cs @@ -1,10 +1,5 @@ #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 { /** @@ -12,7 +7,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators *
* This implementation is based on IEEE P1363/ISO 18033. */ - public class Kdf2BytesGenerator + public sealed class Kdf2BytesGenerator : BaseKdfBytesGenerator { /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Mgf1BytesGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Mgf1BytesGenerator.cs index 0a0dded..2cd9bb3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Mgf1BytesGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Mgf1BytesGenerator.cs @@ -1,124 +1,116 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -//using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; -#if UNITY_WSA && !UNITY_EDITOR && !ENABLE_IL2CPP -using System.TypeFix; -#endif -//using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; -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 { - /** - * Generator for MGF1 as defined in Pkcs 1v2 - */ - public class Mgf1BytesGenerator : IDerivationFunction + /// Generator for MGF1 as defined in Pkcs 1v2 + public sealed 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) + private readonly IDigest m_digest; + private readonly int m_hLen; + + private byte[] m_buffer; + + /// the digest to be used as the source of generated bytes + public Mgf1BytesGenerator(IDigest digest) { - this.digest = digest; - this.hLen = digest.GetDigestSize(); + m_digest = digest; + m_hLen = digest.GetDigestSize(); } - public void Init( - IDerivationParameters parameters) + public void Init(IDerivationParameters parameters) { - if (!(typeof(MgfParameters).IsInstanceOfType(parameters))) - { + if (!(parameters is MgfParameters mgfParameters)) throw new ArgumentException("MGF parameters required for MGF1Generator"); - } - - MgfParameters p = (MgfParameters)parameters; - seed = p.GetSeed(); + m_buffer = new byte[mgfParameters.SeedLength + 4 + m_hLen]; + mgfParameters.GetSeed(m_buffer, 0); } - /** - * return the underlying digest. - */ - public IDigest Digest + /// the underlying digest. + public IDigest Digest => m_digest; + + /// Fill len bytes of the output buffer with bytes generated from the derivation function. + /// + public int GenerateBytes(byte[] output, int outOff, int length) { - get + Check.OutputLength(output, outOff, length, "output buffer too small"); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return GenerateBytes(output.AsSpan(outOff, length)); +#else + int hashPos = m_buffer.Length - m_hLen; + int counterPos = hashPos - 4; + uint counter = 0; + + m_digest.Reset(); + + int end = outOff + length; + int limit = end - m_hLen; + + while (outOff <= limit) + { + Pack.UInt32_To_BE(counter++, m_buffer, counterPos); + + m_digest.BlockUpdate(m_buffer, 0, hashPos); + m_digest.DoFinal(output, outOff); + + outOff += m_hLen; + } + + if (outOff < end) { - return digest; + Pack.UInt32_To_BE(counter, m_buffer, counterPos); + + m_digest.BlockUpdate(m_buffer, 0, hashPos); + m_digest.DoFinal(m_buffer, hashPos); + + Array.Copy(m_buffer, hashPos, output, outOff, end - outOff); } - } - /** - * 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); + return length; +#endif } - /** - * 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 NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int GenerateBytes(Span output) { - if ((output.Length - length) < outOff) - { - throw new DataLengthException("output buffer too small"); - } + int hashPos = m_buffer.Length - m_hLen; + int counterPos = hashPos - 4; + uint counter = 0; - byte[] hashBuf = new byte[hLen]; - byte[] C = new byte[4]; - int counter = 0; + m_digest.Reset(); - digest.Reset(); + int pos = 0, length = output.Length, limit = length - m_hLen; - if (length > hLen) - { - do - { - ItoOSP(counter, C); + while (pos <= limit) + { + Pack.UInt32_To_BE(counter++, m_buffer.AsSpan(counterPos)); - digest.BlockUpdate(seed, 0, seed.Length); - digest.BlockUpdate(C, 0, C.Length); - digest.DoFinal(hashBuf, 0); + m_digest.BlockUpdate(m_buffer.AsSpan(0, hashPos)); + m_digest.DoFinal(output[pos..]); - Array.Copy(hashBuf, 0, output, outOff + counter * hLen, hLen); - } - while (++counter < (length / hLen)); - } + pos += m_hLen; + } - if ((counter * hLen) < length) + if (pos < length) { - ItoOSP(counter, C); + Pack.UInt32_To_BE(counter, m_buffer.AsSpan(counterPos)); - 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)); + m_digest.BlockUpdate(m_buffer.AsSpan(0, hashPos)); + m_digest.DoFinal(m_buffer.AsSpan(hashPos)); + m_buffer.AsSpan(hashPos, length - pos).CopyTo(output[pos..]); } return length; } +#endif } - } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/NaccacheSternKeyPairGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/NaccacheSternKeyPairGenerator.cs index 8caac62..be3b206 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/NaccacheSternKeyPairGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/NaccacheSternKeyPairGenerator.cs @@ -1,14 +1,11 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; -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 { @@ -54,9 +51,9 @@ public AsymmetricCipherKeyPair GenerateKeyPair() SecureRandom rand = param.Random; int certainty = param.Certainty; - IList smallPrimes = findFirstPrimes(param.CountSmallPrimes); + var smallPrimes = FindFirstPrimes(param.CountSmallPrimes); - smallPrimes = permuteList(smallPrimes, rand); + smallPrimes = PermuteList(smallPrimes, rand); BigInteger u = BigInteger.One; BigInteger v = BigInteger.One; @@ -79,8 +76,8 @@ public AsymmetricCipherKeyPair GenerateKeyPair() // 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 a = GeneratePrime(remainingStrength / 2 + 1, certainty, rand); + BigInteger b = GeneratePrime(remainingStrength / 2 + 1, certainty, rand); BigInteger _p; BigInteger _q; @@ -89,14 +86,14 @@ public AsymmetricCipherKeyPair GenerateKeyPair() long tries = 0; - BigInteger _2au = a.Multiply(u).ShiftLeft(1); + BigInteger _2au = a.Multiply(u).ShiftLeft(1); BigInteger _2bv = b.Multiply(v).ShiftLeft(1); for (;;) { tries++; - _p = generatePrime(24, certainty, rand); + _p = GeneratePrime(24, certainty, rand); p = _p.Multiply(_2au).Add(BigInteger.One); @@ -105,7 +102,7 @@ public AsymmetricCipherKeyPair GenerateKeyPair() for (;;) { - _q = generatePrime(24, certainty, rand); + _q = GeneratePrime(24, certainty, rand); if (_p.Equals(_q)) continue; @@ -134,20 +131,20 @@ public AsymmetricCipherKeyPair GenerateKeyPair() BigInteger g; tries = 0; - for (;;) + for (;;) { // TODO After the first loop, just regenerate one randomly-selected gPart each time? - IList gParts = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var gParts = new List(); for (int ind = 0; ind != smallPrimes.Count; ind++) { - BigInteger i = (BigInteger)smallPrimes[ind]; + BigInteger i = smallPrimes[ind]; BigInteger e = phi_n.Divide(i); for (;;) { tries++; - g = generatePrime(strength, certainty, rand); + g = GeneratePrime(strength, certainty, rand); if (!g.ModPow(e, n).Equals(BigInteger.One)) { @@ -207,14 +204,11 @@ public AsymmetricCipherKeyPair GenerateKeyPair() break; } - return new AsymmetricCipherKeyPair(new NaccacheSternKeyParameters(false, g, n, sigma.BitLength), + 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) + private static BigInteger GeneratePrime(int bitLength, int certainty, SecureRandom rand) { return new BigInteger(bitLength, certainty, rand); } @@ -229,15 +223,13 @@ private static BigInteger generatePrime( * the source of Randomness for permutation * @return a new IList with the permuted elements. */ - private static IList permuteList( - IList arr, - SecureRandom rand) + 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); + var retval = new List(arr.Count); - foreach (object element in arr) + foreach (var element in arr) { int index = rand.Next(retval.Count + 1); retval.Insert(index, element); @@ -253,10 +245,9 @@ private static IList permuteList( * the number of primes to find * @return a vector containing the found primes as Integer */ - private static IList findFirstPrimes( - int count) + private static IList FindFirstPrimes(int count) { - IList primes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(count); + var primes = new List(count); for (int i = 0; i != count; i++) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/OpenBsdBCrypt.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/OpenBsdBCrypt.cs index 01914ef..8500c70 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/OpenBsdBCrypt.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/OpenBsdBCrypt.cs @@ -1,11 +1,11 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Collections.Generic; 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 { @@ -37,7 +37,7 @@ public class OpenBsdBCrypt */ private static readonly byte[] DecodingTable = new byte[128]; private static readonly string DefaultVersion = "2y"; - private static readonly ISet AllowedVersions = new HashSet(); + private static readonly HashSet AllowedVersions = new HashSet(); static OpenBsdBCrypt() { @@ -169,18 +169,14 @@ public static bool CheckPassword(string bcryptString, char[] password) if (!AllowedVersions.Contains(version)) throw new ArgumentException("Bcrypt version '" + version + "' is not supported by this implementation", "bcryptString"); - int cost = 0; + int cost; try { - cost = Int32.Parse(bcryptString.Substring(4, 2)); + cost = int.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."); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/OpenSSLPBEParametersGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/OpenSSLPBEParametersGenerator.cs index ab966e8..16a19a3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/OpenSSLPBEParametersGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/OpenSSLPBEParametersGenerator.cs @@ -8,16 +8,11 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators { - /// /// - /// - /// Generator for PBE derived keys and ivs as usd by OpenSSL. - ///

- /// Originally this scheme was a simple extension of PKCS 5 V2.0 Scheme 1 using MD5 with an - /// iteration count of 1. The default digest was changed to SHA-256 with OpenSSL 1.1.0. This - /// implementation still defaults to MD5, but the digest can now be set. + /// Generator for PBE derived keys and IVs as usd by OpenSSL. Originally this scheme was a simple extension of + /// PKCS 5 V2.0 Scheme 1 using MD5 with an iteration count of 1. The default digest was changed to SHA-256 with + /// OpenSSL 1.1.0. This implementation still defaults to MD5, but the digest can now be set. /// - /// public class OpenSslPbeParametersGenerator : PbeParametersGenerator { @@ -101,21 +96,6 @@ private byte[] GenerateDerivedKey( 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. - */ - - public override ICipherParameters GenerateDerivedParameters( - int keySize) - { - return GenerateDerivedMacParameters(keySize); - } - public override ICipherParameters GenerateDerivedParameters( string algorithm, int keySize) @@ -127,29 +107,6 @@ public override ICipherParameters GenerateDerivedParameters( 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. - */ - - 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, diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Pkcs12ParametersGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Pkcs12ParametersGenerator.cs index e7f7467..19879b9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Pkcs12ParametersGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Pkcs12ParametersGenerator.cs @@ -158,23 +158,6 @@ private byte[] GenerateDerivedKey( 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) @@ -186,29 +169,6 @@ public override ICipherParameters GenerateDerivedParameters( 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, diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Pkcs5S1ParametersGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Pkcs5S1ParametersGenerator.cs index bf469e6..9421c2b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Pkcs5S1ParametersGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Pkcs5S1ParametersGenerator.cs @@ -56,20 +56,6 @@ private byte[] GenerateDerivedKey() 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) @@ -87,34 +73,6 @@ public override ICipherParameters GenerateDerivedParameters( 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, diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Pkcs5S2ParametersGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Pkcs5S2ParametersGenerator.cs index 35c5b3e..46ca275 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Pkcs5S2ParametersGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Pkcs5S2ParametersGenerator.cs @@ -101,19 +101,6 @@ private byte[] GenerateDerivedKey( 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) @@ -125,27 +112,6 @@ public override ICipherParameters GenerateDerivedParameters( 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, diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Poly1305KeyGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Poly1305KeyGenerator.cs index 9f33724..89c8ee6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Poly1305KeyGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/Poly1305KeyGenerator.cs @@ -33,7 +33,7 @@ public class Poly1305KeyGenerator /// /// Poly1305 keys are always 256 bits, so the key length in the provided parameters is ignored. /// - protected override void engineInit(KeyGenerationParameters param) + protected override void EngineInit(KeyGenerationParameters param) { // Poly1305 keys are always 256 bits this.random = param.Random; @@ -45,9 +45,9 @@ protected override void engineInit(KeyGenerationParameters param) /// k[0] ... k[15], r[0] ... r[15] with the required bits in r cleared /// as per . ///

- protected override byte[] engineGenerateKey() + protected override byte[] EngineGenerateKey() { - byte[] key = base.engineGenerateKey(); + byte[] key = base.EngineGenerateKey(); Clamp(key); return key; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/RSABlindingFactorGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/RSABlindingFactorGenerator.cs index 89d8a58..5be14e8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/RSABlindingFactorGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/RSABlindingFactorGenerator.cs @@ -23,20 +23,17 @@ public class RsaBlindingFactorGenerator * * @param param the necessary RSA key parameters. */ - public void Init( - ICipherParameters param) + public void Init(ICipherParameters param) { - if (param is ParametersWithRandom) + if (param is ParametersWithRandom rParam) { - ParametersWithRandom rParam = (ParametersWithRandom)param; - key = (RsaKeyParameters)rParam.Parameters; random = rParam.Random; } else { key = (RsaKeyParameters)param; - random = new SecureRandom(); + random = CryptoServicesRegistrar.GetSecureRandom(); } if (key.IsPrivate) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/SCrypt.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/SCrypt.cs index 4a95082..5f55611 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/SCrypt.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/generators/SCrypt.cs @@ -7,6 +7,7 @@ using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators @@ -25,7 +26,7 @@ public class SCrypt /// 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). + /// int.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) @@ -41,7 +42,7 @@ public static byte[] Generate(byte[] P, byte[] S, int N, int r, int p, int dkLen 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); + int maxParallel = int.MaxValue / (128 * r * 8); if (p < 1 || p > maxParallel) { throw new ArgumentException("Parallelisation parameter p must be >= 1 and <= " + maxParallel @@ -83,7 +84,7 @@ private static byte[] MFcrypt(byte[] P, byte[] S, int N, int r, int p, int dkLen { // TODO These can be done in parallel threads SMix(B, BOff, N, d, r); - } + } Pack.UInt32_To_LE(B, bytes, 0); @@ -103,7 +104,76 @@ private static byte[] SingleIterationPBKDF2(byte[] P, byte[] S, int dkLen) return key.GetKey(); } - private static void SMix(uint[] B, int BOff, int N, int d, int r) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void SMix(uint[] B, int BOff, int N, int d, int r) + { + int powN = Integers.NumberOfTrailingZeros(N); + int blocksPerChunk = N >> d; + int chunkCount = 1 << d, chunkMask = blocksPerChunk - 1, chunkPow = powN - d; + + int BCount = r * 32; + + uint[] blockY = new uint[BCount]; + + uint[][] VV = new uint[chunkCount][]; + + try + { + var X = B.AsSpan(BOff, BCount); + + for (int c = 0; c < chunkCount; ++c) + { + uint[] V = new uint[blocksPerChunk * BCount]; + VV[c] = V; + + Nat.Copy(BCount, X, V); + int off = 0; + for (int i = 1; i < blocksPerChunk; ++i) + { + BlockMix(V.AsSpan(off, BCount), V.AsSpan(off + BCount)); + off += BCount; + } + BlockMix(V.AsSpan()[^BCount..], X); + } + + uint mask = (uint)N - 1; + for (int i = 0; i < N; ++i) + { + int j = (int)(X[BCount - 16] & mask); + uint[] V = VV[j >> chunkPow]; + int VOff = (j & chunkMask) * BCount; + Nat.Xor(BCount, V.AsSpan(VOff), X, blockY); + BlockMix(blockY, X); + } + } + finally + { + ClearAll(VV); + Clear(blockY); + } + } + + private static void BlockMix(Span B, Span Y) + { + int BCount = B.Length; + int half = BCount >> 1; + var y1 = B[^16..]; + + for (int pos = 0; pos < BCount; pos += 32) + { + var b0 = B[pos..]; + var y0 = Y[(pos >> 1)..]; + Nat512.Xor(y1, b0, y0); + Salsa20Engine.SalsaCore(8, y0, y0); + + var b1 = b0[16..]; + y1 = y0[half..]; + Nat512.Xor(y0, b1, y1); + Salsa20Engine.SalsaCore(8, y1, y1); + } + } +#else + private static void SMix(uint[] B, int BOff, int N, int d, int r) { int powN = Integers.NumberOfTrailingZeros(N); int blocksPerChunk = N >> d; @@ -112,7 +182,6 @@ private static void SMix(uint[] B, int BOff, int N, int d, 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]; @@ -127,27 +196,27 @@ private static void SMix(uint[] B, int BOff, int N, int d, int r) uint[] V = new uint[blocksPerChunk * BCount]; VV[c] = V; - int off = 0; + int off = 0; for (int i = 0; i < blocksPerChunk; i += 2) - { - Array.Copy(X, 0, V, off, BCount); - off += BCount; - BlockMix(X, blockX1, blockX2, blockY, r); - Array.Copy(blockY, 0, V, off, BCount); - off += BCount; - BlockMix(blockY, blockX1, blockX2, X, r); - } + { + Array.Copy(X, 0, V, off, BCount); + off += BCount; + BlockMix(X, blockX1, blockY, r); + Array.Copy(blockY, 0, V, off, BCount); + off += BCount; + BlockMix(blockY, blockX1, X, r); + } } - uint mask = (uint)N - 1; - for (int i = 0; i < N; ++i) - { - int j = (int)(X[BCount - 16] & mask); + uint mask = (uint)N - 1; + for (int i = 0; i < N; ++i) + { + int j = (int)(X[BCount - 16] & mask); uint[] V = VV[j >> chunkPow]; int VOff = (j & chunkMask) * BCount; - Array.Copy(V, VOff, blockY, 0, BCount); - Xor(blockY, X, 0, blockY); - BlockMix(blockY, blockX1, blockX2, X, r); + Nat.Xor(BCount, V, VOff, X, 0, blockY, 0); + + BlockMix(blockY, blockX1, X, r); } Array.Copy(X, 0, B, BOff, BCount); @@ -155,37 +224,30 @@ private static void SMix(uint[] B, int BOff, int N, int d, int r) finally { ClearAll(VV); - ClearAll(X, blockX1, blockX2, blockY); + ClearAll(X, blockX1, blockY); } } - private static void BlockMix(uint[] B, uint[] X1, uint[] X2, uint[] Y, int r) + private static void BlockMix(uint[] B, uint[] X1, uint[] Y, int r) { - Array.Copy(B, B.Length - 16, X1, 0, 16); + Array.Copy(B, B.Length - 16, X1, 0, 16); - int BOff = 0, YOff = 0, halfLen = B.Length >> 1; + int BOff = 0, YOff = 0, halfLen = B.Length >> 1; - for (int i = 2 * r; i > 0; --i) - { - Xor(X1, B, BOff, X2); + for (int i = 2 * r; i > 0; --i) + { + Nat512.XorTo(B, BOff, X1, 0); - Salsa20Engine.SalsaCore(8, X2, X1); - Array.Copy(X1, 0, Y, YOff, 16); + Salsa20Engine.SalsaCore(8, X1, X1); + Array.Copy(X1, 0, Y, YOff, 16); - YOff = halfLen + BOff - YOff; - BOff += 16; - } - } - - 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]; - } - } + YOff = halfLen + BOff - YOff; + BOff += 16; + } + } +#endif - private static void Clear(Array array) + private static void Clear(Array array) { if (array != null) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/CipherStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/CipherStream.cs index 3a8bb46..faa5f4c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/CipherStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/CipherStream.cs @@ -1,255 +1,328 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +#if NETCOREAPP1_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER +using System.Buffers; +#endif using System.Diagnostics; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO { - public class CipherStream - : Stream + public sealed 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) + private readonly Stream m_stream; + private readonly IBufferedCipher m_readCipher, m_writeCipher; + + private byte[] m_readBuf; + private int m_readBufPos; + private bool m_readEnded; + + public CipherStream(Stream stream, IBufferedCipher readCipher, IBufferedCipher writeCipher) + { + m_stream = stream; + + if (readCipher != null) + { + m_readCipher = readCipher; + m_readBuf = null; + } + + if (writeCipher != null) + { + m_writeCipher = writeCipher; + } + } + + public IBufferedCipher ReadCipher => m_readCipher; + + public IBufferedCipher WriteCipher => m_writeCipher; + + public override bool CanRead { - 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() + get { return m_stream.CanRead; } + } + + public sealed override bool CanSeek { - if (inCipher == null) - return stream.ReadByte(); + get { return false; } + } - if (mInBuf == null || mInPos >= mInBuf.Length) - { - if (!FillInBuf()) - return -1; + public override bool CanWrite + { + get { return m_stream.CanWrite; } + } + +#if NETCOREAPP2_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER || (UNITY_2021_2_OR_NEWER && (NET_STANDARD_2_0 || NET_STANDARD_2_1)) + public override void CopyTo(Stream destination, int bufferSize) + { + if (m_readCipher == null) + { + m_stream.CopyTo(destination, bufferSize); } + else + { + base.CopyTo(destination, bufferSize); + } + } +#endif - return mInBuf[mInPos++]; + public override void Flush() + { + m_stream.Flush(); } - public override int Read( - byte[] buffer, - int offset, - int count) + public sealed override long Length { - 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() + get { throw new NotSupportedException(); } + } + + public sealed override long Position { - 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) + get { throw new NotSupportedException(); } + set { throw new NotSupportedException(); } + } + + public override int Read(byte[] buffer, int offset, int count) { - Debug.Assert(buffer != null); - Debug.Assert(0 <= offset && offset <= buffer.Length); - Debug.Assert(count >= 0); + if (m_readCipher == null) + return m_stream.Read(buffer, offset, count); + + Streams.ValidateBufferArguments(buffer, offset, count); + + int num = 0; + while (num < count) + { + if (m_readBuf == null || m_readBufPos >= m_readBuf.Length) + { + if (!FillInBuf()) + break; + } + + int numToCopy = System.Math.Min(count - num, m_readBuf.Length - m_readBufPos); + Array.Copy(m_readBuf, m_readBufPos, buffer, offset + num, numToCopy); + m_readBufPos += numToCopy; + num += numToCopy; + } + + return num; + } - int end = offset + count; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int Read(Span buffer) + { + if (buffer.IsEmpty) + return 0; - Debug.Assert(0 <= end && end <= buffer.Length); + if (m_readCipher == null) + return m_stream.Read(buffer); - if (outCipher == null) + int num = 0; + while (num < buffer.Length) { - stream.Write(buffer, offset, count); - return; + if (m_readBuf == null || m_readBufPos >= m_readBuf.Length) + { + if (!FillInBuf()) + break; + } + + int numToCopy = System.Math.Min(buffer.Length - num, m_readBuf.Length - m_readBufPos); + m_readBuf.AsSpan(m_readBufPos, numToCopy).CopyTo(buffer[num..]); + + m_readBufPos += numToCopy; + num += numToCopy; } - byte[] data = outCipher.ProcessBytes(buffer, offset, count); - if (data != null) - { - stream.Write(data, 0, data.Length); - } - } + return num; + } +#endif - public override void WriteByte( - byte b) + public override int ReadByte() { - if (outCipher == null) + if (m_readCipher == null) + return m_stream.ReadByte(); + + if (m_readBuf == null || m_readBufPos >= m_readBuf.Length) { - stream.WriteByte(b); - return; + if (!FillInBuf()) + return -1; } - byte[] data = outCipher.ProcessByte(b); - if (data != null) - { - stream.Write(data, 0, data.Length); - } - } + return m_readBuf[m_readBufPos++]; + } - public override bool CanRead + public sealed override long Seek(long offset, SeekOrigin origin) { - get { return stream.CanRead && (inCipher != null); } + throw new NotSupportedException(); } - public override bool CanWrite + public sealed override void SetLength(long length) { - get { return stream.CanWrite && (outCipher != null); } + throw new NotSupportedException(); } - public override bool CanSeek + public override void Write(byte[] buffer, int offset, int count) { - get { return false; } + if (m_writeCipher == null) + { + m_stream.Write(buffer, offset, count); + return; + } + + Streams.ValidateBufferArguments(buffer, offset, count); + + if (count > 0) + { +#if NETCOREAPP1_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER + int outputSize = m_writeCipher.GetUpdateOutputSize(count); + byte[] output = outputSize > 0 ? ArrayPool.Shared.Rent(outputSize) : null; + try + { + int length = m_writeCipher.ProcessBytes(buffer, offset, count, output, 0); + if (length > 0) + { + m_stream.Write(output, 0, length); + } + } + finally + { + if (output != null) + { + ArrayPool.Shared.Return(output); + } + } +#else + byte[] output = m_writeCipher.ProcessBytes(buffer, offset, count); + if (output != null) + { + m_stream.Write(output, 0, output.Length); + } +#endif + } } - public sealed override long Length - { - get { throw new NotSupportedException(); } - } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) + { + if (buffer.IsEmpty) + return; + + if (m_writeCipher == null) + { + m_stream.Write(buffer); + return; + } + + int outputSize = m_writeCipher.GetUpdateOutputSize(buffer.Length); + byte[] output = outputSize > 0 ? ArrayPool.Shared.Rent(outputSize) : null; + try + { + int length = m_writeCipher.ProcessBytes(buffer, Spans.FromNullable(output)); + if (length > 0) + { + m_stream.Write(output[..length]); + } + } + finally + { + if (output != null) + { + ArrayPool.Shared.Return(output); + } + } + } +#endif - public sealed override long Position + public override void WriteByte(byte value) { - get { throw new NotSupportedException(); } - set { throw new NotSupportedException(); } + if (m_writeCipher == null) + { + m_stream.WriteByte(value); + return; + } + + byte[] data = m_writeCipher.ProcessByte(value); + if (data != null) + { + m_stream.Write(data, 0, data.Length); + } } -#if PORTABLE || NETFX_CORE protected override void Dispose(bool disposing) { if (disposing) { - if (outCipher != null) + if (m_writeCipher != null) { - byte[] data = outCipher.DoFinal(); - stream.Write(data, 0, data.Length); - stream.Flush(); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int outputSize = m_writeCipher.GetOutputSize(0); + Span output = outputSize <= 256 + ? stackalloc byte[outputSize] + : new byte[outputSize]; + int len = m_writeCipher.DoFinal(output); + m_stream.Write(output[..len]); +#else + byte[] data = m_writeCipher.DoFinal(); + m_stream.Write(data, 0, data.Length); +#endif } - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(stream); + m_stream.Dispose(); } base.Dispose(disposing); } -#else - public override void Close() + + private bool FillInBuf() { - 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(); + if (m_readEnded) + return false; + + m_readBufPos = 0; + + do + { + m_readBuf = ReadAndProcessBlock(); + } + while (!m_readEnded && m_readBuf == null); + + return m_readBuf != null; } -#endif - public override void Flush() + private byte[] ReadAndProcessBlock() { - // Note: outCipher.DoFinal is only called during Close() - stream.Flush(); - } + int blockSize = m_readCipher.GetBlockSize(); + int readSize = blockSize == 0 ? 256 : blockSize; + + byte[] block = new byte[readSize]; + int numRead = 0; + do + { + int count = m_stream.Read(block, numRead, block.Length - numRead); + if (count < 1) + { + m_readEnded = true; + break; + } + numRead += count; + } + while (numRead < block.Length); - public sealed override long Seek( - long offset, - SeekOrigin origin) - { - throw new NotSupportedException(); - } - - public sealed override void SetLength( - long length) - { - throw new NotSupportedException(); - } + Debug.Assert(m_readEnded || numRead == block.Length); + + byte[] bytes = m_readEnded + ? m_readCipher.DoFinal(block, 0, numRead) + : m_readCipher.ProcessBytes(block); + + if (bytes != null && bytes.Length == 0) + { + bytes = null; + } + + return bytes; + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/DigestSink.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/DigestSink.cs index e5017da..4a325e7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/DigestSink.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/DigestSink.cs @@ -6,33 +6,42 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO { - public class DigestSink + public sealed class DigestSink : BaseOutputStream { - private readonly IDigest mDigest; + private readonly IDigest m_digest; public DigestSink(IDigest digest) { - this.mDigest = digest; + m_digest = digest; } - public virtual IDigest Digest - { - get { return mDigest; } - } + public IDigest Digest => m_digest; - public override void WriteByte(byte b) + public override void Write(byte[] buffer, int offset, int count) { - mDigest.Update(b); + Streams.ValidateBufferArguments(buffer, offset, count); + + if (count > 0) + { + m_digest.BlockUpdate(buffer, offset, count); + } } - public override void Write(byte[] buf, int off, int len) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) { - if (len > 0) + if (!buffer.IsEmpty) { - mDigest.BlockUpdate(buf, off, len); + m_digest.BlockUpdate(buffer); } } +#endif + + public override void WriteByte(byte value) + { + m_digest.Update(value); + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/DigestStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/DigestStream.cs index f6aa9a1..c69798d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/DigestStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/DigestStream.cs @@ -7,149 +7,158 @@ 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) + public sealed class DigestStream + : Stream + { + private readonly Stream m_stream; + private readonly IDigest m_readDigest; + private readonly IDigest m_writeDigest; + + public DigestStream(Stream stream, IDigest readDigest, IDigest writeDigest) { - if (disposing) + m_stream = stream; + m_readDigest = readDigest; + m_writeDigest = writeDigest; + } + + public IDigest ReadDigest => m_readDigest; + + public IDigest WriteDigest => m_writeDigest; + + public override bool CanRead + { + get { return m_stream.CanRead; } + } + + public sealed override bool CanSeek + { + get { return false; } + } + + public override bool CanWrite + { + get { return m_stream.CanWrite; } + } + +#if NETCOREAPP2_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER || (UNITY_2021_2_OR_NEWER && (NET_STANDARD_2_0 || NET_STANDARD_2_1)) + public override void CopyTo(Stream destination, int bufferSize) + { + if (m_readDigest == null) { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(stream); + m_stream.CopyTo(destination, bufferSize); + } + else + { + base.CopyTo(destination, bufferSize); } - 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); - } - } -} + { + m_stream.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 n = m_stream.Read(buffer, offset, count); + + if (m_readDigest != null && n > 0) + { + m_readDigest.BlockUpdate(buffer, offset, n); + } + + return n; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int Read(Span buffer) + { + int n = m_stream.Read(buffer); + + if (m_readDigest != null && n > 0) + { + m_readDigest.BlockUpdate(buffer[..n]); + } + + return n; + } +#endif + + public override int ReadByte() + { + int b = m_stream.ReadByte(); + + if (m_readDigest != null && b >= 0) + { + m_readDigest.Update((byte)b); + } + + return b; + } + + public sealed override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException(); + } + + public sealed override void SetLength(long length) + { + throw new NotSupportedException(); + } + + public override void Write(byte[] buffer, int offset, int count) + { + m_stream.Write(buffer, offset, count); + + if (m_writeDigest != null && count > 0) + { + m_writeDigest.BlockUpdate(buffer, offset, count); + } + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) + { + m_stream.Write(buffer); + + if (m_writeDigest != null && !buffer.IsEmpty) + { + m_writeDigest.BlockUpdate(buffer); + } + } +#endif + + public override void WriteByte(byte value) + { + m_stream.WriteByte(value); + + if (m_writeDigest != null) + { + m_writeDigest.Update(value); + } + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + m_stream.Dispose(); + } + base.Dispose(disposing); + } + } +} #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/MacSink.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/MacSink.cs index 0dbbf52..c803e0e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/MacSink.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/MacSink.cs @@ -6,33 +6,42 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO { - public class MacSink + public sealed class MacSink : BaseOutputStream { - private readonly IMac mMac; + private readonly IMac m_mac; public MacSink(IMac mac) { - this.mMac = mac; + m_mac = mac; } - public virtual IMac Mac - { - get { return mMac; } - } + public IMac Mac => m_mac; - public override void WriteByte(byte b) + public override void Write(byte[] buffer, int offset, int count) { - mMac.Update(b); + Streams.ValidateBufferArguments(buffer, offset, count); + + if (count > 0) + { + m_mac.BlockUpdate(buffer, offset, count); + } } - public override void Write(byte[] buf, int off, int len) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) { - if (len > 0) + if (!buffer.IsEmpty) { - mMac.BlockUpdate(buf, off, len); + m_mac.BlockUpdate(buffer); } } +#endif + + public override void WriteByte(byte value) + { + m_mac.Update(value); + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/MacStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/MacStream.cs index b11fc1f..e15a109 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/MacStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/MacStream.cs @@ -7,148 +7,158 @@ 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) + public sealed class MacStream + : Stream + { + private readonly Stream m_stream; + private readonly IMac m_readMac; + private readonly IMac m_writeMac; + + public MacStream(Stream stream, IMac readMac, IMac writeMac) { - if (disposing) + m_stream = stream; + m_readMac = readMac; + m_writeMac = writeMac; + } + + public IMac ReadMac => m_readMac; + + public IMac WriteMac => m_writeMac; + + public override bool CanRead + { + get { return m_stream.CanRead; } + } + + public sealed override bool CanSeek + { + get { return false; } + } + + public override bool CanWrite + { + get { return m_stream.CanWrite; } + } + +#if NETCOREAPP2_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER || (UNITY_2021_2_OR_NEWER && (NET_STANDARD_2_0 || NET_STANDARD_2_1)) + public override void CopyTo(Stream destination, int bufferSize) + { + if (m_readMac == null) { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(stream); + m_stream.CopyTo(destination, bufferSize); } - base.Dispose(disposing); + else + { + base.CopyTo(destination, bufferSize); + } + } +#endif + + public override void Flush() + { + m_stream.Flush(); } -#else - public override void Close() + + public sealed override long Length { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(stream); - base.Close(); + 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 n = m_stream.Read(buffer, offset, count); + + if (m_readMac != null && n > 0) + { + m_readMac.BlockUpdate(buffer, offset, n); + } + + return n; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int Read(Span buffer) + { + int n = m_stream.Read(buffer); + + if (m_readMac != null && n > 0) + { + m_readMac.BlockUpdate(buffer[..n]); + } + + return n; } #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); - } - } -} + public override int ReadByte() + { + int b = m_stream.ReadByte(); + + if (m_readMac != null && b >= 0) + { + m_readMac.Update((byte)b); + } + + return b; + } + + public sealed override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException(); + } + public sealed override void SetLength(long length) + { + throw new NotSupportedException(); + } + + public override void Write(byte[] buffer, int offset, int count) + { + m_stream.Write(buffer, offset, count); + + if (m_writeMac != null && count > 0) + { + m_writeMac.BlockUpdate(buffer, offset, count); + } + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) + { + m_stream.Write(buffer); + + if (m_writeMac != null && !buffer.IsEmpty) + { + m_writeMac.BlockUpdate(buffer); + } + } +#endif + + public override void WriteByte(byte value) + { + m_stream.WriteByte(value); + + if (m_writeMac != null) + { + m_writeMac.Update(value); + } + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + m_stream.Dispose(); + } + base.Dispose(disposing); + } + } +} #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/SignerSink.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/SignerSink.cs index 2f6b286..0d43fcf 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/SignerSink.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/SignerSink.cs @@ -6,33 +6,42 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO { - public class SignerSink + public sealed class SignerSink : BaseOutputStream { - private readonly ISigner mSigner; + private readonly ISigner m_signer; public SignerSink(ISigner signer) { - this.mSigner = signer; + m_signer = signer; } - public virtual ISigner Signer - { - get { return mSigner; } - } + public ISigner Signer => m_signer; - public override void WriteByte(byte b) + public override void Write(byte[] buffer, int offset, int count) { - mSigner.Update(b); + Streams.ValidateBufferArguments(buffer, offset, count); + + if (count > 0) + { + m_signer.BlockUpdate(buffer, offset, count); + } } - public override void Write(byte[] buf, int off, int len) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) { - if (len > 0) + if (!buffer.IsEmpty) { - mSigner.BlockUpdate(buf, off, len); + m_signer.BlockUpdate(buffer); } } +#endif + + public override void WriteByte(byte value) + { + m_signer.Update(value); + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/SignerStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/SignerStream.cs index 3d3ea75..a75fb69 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/SignerStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/io/SignerStream.cs @@ -7,149 +7,158 @@ 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) + public sealed class SignerStream + : Stream + { + private readonly Stream stream; + private readonly ISigner inSigner; + private readonly ISigner outSigner; + + public SignerStream(Stream stream, ISigner readSigner, ISigner writeSigner) { - if (disposing) + this.stream = stream; + this.inSigner = readSigner; + this.outSigner = writeSigner; + } + + public ISigner ReadSigner => inSigner; + + public ISigner WriteSigner => outSigner; + + public override bool CanRead + { + get { return stream.CanRead; } + } + + public sealed override bool CanSeek + { + get { return false; } + } + + public override bool CanWrite + { + get { return stream.CanWrite; } + } + +#if NETCOREAPP2_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER || (UNITY_2021_2_OR_NEWER && (NET_STANDARD_2_0 || NET_STANDARD_2_1)) + public override void CopyTo(Stream destination, int bufferSize) + { + if (inSigner == null) { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(stream); + stream.CopyTo(destination, bufferSize); } - base.Dispose(disposing); + else + { + base.CopyTo(destination, bufferSize); + } + } +#endif + + public override void Flush() + { + stream.Flush(); } -#else - public override void Close() + + public sealed override long Length { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(stream); - base.Close(); + 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 n = stream.Read(buffer, offset, count); + + if (inSigner != null && n > 0) + { + inSigner.BlockUpdate(buffer, offset, n); + } + + return n; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int Read(Span buffer) + { + int n = stream.Read(buffer); + + if (inSigner != null && n > 0) + { + inSigner.BlockUpdate(buffer[..n]); + } + + return n; } #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); - } - } -} + public override int ReadByte() + { + int b = stream.ReadByte(); + + if (inSigner != null && b >= 0) + { + inSigner.Update((byte)b); + } + + return b; + } + + public sealed override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException(); + } + public sealed override void SetLength(long length) + { + throw new NotSupportedException(); + } + + public override void Write(byte[] buffer, int offset, int count) + { + stream.Write(buffer, offset, count); + + if (outSigner != null && count > 0) + { + outSigner.BlockUpdate(buffer, offset, count); + } + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) + { + stream.Write(buffer); + + if (outSigner != null && !buffer.IsEmpty) + { + outSigner.BlockUpdate(buffer); + } + } +#endif + + public override void WriteByte(byte value) + { + stream.WriteByte(value); + + if (outSigner != null) + { + outSigner.Update(value); + } + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + stream.Dispose(); + } + base.Dispose(disposing); + } + } +} #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/CMac.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/CMac.cs index 10c19f2..4607a34 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/CMac.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/CMac.cs @@ -39,7 +39,7 @@ public class CMac private byte[] buf; private int bufOff; - private IBlockCipher cipher; + private IBlockCipherMode m_cipherMode; private int macSize; @@ -90,7 +90,7 @@ public CMac( "Block size must be either 64 or 128 bits"); } - this.cipher = new CbcBlockCipher(cipher); + m_cipherMode = new CbcBlockCipher(cipher); this.macSize = macSizeInBits / 8; mac = new byte[cipher.GetBlockSize()]; @@ -104,7 +104,7 @@ public CMac( public string AlgorithmName { - get { return cipher.AlgorithmName; } + get { return m_cipherMode.AlgorithmName; } } private static int ShiftLeft(byte[] block, byte[] output) @@ -134,16 +134,15 @@ private static byte[] DoubleLu(byte[] input) return ret; } - public void Init( - ICipherParameters parameters) + public void Init(ICipherParameters parameters) { if (parameters is KeyParameter) { - cipher.Init(true, parameters); + m_cipherMode.Init(true, parameters); //initializes the L, Lu, Lu2 numbers L = new byte[ZEROES.Length]; - cipher.ProcessBlock(ZEROES, 0, L, 0); + m_cipherMode.ProcessBlock(ZEROES, 0, L, 0); Lu = DoubleLu(L); Lu2 = DoubleLu(Lu); } @@ -161,34 +160,33 @@ public int GetMacSize() return macSize; } - public void Update( - byte input) + public void Update(byte input) { if (bufOff == buf.Length) { - cipher.ProcessBlock(buf, 0, mac, 0); + m_cipherMode.ProcessBlock(buf, 0, mac, 0); bufOff = 0; } buf[bufOff++] = input; } - public void BlockUpdate( - byte[] inBytes, - int inOff, - int len) + 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(); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BlockUpdate(inBytes.AsSpan(inOff, len)); +#else + int blockSize = m_cipherMode.GetBlockSize(); int gapLen = blockSize - bufOff; if (len > gapLen) { Array.Copy(inBytes, inOff, buf, bufOff, gapLen); - cipher.ProcessBlock(buf, 0, mac, 0); + m_cipherMode.ProcessBlock(buf, 0, mac, 0); bufOff = 0; len -= gapLen; @@ -196,7 +194,7 @@ public void BlockUpdate( while (len > blockSize) { - cipher.ProcessBlock(inBytes, inOff, mac, 0); + m_cipherMode.ProcessBlock(inBytes, inOff, mac, 0); len -= blockSize; inOff += blockSize; @@ -206,13 +204,43 @@ public void BlockUpdate( Array.Copy(inBytes, inOff, buf, bufOff, len); bufOff += len; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + int blockSize = m_cipherMode.GetBlockSize(); + int gapLen = blockSize - bufOff; + + if (input.Length > gapLen) + { + input[..gapLen].CopyTo(buf.AsSpan(bufOff)); + + m_cipherMode.ProcessBlock(buf, mac); + + bufOff = 0; + input = input[gapLen..]; + + while (input.Length > blockSize) + { + m_cipherMode.ProcessBlock(input, mac); + input = input[blockSize..]; + } + } + + input.CopyTo(buf.AsSpan(bufOff)); + + bufOff += input.Length; } +#endif - public int DoFinal( - byte[] outBytes, - int outOff) + public int DoFinal(byte[] outBytes, int outOff) { - int blockSize = cipher.GetBlockSize(); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(outBytes.AsSpan(outOff)); +#else + int blockSize = m_cipherMode.GetBlockSize(); byte[] lu; if (bufOff == blockSize) @@ -230,14 +258,46 @@ public int DoFinal( buf[i] ^= lu[i]; } - cipher.ProcessBlock(buf, 0, mac, 0); + m_cipherMode.ProcessBlock(buf, 0, mac, 0); Array.Copy(mac, 0, outBytes, outOff, macSize); Reset(); + return macSize; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + int blockSize = m_cipherMode.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]; + } + + m_cipherMode.ProcessBlock(buf, mac); + + mac.AsSpan(0, macSize).CopyTo(output); + + Reset(); + return macSize; } +#endif /** * Reset the mac generator. @@ -253,7 +313,7 @@ public void Reset() /* * Reset the underlying cipher. */ - cipher.Reset(); + m_cipherMode.Reset(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/CbcBlockCipherMac.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/CbcBlockCipherMac.cs index 1b0c82c..2145149 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/CbcBlockCipherMac.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/CbcBlockCipherMac.cs @@ -16,7 +16,7 @@ public class CbcBlockCipherMac { private byte[] buf; private int bufOff; - private IBlockCipher cipher; + private IBlockCipherMode m_cipherMode; private IBlockCipherPadding padding; private int macSize; @@ -88,7 +88,7 @@ public CbcBlockCipherMac( if ((macSizeInBits % 8) != 0) throw new ArgumentException("MAC size must be multiple of 8"); - this.cipher = new CbcBlockCipher(cipher); + this.m_cipherMode = new CbcBlockCipher(cipher); this.padding = padding; this.macSize = macSizeInBits / 8; @@ -98,15 +98,14 @@ public CbcBlockCipherMac( public string AlgorithmName { - get { return cipher.AlgorithmName; } + get { return m_cipherMode.AlgorithmName; } } - public void Init( - ICipherParameters parameters) + public void Init(ICipherParameters parameters) { Reset(); - cipher.Init(true, parameters); + m_cipherMode.Init(true, parameters); } public int GetMacSize() @@ -114,34 +113,33 @@ public int GetMacSize() return macSize; } - public void Update( - byte input) + public void Update(byte input) { if (bufOff == buf.Length) { - cipher.ProcessBlock(buf, 0, buf, 0); + m_cipherMode.ProcessBlock(buf, 0, buf, 0); bufOff = 0; } buf[bufOff++] = input; } - public void BlockUpdate( - byte[] input, - int inOff, - int len) + 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(); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BlockUpdate(input.AsSpan(inOff, len)); +#else + int blockSize = m_cipherMode.GetBlockSize(); int gapLen = blockSize - bufOff; if (len > gapLen) { Array.Copy(input, inOff, buf, bufOff, gapLen); - cipher.ProcessBlock(buf, 0, buf, 0); + m_cipherMode.ProcessBlock(buf, 0, buf, 0); bufOff = 0; len -= gapLen; @@ -149,7 +147,7 @@ public void BlockUpdate( while (len > blockSize) { - cipher.ProcessBlock(input, inOff, buf, 0); + m_cipherMode.ProcessBlock(input, inOff, buf, 0); len -= blockSize; inOff += blockSize; @@ -159,13 +157,43 @@ public void BlockUpdate( Array.Copy(input, inOff, buf, bufOff, len); bufOff += len; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + int blockSize = m_cipherMode.GetBlockSize(); + int gapLen = blockSize - bufOff; + + if (input.Length > gapLen) + { + input[..gapLen].CopyTo(buf.AsSpan(bufOff)); + + m_cipherMode.ProcessBlock(buf, buf); + + bufOff = 0; + input = input[gapLen..]; + + while (input.Length > blockSize) + { + m_cipherMode.ProcessBlock(input, buf); + input = input[blockSize..]; + } + } + + input.CopyTo(buf.AsSpan(bufOff)); + + bufOff += input.Length; } +#endif - public int DoFinal( - byte[] output, - int outOff) + public int DoFinal(byte[] output, int outOff) { - int blockSize = cipher.GetBlockSize(); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(output.AsSpan(outOff)); +#else + int blockSize = m_cipherMode.GetBlockSize(); if (padding == null) { @@ -179,23 +207,58 @@ public int DoFinal( { if (bufOff == blockSize) { - cipher.ProcessBlock(buf, 0, buf, 0); + m_cipherMode.ProcessBlock(buf, 0, buf, 0); bufOff = 0; } padding.AddPadding(buf, bufOff); } - cipher.ProcessBlock(buf, 0, buf, 0); + m_cipherMode.ProcessBlock(buf, 0, buf, 0); Array.Copy(buf, 0, output, outOff, macSize); Reset(); return macSize; +#endif } - /** +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + int blockSize = m_cipherMode.GetBlockSize(); + + if (padding == null) + { + // pad with zeroes + while (bufOff < blockSize) + { + buf[bufOff++] = 0; + } + } + else + { + if (bufOff == blockSize) + { + m_cipherMode.ProcessBlock(buf, buf); + bufOff = 0; + } + + padding.AddPadding(buf, bufOff); + } + + m_cipherMode.ProcessBlock(buf, buf); + + buf.AsSpan(0, macSize).CopyTo(output); + + Reset(); + + return macSize; + } +#endif + + /** * Reset the mac generator. */ public void Reset() @@ -204,8 +267,8 @@ public void Reset() Array.Clear(buf, 0, buf.Length); bufOff = 0; - // Reset the underlying cipher. - cipher.Reset(); + // Reset the underlying cipher. + m_cipherMode.Reset(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/CfbBlockCipherMac.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/CfbBlockCipherMac.cs index 9bfa80b..62649e3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/CfbBlockCipherMac.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/CfbBlockCipherMac.cs @@ -11,8 +11,8 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs /** * implements a Cipher-FeedBack (CFB) mode on top of a simple cipher. */ - class MacCFBBlockCipher - : IBlockCipher + internal class MacCfbBlockCipher + : IBlockCipherMode { private byte[] IV; private byte[] cfbV; @@ -28,7 +28,7 @@ class MacCFBBlockCipher * feedback mode. * @param blockSize the block size in bits (note: a multiple of 8) */ - public MacCFBBlockCipher( + public MacCfbBlockCipher( IBlockCipher cipher, int bitBlockSize) { @@ -49,13 +49,10 @@ public MacCFBBlockCipher( * @exception ArgumentException if the parameters argument is * inappropriate. */ - public void Init( - bool forEncryption, - ICipherParameters parameters) + public void Init(bool forEncryption, ICipherParameters parameters) { - if (parameters is ParametersWithIV) + if (parameters is ParametersWithIV ivParam) { - ParametersWithIV ivParam = (ParametersWithIV)parameters; byte[] iv = ivParam.GetIV(); if (iv.Length < IV.Length) @@ -86,7 +83,9 @@ public string AlgorithmName get { return cipher.AlgorithmName + "/CFB" + (blockSize * 8); } } - public bool IsPartialBlockOkay + public IBlockCipher UnderlyingCipher => cipher; + + public bool IsPartialBlockOkay { get { return true; } } @@ -101,30 +100,10 @@ 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) + 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"); + Check.DataLength(input, inOff, blockSize, "input buffer too short"); + Check.OutputLength(outBytes, outOff, blockSize, "output buffer too short"); cipher.ProcessBlock(cfbV, 0, cfbOutV, 0); @@ -145,15 +124,39 @@ public int ProcessBlock( return blockSize; } - /** +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessBlock(ReadOnlySpan input, Span output) + { + Check.DataLength(input, blockSize, "input buffer too short"); + Check.OutputLength(output, blockSize, "output buffer too short"); + + cipher.ProcessBlock(cfbV, cfbOutV); + + // + // XOR the cfbV with the plaintext producing the cipher text + // + for (int i = 0; i < blockSize; i++) + { + output[i] = (byte)(cfbOutV[i] ^ input[i]); + } + + // + // change over the input block. + // + Array.Copy(cfbV, blockSize, cfbV, 0, cfbV.Length - blockSize); + output[..blockSize].CopyTo(cfbV.AsSpan(cfbV.Length - blockSize)); + + return blockSize; + } +#endif + + /** * 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( @@ -169,7 +172,7 @@ public class CfbBlockCipherMac private byte[] mac; private byte[] Buffer; private int bufOff; - private MacCFBBlockCipher cipher; + private MacCfbBlockCipher cipher; private IBlockCipherPadding padding; private int macSize; @@ -249,7 +252,7 @@ public CfbBlockCipherMac( mac = new byte[cipher.GetBlockSize()]; - this.cipher = new MacCFBBlockCipher(cipher, cfbBitSize); + this.cipher = new MacCfbBlockCipher(cipher, cfbBitSize); this.padding = padding; this.macSize = macSizeInBits / 8; @@ -262,8 +265,7 @@ public string AlgorithmName get { return cipher.AlgorithmName; } } - public void Init( - ICipherParameters parameters) + public void Init(ICipherParameters parameters) { Reset(); @@ -275,8 +277,7 @@ public int GetMacSize() return macSize; } - public void Update( - byte input) + public void Update(byte input) { if (bufOff == Buffer.Length) { @@ -287,15 +288,15 @@ public void Update( Buffer[bufOff++] = input; } - public void BlockUpdate( - byte[] input, - int inOff, - int len) + 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(); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BlockUpdate(input.AsSpan(inOff, len)); +#else + int blockSize = cipher.GetBlockSize(); int resultLen = 0; int gapLen = blockSize - bufOff; @@ -321,12 +322,43 @@ public void BlockUpdate( Array.Copy(input, inOff, Buffer, bufOff, len); bufOff += len; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + int blockSize = cipher.GetBlockSize(); + int resultLen = 0; + int gapLen = blockSize - bufOff; + + if (input.Length > gapLen) + { + input[..gapLen].CopyTo(Buffer.AsSpan(bufOff)); + + resultLen += cipher.ProcessBlock(Buffer, mac); + + bufOff = 0; + input = input[gapLen..]; + + while (input.Length > blockSize) + { + resultLen += cipher.ProcessBlock(input, mac); + input = input[blockSize..]; + } + } + + input.CopyTo(Buffer.AsSpan(bufOff)); + + bufOff += input.Length; } +#endif - public int DoFinal( - byte[] output, - int outOff) + public int DoFinal(byte[] output, int outOff) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(output.AsSpan(outOff)); +#else int blockSize = cipher.GetBlockSize(); // pad with zeroes @@ -351,8 +383,39 @@ public int DoFinal( Reset(); return macSize; +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + 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); + + mac.AsSpan(0, macSize).CopyTo(output); + + Reset(); + + return macSize; + } +#endif + /** * Reset the mac generator. */ @@ -366,7 +429,6 @@ public void Reset() cipher.Reset(); } } - } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/DSTU7564Mac.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/DSTU7564Mac.cs index 0041617..3e0e647 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/DSTU7564Mac.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/DSTU7564Mac.cs @@ -63,7 +63,7 @@ public int GetMacSize() public void BlockUpdate(byte[] input, int inOff, int len) { - Check.DataLength(input, inOff, len, "Input buffer too short"); + Check.DataLength(input, inOff, len, "input buffer too short"); if (paddedKey == null) throw new InvalidOperationException(AlgorithmName + " not initialised"); @@ -72,6 +72,17 @@ public void BlockUpdate(byte[] input, int inOff, int len) inputLength += (ulong)len; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + if (paddedKey == null) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + + engine.BlockUpdate(input); + inputLength += (ulong)input.Length; + } +#endif + public void Update(byte input) { engine.Update(input); @@ -80,11 +91,11 @@ public void Update(byte input) 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"); + Check.OutputLength(output, outOff, macSize, "output buffer too short"); + Pad(); engine.BlockUpdate(invertedKey, 0, invertedKey.Length); @@ -94,6 +105,24 @@ public int DoFinal(byte[] output, int outOff) return engine.DoFinal(output, outOff); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + if (paddedKey == null) + throw new InvalidOperationException(AlgorithmName + " not initialised"); + + Check.OutputLength(output, macSize, "output buffer too short"); + + Pad(); + + engine.BlockUpdate(invertedKey); + + inputLength = 0; + + return engine.DoFinal(output); + } +#endif + public void Reset() { inputLength = 0; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/DSTU7624Mac.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/DSTU7624Mac.cs index af26c5d..2e31f31 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/DSTU7624Mac.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/DSTU7624Mac.cs @@ -2,88 +2,90 @@ #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; - +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; 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; + 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]; - private byte[] c, cTemp, kDelta; - private byte[] buf; - private int bufOff; + cTemp = new byte[blockSize]; - public Dstu7624Mac(int blockSizeBits, int q) - { - engine = new Dstu7624Engine(blockSizeBits); + kDelta = new byte[blockSize]; + buf = new byte[blockSize]; + } - blockSize = blockSizeBits / 8; + public void Init(ICipherParameters parameters) + { + if (parameters is KeyParameter) + { + engine.Init(true, (KeyParameter)parameters); - macSize = q / 8; + engine.ProcessBlock(kDelta, 0, kDelta, 0); + } + else + { + throw new ArgumentException("invalid parameter passed to Dstu7624Mac init - " + + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + } + } - c = new byte[blockSize]; - - cTemp = new byte[blockSize]; + public string AlgorithmName + { + get { return "Dstu7624Mac"; } + } - kDelta = new byte[blockSize]; - buf = new byte[blockSize]; + public int GetMacSize() + { + return macSize; } - 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) - { + public void Update(byte input) + { if (bufOff == buf.Length) { - processBlock(buf, 0); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ProcessBlock(buf); +#else + ProcessBlock(buf, 0); +#endif bufOff = 0; } buf[bufOff++] = input; } - public void BlockUpdate(byte[] input, int inOff, int len) - { + public void BlockUpdate(byte[] input, int inOff, int len) + { if (len < 0) - { - throw new ArgumentException( - "Can't have a negative input length!"); - } + throw new ArgumentException("Can't have a negative input length!"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BlockUpdate(input.AsSpan(inOff, len)); +#else int blockSize = engine.GetBlockSize(); int gapLen = blockSize - bufOff; @@ -91,7 +93,7 @@ public void BlockUpdate(byte[] input, int inOff, int len) { Array.Copy(input, inOff, buf, bufOff, gapLen); - processBlock(buf, 0); + ProcessBlock(buf, 0); bufOff = 0; len -= gapLen; @@ -99,7 +101,7 @@ public void BlockUpdate(byte[] input, int inOff, int len) while (len > blockSize) { - processBlock(input, inOff); + ProcessBlock(input, inOff); len -= blockSize; inOff += blockSize; @@ -109,56 +111,115 @@ public void BlockUpdate(byte[] input, int inOff, int len) Array.Copy(input, inOff, buf, bufOff, len); bufOff += len; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + int blockSize = engine.GetBlockSize(); + int gapLen = blockSize - bufOff; + + if (input.Length > gapLen) + { + input[..gapLen].CopyTo(buf.AsSpan(bufOff)); + + ProcessBlock(buf); + + bufOff = 0; + input = input[gapLen..]; + + while (input.Length > blockSize) + { + ProcessBlock(input); + input = input[blockSize..]; + } + } + + input.CopyTo(buf.AsSpan(bufOff)); + + bufOff += input.Length; + } +#endif + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void ProcessBlock(ReadOnlySpan input) + { + Xor(c, input, cTemp); + + engine.ProcessBlock(cTemp, c); } - private void processBlock(byte[] input, int inOff) + private void Xor(ReadOnlySpan c, ReadOnlySpan input, Span xorResult) + { + for (int byteIndex = 0; byteIndex < blockSize; byteIndex++) + { + xorResult[byteIndex] = (byte)(c[byteIndex] ^ input[byteIndex]); + } + } +#else + private void ProcessBlock(byte[] input, int inOff) { Xor(c, 0, input, inOff, cTemp); engine.ProcessBlock(cTemp, 0, c, 0); } +#endif 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) + { + for (int byteIndex = 0; byteIndex < blockSize; byteIndex++) { - throw new DataLengthException("Input must be a multiple of blocksize"); + 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"); + + Check.OutputLength(output, outOff, macSize, "output buffer too short"); //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() - { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + if (bufOff % buf.Length != 0) + throw new DataLengthException("Input must be a multiple of blocksize"); + + Check.OutputLength(output, macSize, "output buffer too short"); + + //Last block + Xor(c, 0, buf, 0, cTemp); + Xor(cTemp, 0, kDelta, 0, c); + engine.ProcessBlock(c, c); + + c.AsSpan(0, macSize).CopyTo(output); + + return macSize; + } +#endif + + 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/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/GMac.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/GMac.cs index ba0389c..b737126 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/GMac.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/GMac.cs @@ -1,12 +1,9 @@ #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 { @@ -57,10 +54,8 @@ public GMac(GcmBlockCipher cipher, int macSizeBits) ///
public void Init(ICipherParameters parameters) { - if (parameters is ParametersWithIV) + if (parameters is ParametersWithIV param) { - ParametersWithIV param = (ParametersWithIV)parameters; - byte[] iv = param.GetIV(); KeyParameter keyParam = (KeyParameter)param.Parameters; @@ -75,7 +70,7 @@ public void Init(ICipherParameters parameters) public string AlgorithmName { - get { return cipher.GetUnderlyingCipher().AlgorithmName + "-GMAC"; } + get { return cipher.UnderlyingCipher.AlgorithmName + "-GMAC"; } } public int GetMacSize() @@ -93,6 +88,13 @@ public void BlockUpdate(byte[] input, int inOff, int len) cipher.ProcessAadBytes(input, inOff, len); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + cipher.ProcessAadBytes(input); + } +#endif + public int DoFinal(byte[] output, int outOff) { try @@ -106,6 +108,21 @@ public int DoFinal(byte[] output, int outOff) } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + try + { + return cipher.DoFinal(output); + } + catch (InvalidCipherTextException e) + { + // Impossible in encrypt mode + throw new InvalidOperationException(e.ToString()); + } + } +#endif + public void Reset() { cipher.Reset(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/GOST28147Mac.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/GOST28147Mac.cs index 0d5addd..199ebf4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/GOST28147Mac.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/GOST28147Mac.cs @@ -2,8 +2,8 @@ #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; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs @@ -11,10 +11,11 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs /** * implementation of GOST 28147-89 MAC */ - public class Gost28147Mac : IMac + public class Gost28147Mac + : IMac { - private const int blockSize = 8; - private const int macSize = 4; + private const int BlockSize = 8; + private const int MacSize = 4; private int bufOff; private byte[] buf; private byte[] mac; @@ -38,8 +39,8 @@ public class Gost28147Mac : IMac public Gost28147Mac() { - mac = new byte[blockSize]; - buf = new byte[blockSize]; + mac = new byte[BlockSize]; + buf = new byte[BlockSize]; bufOff = 0; } @@ -52,22 +53,19 @@ private static int[] GenerateWorkingKey( int[] key = new int[8]; for(int i=0; i!=8; i++) { - key[i] = bytesToint(userKey,i*4); + key[i] = (int)Pack.LE_To_UInt32(userKey, i * 4); } return key; } - public void Init( - ICipherParameters parameters) + public void Init(ICipherParameters parameters) { Reset(); - buf = new byte[blockSize]; + buf = new byte[BlockSize]; macIV = null; - if (parameters is ParametersWithSBox) + if (parameters is ParametersWithSBox param) { - ParametersWithSBox param = (ParametersWithSBox)parameters; - // // Set the S-Box // @@ -81,22 +79,20 @@ public void Init( workingKey = GenerateWorkingKey(((KeyParameter)param.Parameters).GetKey()); } } - else if (parameters is KeyParameter) + else if (parameters is KeyParameter keyParameter) { - workingKey = GenerateWorkingKey(((KeyParameter)parameters).GetKey()); + workingKey = GenerateWorkingKey(keyParameter.GetKey()); } - else if (parameters is ParametersWithIV) + else if (parameters is ParametersWithIV ivParam) { - 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 + workingKey = GenerateWorkingKey(((KeyParameter)ivParam.Parameters).GetKey()); + macIV = ivParam.GetIV(); // don't skip the initial CM5Func + Array.Copy(macIV, 0, mac, 0, mac.Length); } else { throw new ArgumentException("invalid parameter passed to Gost28147 init - " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); } } @@ -107,10 +103,10 @@ public string AlgorithmName public int GetMacSize() { - return macSize; + return MacSize; } - private int gost28147_mainStep(int n1, int key) + private int Gost28147_mainStep(int n1, int key) { int cm = (key + n1); // CM1 @@ -132,178 +128,222 @@ private int gost28147_mainStep(int n1, int key) return omLeft | omRight; } - private void gost28147MacFunc( + 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); + int N1 = (int)Pack.LE_To_UInt32(input, inOff); + int N2 = (int)Pack.LE_To_UInt32(input, inOff + 4); + int tmp; //tmp -> for saving N1 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 + 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; + Pack.UInt32_To_LE((uint)N1, output, outOff); + Pack.UInt32_To_LE((uint)N2, output, outOff + 4); } - 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) + public void Update(byte input) { if (bufOff == buf.Length) { - byte[] sumbuf = new byte[buf.Length]; - Array.Copy(buf, 0, sumbuf, 0, mac.Length); - + byte[] sum = new byte[buf.Length]; if (firstStep) { firstStep = false; if (macIV != null) { - sumbuf = CM5func(buf, 0, macIV); + Cm5Func(buf, 0, macIV, sum); } - } + else + { + Array.Copy(buf, 0, sum, 0, mac.Length); + } + } else { - sumbuf = CM5func(buf, 0, mac); + Cm5Func(buf, 0, mac, sum); } - gost28147MacFunc(workingKey, sumbuf, 0, mac, 0); + Gost28147MacFunc(workingKey, sum, 0, mac, 0); bufOff = 0; } buf[bufOff++] = input; } - public void BlockUpdate( - byte[] input, - int inOff, - int len) + 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 NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BlockUpdate(input.AsSpan(inOff, len)); +#else + 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); - + byte[] sum = new byte[buf.Length]; if (firstStep) { firstStep = false; if (macIV != null) { - sumbuf = CM5func(buf, 0, macIV); + Cm5Func(buf, 0, macIV, sum); } - } + else + { + Array.Copy(buf, 0, sum, 0, mac.Length); + } + } else { - sumbuf = CM5func(buf, 0, mac); + Cm5Func(buf, 0, mac, sum); } - gost28147MacFunc(workingKey, sumbuf, 0, mac, 0); + Gost28147MacFunc(workingKey, sum, 0, mac, 0); bufOff = 0; len -= gapLen; inOff += gapLen; - while (len > blockSize) + while (len > BlockSize) { - sumbuf = CM5func(input, inOff, mac); - gost28147MacFunc(workingKey, sumbuf, 0, mac, 0); + Cm5Func(input, inOff, mac, sum); + Gost28147MacFunc(workingKey, sum, 0, mac, 0); - len -= blockSize; - inOff += blockSize; + len -= BlockSize; + inOff += BlockSize; } } Array.Copy(input, inOff, buf, bufOff, len); bufOff += len; +#endif } - public int DoFinal( - byte[] output, - int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + int gapLen = BlockSize - bufOff; + + if (input.Length > gapLen) + { + input[..gapLen].CopyTo(buf.AsSpan(bufOff)); + + byte[] sum = new byte[buf.Length]; + if (firstStep) + { + firstStep = false; + if (macIV != null) + { + Cm5Func(buf, macIV, sum); + } + else + { + Array.Copy(buf, 0, sum, 0, mac.Length); + } + } + else + { + Cm5Func(buf, mac, sum); + } + + Gost28147MacFunc(workingKey, sum, 0, mac, 0); + + bufOff = 0; + input = input[gapLen..]; + + while (input.Length > BlockSize) + { + Cm5Func(input, mac, sum); + Gost28147MacFunc(workingKey, sum, 0, mac, 0); + + input = input[BlockSize..]; + } + } + + input.CopyTo(buf.AsSpan(bufOff)); + + bufOff += input.Length; + } +#endif + + public int DoFinal(byte[] output, int outOff) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(output.AsSpan(outOff)); +#else //padding with zero - while (bufOff < blockSize) + while (bufOff < BlockSize) { buf[bufOff++] = 0; } - byte[] sumbuf = new byte[buf.Length]; - Array.Copy(buf, 0, sumbuf, 0, mac.Length); + byte[] sum = new byte[buf.Length]; + if (firstStep) + { + firstStep = false; + Array.Copy(buf, 0, sum, 0, mac.Length); + } + else + { + Cm5Func(buf, 0, mac, sum); + } + + Gost28147MacFunc(workingKey, sum, 0, mac, 0); + Array.Copy(mac, (mac.Length/2)-MacSize, output, outOff, MacSize); + + Reset(); + + return MacSize; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + //padding with zero + while (bufOff < BlockSize) + { + buf[bufOff++] = 0; + } + + byte[] sum = new byte[buf.Length]; if (firstStep) { firstStep = false; + Array.Copy(buf, 0, sum, 0, mac.Length); } else { - sumbuf = CM5func(buf, 0, mac); + Cm5Func(buf, 0, mac, sum); } - gost28147MacFunc(workingKey, sumbuf, 0, mac, 0); + Gost28147MacFunc(workingKey, sum, 0, mac, 0); - Array.Copy(mac, (mac.Length/2)-macSize, output, outOff, macSize); + mac.AsSpan((mac.Length / 2) - MacSize, MacSize).CopyTo(output); Reset(); - return macSize; + return MacSize; } +#endif public void Reset() { @@ -313,6 +353,24 @@ public void Reset() firstStep = true; } + + private static void Cm5Func(byte[] buf, int bufOff, byte[] mac, byte[] sum) + { + for (int i = 0; i < BlockSize; ++i) + { + sum[i] = (byte)(buf[bufOff + i] ^ mac[i]); + } + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void Cm5Func(ReadOnlySpan buffer, ReadOnlySpan mac, Span sum) + { + for (int i = 0; i < BlockSize; ++i) + { + sum[i] = (byte)(buffer[i] ^ mac[i]); + } + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/HMac.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/HMac.cs index 1fa0c18..72d11a2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/HMac.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/HMac.cs @@ -1,9 +1,7 @@ #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; @@ -14,11 +12,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs * * H(K XOR opad, H(K XOR ipad, text)) */ - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] - public sealed class HMac + public class HMac : IMac { private const byte IPAD = (byte)0x36; @@ -42,17 +36,17 @@ public HMac(IDigest digest) this.outputBuf = new byte[blockLength + digestSize]; } - public /*virtual */string AlgorithmName + public virtual string AlgorithmName { get { return digest.AlgorithmName + "/HMAC"; } } - public /*virtual */IDigest GetUnderlyingDigest() + public virtual IDigest GetUnderlyingDigest() { return digest; } - public /*virtual */void Init(ICipherParameters parameters) + public virtual void Init(ICipherParameters parameters) { digest.Reset(); @@ -92,29 +86,39 @@ public HMac(IDigest digest) } } - public /*virtual */int GetMacSize() + public virtual int GetMacSize() { return digestSize; } - public /*virtual */void Update(byte input) + public virtual void Update(byte input) { digest.Update(input); } - public /*virtual */void BlockUpdate(byte[] input, int inOff, int len) + public virtual void BlockUpdate(byte[] input, int inOff, int len) { digest.BlockUpdate(input, inOff, len); } - public /*virtual */int DoFinal(byte[] output, int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) { + digest.BlockUpdate(input); + } +#endif + + public virtual int DoFinal(byte[] output, int outOff) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(output.AsSpan(outOff)); +#else digest.DoFinal(outputBuf, blockLength); if (opadState != null) { ((IMemoable)digest).Reset(opadState); - digest.BlockUpdate(outputBuf, blockLength, digest.GetDigestSize()); + digest.BlockUpdate(outputBuf, blockLength, digestSize); } else { @@ -134,19 +138,56 @@ public HMac(IDigest digest) digest.BlockUpdate(inputPad, 0, inputPad.Length); } + return len; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int DoFinal(Span output) + { + digest.DoFinal(outputBuf.AsSpan(blockLength)); + + if (opadState != null) + { + ((IMemoable)digest).Reset(opadState); + digest.BlockUpdate(outputBuf.AsSpan(blockLength, digestSize)); + } + else + { + digest.BlockUpdate(outputBuf); + } + + int len = digest.DoFinal(output); + + Array.Clear(outputBuf, blockLength, digestSize); + + if (ipadState != null) + { + ((IMemoable)digest).Reset(ipadState); + } + else + { + digest.BlockUpdate(inputPad); + } + return len; } +#endif /** * Reset the mac generator. */ - public /*virtual */void Reset() + public virtual void Reset() { - // Reset underlying digest - digest.Reset(); - - // Initialise the digest - digest.BlockUpdate(inputPad, 0, inputPad.Length); + if (ipadState != null) + { + ((IMemoable)digest).Reset(ipadState); + } + else + { + digest.Reset(); + digest.BlockUpdate(inputPad, 0, inputPad.Length); + } } private static void XorPad(byte[] pad, int len, byte n) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/ISO9797Alg3Mac.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/ISO9797Alg3Mac.cs index 31d8d91..916c884 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/ISO9797Alg3Mac.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/ISO9797Alg3Mac.cs @@ -15,7 +15,8 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs * 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 + public class ISO9797Alg3Mac + : IMac { private byte[] mac; private byte[] buf; @@ -182,14 +183,14 @@ public void Update( buf[bufOff++] = input; } - public void BlockUpdate( - byte[] input, - int inOff, - int len) + public void BlockUpdate(byte[] input, int inOff, int len) { if (len < 0) throw new ArgumentException("Can't have a negative input length!"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BlockUpdate(input.AsSpan(inOff, len)); +#else int blockSize = cipher.GetBlockSize(); int resultLen = 0; int gapLen = blockSize - bufOff; @@ -216,13 +217,44 @@ public void BlockUpdate( Array.Copy(input, inOff, buf, bufOff, len); bufOff += len; +#endif } - public int DoFinal( - byte[] output, - int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) { int blockSize = cipher.GetBlockSize(); + int resultLen = 0; + int gapLen = blockSize - bufOff; + + if (input.Length > gapLen) + { + input[..gapLen].CopyTo(buf.AsSpan(bufOff)); + + resultLen += cipher.ProcessBlock(buf, mac); + + bufOff = 0; + input = input[gapLen..]; + + while (input.Length > blockSize) + { + resultLen += cipher.ProcessBlock(input, mac); + input = input[blockSize..]; + } + } + + input.CopyTo(buf.AsSpan(bufOff)); + + bufOff += input.Length; + } +#endif + + public int DoFinal(byte[] output, int outOff) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(output.AsSpan(outOff)); +#else + int blockSize = cipher.GetBlockSize(); if (padding == null) { @@ -259,8 +291,53 @@ public int DoFinal( Reset(); + return macSize; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + int blockSize = cipher.GetBlockSize(); + + if (padding == null) + { + // pad with zeroes + while (bufOff < blockSize) + { + buf[bufOff++] = 0; + } + } + else + { + if (bufOff == blockSize) + { + cipher.ProcessBlock(buf, mac); + bufOff = 0; + } + + padding.AddPadding(buf, bufOff); + } + + cipher.ProcessBlock(buf, mac); + + // Added to code from base class + DesEngine deseng = new DesEngine(); + + deseng.Init(false, this.lastKey2); + deseng.ProcessBlock(mac, mac); + + deseng.Init(true, this.lastKey3); + deseng.ProcessBlock(mac, mac); + // **** + + mac.AsSpan(0, macSize).CopyTo(output); + + Reset(); + return macSize; } +#endif /** * Reset the mac generator. @@ -269,9 +346,6 @@ public void Reset() { Array.Clear(buf, 0, buf.Length); bufOff = 0; - - // reset the underlying cipher. - cipher.Reset(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/KMac.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/KMac.cs index f518b30..679c75a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/KMac.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/KMac.cs @@ -41,6 +41,16 @@ public void BlockUpdate(byte[] input, int inOff, int len) cshake.BlockUpdate(input, inOff, len); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + if (!initialised) + throw new InvalidOperationException("KMAC not initialized"); + + cshake.BlockUpdate(input); + } +#endif + public int DoFinal(byte[] output, int outOff) { if (firstOutput) @@ -53,14 +63,35 @@ public int DoFinal(byte[] output, int outOff) cshake.BlockUpdate(encOut, 0, encOut.Length); } - int rv = cshake.DoFinal(output, outOff, GetMacSize()); + int rv = cshake.OutputFinal(output, outOff, GetMacSize()); Reset(); return rv; } - public int DoFinal(byte[] output, int outOff, int outLen) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + if (firstOutput) + { + if (!initialised) + throw new InvalidOperationException("KMAC not initialized"); + + Span lengthEncoding = stackalloc byte[9]; + int count = XofUtilities.RightEncode(GetMacSize() * 8, lengthEncoding); + cshake.BlockUpdate(lengthEncoding[..count]); + } + + int rv = cshake.OutputFinal(output[..GetMacSize()]); + + Reset(); + + return rv; + } +#endif + + public int OutputFinal(byte[] output, int outOff, int outLen) { if (firstOutput) { @@ -72,14 +103,35 @@ public int DoFinal(byte[] output, int outOff, int outLen) cshake.BlockUpdate(encOut, 0, encOut.Length); } - int rv = cshake.DoFinal(output, outOff, outLen); + int rv = cshake.OutputFinal(output, outOff, outLen); + + Reset(); + + return rv; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int OutputFinal(Span output) + { + if (firstOutput) + { + if (!initialised) + throw new InvalidOperationException("KMAC not initialized"); + + Span lengthEncoding = stackalloc byte[9]; + int count = XofUtilities.RightEncode(output.Length * 8, lengthEncoding); + cshake.BlockUpdate(lengthEncoding[..count]); + } + + int rv = cshake.OutputFinal(output); Reset(); return rv; } +#endif - public int DoOutput(byte[] output, int outOff, int outLen) + public int Output(byte[] output, int outOff, int outLen) { if (firstOutput) { @@ -93,9 +145,28 @@ public int DoOutput(byte[] output, int outOff, int outLen) firstOutput = false; } - return cshake.DoOutput(output, outOff, outLen); + return cshake.Output(output, outOff, outLen); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int Output(Span output) + { + if (firstOutput) + { + if (!initialised) + throw new InvalidOperationException("KMAC not initialized"); + + Span lengthEncoding = stackalloc byte[9]; + int count = XofUtilities.RightEncode(0, lengthEncoding); + cshake.BlockUpdate(lengthEncoding[..count]); + + firstOutput = false; + } + + return cshake.Output(output); + } +#endif + public int GetByteLength() { return cshake.GetByteLength(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/Poly1305.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/Poly1305.cs index 609e19a..01aa348 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/Poly1305.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/Poly1305.cs @@ -1,8 +1,11 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Diagnostics; +#if NETCOREAPP3_0_OR_GREATER +using System.Runtime.CompilerServices; +#endif -using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; @@ -22,18 +25,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs /// by Andrew M (@floodyberry). /// /// - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] - public sealed class Poly1305 : IMac + public class Poly1305 + : IMac { private const int BlockSize = 16; private readonly IBlockCipher cipher; - private readonly byte[] singleByte = new byte[1]; - // Initialised state /** Polynomial key */ @@ -168,119 +166,214 @@ public int GetMacSize() public void Update(byte input) { - singleByte[0] = input; - BlockUpdate(singleByte, 0, 1); + currentBlock[currentBlockOffset++] = input; + if (currentBlockOffset == BlockSize) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ProcessBlock(currentBlock); +#else + ProcessBlock(currentBlock, 0); +#endif + currentBlockOffset = 0; + } } public void BlockUpdate(byte[] input, int inOff, int len) + { + Check.DataLength(input, inOff, len, "input buffer too short"); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BlockUpdate(input.AsSpan(inOff, len)); +#else + int available = BlockSize - currentBlockOffset; + if (len < available) { - int copied = 0; - while (len > copied) - { - if (currentBlockOffset == BlockSize) - { - ProcessBlock(); - currentBlockOffset = 0; - } + Array.Copy(input, inOff, currentBlock, currentBlockOffset, len); + currentBlockOffset += len; + return; + } - int toCopy = System.Math.Min((len - copied), BlockSize - currentBlockOffset); - Array.Copy(input, copied + inOff, currentBlock, currentBlockOffset, toCopy); - copied += toCopy; - currentBlockOffset += toCopy; - } + int pos = 0; + if (currentBlockOffset > 0) + { + Array.Copy(input, inOff, currentBlock, currentBlockOffset, available); + pos = available; + ProcessBlock(currentBlock, 0); } - private void ProcessBlock() + int remaining; + while ((remaining = len - pos) >= BlockSize) { + ProcessBlock(input, inOff + pos); + pos += BlockSize; + } + + Array.Copy(input, inOff + pos, currentBlock, 0, remaining); + currentBlockOffset = remaining; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + int available = BlockSize - currentBlockOffset; + if (input.Length < available) + { + input.CopyTo(currentBlock.AsSpan(currentBlockOffset)); + currentBlockOffset += input.Length; + return; + } + + int pos = 0; + if (currentBlockOffset > 0) + { + input[..available].CopyTo(currentBlock.AsSpan(currentBlockOffset)); + pos = available; + ProcessBlock(currentBlock); + } + + int remaining; + while ((remaining = input.Length - pos) >= BlockSize) + { + ProcessBlock(input[pos..]); + pos += BlockSize; + } + + input[pos..].CopyTo(currentBlock); + currentBlockOffset = remaining; + } +#endif + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void ProcessBlock(ReadOnlySpan block) + { + uint t0 = Pack.LE_To_UInt32(block); + uint t1 = Pack.LE_To_UInt32(block[4..]); + uint t2 = Pack.LE_To_UInt32(block[8..]); + uint t3 = Pack.LE_To_UInt32(block[12..]); +#else + private void ProcessBlock(byte[] buf, int off) + { + uint t0 = Pack.LE_To_UInt32(buf, off + 0); + uint t1 = Pack.LE_To_UInt32(buf, off + 4); + uint t2 = Pack.LE_To_UInt32(buf, off + 8); + uint t3 = Pack.LE_To_UInt32(buf, off + 12); +#endif + + h0 += t0 & 0x3ffffffU; + h1 += ((t1 << 6) | (t0 >> 26)) & 0x3ffffffU; + h2 += ((t2 << 12) | (t1 >> 20)) & 0x3ffffffU; + h3 += ((t3 << 18) | (t2 >> 14)) & 0x3ffffffU; + h4 += ( 1 << 24) | (t3 >> 8); + + ulong tp0 = (ulong)h0 * r0 + (ulong)h1 * s4 + (ulong)h2 * s3 + (ulong)h3 * s2 + (ulong)h4 * s1; + ulong tp1 = (ulong)h0 * r1 + (ulong)h1 * r0 + (ulong)h2 * s4 + (ulong)h3 * s3 + (ulong)h4 * s2; + ulong tp2 = (ulong)h0 * r2 + (ulong)h1 * r1 + (ulong)h2 * r0 + (ulong)h3 * s4 + (ulong)h4 * s3; + ulong tp3 = (ulong)h0 * r3 + (ulong)h1 * r2 + (ulong)h2 * r1 + (ulong)h3 * r0 + (ulong)h4 * s4; + ulong tp4 = (ulong)h0 * r4 + (ulong)h1 * r3 + (ulong)h2 * r2 + (ulong)h3 * r1 + (ulong)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) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(output.AsSpan(outOff)); +#else + Check.OutputLength(output, outOff, BlockSize, "output buffer is too short."); + + if (currentBlockOffset > 0) + { + // Process padded block if (currentBlockOffset < BlockSize) { - currentBlock[currentBlockOffset] = 1; - for (int i = currentBlockOffset + 1; i < BlockSize; i++) + currentBlock[currentBlockOffset++] = 1; + while (currentBlockOffset < BlockSize) { - currentBlock[i] = 0; + currentBlock[currentBlockOffset++] = 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); + h4 -= (1 << 24); + } - 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); + ProcessBlock(currentBlock, 0); + } - if (currentBlockOffset == BlockSize) - { - h4 += (1 << 24); - } + Debug.Assert(h4 >> 26 == 0); + + //h0 += (h4 >> 26) * 5U + 5U; h4 &= 0x3ffffff; + h0 += 5U; + h1 += h0 >> 26; h0 &= 0x3ffffff; + h2 += h1 >> 26; h1 &= 0x3ffffff; + h3 += h2 >> 26; h2 &= 0x3ffffff; + h4 += h3 >> 26; h3 &= 0x3ffffff; + + long c = ((int)(h4 >> 26) - 1) * 5; + c += (long)k0 + ((h0 ) | (h1 << 26)); + Pack.UInt32_To_LE((uint)c, output, outOff ); c >>= 32; + c += (long)k1 + ((h1 >> 6) | (h2 << 20)); + Pack.UInt32_To_LE((uint)c, output, outOff + 4); c >>= 32; + c += (long)k2 + ((h2 >> 12) | (h3 << 14)); + Pack.UInt32_To_LE((uint)c, output, outOff + 8); c >>= 32; + c += (long)k3 + ((h3 >> 18) | (h4 << 8)); + Pack.UInt32_To_LE((uint)c, output, outOff + 12); - 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; + Reset(); + return BlockSize; +#endif } - public int DoFinal(byte[] output, int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) { - Check.DataLength(output, outOff, BlockSize, "Output buffer is too short."); + Check.OutputLength(output, BlockSize, "output buffer is too short."); if (currentBlockOffset > 0) { // Process padded block - ProcessBlock(); + if (currentBlockOffset < BlockSize) + { + currentBlock[currentBlockOffset++] = 1; + while (currentBlockOffset < BlockSize) + { + currentBlock[currentBlockOffset++] = 0; + } + + h4 -= (1 << 24); + } + + ProcessBlock(currentBlock); } - 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); + Debug.Assert(h4 >> 26 == 0); + + //h0 += (h4 >> 26) * 5U + 5U; h4 &= 0x3ffffff; + h0 += 5U; + h1 += h0 >> 26; h0 &= 0x3ffffff; + h2 += h1 >> 26; h1 &= 0x3ffffff; + h3 += h2 >> 26; h2 &= 0x3ffffff; + h4 += h3 >> 26; h3 &= 0x3ffffff; + + long c = ((int)(h4 >> 26) - 1) * 5; + c += (long)k0 + ((h0) | (h1 << 26)); + Pack.UInt32_To_LE((uint)c, output); c >>= 32; + c += (long)k1 + ((h1 >> 6) | (h2 << 20)); + Pack.UInt32_To_LE((uint)c, output[4..]); c >>= 32; + c += (long)k2 + ((h2 >> 12) | (h3 << 14)); + Pack.UInt32_To_LE((uint)c, output[8..]); c >>= 32; + c += (long)k3 + ((h3 >> 18) | (h4 << 8)); + Pack.UInt32_To_LE((uint)c, output[12..]); Reset(); return BlockSize; } +#endif public void Reset() { @@ -288,11 +381,6 @@ public void Reset() h0 = h1 = h2 = h3 = h4 = 0; } - - private static ulong mul32x32_64(uint i1, uint i2) - { - return ((ulong)i1) * i2; - } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/SipHash.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/SipHash.cs index 74f7e8d..844bd9d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/SipHash.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/SipHash.cs @@ -82,6 +82,9 @@ public virtual void Update(byte input) public virtual void BlockUpdate(byte[] input, int offset, int length) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BlockUpdate(input.AsSpan(offset, length)); +#else int i = 0, fullWords = length & ~7; if (wordPos == 0) { @@ -110,6 +113,48 @@ public virtual void BlockUpdate(byte[] input, int offset, int length) { m = (long)(((ulong)m >> 8) | ((ulong)input[offset + i] << 56)); + if (++wordPos == 8) + { + ProcessMessageWord(); + wordPos = 0; + } + } + } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) + { + int length = input.Length; + int i = 0, fullWords = length & ~7; + if (wordPos == 0) + { + for (; i < fullWords; i += 8) + { + m = (long)Pack.LE_To_UInt64(input[i..]); + ProcessMessageWord(); + } + for (; i < length; ++i) + { + m = (long)(((ulong)m >> 8) | ((ulong)input[i] << 56)); + } + wordPos = length - fullWords; + } + else + { + int bits = wordPos << 3; + for (; i < fullWords; i += 8) + { + ulong n = Pack.LE_To_UInt64(input[i..]); + m = (long)((n << bits) | ((ulong)m >> -bits)); + ProcessMessageWord(); + m = (long)n; + } + for (; i < length; ++i) + { + m = (long)(((ulong)m >> 8) | ((ulong)input[i] << 56)); + if (++wordPos == 8) { ProcessMessageWord(); @@ -118,6 +163,7 @@ public virtual void BlockUpdate(byte[] input, int offset, int length) } } } +#endif public virtual long DoFinal() { @@ -146,6 +192,15 @@ public virtual int DoFinal(byte[] output, int outOff) return 8; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + long result = DoFinal(); + Pack.UInt64_To_LE((ulong)result, output); + return 8; + } +#endif + public virtual void Reset() { v0 = k0 ^ 0x736f6d6570736575L; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/SkeinMac.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/SkeinMac.cs index 3daaf46..ab8079b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/SkeinMac.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/SkeinMac.cs @@ -82,7 +82,7 @@ public void Init(ICipherParameters parameters) else { throw new ArgumentException("Invalid parameter passed to Skein MAC init - " - + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); + + Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters)); } if (skeinParameters.GetKey() == null) { @@ -108,14 +108,27 @@ public void Update(byte inByte) public void BlockUpdate(byte[] input, int inOff, int len) { - engine.Update(input, inOff, len); + engine.BlockUpdate(input, inOff, len); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void BlockUpdate(ReadOnlySpan input) + { + engine.BlockUpdate(input); + } +#endif + public int DoFinal(byte[] output, int outOff) { return engine.DoFinal(output, outOff); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) + { + return engine.DoFinal(output); + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/VMPCMac.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/VMPCMac.cs index 03c0883..769cbdd 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/VMPCMac.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/macs/VMPCMac.cs @@ -24,6 +24,9 @@ public class VmpcMac public virtual int DoFinal(byte[] output, int outOff) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(output.AsSpan(outOff)); +#else // Execute the Post-Processing Phase for (int r = 1; r < 25; r++) { @@ -69,8 +72,61 @@ public virtual int DoFinal(byte[] output, int outOff) Array.Copy(M, 0, output, outOff, M.Length); Reset(); + return M.Length; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int DoFinal(Span output) + { + // 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; + } + + M.CopyTo(output); + Reset(); + return M.Length; } +#endif public virtual string AlgorithmName { @@ -161,16 +217,25 @@ public virtual void Update(byte input) n = (byte) ((n + 1) & 0xff); } - public virtual void BlockUpdate(byte[] input, int inOff, int len) + public virtual void BlockUpdate(byte[] input, int inOff, int inLen) { - if ((inOff + len) > input.Length) - throw new DataLengthException("input buffer too short"); + Check.DataLength(input, inOff, inLen, "input buffer too short"); - for (int i = 0; i < len; i++) + for (int i = 0; i < inLen; i++) { Update(input[inOff + i]); } } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) + { + for (int i = 0; i < input.Length; i++) + { + Update(input[i]); + } + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/CbcBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/CbcBlockCipher.cs index a02e394..264d30c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/CbcBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/CbcBlockCipher.cs @@ -9,12 +9,8 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes /** * implements Cipher-Block-Chaining (CBC) mode on top of a simple cipher. */ - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] - public class CbcBlockCipher - : IBlockCipher + public sealed class CbcBlockCipher + : IBlockCipherMode { private byte[] IV, cbcV, cbcNextV; private int blockSize; @@ -42,10 +38,7 @@ public CbcBlockCipher( * * @return the underlying block cipher that we are wrapping. */ - public IBlockCipher GetUnderlyingCipher() - { - return cipher; - } + public IBlockCipher UnderlyingCipher => cipher; /** * Initialise the cipher and, possibly, the initialisation vector (IV). @@ -57,23 +50,18 @@ public IBlockCipher GetUnderlyingCipher() * @exception ArgumentException if the parameters argument is * inappropriate. */ - public void Init( - bool forEncryption, - ICipherParameters parameters) + public void Init(bool forEncryption, ICipherParameters parameters) { bool oldEncrypting = this.encrypting; this.encrypting = forEncryption; - if (parameters is ParametersWithIV) + if (parameters is ParametersWithIV ivParam) { - ParametersWithIV ivParam = (ParametersWithIV)parameters; - byte[] iv = ivParam.GetIV(); + 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); @@ -118,30 +106,28 @@ 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) + public int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { - return (encrypting) - ? EncryptBlock(input, inOff, output, outOff) - : DecryptBlock(input, inOff, output, outOff); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return encrypting + ? EncryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)) + : DecryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); +#else + return encrypting + ? EncryptBlock(input, inOff, output, outOff) + : DecryptBlock(input, inOff, output, outOff); +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessBlock(ReadOnlySpan input, Span output) + { + return encrypting + ? EncryptBlock(input, output) + : DecryptBlock(input, output); + } +#endif + /** * reset the chaining vector back to the IV and reset the underlying * cipher. @@ -150,114 +136,86 @@ 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 unsafe int EncryptBlock( - byte[] input, - int inOff, - byte[] outBytes, - int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int EncryptBlock(ReadOnlySpan input, Span output) { - if ((inOff + blockSize) > input.Length) + Check.DataLength(input, blockSize, "input buffer too short"); + Check.OutputLength(output, blockSize, "output buffer too short"); + + for (int i = 0; i < blockSize; i++) { - throw new DataLengthException("input buffer too short"); + cbcV[i] ^= input[i]; } - /* - * XOR the cbcV and the input, - * then encrypt the cbcV - */ - //for (int i = 0; i < blockSize; i++) - //{ - // cbcV[i] ^= input[inOff + i]; - //} - fixed (byte* pinput = input, pcbcV = cbcV) + int length = cipher.ProcessBlock(cbcV, output); + + output[..blockSize].CopyTo(cbcV); + + return length; + } + + private int DecryptBlock(ReadOnlySpan input, Span output) + { + Check.DataLength(input, blockSize, "input buffer too short"); + Check.OutputLength(output, blockSize, "output buffer too short"); + + input[..blockSize].CopyTo(cbcNextV); + + int length = cipher.ProcessBlock(input, output); + + for (int i = 0; i < blockSize; i++) { - ulong* pulongInput = (ulong*)&pinput[inOff], pulongcbcV = (ulong*)pcbcV; + output[i] ^= cbcV[i]; + } + + byte[] tmp = cbcV; + cbcV = cbcNextV; + cbcNextV = tmp; + + return length; + } +#else + private int EncryptBlock(byte[] input, int inOff, byte[] outBytes, int outOff) + { + Check.DataLength(input, inOff, blockSize, "input buffer too short"); + Check.OutputLength(outBytes, outOff, blockSize, "output buffer too short"); - for (int i = 0; i < blockSize / 8; i++) - pulongcbcV[i] ^= pulongInput[i]; + 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 unsafe int DecryptBlock( - byte[] input, - int inOff, - byte[] outBytes, - int outOff) + private int DecryptBlock(byte[] input, int inOff, byte[] outBytes, int outOff) { - if ((inOff + blockSize) > input.Length) - { - throw new DataLengthException("input buffer too short"); - } + Check.DataLength(input, inOff, blockSize, "input buffer too short"); + Check.OutputLength(outBytes, outOff, blockSize, "output 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]; - //} - fixed (byte* poutBytes = outBytes, pcbcV = cbcV) + for (int i = 0; i < blockSize; i++) { - ulong* pulongBytes = (ulong*)&poutBytes[outOff], pulongcbcV = (ulong*)pcbcV; - - for (int i = 0; i < blockSize / 8; i++) - pulongBytes[i] ^= pulongcbcV[i]; + outBytes[outOff + i] ^= cbcV[i]; } - /* - * swap the back up buffer into next position - */ - byte[] tmp; - - tmp = cbcV; + byte[] tmp = cbcV; cbcV = cbcNextV; cbcNextV = tmp; return length; } +#endif } - } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/CcmBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/CcmBlockCipher.cs index b11cb8b..ec116c0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/CcmBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/CcmBlockCipher.cs @@ -3,7 +3,6 @@ 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; @@ -52,35 +51,26 @@ public CcmBlockCipher( * * @return the underlying block cipher that we are wrapping. */ - public virtual IBlockCipher GetUnderlyingCipher() - { - return cipher; - } + public virtual IBlockCipher UnderlyingCipher => cipher; - public virtual void Init( - bool forEncryption, - ICipherParameters parameters) + public virtual void Init(bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; ICipherParameters cipherParameters; - if (parameters is AeadParameters) + if (parameters is AeadParameters aeadParameters) { - AeadParameters param = (AeadParameters) parameters; - - nonce = param.GetNonce(); - initialAssociatedText = param.GetAssociatedText(); - macSize = GetMacSize(forEncryption, param.MacSize); - cipherParameters = param.Key; + nonce = aeadParameters.GetNonce(); + initialAssociatedText = aeadParameters.GetAssociatedText(); + macSize = GetMacSize(forEncryption, aeadParameters.MacSize); + cipherParameters = aeadParameters.Key; } - else if (parameters is ParametersWithIV) + else if (parameters is ParametersWithIV parametersWithIV) { - ParametersWithIV param = (ParametersWithIV) parameters; - - nonce = param.GetIV(); + nonce = parametersWithIV.GetIV(); initialAssociatedText = null; macSize = GetMacSize(forEncryption, 64); - cipherParameters = param.Parameters; + cipherParameters = parametersWithIV.Parameters; } else { @@ -99,10 +89,7 @@ public virtual void Init( Reset(); } - public virtual string AlgorithmName - { - get { return cipher.AlgorithmName + "/CCM"; } - } + public virtual string AlgorithmName => cipher.AlgorithmName + "/CCM"; public virtual int GetBlockSize() { @@ -120,52 +107,80 @@ public virtual void ProcessAadBytes(byte[] inBytes, int inOff, int len) associatedText.Write(inBytes, inOff, len); } - public virtual int ProcessByte( - byte input, - byte[] outBytes, - int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void ProcessAadBytes(ReadOnlySpan input) + { + // TODO: Process AAD online + associatedText.Write(input); + } +#endif + + 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) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessByte(byte input, Span output) { - Check.DataLength(inBytes, inOff, inLen, "Input buffer too short"); + data.WriteByte(input); + + return 0; + } +#endif + + 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 NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBytes(ReadOnlySpan input, Span output) { -#if PORTABLE || NETFX_CORE - byte[] input = data.ToArray(); - int inLen = input.Length; + data.Write(input); + + return 0; + } +#endif + + public virtual int DoFinal(byte[] outBytes, int outOff) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(outBytes.AsSpan(outOff)); #else byte[] input = data.GetBuffer(); - int inLen = (int)data.Position; -#endif + int inLen = Convert.ToInt32(data.Length); int len = ProcessPacket(input, 0, inLen, outBytes, outOff); Reset(); + return len; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int DoFinal(Span output) + { + byte[] input = data.GetBuffer(); + int inLen = Convert.ToInt32(data.Length); + + int len = ProcessPacket(input.AsSpan(0, inLen), output); + + Reset(); + return len; } +#endif public virtual void Reset() { - cipher.Reset(); associatedText.SetLength(0); data.SetLength(0); } @@ -181,16 +196,14 @@ public virtual byte[] GetMac() return Arrays.CopyOfRange(macBlock, 0, macSize); } - public virtual int GetUpdateOutputSize( - int len) + public virtual int GetUpdateOutputSize(int len) { return 0; } - public virtual int GetOutputSize( - int len) + public virtual int GetOutputSize(int len) { - int totalData = (int)data.Length + len; + int totalData = Convert.ToInt32(data.Length) + len; if (forEncryption) { @@ -341,8 +354,106 @@ public virtual int ProcessPacket(byte[] input, int inOff, int inLen, byte[] outp return outputLen; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessPacket(ReadOnlySpan input, Span output) + { + int inLen = input.Length; + + // 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 index = 0; + Span block = stackalloc byte[BlockSize]; + + if (forEncryption) + { + outputLen = inLen + macSize; + Check.OutputLength(output, outputLen, "output buffer too short"); + + CalculateMac(input, macBlock); + + byte[] encMac = new byte[BlockSize]; + ctrCipher.ProcessBlock(macBlock, encMac); // S0 + + while (index < (inLen - BlockSize)) // S1... + { + ctrCipher.ProcessBlock(input[index..], output[index..]); + index += BlockSize; + } + + input[index..].CopyTo(block); + + ctrCipher.ProcessBlock(block, block); + + block[..(inLen - index)].CopyTo(output[index..]); + + encMac.AsSpan(0, macSize).CopyTo(output[inLen..]); + } + else + { + if (inLen < macSize) + throw new InvalidCipherTextException("data too short"); + + outputLen = inLen - macSize; + Check.OutputLength(output, outputLen, "output buffer too short"); + + input[outputLen..].CopyTo(macBlock); + + ctrCipher.ProcessBlock(macBlock, macBlock); + + for (int i = macSize; i != macBlock.Length; i++) + { + macBlock[i] = 0; + } + + while (index < (outputLen - BlockSize)) + { + ctrCipher.ProcessBlock(input[index..], output[index..]); + index += BlockSize; + } + + input[index..outputLen].CopyTo(block); + + ctrCipher.ProcessBlock(block, block); + + block[..(outputLen - index)].CopyTo(output[index..]); + + Span calculatedMacBlock = stackalloc byte[BlockSize]; + + CalculateMac(output[..outputLen], calculatedMacBlock); + + if (!Arrays.ConstantTimeAreEqual(macBlock, calculatedMacBlock)) + throw new InvalidCipherTextException("mac check in CCM failed"); + } + + return outputLen; + } +#endif + private int CalculateMac(byte[] data, int dataOff, int dataLen, byte[] macBlock) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return CalculateMac(data.AsSpan(dataOff, dataLen), macBlock); +#else IMac cMac = new CbcBlockCipherMac(cipher, macSize * 8); cMac.Init(keyParam); @@ -405,15 +516,10 @@ private int CalculateMac(byte[] data, int dataOff, int dataLen, byte[] macBlock) { cMac.BlockUpdate(initialAssociatedText, 0, initialAssociatedText.Length); } - if (associatedText.Position > 0) + if (associatedText.Length > 0) { -#if PORTABLE || NETFX_CORE - byte[] input = associatedText.ToArray(); - int len = input.Length; -#else byte[] input = associatedText.GetBuffer(); - int len = (int)associatedText.Position; -#endif + int len = Convert.ToInt32(associatedText.Length); cMac.BlockUpdate(input, 0, len); } @@ -434,7 +540,100 @@ private int CalculateMac(byte[] data, int dataOff, int dataLen, byte[] macBlock) cMac.BlockUpdate(data, dataOff, dataLen); return cMac.DoFinal(macBlock, 0); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int CalculateMac(ReadOnlySpan data, Span 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 = data.Length; + 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.Length > 0) + { + byte[] input = associatedText.GetBuffer(); + int len = Convert.ToInt32(associatedText.Length); + + 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); + + return cMac.DoFinal(macBlock); } +#endif private int GetMacSize(bool forEncryption, int requestedMacBits) { @@ -446,7 +645,8 @@ private int GetMacSize(bool forEncryption, int requestedMacBits) private int GetAssociatedTextLength() { - return (int)associatedText.Length + ((initialAssociatedText == null) ? 0 : initialAssociatedText.Length); + return Convert.ToInt32(associatedText.Length) + + (initialAssociatedText == null ? 0 : initialAssociatedText.Length); } private bool HasAssociatedText() diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/CfbBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/CfbBlockCipher.cs index 997aa60..abd759f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/CfbBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/CfbBlockCipher.cs @@ -10,7 +10,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes * implements a Cipher-FeedBack (CFB) mode on top of a simple cipher. */ public class CfbBlockCipher - : IBlockCipher + : IBlockCipherMode { private byte[] IV; private byte[] cfbV; @@ -45,10 +45,8 @@ public CfbBlockCipher( * * @return the underlying block cipher that we are wrapping. */ - public IBlockCipher GetUnderlyingCipher() - { - return cipher; - } + public IBlockCipher UnderlyingCipher => 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. @@ -110,56 +108,76 @@ 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) + public int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { - return (encrypting) - ? EncryptBlock(input, inOff, output, outOff) - : DecryptBlock(input, inOff, output, outOff); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return encrypting + ? EncryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)) + : DecryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); +#else + return encrypting + ? EncryptBlock(input, inOff, output, outOff) + : DecryptBlock(input, inOff, output, outOff); +#endif } - /** - * 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 NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessBlock(ReadOnlySpan input, Span output) + { + return encrypting + ? EncryptBlock(input, output) + : DecryptBlock(input, output); + } +#endif + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int EncryptBlock(ReadOnlySpan input, Span output) { - if ((inOff + blockSize) > input.Length) + Check.DataLength(input, blockSize, "input buffer too short"); + Check.OutputLength(output, blockSize, "output buffer too short"); + + cipher.ProcessBlock(cfbV, cfbOutV); + // + // XOR the cfbV with the plaintext producing the ciphertext + // + for (int i = 0; i < blockSize; i++) { - throw new DataLengthException("input buffer too short"); + output[i] = (byte)(cfbOutV[i] ^ input[i]); } - if ((outOff + blockSize) > outBytes.Length) + // + // change over the input block. + // + Array.Copy(cfbV, blockSize, cfbV, 0, cfbV.Length - blockSize); + output[..blockSize].CopyTo(cfbV.AsSpan(cfbV.Length - blockSize)); + return blockSize; + } + + private int DecryptBlock(ReadOnlySpan input, Span output) + { + Check.DataLength(input, blockSize, "input buffer too short"); + Check.OutputLength(output, blockSize, "output buffer too short"); + + cipher.ProcessBlock(cfbV, 0, cfbOutV, 0); + // + // change over the input block. + // + Array.Copy(cfbV, blockSize, cfbV, 0, cfbV.Length - blockSize); + input[..blockSize].CopyTo(cfbV.AsSpan(cfbV.Length - blockSize)); + // + // XOR the cfbV with the ciphertext producing the plaintext + // + for (int i = 0; i < blockSize; i++) { - throw new DataLengthException("output buffer too short"); + output[i] = (byte)(cfbOutV[i] ^ input[i]); } + return blockSize; + } +#else + private int EncryptBlock(byte[] input, int inOff, byte[] outBytes, int outOff) + { + Check.DataLength(input, inOff, blockSize, "input buffer too short"); + Check.OutputLength(outBytes, outOff, blockSize, "output buffer too short"); + cipher.ProcessBlock(cfbV, 0, cfbOutV, 0); // // XOR the cfbV with the plaintext producing the ciphertext @@ -175,32 +193,12 @@ public int EncryptBlock( 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) + + 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"); - } + Check.DataLength(input, inOff, blockSize, "input buffer too short"); + Check.OutputLength(outBytes, outOff, blockSize, "output buffer too short"); + cipher.ProcessBlock(cfbV, 0, cfbOutV, 0); // // change over the input block. @@ -216,6 +214,8 @@ public int DecryptBlock( } return blockSize; } +#endif + /** * reset the chaining vector back to the IV and reset the underlying * cipher. @@ -223,7 +223,6 @@ public int DecryptBlock( public void Reset() { Array.Copy(IV, 0, cfbV, 0, IV.Length); - cipher.Reset(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/ChaCha20Poly1305.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/ChaCha20Poly1305.cs index 5612c26..7427369 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/ChaCha20Poly1305.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/ChaCha20Poly1305.cs @@ -211,6 +211,19 @@ public virtual void ProcessAadBytes(byte[] inBytes, int inOff, int len) } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void ProcessAadBytes(ReadOnlySpan input) + { + CheckAad(); + + if (!input.IsEmpty) + { + this.mAadCount = IncrementCount(mAadCount, (uint)input.Length, AadLimit); + mPoly1305.BlockUpdate(input); + } + } +#endif + public virtual int ProcessByte(byte input, byte[] outBytes, int outOff) { CheckData(); @@ -223,7 +236,11 @@ public virtual int ProcessByte(byte input, byte[] outBytes, int outOff) if (++mBufPos == mBuf.Length) { mPoly1305.BlockUpdate(mBuf, 0, BufSize); - ProcessData(mBuf, 0, BufSize, outBytes, outOff); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ProcessBlock(mBuf, outBytes.AsSpan(outOff)); +#else + ProcessBlock(mBuf, 0, outBytes, outOff); +#endif Array.Copy(mBuf, BufSize, mBuf, 0, MacSize); this.mBufPos = MacSize; return BufSize; @@ -236,7 +253,11 @@ public virtual int ProcessByte(byte input, byte[] outBytes, int outOff) mBuf[mBufPos] = input; if (++mBufPos == BufSize) { - ProcessData(mBuf, 0, BufSize, outBytes, outOff); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ProcessBlock(mBuf, outBytes.AsSpan(outOff)); +#else + ProcessBlock(mBuf, 0, outBytes, outOff); +#endif mPoly1305.BlockUpdate(outBytes, outOff, BufSize); this.mBufPos = 0; return BufSize; @@ -249,6 +270,46 @@ public virtual int ProcessByte(byte input, byte[] outBytes, int outOff) } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessByte(byte input, Span output) + { + CheckData(); + + switch (mState) + { + case State.DecData: + { + mBuf[mBufPos] = input; + if (++mBufPos == mBuf.Length) + { + mPoly1305.BlockUpdate(mBuf.AsSpan(0, BufSize)); + ProcessBlock(mBuf, output); + Array.Copy(mBuf, BufSize, mBuf, 0, MacSize); + this.mBufPos = MacSize; + return BufSize; + } + + return 0; + } + case State.EncData: + { + mBuf[mBufPos] = input; + if (++mBufPos == BufSize) + { + ProcessBlock(mBuf, output); + mPoly1305.BlockUpdate(output[..BufSize]); + this.mBufPos = 0; + return BufSize; + } + + return 0; + } + default: + throw new InvalidOperationException(); + } + } +#endif + public virtual int ProcessBytes(byte[] inBytes, int inOff, int len, byte[] outBytes, int outOff) { if (null == inBytes) @@ -269,6 +330,9 @@ public virtual int ProcessBytes(byte[] inBytes, int inOff, int len, byte[] outBy if (outOff < 0) throw new ArgumentException("cannot be negative", "outOff"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ProcessBytes(inBytes.AsSpan(inOff, len), Spans.FromNullable(outBytes, outOff)); +#else CheckData(); int resultLen = 0; @@ -277,53 +341,210 @@ public virtual int ProcessBytes(byte[] inBytes, int inOff, int len, byte[] outBy { case State.DecData: { - for (int i = 0; i < len; ++i) + int available = mBuf.Length - mBufPos; + if (len < available) + { + Array.Copy(inBytes, inOff, mBuf, mBufPos, len); + mBufPos += len; + break; + } + + if (mBufPos >= BufSize) { - mBuf[mBufPos] = inBytes[inOff + i]; - if (++mBufPos == mBuf.Length) + mPoly1305.BlockUpdate(mBuf, 0, BufSize); + ProcessBlock(mBuf, 0, outBytes, outOff); + Array.Copy(mBuf, BufSize, mBuf, 0, mBufPos -= BufSize); + resultLen = BufSize; + + available += BufSize; + if (len < available) { - mPoly1305.BlockUpdate(mBuf, 0, BufSize); - ProcessData(mBuf, 0, BufSize, outBytes, outOff + resultLen); - Array.Copy(mBuf, BufSize, mBuf, 0, MacSize); - this.mBufPos = MacSize; - resultLen += BufSize; + Array.Copy(inBytes, inOff, mBuf, mBufPos, len); + mBufPos += len; + break; } } + + int inLimit1 = inOff + len - mBuf.Length; + int inLimit2 = inLimit1 - BufSize; + + available = BufSize - mBufPos; + Array.Copy(inBytes, inOff, mBuf, mBufPos, available); + mPoly1305.BlockUpdate(mBuf, 0, BufSize); + ProcessBlock(mBuf, 0, outBytes, outOff + resultLen); + inOff += available; + resultLen += BufSize; + + while (inOff <= inLimit2) + { + mPoly1305.BlockUpdate(inBytes, inOff, BufSize * 2); + ProcessBlocks2(inBytes, inOff, outBytes, outOff + resultLen); + inOff += BufSize * 2; + resultLen += BufSize * 2; + } + + if (inOff <= inLimit1) + { + mPoly1305.BlockUpdate(inBytes, inOff, BufSize); + ProcessBlock(inBytes, inOff, outBytes, outOff + resultLen); + inOff += BufSize; + resultLen += BufSize; + } + + mBufPos = mBuf.Length + inLimit1 - inOff; + Array.Copy(inBytes, inOff, mBuf, 0, mBufPos); break; } case State.EncData: { - if (mBufPos != 0) + int available = BufSize - mBufPos; + if (len < available) { - while (len > 0) + Array.Copy(inBytes, inOff, mBuf, mBufPos, len); + mBufPos += len; + break; + } + + int inLimit1 = inOff + len - BufSize; + int inLimit2 = inLimit1 - BufSize; + + if (mBufPos > 0) + { + Array.Copy(inBytes, inOff, mBuf, mBufPos, available); + ProcessBlock(mBuf, 0, outBytes, outOff); + inOff += available; + resultLen = BufSize; + } + + while (inOff <= inLimit2) + { + ProcessBlocks2(inBytes, inOff, outBytes, outOff + resultLen); + inOff += BufSize * 2; + resultLen += BufSize * 2; + } + + if (inOff <= inLimit1) + { + ProcessBlock(inBytes, inOff, outBytes, outOff + resultLen); + inOff += BufSize; + resultLen += BufSize; + } + + mPoly1305.BlockUpdate(outBytes, outOff, resultLen); + + mBufPos = BufSize + inLimit1 - inOff; + Array.Copy(inBytes, inOff, mBuf, 0, mBufPos); + break; + } + default: + throw new InvalidOperationException(); + } + + return resultLen; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBytes(ReadOnlySpan input, Span output) + { + CheckData(); + + int resultLen = 0; + + switch (mState) + { + case State.DecData: + { + int available = mBuf.Length - mBufPos; + if (input.Length < available) + { + input.CopyTo(mBuf.AsSpan(mBufPos)); + mBufPos += input.Length; + break; + } + + if (mBufPos >= BufSize) + { + mPoly1305.BlockUpdate(mBuf.AsSpan(0, BufSize)); + ProcessBlock(mBuf, output); + Array.Copy(mBuf, BufSize, mBuf, 0, mBufPos -= BufSize); + resultLen = BufSize; + + available += BufSize; + if (input.Length < available) { - --len; - mBuf[mBufPos] = inBytes[inOff++]; - if (++mBufPos == BufSize) - { - ProcessData(mBuf, 0, BufSize, outBytes, outOff); - mPoly1305.BlockUpdate(outBytes, outOff, BufSize); - this.mBufPos = 0; - resultLen = BufSize; - break; - } + input.CopyTo(mBuf.AsSpan(mBufPos)); + mBufPos += input.Length; + break; } } - while (len >= BufSize) + int inLimit1 = mBuf.Length; + int inLimit2 = inLimit1 + BufSize; + + available = BufSize - mBufPos; + input[..available].CopyTo(mBuf.AsSpan(mBufPos)); + mPoly1305.BlockUpdate(mBuf.AsSpan(0, BufSize)); + ProcessBlock(mBuf, output[resultLen..]); + input = input[available..]; + resultLen += BufSize; + + while (input.Length >= inLimit2) { - ProcessData(inBytes, inOff, BufSize, outBytes, outOff + resultLen); - mPoly1305.BlockUpdate(outBytes, outOff + resultLen, BufSize); - inOff += BufSize; - len -= BufSize; + mPoly1305.BlockUpdate(input[..(BufSize * 2)]); + ProcessBlocks2(input, output[resultLen..]); + input = input[(BufSize * 2)..]; + resultLen += BufSize * 2; + } + + if (input.Length >= inLimit1) + { + mPoly1305.BlockUpdate(input[..BufSize]); + ProcessBlock(input, output[resultLen..]); + input = input[BufSize..]; resultLen += BufSize; } - if (len > 0) + mBufPos = input.Length; + input.CopyTo(mBuf); + break; + } + case State.EncData: + { + int available = BufSize - mBufPos; + if (input.Length < available) + { + input.CopyTo(mBuf.AsSpan(mBufPos)); + mBufPos += input.Length; + break; + } + + if (mBufPos > 0) + { + input[..available].CopyTo(mBuf.AsSpan(mBufPos)); + ProcessBlock(mBuf, output); + input = input[available..]; + resultLen = BufSize; + } + + while (input.Length >= BufSize * 2) { - Array.Copy(inBytes, inOff, mBuf, 0, len); - this.mBufPos = len; + ProcessBlocks2(input, output[resultLen..]); + input = input[(BufSize * 2)..]; + resultLen += BufSize * 2; } + + if (input.Length >= BufSize) + { + ProcessBlock(input, output[resultLen..]); + input = input[BufSize..]; + resultLen += BufSize; + } + + mPoly1305.BlockUpdate(output[..resultLen]); + + mBufPos = input.Length; + input.CopyTo(mBuf); break; } default: @@ -332,6 +553,7 @@ public virtual int ProcessBytes(byte[] inBytes, int inOff, int len, byte[] outBy return resultLen; } +#endif public virtual int DoFinal(byte[] outBytes, int outOff) { @@ -340,6 +562,9 @@ public virtual int DoFinal(byte[] outBytes, int outOff) if (outOff < 0) throw new ArgumentException("cannot be negative", "outOff"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(outBytes.AsSpan(outOff)); +#else CheckData(); Array.Clear(mMac, 0, MacSize); @@ -366,9 +591,7 @@ public virtual int DoFinal(byte[] outBytes, int outOff) FinishData(State.DecFinal); if (!Arrays.ConstantTimeAreEqual(MacSize, mMac, 0, mBuf, resultLen)) - { throw new InvalidCipherTextException("mac check in ChaCha20Poly1305 failed"); - } break; } @@ -396,8 +619,69 @@ public virtual int DoFinal(byte[] outBytes, int outOff) Reset(false, true); return resultLen; +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int DoFinal(Span output) + { + CheckData(); + + Array.Clear(mMac, 0, MacSize); + + int resultLen = 0; + + switch (mState) + { + case State.DecData: + { + if (mBufPos < MacSize) + throw new InvalidCipherTextException("data too short"); + + resultLen = mBufPos - MacSize; + + Check.OutputLength(output, resultLen, "output buffer too short"); + + if (resultLen > 0) + { + mPoly1305.BlockUpdate(mBuf, 0, resultLen); + ProcessData(mBuf.AsSpan(0, resultLen), output); + } + + FinishData(State.DecFinal); + + if (!Arrays.ConstantTimeAreEqual(MacSize, mMac, 0, mBuf, resultLen)) + throw new InvalidCipherTextException("mac check in ChaCha20Poly1305 failed"); + + break; + } + case State.EncData: + { + resultLen = mBufPos + MacSize; + + Check.OutputLength(output, resultLen, "output buffer too short"); + + if (mBufPos > 0) + { + ProcessData(mBuf.AsSpan(0, mBufPos), output); + mPoly1305.BlockUpdate(output[..mBufPos]); + } + + FinishData(State.EncFinal); + + mMac.AsSpan(0, MacSize).CopyTo(output[mBufPos..]); + break; + } + default: + throw new InvalidOperationException(); + } + + Reset(false, true); + + return resultLen; + } +#endif + public virtual byte[] GetMac() { return Arrays.Clone(mMac); @@ -481,6 +765,18 @@ private ulong IncrementCount(ulong count, uint increment, ulong limit) private void InitMac() { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span firstBlock = stackalloc byte[64]; + try + { + mChacha20.ProcessBytes(firstBlock, firstBlock); + mPoly1305.Init(new KeyParameter(firstBlock[..32])); + } + finally + { + firstBlock.Fill(0x00); + } +#else byte[] firstBlock = new byte[64]; try { @@ -491,6 +787,7 @@ private void InitMac() { Array.Clear(firstBlock, 0, 64); } +#endif } private void PadMac(ulong count) @@ -502,6 +799,52 @@ private void PadMac(ulong count) } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void ProcessBlock(ReadOnlySpan input, Span output) + { + Check.OutputLength(output, 64, "output buffer too short"); + + mChacha20.ProcessBlock(input, output); + + this.mDataCount = IncrementCount(mDataCount, 64U, DataLimit); + } + + private void ProcessBlocks2(ReadOnlySpan input, Span output) + { + Check.OutputLength(output, 128, "output buffer too short"); + + mChacha20.ProcessBlocks2(input, output); + + this.mDataCount = IncrementCount(mDataCount, 128U, DataLimit); + } + + private void ProcessData(ReadOnlySpan input, Span output) + { + Check.OutputLength(output, input.Length, "output buffer too short"); + + mChacha20.ProcessBytes(input, output); + + this.mDataCount = IncrementCount(mDataCount, (uint)input.Length, DataLimit); + } +#else + private void ProcessBlock(byte[] inBytes, int inOff, byte[] outBytes, int outOff) + { + Check.OutputLength(outBytes, outOff, 64, "output buffer too short"); + + mChacha20.ProcessBlock(inBytes, inOff, outBytes, outOff); + + this.mDataCount = IncrementCount(mDataCount, 64U, DataLimit); + } + + private void ProcessBlocks2(byte[] inBytes, int inOff, byte[] outBytes, int outOff) + { + Check.OutputLength(outBytes, outOff, 128, "output buffer too short"); + + mChacha20.ProcessBlocks2(inBytes, inOff, outBytes, outOff); + + this.mDataCount = IncrementCount(mDataCount, 128U, DataLimit); + } + private void ProcessData(byte[] inBytes, int inOff, int inLen, byte[] outBytes, int outOff) { Check.OutputLength(outBytes, outOff, inLen, "output buffer too short"); @@ -510,6 +853,7 @@ private void ProcessData(byte[] inBytes, int inOff, int inLen, byte[] outBytes, this.mDataCount = IncrementCount(mDataCount, (uint)inLen, DataLimit); } +#endif private void Reset(bool clearMac, bool resetCipher) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/CtsBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/CtsBlockCipher.cs index 5008ae4..62ede1a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/CtsBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/CtsBlockCipher.cs @@ -3,9 +3,6 @@ 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 { /** @@ -17,21 +14,24 @@ public class CtsBlockCipher { private readonly int blockSize; + public CtsBlockCipher(IBlockCipher cipher) + : this(EcbBlockCipher.GetBlockCipherMode(cipher)) + { + } + /** * Create a buffered block cipher that uses Cipher Text Stealing * * @param cipher the underlying block cipher this buffering object wraps. */ - public CtsBlockCipher( - IBlockCipher cipher) + public CtsBlockCipher(IBlockCipherMode cipherMode) { - // TODO Should this test for acceptable ones instead? - if (cipher is OfbBlockCipher || cipher is CfbBlockCipher) + if (!(cipherMode is CbcBlockCipher || cipherMode is EcbBlockCipher)) throw new ArgumentException("CtsBlockCipher can only accept ECB, or CBC ciphers"); - this.cipher = cipher; + m_cipherMode = cipherMode; - blockSize = cipher.GetBlockSize(); + blockSize = cipherMode.GetBlockSize(); buf = new byte[blockSize * 2]; bufOff = 0; @@ -82,16 +82,13 @@ public override int GetOutputSize( * @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) + public override int ProcessByte(byte input, byte[] output, int outOff) { int resultLen = 0; if (bufOff == buf.Length) { - resultLen = cipher.ProcessBlock(buf, 0, output, outOff); + resultLen = m_cipherMode.ProcessBlock(buf, 0, output, outOff); Debug.Assert(resultLen == blockSize); Array.Copy(buf, blockSize, buf, 0, blockSize); @@ -103,7 +100,27 @@ public override int ProcessByte( return resultLen; } - /** +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int ProcessByte(byte input, Span output) + { + int resultLen = 0; + + if (bufOff == buf.Length) + { + resultLen = m_cipherMode.ProcessBlock(buf, output); + Debug.Assert(resultLen == blockSize); + + Array.Copy(buf, blockSize, buf, 0, blockSize); + bufOff = blockSize; + } + + buf[bufOff++] = input; + + return resultLen; + } +#endif + + /** * process an array of bytes, producing output if necessary. * * @param in the input byte array. @@ -115,27 +132,17 @@ public override int ProcessByte( * @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) + 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!"); - } + throw new ArgumentException("Can't have a negative input length!"); int blockSize = GetBlockSize(); int outLength = GetUpdateOutputSize(length); if (outLength > 0) { - if ((outOff + outLength) > output.Length) - { - throw new DataLengthException("output buffer too short"); - } + Check.OutputLength(output, outOff, outLength, "output buffer too short"); } int resultLen = 0; @@ -145,7 +152,7 @@ public override int ProcessBytes( { Array.Copy(input, inOff, buf, bufOff, gapLen); - resultLen += cipher.ProcessBlock(buf, 0, output, outOff); + resultLen = m_cipherMode.ProcessBlock(buf, 0, output, outOff); Array.Copy(buf, blockSize, buf, 0, blockSize); bufOff = blockSize; @@ -156,7 +163,7 @@ public override int ProcessBytes( while (length > blockSize) { Array.Copy(input, inOff, buf, bufOff, blockSize); - resultLen += cipher.ProcessBlock(buf, 0, output, outOff + resultLen); + resultLen += m_cipherMode.ProcessBlock(buf, 0, output, outOff + resultLen); Array.Copy(buf, blockSize, buf, 0, blockSize); length -= blockSize; @@ -171,6 +178,49 @@ public override int ProcessBytes( return resultLen; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int ProcessBytes(ReadOnlySpan input, Span output) + { + int blockSize = GetBlockSize(); + int outLength = GetUpdateOutputSize(input.Length); + + if (outLength > 0) + { + Check.OutputLength(output, outLength, "output buffer too short"); + } + + int resultLen = 0; + int gapLen = buf.Length - bufOff; + + if (input.Length > gapLen) + { + input[..gapLen].CopyTo(buf.AsSpan(bufOff)); + + resultLen = m_cipherMode.ProcessBlock(buf, output); + Array.Copy(buf, blockSize, buf, 0, blockSize); + + bufOff = blockSize; + + input = input[gapLen..]; + + while (input.Length > blockSize) + { + input[..blockSize].CopyTo(buf.AsSpan(bufOff)); + resultLen += m_cipherMode.ProcessBlock(buf, output[resultLen..]); + Array.Copy(buf, blockSize, buf, 0, blockSize); + + input = input[blockSize..]; + } + } + + input.CopyTo(buf.AsSpan(bufOff)); + + bufOff += input.Length; + + return resultLen; + } +#endif + /** * Process the last block in the buffer. * @@ -184,27 +234,21 @@ public override int ProcessBytes( * @exception InvalidCipherTextException if cipher text decrypts wrongly (in * case the exception will never Get thrown). */ - public override int DoFinal( - byte[] output, - int outOff) + public override int DoFinal(byte[] output, int outOff) { if (bufOff + outOff > output.Length) - { - throw new DataLengthException("output buffer too small in doFinal"); - } + throw new DataLengthException("output buffer too small in DoFinal"); - int blockSize = cipher.GetBlockSize(); + int blockSize = m_cipherMode.GetBlockSize(); int length = bufOff - blockSize; byte[] block = new byte[blockSize]; if (forEncryption) { - cipher.ProcessBlock(buf, 0, block, 0); + m_cipherMode.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++) { @@ -216,11 +260,7 @@ public override int DoFinal( buf[i] ^= block[i - blockSize]; } - IBlockCipher c = (cipher is CbcBlockCipher) - ? ((CbcBlockCipher)cipher).GetUnderlyingCipher() - : cipher; - - c.ProcessBlock(buf, blockSize, output, outOff); + m_cipherMode.UnderlyingCipher.ProcessBlock(buf, blockSize, output, outOff); Array.Copy(block, 0, output, outOff + blockSize, length); } @@ -228,11 +268,7 @@ public override int DoFinal( { byte[] lastBlock = new byte[blockSize]; - IBlockCipher c = (cipher is CbcBlockCipher) - ? ((CbcBlockCipher)cipher).GetUnderlyingCipher() - : cipher; - - c.ProcessBlock(buf, 0, block, 0); + m_cipherMode.UnderlyingCipher.ProcessBlock(buf, 0, block, 0); for (int i = blockSize; i != bufOff; i++) { @@ -241,7 +277,7 @@ public override int DoFinal( Array.Copy(buf, blockSize, block, 0, length); - cipher.ProcessBlock(block, 0, output, outOff); + m_cipherMode.ProcessBlock(block, 0, output, outOff); Array.Copy(lastBlock, 0, output, outOff + blockSize, length); } @@ -251,6 +287,66 @@ public override int DoFinal( return offset; } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + if (bufOff > output.Length) + throw new DataLengthException("output buffer too small in DoFinal"); + + int blockSize = m_cipherMode.GetBlockSize(); + int length = bufOff - blockSize; + Span block = blockSize <= 64 + ? stackalloc byte[blockSize] + : new byte[blockSize]; + + if (forEncryption) + { + m_cipherMode.ProcessBlock(buf, block); + + 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]; + } + + m_cipherMode.UnderlyingCipher.ProcessBlock(buf.AsSpan(blockSize), output); + + block[..length].CopyTo(output[blockSize..]); + } + else + { + Span lastBlock = blockSize <= 64 + ? stackalloc byte[blockSize] + : new byte[blockSize]; + + m_cipherMode.UnderlyingCipher.ProcessBlock(buf, block); + + for (int i = blockSize; i != bufOff; i++) + { + lastBlock[i - blockSize] = (byte)(block[i - blockSize] ^ buf[i]); + } + + buf.AsSpan(blockSize, length).CopyTo(block); + + m_cipherMode.ProcessBlock(block, output); + lastBlock[..length].CopyTo(output[blockSize..]); + } + + int offset = bufOff; + + Reset(); + + return offset; + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/EAXBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/EAXBlockCipher.cs index 966b4cb..a8dbd51 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/EAXBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/EAXBlockCipher.cs @@ -61,47 +61,35 @@ public EaxBlockCipher( this.cipher = new SicBlockCipher(cipher); } - public virtual string AlgorithmName - { - get { return cipher.GetUnderlyingCipher().AlgorithmName + "/EAX"; } - } + public virtual string AlgorithmName => cipher.UnderlyingCipher.AlgorithmName + "/EAX"; - public virtual IBlockCipher GetUnderlyingCipher() - { - return cipher; - } + public virtual IBlockCipher UnderlyingCipher => cipher; public virtual int GetBlockSize() { return cipher.GetBlockSize(); } - public virtual void Init( - bool forEncryption, - ICipherParameters parameters) + public virtual void Init(bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; byte[] nonce; ICipherParameters keyParam; - if (parameters is AeadParameters) + if (parameters is AeadParameters aeadParameters) { - AeadParameters param = (AeadParameters) parameters; - - nonce = param.GetNonce(); - initialAssociatedText = param.GetAssociatedText(); - macSize = param.MacSize / 8; - keyParam = param.Key; + nonce = aeadParameters.GetNonce(); + initialAssociatedText = aeadParameters.GetAssociatedText(); + macSize = aeadParameters.MacSize / 8; + keyParam = aeadParameters.Key; } - else if (parameters is ParametersWithIV) + else if (parameters is ParametersWithIV parametersWithIV) { - ParametersWithIV param = (ParametersWithIV) parameters; - - nonce = param.GetIV(); + nonce = parametersWithIV.GetIV(); initialAssociatedText = null; macSize = mac.GetMacSize() / 2; - keyParam = param.Parameters; + keyParam = parametersWithIV.Parameters; } else { @@ -196,31 +184,48 @@ public virtual void ProcessAadByte(byte 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) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void ProcessAadBytes(ReadOnlySpan input) { - InitCipher(); + if (cipherInitialized) + throw new InvalidOperationException("AAD data cannot be added after encryption/decryption processing has begun."); - return Process(input, outBytes, outOff); + mac.BlockUpdate(input); } +#endif - public virtual int ProcessBytes( - byte[] inBytes, - int inOff, - int len, - byte[] outBytes, - int outOff) + public virtual int ProcessByte(byte input, byte[] outBytes, int outOff) { InitCipher(); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return Process(input, Spans.FromNullable(outBytes, outOff)); +#else + return Process(input, outBytes, outOff); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessByte(byte input, Span output) + { + InitCipher(); + + return Process(input, output); + } +#endif + + public virtual int ProcessBytes(byte[] inBytes, int inOff, int len, byte[] outBytes, int outOff) + { + InitCipher(); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ProcessBytes(inBytes.AsSpan(inOff, len), Spans.FromNullable(outBytes, outOff)); +#else int resultLen = 0; for (int i = 0; i != len; i++) @@ -229,14 +234,33 @@ public virtual int ProcessBytes( } return resultLen; +#endif } - public virtual int DoFinal( - byte[] outBytes, - int outOff) - { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBytes(ReadOnlySpan input, Span output) + { InitCipher(); + int len = input.Length; + int resultLen = 0; + + for (int i = 0; i != len; i++) + { + resultLen += Process(input[i], output[resultLen..]); + } + + return resultLen; + } +#endif + + public virtual int DoFinal(byte[] outBytes, int outOff) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(outBytes.AsSpan(outOff)); +#else + InitCipher(); + int extra = bufOff; byte[] tmp = new byte[bufBlock.Length]; @@ -244,7 +268,7 @@ public virtual int DoFinal( if (forEncryption) { - Check.OutputLength(outBytes, outOff, extra + macSize, "Output buffer too short"); + Check.OutputLength(outBytes, outOff, extra + macSize, "output buffer too short"); cipher.ProcessBlock(bufBlock, 0, tmp, 0); @@ -265,7 +289,7 @@ public virtual int DoFinal( if (extra < macSize) throw new InvalidCipherTextException("data too short"); - Check.OutputLength(outBytes, outOff, extra - macSize, "Output buffer too short"); + Check.OutputLength(outBytes, outOff, extra - macSize, "output buffer too short"); if (extra > macSize) { @@ -285,9 +309,70 @@ public virtual int DoFinal( return extra - macSize; } +#endif } - public virtual byte[] GetMac() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int DoFinal(Span output) + { + InitCipher(); + + int extra = bufOff; + int tmpLength = bufBlock.Length; + + Span tmp = tmpLength <= 128 + ? stackalloc byte[tmpLength] + : new byte[tmpLength]; + + bufOff = 0; + + if (forEncryption) + { + Check.OutputLength(output, extra + macSize, "output buffer too short"); + + cipher.ProcessBlock(bufBlock, tmp); + + tmp[..extra].CopyTo(output); + + mac.BlockUpdate(tmp[..extra]); + + CalculateMac(); + + macBlock.AsSpan(0, macSize).CopyTo(output[extra..]); + + Reset(false); + + return extra + macSize; + } + else + { + if (extra < macSize) + throw new InvalidCipherTextException("data too short"); + + Check.OutputLength(output, extra - macSize, "output buffer too short"); + + if (extra > macSize) + { + mac.BlockUpdate(bufBlock.AsSpan(0, extra - macSize)); + + cipher.ProcessBlock(bufBlock, tmp); + + tmp[..(extra - macSize)].CopyTo(output); + } + + CalculateMac(); + + if (!VerifyMac(bufBlock, extra - macSize)) + throw new InvalidCipherTextException("mac check in EAX failed"); + + Reset(false); + + return extra - macSize; + } + } +#endif + + public virtual byte[] GetMac() { byte[] mac = new byte[macSize]; @@ -324,12 +409,49 @@ public virtual int GetOutputSize( return totalData < macSize ? 0 : totalData - macSize; } - private int Process( - byte b, - byte[] outBytes, - int outOff) - { - bufBlock[bufOff++] = b; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int Process(byte b, Span output) + { + bufBlock[bufOff++] = b; + + if (bufOff == bufBlock.Length) + { + Check.OutputLength(output, blockSize, "output buffer too short"); + + // TODO Could move the ProcessByte(s) calls to here + //InitCipher(); + + int size; + + if (forEncryption) + { + size = cipher.ProcessBlock(bufBlock, output); + + mac.BlockUpdate(output[..blockSize]); + } + else + { + mac.BlockUpdate(bufBlock.AsSpan(0, blockSize)); + + size = cipher.ProcessBlock(bufBlock, output); + } + + bufOff = 0; + if (!forEncryption) + { + Array.Copy(bufBlock, blockSize, bufBlock, 0, macSize); + bufOff = macSize; + } + + return size; + } + + return 0; + } +#else + private int Process(byte b, byte[] outBytes, int outOff) + { + bufBlock[bufOff++] = b; if (bufOff == bufBlock.Length) { @@ -365,8 +487,9 @@ private int Process( return 0; } +#endif - private bool VerifyMac(byte[] mac, int off) + private bool VerifyMac(byte[] mac, int off) { int nonEqual = 0; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/EcbBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/EcbBlockCipher.cs new file mode 100644 index 0000000..467f82e --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/EcbBlockCipher.cs @@ -0,0 +1,62 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes +{ + public class EcbBlockCipher + : IBlockCipherMode + { + internal static IBlockCipherMode GetBlockCipherMode(IBlockCipher blockCipher) + { + if (blockCipher is IBlockCipherMode blockCipherMode) + return blockCipherMode; + + return new EcbBlockCipher(blockCipher); + } + + private readonly IBlockCipher m_cipher; + + public EcbBlockCipher(IBlockCipher cipher) + { + if (cipher == null) + throw new ArgumentNullException(nameof(cipher)); + + m_cipher = cipher; + } + + public bool IsPartialBlockOkay => false; + + public string AlgorithmName => m_cipher.AlgorithmName + "/ECB"; + + public int GetBlockSize() + { + return m_cipher.GetBlockSize(); + } + + public IBlockCipher UnderlyingCipher => m_cipher; + + public void Init(bool forEncryption, ICipherParameters parameters) + { + m_cipher.Init(forEncryption, parameters); + } + + public int ProcessBlock(byte[] inBuf, int inOff, byte[] outBuf, int outOff) + { + return m_cipher.ProcessBlock(inBuf, inOff, outBuf, outOff); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessBlock(ReadOnlySpan input, Span output) + { + return m_cipher.ProcessBlock(input, output); + } +#endif + + public void Reset() + { + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/EcbBlockCipher.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/EcbBlockCipher.cs.meta new file mode 100644 index 0000000..ca8303a --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/EcbBlockCipher.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fa9cffbd193364f42914635a318885f7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/GCMBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/GCMBlockCipher.cs index 05678ec..2fca67f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/GCMBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/GCMBlockCipher.cs @@ -1,9 +1,15 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ +using System.Runtime.CompilerServices; +#endif +#if NETCOREAPP3_0_OR_GREATER +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +#endif -using BestHTTP.PlatformSupport.Memory; -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; @@ -12,20 +18,29 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes { /// - /// Implements the Galois/Counter mode (GCM) detailed in - /// NIST Special Publication 800-38D. + /// Implements the Galois/Counter mode (GCM) detailed in NIST Special Publication 800-38D. /// - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] public sealed class GcmBlockCipher : IAeadBlockCipher { + private static IGcmMultiplier CreateGcmMultiplier() + { +#if NETCOREAPP3_0_OR_GREATER + // TODO Prefer more tightly coupled test + if (Pclmulqdq.IsSupported) + { + return new BasicGcmMultiplier(); + } +#endif + + return new Tables4kGcmMultiplier(); + } + 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 @@ -39,11 +54,11 @@ public sealed class GcmBlockCipher private byte[] J0; // These fields are modified during processing - private int bufLength; private byte[] bufBlock; private byte[] macBlock; private byte[] S, S_at, S_atPre; private byte[] counter; + private uint counter32; private uint blocksRemaining; private int bufOff; private ulong totalLength; @@ -65,22 +80,20 @@ public GcmBlockCipher( if (c.GetBlockSize() != BlockSize) throw new ArgumentException("cipher required with a block size of " + BlockSize + "."); - if (m != null) - throw new NotImplementedException("IGcmMultiplier"); + if (m == null) + { + m = CreateGcmMultiplier(); + } + this.cipher = c; + this.multiplier = m; } - public /*virtual*/ string AlgorithmName - { - get { return cipher.AlgorithmName + "/GCM"; } - } + public string AlgorithmName => cipher.AlgorithmName + "/GCM"; - public IBlockCipher GetUnderlyingCipher() - { - return cipher; - } + public IBlockCipher UnderlyingCipher => cipher; - public /*virtual*/ int GetBlockSize() + public int GetBlockSize() { return BlockSize; } @@ -89,18 +102,14 @@ public IBlockCipher GetUnderlyingCipher() /// 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) + public void Init(bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; - //this.macBlock = null; - if (this.macBlock != null) - Array.Clear(this.macBlock, 0, this.macBlock.Length); + this.macBlock = null; this.initialised = true; KeyParameter keyParam; - byte[] newNonce = null; + byte[] newNonce; if (parameters is AeadParameters) { @@ -132,9 +141,8 @@ public IBlockCipher GetUnderlyingCipher() throw new ArgumentException("invalid parameters passed to GCM"); } - this.bufLength = forEncryption ? BlockSize : (BlockSize + macSize); - if (this.bufBlock == null || this.bufLength < this.bufBlock.Length) - BufferPool.Resize(ref this.bufBlock, this.bufLength, true, true); + int bufLength = forEncryption ? BlockSize : (BlockSize + macSize); + this.bufBlock = new byte[bufLength]; if (newNonce == null || newNonce.Length < 1) { @@ -170,14 +178,11 @@ public IBlockCipher GetUnderlyingCipher() { cipher.Init(true, keyParam); - if (this.H == null) - this.H = new byte[BlockSize]; - else - Array.Clear(this.H, 0, BlockSize); + 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 - Tables8kGcmMultiplier_Init(H); + multiplier.Init(H); exp = null; } else if (this.H == null) @@ -185,10 +190,7 @@ public IBlockCipher GetUnderlyingCipher() throw new ArgumentException("Key must be specified in initial init"); } - if (this.J0 == null) - this.J0 = new byte[BlockSize]; - else - Array.Clear(this.J0, 0, BlockSize); + this.J0 = new byte[BlockSize]; if (nonce.Length == 12) { @@ -198,49 +200,20 @@ public IBlockCipher GetUnderlyingCipher() else { gHASH(J0, nonce, nonce.Length); - byte[] X = BufferPool.Get(BlockSize, false); + byte[] X = new byte[BlockSize]; Pack.UInt64_To_BE((ulong)nonce.Length * 8UL, X, 8); gHASHBlock(J0, X); - BufferPool.Release(X); } - //BufferPool.Resize(ref this.S, BlockSize, false, true); - //BufferPool.Resize(ref this.S_at, BlockSize, false, true); - //BufferPool.Resize(ref this.S_atPre, BlockSize, false, true); - //BufferPool.Resize(ref this.atBlock, BlockSize, false, true); - if (this.S == null) - this.S = new byte[BlockSize]; - else - Array.Clear(this.S, 0, this.S.Length); - - if (this.S_at == null) - this.S_at = new byte[BlockSize]; - else - Array.Clear(this.S_at, 0, this.S_at.Length); - - if (this.S_atPre == null) - this.S_atPre = new byte[BlockSize]; - else - Array.Clear(this.S_atPre, 0, this.S_atPre.Length); - - if (this.atBlock == null) - this.atBlock = new byte[BlockSize]; - else - Array.Clear(this.atBlock, 0, this.atBlock.Length); - + 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); - //BufferPool.Resize(ref this.counter, BlockSize, false, true); - if (this.counter == null) - this.counter = new byte[BlockSize]; - else - Array.Clear(this.counter, 0, this.counter.Length); - - Array.Copy(this.J0, 0, this.counter, 0, BlockSize); - + this.counter = Arrays.Clone(J0); + this.counter32 = Pack.BE_To_UInt32(counter, 12); this.blocksRemaining = uint.MaxValue - 1; // page 8, len(P) <= 2^39 - 256, 1 block used by tag this.bufOff = 0; this.totalLength = 0; @@ -251,15 +224,14 @@ public IBlockCipher GetUnderlyingCipher() } } - public /*virtual*/ byte[] GetMac() + public byte[] GetMac() { return macBlock == null ? new byte[macSize] : Arrays.Clone(macBlock); } - public /*virtual*/ int GetOutputSize( - int len) + public int GetOutputSize(int len) { int totalData = len + bufOff; @@ -271,8 +243,7 @@ public IBlockCipher GetUnderlyingCipher() return totalData < macSize ? 0 : totalData - macSize; } - public /*virtual*/ int GetUpdateOutputSize( - int len) + public int GetUpdateOutputSize(int len) { int totalData = len + bufOff; if (!forEncryption) @@ -286,7 +257,7 @@ public IBlockCipher GetUnderlyingCipher() return totalData - totalData % BlockSize; } - public /*virtual*/ void ProcessAadByte(byte input) + public void ProcessAadByte(byte input) { CheckStatus(); @@ -300,22 +271,78 @@ public IBlockCipher GetUnderlyingCipher() } } - public /*virtual*/ void ProcessAadBytes(byte[] inBytes, int inOff, int len) + public void ProcessAadBytes(byte[] inBytes, int inOff, int len) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ProcessAadBytes(inBytes.AsSpan(inOff, len)); +#else + CheckStatus(); + + if (atBlockPos > 0) + { + int available = BlockSize - atBlockPos; + if (len < available) + { + Array.Copy(inBytes, inOff, atBlock, atBlockPos, len); + atBlockPos += len; + return; + } + + Array.Copy(inBytes, inOff, atBlock, atBlockPos, available); + gHASHBlock(S_at, atBlock); + atLength += BlockSize; + inOff += available; + len -= available; + //atBlockPos = 0; + } + + int inLimit = inOff + len - BlockSize; + + while (inOff <= inLimit) + { + gHASHBlock(S_at, inBytes, inOff); + atLength += BlockSize; + inOff += BlockSize; + } + + atBlockPos = BlockSize + inLimit - inOff; + Array.Copy(inBytes, inOff, atBlock, 0, atBlockPos); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void ProcessAadBytes(ReadOnlySpan input) { CheckStatus(); - for (int i = 0; i < len; ++i) + if (atBlockPos > 0) { - atBlock[atBlockPos] = inBytes[inOff + i]; - if (++atBlockPos == BlockSize) + int available = BlockSize - atBlockPos; + if (input.Length < available) { - // Hash each block as it fills - gHASHBlock(S_at, atBlock); - atBlockPos = 0; - atLength += BlockSize; + input.CopyTo(atBlock.AsSpan(atBlockPos)); + atBlockPos += input.Length; + return; } + + input[..available].CopyTo(atBlock.AsSpan(atBlockPos)); + gHASHBlock(S_at, atBlock); + atLength += BlockSize; + input = input[available..]; + //atBlockPos = 0; + } + + while (input.Length >= BlockSize) + { + gHASHBlock(S_at, input); + atLength += BlockSize; + input = input[BlockSize..]; } + + input.CopyTo(atBlock); + atBlockPos = input.Length; } +#endif private void InitCipher() { @@ -338,23 +365,29 @@ private void InitCipher() } } - public /*virtual*/ int ProcessByte( - byte input, - byte[] output, - int outOff) + public int ProcessByte(byte input, byte[] output, int outOff) { CheckStatus(); bufBlock[bufOff] = input; - if (++bufOff == bufLength) + if (++bufOff == bufBlock.Length) { - ProcessBlock(bufBlock, 0, output, outOff); if (forEncryption) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + EncryptBlock(bufBlock, output.AsSpan(outOff)); +#else + EncryptBlock(bufBlock, 0, output, outOff); +#endif bufOff = 0; } else { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + DecryptBlock(bufBlock, output.AsSpan(outOff)); +#else + DecryptBlock(bufBlock, 0, output, outOff); +#endif Array.Copy(bufBlock, BlockSize, bufBlock, 0, macSize); bufOff = macSize; } @@ -363,251 +396,355 @@ private void InitCipher() return 0; } - public unsafe /*virtual*/ int ProcessBytes( - byte[] input, - int inOff, - int len, - byte[] output, - int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessByte(byte input, Span output) + { + CheckStatus(); + + bufBlock[bufOff] = input; + if (++bufOff == bufBlock.Length) + { + if (forEncryption) + { + EncryptBlock(bufBlock, output); + bufOff = 0; + } + else + { + DecryptBlock(bufBlock, output); + Array.Copy(bufBlock, BlockSize, bufBlock, 0, macSize); + bufOff = macSize; + } + return BlockSize; + } + return 0; + } +#endif + + public int ProcessBytes(byte[] input, int inOff, int len, byte[] output, int outOff) { CheckStatus(); Check.DataLength(input, inOff, len, "input buffer too short"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ProcessBytes(input.AsSpan(inOff, len), Spans.FromNullable(output, outOff)); +#else int resultLen = 0; if (forEncryption) { - if (bufOff != 0) + if (bufOff > 0) { - while (len > 0) + int available = BlockSize - bufOff; + if (len < available) { - --len; - bufBlock[bufOff] = input[inOff++]; - if (++bufOff == BlockSize) - { - ProcessBlock(bufBlock, 0, output, outOff); - bufOff = 0; - resultLen += BlockSize; - break; - } + Array.Copy(input, inOff, bufBlock, bufOff, len); + bufOff += len; + return 0; } + + Array.Copy(input, inOff, bufBlock, bufOff, available); + EncryptBlock(bufBlock, 0, output, outOff); + inOff += available; + len -= available; + resultLen = BlockSize; + //bufOff = 0; } - fixed (byte* pctrBlock = ctrBlock, pbuf = input, pS = S, poutput = output) + int inLimit1 = inOff + len - BlockSize; + int inLimit2 = inLimit1 - BlockSize; + + while (inOff <= inLimit2) { - while (len >= BlockSize) - { - // ProcessBlock(byte[] buf, int bufOff, byte[] output, int outOff) - #region ProcessBlock(buf: input, bufOff: inOff, output: output, outOff: outOff + resultLen); + EncryptBlocks2(input, inOff, output, outOff + resultLen); + inOff += BlockSize * 2; + resultLen += BlockSize * 2; + } - if (totalLength == 0) - InitCipher(); + if (inOff <= inLimit1) + { + EncryptBlock(input, inOff, output, outOff + resultLen); + inOff += BlockSize; + resultLen += BlockSize; + } - #region GetNextCtrBlock(ctrBlock); - blocksRemaining--; + bufOff = BlockSize + inLimit1 - inOff; + Array.Copy(input, inOff, bufBlock, 0, bufOff); + } + else + { + int available = bufBlock.Length - bufOff; + if (len < available) + { + Array.Copy(input, inOff, bufBlock, bufOff, len); + bufOff += len; + return 0; + } - 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; + if (bufOff >= BlockSize) + { + DecryptBlock(bufBlock, 0, output, outOff); + Array.Copy(bufBlock, BlockSize, bufBlock, 0, bufOff -= BlockSize); + resultLen = BlockSize; - cipher.ProcessBlock(counter, 0, ctrBlock, 0); - #endregion + available += BlockSize; + if (len < available) + { + Array.Copy(input, inOff, bufBlock, bufOff, len); + bufOff += len; + return resultLen; + } + } + + int inLimit1 = inOff + len - bufBlock.Length; + int inLimit2 = inLimit1 - BlockSize; + + available = BlockSize - bufOff; + Array.Copy(input, inOff, bufBlock, bufOff, available); + DecryptBlock(bufBlock, 0, output, outOff + resultLen); + inOff += available; + resultLen += BlockSize; + //bufOff = 0; - ulong* pulongBuf = (ulong*)&pbuf[inOff]; - ulong* pulongctrBlock = (ulong*)pctrBlock; - pulongctrBlock[0] ^= pulongBuf[0]; - pulongctrBlock[1] ^= pulongBuf[1]; + while (inOff <= inLimit2) + { + DecryptBlocks2(input, inOff, output, outOff + resultLen); + inOff += BlockSize * 2; + resultLen += BlockSize * 2; + } - ulong* pulongS = (ulong*)pS; - pulongS[0] ^= pulongctrBlock[0]; - pulongS[1] ^= pulongctrBlock[1]; + if (inOff <= inLimit1) + { + DecryptBlock(input, inOff, output, outOff + resultLen); + inOff += BlockSize; + resultLen += BlockSize; + } - Tables8kGcmMultiplier_MultiplyH(S); + bufOff = bufBlock.Length + inLimit1 - inOff; + Array.Copy(input, inOff, bufBlock, 0, bufOff); + } - ulong* pulongoutput = (ulong*)&poutput[outOff + resultLen]; - pulongoutput[0] = pulongctrBlock[0]; - pulongoutput[1] = pulongctrBlock[1]; + return resultLen; +#endif + } - totalLength += BlockSize; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessBytes(ReadOnlySpan input, Span output) + { + CheckStatus(); - #endregion + int resultLen = 0; - inOff += BlockSize; - len -= BlockSize; - resultLen += BlockSize; + if (forEncryption) + { + if (bufOff > 0) + { + int available = BlockSize - bufOff; + if (input.Length < available) + { + input.CopyTo(bufBlock.AsSpan(bufOff)); + bufOff += input.Length; + return 0; } + + input[..available].CopyTo(bufBlock.AsSpan(bufOff)); + EncryptBlock(bufBlock, output); + input = input[available..]; + resultLen = BlockSize; + //bufOff = 0; } - if (len > 0) + while (input.Length >= BlockSize * 2) { - Array.Copy(input, inOff, bufBlock, 0, len); - bufOff = len; + EncryptBlocks2(input, output[resultLen..]); + input = input[(BlockSize * 2)..]; + resultLen += BlockSize * 2; } + + if (input.Length >= BlockSize) + { + EncryptBlock(input, output[resultLen..]); + input = input[BlockSize..]; + resultLen += BlockSize; + } + + bufOff = input.Length; + input.CopyTo(bufBlock); } else { - fixed (byte* pinput = input, pbufBlock = bufBlock, pctrBlock = ctrBlock, pS = S, poutput = output) + int available = bufBlock.Length - bufOff; + if (input.Length < available) { - ulong* pulongbufBlock = (ulong*)pbufBlock; + input.CopyTo(bufBlock.AsSpan(bufOff)); + bufOff += input.Length; + return 0; + } + + if (bufOff >= BlockSize) + { + DecryptBlock(bufBlock, output); + Array.Copy(bufBlock, BlockSize, bufBlock, 0, bufOff -= BlockSize); + resultLen = BlockSize; - // adjust bufOff to be on a 8 byte boundary - int adjustCount = 0; - for (int i = 0; i < len && (bufOff % 8) != 0; ++i) + available += BlockSize; + if (input.Length < available) { - pbufBlock[bufOff++] = pinput[inOff++ + i]; - adjustCount++; + input.CopyTo(bufBlock.AsSpan(bufOff)); + bufOff += input.Length; + return resultLen; + } + } - if (bufOff == bufLength) - { - ProcessBlock(bufBlock, 0, output, outOff + resultLen); + int inLimit1 = bufBlock.Length; + int inLimit2 = inLimit1 + BlockSize; - pulongbufBlock[0] = pulongbufBlock[2]; - pulongbufBlock[1] = pulongbufBlock[3]; + available = BlockSize - bufOff; + input[..available].CopyTo(bufBlock.AsSpan(bufOff)); + DecryptBlock(bufBlock, output[resultLen..]); + input = input[available..]; + resultLen += BlockSize; + //bufOff = 0; - bufOff = macSize; - resultLen += BlockSize; - } - } - - int longLen = (len - adjustCount) / 8; - if (longLen > 0) - { - ulong* pulonginput = (ulong*)&pinput[inOff]; - - int bufLongOff = bufOff / 8; - - // copy 8 bytes per cycle instead of just 1 - for (int i = 0; i < longLen; ++i) - { - pulongbufBlock[bufLongOff++] = pulonginput[i]; - bufOff += 8; - - if (bufOff == bufLength) - { - #region ProcessBlock(buf: bufBlock, bufOff: 0, output: output, outOff: outOff + resultLen); - if (totalLength == 0) - InitCipher(); - - #region GetNextCtrBlock(ctrBlock); - 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, ctrBlock, 0); - #endregion - - ulong* pulongS = (ulong*)pS; - - pulongS[0] ^= pulongbufBlock[0]; - pulongS[1] ^= pulongbufBlock[1]; - - Tables8kGcmMultiplier_MultiplyH(S); - - ulong* pulongOutput = (ulong*)&poutput[outOff + resultLen]; - ulong* pulongctrBlock = (ulong*)pctrBlock; - - pulongOutput[0] = pulongctrBlock[0] ^ pulongbufBlock[0]; - pulongOutput[1] = pulongctrBlock[1] ^ pulongbufBlock[1]; - - totalLength += BlockSize; - - #endregion - - pulongbufBlock[0] = pulongbufBlock[2]; - pulongbufBlock[1] = pulongbufBlock[3]; - - bufOff = macSize; - resultLen += BlockSize; - - bufLongOff = bufOff / 8; - } - } - } + while (input.Length >= inLimit2) + { + DecryptBlocks2(input, output[resultLen..]); + input = input[(BlockSize * 2)..]; + resultLen += BlockSize * 2; + } - for (int i = longLen * 8; i < len; i++) - { - pbufBlock[bufOff++] = pinput[inOff + i]; - - if (bufOff == bufLength) - { - ProcessBlock(bufBlock, 0, output, outOff + resultLen); - - pulongbufBlock[0] = pulongbufBlock[2]; - pulongbufBlock[1] = pulongbufBlock[3]; - - bufOff = macSize; - resultLen += BlockSize; - } - } + if (input.Length >= inLimit1) + { + DecryptBlock(input, output[resultLen..]); + input = input[BlockSize..]; + resultLen += BlockSize; } + + bufOff = input.Length; + input.CopyTo(bufBlock); } return resultLen; } +#endif - private unsafe void ProcessBlock(byte[] buf, int bufOff, byte[] output, int outOff) + public int DoFinal(byte[] output, int outOff) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(output.AsSpan(outOff)); +#else + CheckStatus(); + if (totalLength == 0) + { InitCipher(); + } - GetNextCtrBlock(ctrBlock); + int extra = bufOff; if (forEncryption) { - fixed (byte* pctrBlock = ctrBlock, pbuf = buf, pS = S) - { - - ulong* pulongBuf = (ulong*)&pbuf[bufOff]; - ulong* pulongctrBlock = (ulong*)pctrBlock; - pulongctrBlock[0] ^= pulongBuf[0]; - pulongctrBlock[1] ^= pulongBuf[1]; + Check.OutputLength(output, outOff, extra + macSize, "output buffer too short"); + } + else + { + if (extra < macSize) + throw new InvalidCipherTextException("data too short"); - ulong* pulongS = (ulong*)pS; - pulongS[0] ^= pulongctrBlock[0]; - pulongS[1] ^= pulongctrBlock[1]; + extra -= macSize; - Tables8kGcmMultiplier_MultiplyH(S); + Check.OutputLength(output, outOff, extra, "output buffer too short"); + } - fixed (byte* poutput = output) - { - ulong* pulongoutput = (ulong*)&poutput[outOff]; - pulongoutput[0] = pulongctrBlock[0]; - pulongoutput[1] = pulongctrBlock[1]; - } - } + if (extra > 0) + { + ProcessPartial(bufBlock, 0, extra, output, outOff); } - else + + atLength += (uint)atBlockPos; + + if (atLength > atLengthPre) { - // moved this part to ProcessBytes's main part - fixed (byte* pctrBlock = ctrBlock, pbuf = buf, pS = S, poutput = output) + /* + * 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) { - ulong* pulongS = (ulong*)pS; - ulong* pulongBuf = (ulong*)&pbuf[bufOff]; + gHASHPartial(S_at, atBlock, 0, atBlockPos); + } - pulongS[0] ^= pulongBuf[0]; - pulongS[1] ^= pulongBuf[1]; + // Find the difference between the AAD hashes + if (atLengthPre > 0) + { + GcmUtilities.Xor(S_at, S_atPre); + } - Tables8kGcmMultiplier_MultiplyH(S); + // Number of cipher-text blocks produced + long c = (long)(((totalLength * 8) + 127) >> 7); - ulong* pulongOutput = (ulong*)&poutput[outOff]; - ulong* pulongctrBlock = (ulong*)pctrBlock; - - pulongOutput[0] = pulongctrBlock[0] ^ pulongBuf[0]; - pulongOutput[1] = pulongctrBlock[1] ^ pulongBuf[1]; + // Calculate the adjustment factor + byte[] H_c = new byte[16]; + if (exp == null) + { + exp = new BasicGcmExponentiator(); + 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); } - totalLength += BlockSize; + // 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; +#endif } - public int DoFinal(byte[] output, int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int DoFinal(Span output) { CheckStatus(); @@ -620,7 +757,7 @@ public int DoFinal(byte[] output, int outOff) if (forEncryption) { - Check.OutputLength(output, outOff, extra + macSize, "Output buffer too short"); + Check.OutputLength(output, extra + macSize, "output buffer too short"); } else { @@ -629,12 +766,12 @@ public int DoFinal(byte[] output, int outOff) extra -= macSize; - Check.OutputLength(output, outOff, extra, "Output buffer too short"); + Check.OutputLength(output, extra, "output buffer too short"); } if (extra > 0) { - ProcessPartial(bufBlock, 0, extra, output, outOff); + ProcessPartial(bufBlock.AsSpan(0, extra), output); } atLength += (uint)atBlockPos; @@ -664,10 +801,10 @@ public int DoFinal(byte[] output, int outOff) long c = (long)(((totalLength * 8) + 127) >> 7); // Calculate the adjustment factor - byte[] H_c = BufferPool.Get(16, true); + byte[] H_c = new byte[16]; if (exp == null) { - exp = new Tables1kGcmExponentiator(); + exp = new BasicGcmExponentiator(); exp.Init(H); } exp.ExponentiateX(c, H_c); @@ -677,100 +814,77 @@ public int DoFinal(byte[] output, int outOff) // Adjust the current hash GcmUtilities.Xor(S, S_at); - - BufferPool.Release(H_c); } // Final gHASH - byte[] X = BufferPool.Get(BlockSize, false); - Pack.UInt64_To_BE(atLength * 8UL, X, 0); - Pack.UInt64_To_BE(totalLength * 8UL, X, 8); + Span X = stackalloc byte[BlockSize]; + Pack.UInt64_To_BE(atLength * 8UL, X); + Pack.UInt64_To_BE(totalLength * 8UL, X[8..]); gHASHBlock(S, X); - BufferPool.Release(X); - // T = MSBt(GCTRk(J0,S)) - byte[] tag = BufferPool.Get(BlockSize, false); - cipher.ProcessBlock(J0, 0, tag, 0); + Span tag = stackalloc byte[BlockSize]; + cipher.ProcessBlock(J0, tag); GcmUtilities.Xor(tag, S); int resultLen = extra; // We place into macBlock our calculated value for T - - if (this.macBlock == null || this.macBlock.Length < macSize) - this.macBlock = BufferPool.Resize(ref this.macBlock, macSize, false, false); - - Array.Copy(tag, 0, macBlock, 0, macSize); - - BufferPool.Release(tag); + this.macBlock = new byte[macSize]; + tag[..macSize].CopyTo(macBlock); if (forEncryption) { // Append T to the message - Array.Copy(macBlock, 0, output, outOff + bufOff, macSize); + macBlock.CopyTo(output[bufOff..]); resultLen += macSize; } else { // Retrieve the T value from the message and compare to calculated one - byte[] msgMac = BufferPool.Get(macSize, false); - Array.Copy(bufBlock, extra, msgMac, 0, macSize); + Span msgMac = stackalloc byte[macSize]; + bufBlock.AsSpan(extra, macSize).CopyTo(msgMac); if (!Arrays.ConstantTimeAreEqual(this.macBlock, msgMac)) throw new InvalidCipherTextException("mac check in GCM failed"); - BufferPool.Release(msgMac); } Reset(false); return resultLen; } +#endif - public /*virtual*/ void Reset() + public void Reset() { Reset(true); } - private unsafe void Reset( - bool clearMac) + private void Reset(bool clearMac) { - cipher.Reset(); - // note: we do not reset the nonce. - //BufferPool.Resize(ref this.S, BlockSize, false, true); - //BufferPool.Resize(ref this.S_at, BlockSize, false, true); - //BufferPool.Resize(ref this.S_atPre, BlockSize, false, true); - //BufferPool.Resize(ref this.atBlock, BlockSize, false, true); - fixed (byte* pS = S, pS_at = S_at, pS_atPre = S_atPre, patBlock = atBlock) - { - for (int i = 0; i < BlockSize; ++i) - { - pS[i] = pS_at[i] = pS_atPre[i] = patBlock[i] = 0; - } - } - + S = new byte[BlockSize]; + S_at = new byte[BlockSize]; + S_atPre = new byte[BlockSize]; + atBlock = new byte[BlockSize]; atBlockPos = 0; atLength = 0; atLengthPre = 0; - - //BufferPool.Resize(ref this.counter, BlockSize, false, false); - Array.Copy(this.J0, 0, this.counter, 0, BlockSize); - + counter = Arrays.Clone(J0); + counter32 = Pack.BE_To_UInt32(counter, 12); blocksRemaining = uint.MaxValue - 1; bufOff = 0; totalLength = 0; if (bufBlock != null) { - //Arrays.Fill(bufBlock, 0); + Arrays.Fill(bufBlock, 0); } if (clearMac) { - //macBlock = null; - Array.Clear(this.macBlock, 0, this.macSize); + macBlock = null; } if (forEncryption) @@ -786,207 +900,605 @@ private unsafe void Reset( } } - private void ProcessPartial(byte[] buf, int off, int len, byte[] output, int outOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void DecryptBlock(ReadOnlySpan input, Span output) { - //byte[] ctrBlock = new byte[BlockSize]; - GetNextCtrBlock(ctrBlock); + Check.OutputLength(output, BlockSize, "output buffer too short"); - if (forEncryption) + if (totalLength == 0) { - GcmUtilities.Xor(buf, off, ctrBlock, 0, len); - gHASHPartial(S, buf, off, len); + InitCipher(); + } + + Span ctrBlock = stackalloc byte[BlockSize]; + + GetNextCtrBlock(ctrBlock); +#if NETCOREAPP3_0_OR_GREATER + if (Sse2.IsSupported && Unsafe.SizeOf>() == BlockSize) + { + var t0 = MemoryMarshal.Read>(input); + var t1 = MemoryMarshal.Read>(ctrBlock); + var t2 = MemoryMarshal.Read>(S.AsSpan()); + + t1 = Sse2.Xor(t1, t0); + t2 = Sse2.Xor(t2, t0); + + MemoryMarshal.Write(output, ref t1); + MemoryMarshal.Write(S.AsSpan(), ref t2); } else +#endif { - gHASHPartial(S, buf, off, len); - GcmUtilities.Xor(buf, off, ctrBlock, 0, len); + for (int i = 0; i < BlockSize; i += 4) + { + byte c0 = input[i + 0]; + byte c1 = input[i + 1]; + byte c2 = input[i + 2]; + byte c3 = input[i + 3]; + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + output[i + 0] = (byte)(c0 ^ ctrBlock[i + 0]); + output[i + 1] = (byte)(c1 ^ ctrBlock[i + 1]); + output[i + 2] = (byte)(c2 ^ ctrBlock[i + 2]); + output[i + 3] = (byte)(c3 ^ ctrBlock[i + 3]); + } } + multiplier.MultiplyH(S); - Array.Copy(buf, off, output, outOff, len); - totalLength += (uint)len; + totalLength += BlockSize; } - private void gHASH(byte[] Y, byte[] b, int len) + private void DecryptBlocks2(ReadOnlySpan input, Span output) { - for (int pos = 0; pos < len; pos += BlockSize) + Check.OutputLength(output, BlockSize * 2, "output buffer too short"); + + if (totalLength == 0) { - int num = System.Math.Min(len - pos, BlockSize); - gHASHPartial(Y, b, pos, num); + InitCipher(); } - } - private void gHASHBlock(byte[] Y, byte[] b) - { - GcmUtilities.Xor(Y, b); - Tables8kGcmMultiplier_MultiplyH(Y); + Span ctrBlock = stackalloc byte[BlockSize]; + + GetNextCtrBlock(ctrBlock); +#if NETCOREAPP3_0_OR_GREATER + if (Sse2.IsSupported && Unsafe.SizeOf>() == BlockSize) + { + var t0 = MemoryMarshal.Read>(input); + var t1 = MemoryMarshal.Read>(ctrBlock); + var t2 = MemoryMarshal.Read>(S.AsSpan()); + + t1 = Sse2.Xor(t1, t0); + t2 = Sse2.Xor(t2, t0); + + MemoryMarshal.Write(output, ref t1); + MemoryMarshal.Write(S.AsSpan(), ref t2); + } + else +#endif + { + for (int i = 0; i < BlockSize; i += 4) + { + byte c0 = input[i + 0]; + byte c1 = input[i + 1]; + byte c2 = input[i + 2]; + byte c3 = input[i + 3]; + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + output[i + 0] = (byte)(c0 ^ ctrBlock[i + 0]); + output[i + 1] = (byte)(c1 ^ ctrBlock[i + 1]); + output[i + 2] = (byte)(c2 ^ ctrBlock[i + 2]); + output[i + 3] = (byte)(c3 ^ ctrBlock[i + 3]); + } + } + multiplier.MultiplyH(S); + + input = input[BlockSize..]; + output = output[BlockSize..]; + + GetNextCtrBlock(ctrBlock); +#if NETCOREAPP3_0_OR_GREATER + if (Sse2.IsSupported && Unsafe.SizeOf>() == BlockSize) + { + var t0 = MemoryMarshal.Read>(input); + var t1 = MemoryMarshal.Read>(ctrBlock); + var t2 = MemoryMarshal.Read>(S.AsSpan()); + + t1 = Sse2.Xor(t1, t0); + t2 = Sse2.Xor(t2, t0); + + MemoryMarshal.Write(output, ref t1); + MemoryMarshal.Write(S.AsSpan(), ref t2); + } + else +#endif + { + for (int i = 0; i < BlockSize; i += 4) + { + byte c0 = input[i + 0]; + byte c1 = input[i + 1]; + byte c2 = input[i + 2]; + byte c3 = input[i + 3]; + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + output[i + 0] = (byte)(c0 ^ ctrBlock[i + 0]); + output[i + 1] = (byte)(c1 ^ ctrBlock[i + 1]); + output[i + 2] = (byte)(c2 ^ ctrBlock[i + 2]); + output[i + 3] = (byte)(c3 ^ ctrBlock[i + 3]); + } + } + multiplier.MultiplyH(S); + + totalLength += BlockSize * 2; } - private void gHASHBlock(byte[] Y, byte[] b, int off) + private void EncryptBlock(ReadOnlySpan input, Span output) { - GcmUtilities.Xor(Y, b, off); - Tables8kGcmMultiplier_MultiplyH(Y); + Check.OutputLength(output, BlockSize, "output buffer too short"); + + if (totalLength == 0) + { + InitCipher(); + } + + Span ctrBlock = stackalloc byte[BlockSize]; + + GetNextCtrBlock(ctrBlock); +#if NETCOREAPP3_0_OR_GREATER + if (Sse2.IsSupported && Unsafe.SizeOf>() == BlockSize) + { + var t0 = MemoryMarshal.Read>(input); + var t1 = MemoryMarshal.Read>(ctrBlock); + var t2 = MemoryMarshal.Read>(S.AsSpan()); + + t1 = Sse2.Xor(t1, t0); + t2 = Sse2.Xor(t2, t1); + + MemoryMarshal.Write(output, ref t1); + MemoryMarshal.Write(S.AsSpan(), ref t2); + } + else +#endif + { + for (int i = 0; i < BlockSize; i += 4) + { + byte c0 = (byte)(ctrBlock[i + 0] ^ input[i + 0]); + byte c1 = (byte)(ctrBlock[i + 1] ^ input[i + 1]); + byte c2 = (byte)(ctrBlock[i + 2] ^ input[i + 2]); + byte c3 = (byte)(ctrBlock[i + 3] ^ input[i + 3]); + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + output[i + 0] = c0; + output[i + 1] = c1; + output[i + 2] = c2; + output[i + 3] = c3; + } + } + multiplier.MultiplyH(S); + + totalLength += BlockSize; } - private void gHASHPartial(byte[] Y, byte[] b, int off, int len) + private void EncryptBlocks2(ReadOnlySpan input, Span output) { - GcmUtilities.Xor(Y, b, off, len); - Tables8kGcmMultiplier_MultiplyH(Y); + Check.OutputLength(output, BlockSize * 2, "Output buffer too short"); + + if (totalLength == 0) + { + InitCipher(); + } + + Span ctrBlock = stackalloc byte[BlockSize]; + + GetNextCtrBlock(ctrBlock); +#if NETCOREAPP3_0_OR_GREATER + if (Sse2.IsSupported && Unsafe.SizeOf>() == BlockSize) + { + var t0 = MemoryMarshal.Read>(input); + var t1 = MemoryMarshal.Read>(ctrBlock); + var t2 = MemoryMarshal.Read>(S.AsSpan()); + + t1 = Sse2.Xor(t1, t0); + t2 = Sse2.Xor(t2, t1); + + MemoryMarshal.Write(output, ref t1); + MemoryMarshal.Write(S.AsSpan(), ref t2); + } + else +#endif + { + for (int i = 0; i < BlockSize; i += 4) + { + byte c0 = (byte)(ctrBlock[i + 0] ^ input[i + 0]); + byte c1 = (byte)(ctrBlock[i + 1] ^ input[i + 1]); + byte c2 = (byte)(ctrBlock[i + 2] ^ input[i + 2]); + byte c3 = (byte)(ctrBlock[i + 3] ^ input[i + 3]); + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + output[i + 0] = c0; + output[i + 1] = c1; + output[i + 2] = c2; + output[i + 3] = c3; + } + } + multiplier.MultiplyH(S); + + input = input[BlockSize..]; + output = output[BlockSize..]; + + GetNextCtrBlock(ctrBlock); +#if NETCOREAPP3_0_OR_GREATER + if (Sse2.IsSupported && Unsafe.SizeOf>() == BlockSize) + { + var t0 = MemoryMarshal.Read>(input); + var t1 = MemoryMarshal.Read>(ctrBlock); + var t2 = MemoryMarshal.Read>(S.AsSpan()); + + t1 = Sse2.Xor(t1, t0); + t2 = Sse2.Xor(t2, t1); + + MemoryMarshal.Write(output, ref t1); + MemoryMarshal.Write(S.AsSpan(), ref t2); + } + else +#endif + { + for (int i = 0; i < BlockSize; i += 4) + { + byte c0 = (byte)(ctrBlock[i + 0] ^ input[i + 0]); + byte c1 = (byte)(ctrBlock[i + 1] ^ input[i + 1]); + byte c2 = (byte)(ctrBlock[i + 2] ^ input[i + 2]); + byte c3 = (byte)(ctrBlock[i + 3] ^ input[i + 3]); + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + output[i + 0] = c0; + output[i + 1] = c1; + output[i + 2] = c2; + output[i + 3] = c3; + } + } + multiplier.MultiplyH(S); + + totalLength += BlockSize * 2; } - private void GetNextCtrBlock(byte[] block) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void GetNextCtrBlock(Span 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; + Pack.UInt32_To_BE(++counter32, counter, 12); - cipher.ProcessBlock(counter, 0, block, 0); + cipher.ProcessBlock(counter, block); } - private void CheckStatus() + private void ProcessPartial(Span partialBlock, Span output) { - if (!initialised) + Span ctrBlock = stackalloc byte[BlockSize]; + GetNextCtrBlock(ctrBlock); + + if (forEncryption) { - if (forEncryption) + GcmUtilities.Xor(partialBlock, ctrBlock, partialBlock.Length); + gHASHPartial(S, partialBlock); + } + else + { + gHASHPartial(S, partialBlock); + GcmUtilities.Xor(partialBlock, ctrBlock, partialBlock.Length); + } + + partialBlock.CopyTo(output); + totalLength += (uint)partialBlock.Length; + } +#else + private void DecryptBlock(byte[] inBuf, int inOff, byte[] outBuf, int outOff) + { + Check.OutputLength(outBuf, outOff, BlockSize, "Output buffer too short"); + + if (totalLength == 0) + { + InitCipher(); + } + + //byte[] ctrBlock = new byte[BlockSize]; + + GetNextCtrBlock(ctrBlock); + { + for (int i = 0; i < BlockSize; i += 4) { - throw new InvalidOperationException("GCM cipher cannot be reused for encryption"); + byte c0 = inBuf[inOff + i + 0]; + byte c1 = inBuf[inOff + i + 1]; + byte c2 = inBuf[inOff + i + 2]; + byte c3 = inBuf[inOff + i + 3]; + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + outBuf[outOff + i + 0] = (byte)(c0 ^ ctrBlock[i + 0]); + outBuf[outOff + i + 1] = (byte)(c1 ^ ctrBlock[i + 1]); + outBuf[outOff + i + 2] = (byte)(c2 ^ ctrBlock[i + 2]); + outBuf[outOff + i + 3] = (byte)(c3 ^ ctrBlock[i + 3]); } - throw new InvalidOperationException("GCM cipher needs to be initialised"); } + multiplier.MultiplyH(S); + + totalLength += BlockSize; } - #region Tables8kGcmMultiplier + private void DecryptBlocks2(byte[] inBuf, int inOff, byte[] outBuf, int outOff) + { + Check.OutputLength(outBuf, outOff, BlockSize * 2, "Output buffer too short"); + + if (totalLength == 0) + { + InitCipher(); + } - private byte[] Tables8kGcmMultiplier_H; - private uint[][][] Tables8kGcmMultiplier_M; + //byte[] ctrBlock = new byte[BlockSize]; - public void Tables8kGcmMultiplier_Init(byte[] H) - { - if (Tables8kGcmMultiplier_M == null) + GetNextCtrBlock(ctrBlock); { - Tables8kGcmMultiplier_M = new uint[32][][]; + for (int i = 0; i < BlockSize; i += 4) + { + byte c0 = inBuf[inOff + i + 0]; + byte c1 = inBuf[inOff + i + 1]; + byte c2 = inBuf[inOff + i + 2]; + byte c3 = inBuf[inOff + i + 3]; + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + outBuf[outOff + i + 0] = (byte)(c0 ^ ctrBlock[i + 0]); + outBuf[outOff + i + 1] = (byte)(c1 ^ ctrBlock[i + 1]); + outBuf[outOff + i + 2] = (byte)(c2 ^ ctrBlock[i + 2]); + outBuf[outOff + i + 3] = (byte)(c3 ^ ctrBlock[i + 3]); + } } - else if (Arrays.AreEqual(this.Tables8kGcmMultiplier_H, H)) + multiplier.MultiplyH(S); + + inOff += BlockSize; + outOff += BlockSize; + + GetNextCtrBlock(ctrBlock); { - return; + for (int i = 0; i < BlockSize; i += 4) + { + byte c0 = inBuf[inOff + i + 0]; + byte c1 = inBuf[inOff + i + 1]; + byte c2 = inBuf[inOff + i + 2]; + byte c3 = inBuf[inOff + i + 3]; + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + outBuf[outOff + i + 0] = (byte)(c0 ^ ctrBlock[i + 0]); + outBuf[outOff + i + 1] = (byte)(c1 ^ ctrBlock[i + 1]); + outBuf[outOff + i + 2] = (byte)(c2 ^ ctrBlock[i + 2]); + outBuf[outOff + i + 3] = (byte)(c3 ^ ctrBlock[i + 3]); + } } + multiplier.MultiplyH(S); - this.Tables8kGcmMultiplier_H = Arrays.Clone(H); + totalLength += BlockSize * 2; + } - Tables8kGcmMultiplier_M[0] = new uint[16][]; - Tables8kGcmMultiplier_M[1] = new uint[16][]; - Tables8kGcmMultiplier_M[0][0] = new uint[4]; - Tables8kGcmMultiplier_M[1][0] = new uint[4]; - Tables8kGcmMultiplier_M[1][8] = GcmUtilities.AsUints(H); + private void EncryptBlock(byte[] inBuf, int inOff, byte[] outBuf, int outOff) + { + Check.OutputLength(outBuf, outOff, BlockSize, "Output buffer too short"); - for (int j = 4; j >= 1; j >>= 1) + if (totalLength == 0) { - uint[] tmp = (uint[])Tables8kGcmMultiplier_M[1][j + j].Clone(); - GcmUtilities.MultiplyP(tmp); - Tables8kGcmMultiplier_M[1][j] = tmp; + InitCipher(); } + //byte[] ctrBlock = new byte[BlockSize]; + + GetNextCtrBlock(ctrBlock); { - uint[] tmp = (uint[])Tables8kGcmMultiplier_M[1][1].Clone(); - GcmUtilities.MultiplyP(tmp); - Tables8kGcmMultiplier_M[0][8] = tmp; + for (int i = 0; i < BlockSize; i += 4) + { + byte c0 = (byte)(ctrBlock[i + 0] ^ inBuf[inOff + i + 0]); + byte c1 = (byte)(ctrBlock[i + 1] ^ inBuf[inOff + i + 1]); + byte c2 = (byte)(ctrBlock[i + 2] ^ inBuf[inOff + i + 2]); + byte c3 = (byte)(ctrBlock[i + 3] ^ inBuf[inOff + i + 3]); + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + outBuf[outOff + i + 0] = c0; + outBuf[outOff + i + 1] = c1; + outBuf[outOff + i + 2] = c2; + outBuf[outOff + i + 3] = c3; + } } + multiplier.MultiplyH(S); + + totalLength += BlockSize; + } + + private void EncryptBlocks2(byte[] inBuf, int inOff, byte[] outBuf, int outOff) + { + Check.OutputLength(outBuf, outOff, BlockSize * 2, "Output buffer too short"); - for (int j = 4; j >= 1; j >>= 1) + if (totalLength == 0) { - uint[] tmp = (uint[])Tables8kGcmMultiplier_M[0][j + j].Clone(); - GcmUtilities.MultiplyP(tmp); - Tables8kGcmMultiplier_M[0][j] = tmp; + InitCipher(); } - for (int i = 0; ;) + //byte[] ctrBlock = new byte[BlockSize]; + + GetNextCtrBlock(ctrBlock); { - for (int j = 2; j < 16; j += j) + for (int i = 0; i < BlockSize; i += 4) { - for (int k = 1; k < j; ++k) - { - uint[] tmp = (uint[])Tables8kGcmMultiplier_M[i][j].Clone(); - GcmUtilities.Xor(tmp, Tables8kGcmMultiplier_M[i][k]); - Tables8kGcmMultiplier_M[i][j + k] = tmp; - } + byte c0 = (byte)(ctrBlock[i + 0] ^ inBuf[inOff + i + 0]); + byte c1 = (byte)(ctrBlock[i + 1] ^ inBuf[inOff + i + 1]); + byte c2 = (byte)(ctrBlock[i + 2] ^ inBuf[inOff + i + 2]); + byte c3 = (byte)(ctrBlock[i + 3] ^ inBuf[inOff + i + 3]); + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + outBuf[outOff + i + 0] = c0; + outBuf[outOff + i + 1] = c1; + outBuf[outOff + i + 2] = c2; + outBuf[outOff + i + 3] = c3; } + } + multiplier.MultiplyH(S); - if (++i == 32) return; + inOff += BlockSize; + outOff += BlockSize; - if (i > 1) + GetNextCtrBlock(ctrBlock); + { + for (int i = 0; i < BlockSize; i += 4) { - Tables8kGcmMultiplier_M[i] = new uint[16][]; - Tables8kGcmMultiplier_M[i][0] = new uint[4]; - for (int j = 8; j > 0; j >>= 1) - { - uint[] tmp = (uint[])Tables8kGcmMultiplier_M[i - 2][j].Clone(); - GcmUtilities.MultiplyP8(tmp); - Tables8kGcmMultiplier_M[i][j] = tmp; - } + byte c0 = (byte)(ctrBlock[i + 0] ^ inBuf[inOff + i + 0]); + byte c1 = (byte)(ctrBlock[i + 1] ^ inBuf[inOff + i + 1]); + byte c2 = (byte)(ctrBlock[i + 2] ^ inBuf[inOff + i + 2]); + byte c3 = (byte)(ctrBlock[i + 3] ^ inBuf[inOff + i + 3]); + + S[i + 0] ^= c0; + S[i + 1] ^= c1; + S[i + 2] ^= c2; + S[i + 3] ^= c3; + + outBuf[outOff + i + 0] = c0; + outBuf[outOff + i + 1] = c1; + outBuf[outOff + i + 2] = c2; + outBuf[outOff + i + 3] = c3; } } + multiplier.MultiplyH(S); + + totalLength += BlockSize * 2; } - uint[] Tables8kGcmMultiplier_z = new uint[4]; - public unsafe void Tables8kGcmMultiplier_MultiplyH(byte[] x) + private void GetNextCtrBlock(byte[] block) { - fixed (byte* px = x) - fixed (uint* pz = Tables8kGcmMultiplier_z) - { - ulong* pulongZ = (ulong*)pz; - pulongZ[0] = 0; - pulongZ[1] = 0; + if (blocksRemaining == 0) + throw new InvalidOperationException("Attempt to process too many blocks"); - for (int i = 15; i >= 0; --i) - { - uint[] m = Tables8kGcmMultiplier_M[i + i][px[i] & 0x0f]; - fixed (uint* pm = m) - { - ulong* pulongm = (ulong*)pm; + blocksRemaining--; - pulongZ[0] ^= pulongm[0]; - pulongZ[1] ^= pulongm[1]; - } + Pack.UInt32_To_BE(++counter32, counter, 12); - m = Tables8kGcmMultiplier_M[i + i + 1][(px[i] & 0xf0) >> 4]; - fixed (uint* pm = m) - { - ulong* pulongm = (ulong*)pm; + cipher.ProcessBlock(counter, 0, block, 0); + } - pulongZ[0] ^= pulongm[0]; - pulongZ[1] ^= pulongm[1]; - } - } + private void ProcessPartial(byte[] buf, int off, int len, byte[] output, int outOff) + { + //byte[] ctrBlock = new byte[BlockSize]; + GetNextCtrBlock(ctrBlock); - byte* pbyteZ = (byte*)pz; - px[0] = pbyteZ[3]; - px[1] = pbyteZ[2]; - px[2] = pbyteZ[1]; - px[3] = pbyteZ[0]; + 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); + } - px[4] = pbyteZ[7]; - px[5] = pbyteZ[6]; - px[6] = pbyteZ[5]; - px[7] = pbyteZ[4]; + Array.Copy(buf, off, output, outOff, len); + totalLength += (uint)len; + } +#endif - px[8] = pbyteZ[11]; - px[9] = pbyteZ[10]; - px[10] = pbyteZ[9]; - px[11] = pbyteZ[8]; + 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); + } + } - px[12] = pbyteZ[15]; - px[13] = pbyteZ[14]; - px[14] = pbyteZ[13]; - px[15] = pbyteZ[12]; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void gHASHBlock(byte[] Y, ReadOnlySpan b) + { + GcmUtilities.Xor(Y, b); + multiplier.MultiplyH(Y); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void gHASHPartial(byte[] Y, ReadOnlySpan b) + { + GcmUtilities.Xor(Y, b, b.Length); + multiplier.MultiplyH(Y); + } +#else + 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); + } +#endif + + private void gHASHPartial(byte[] Y, byte[] b, int off, int len) + { + GcmUtilities.Xor(Y, b, off, len); + multiplier.MultiplyH(Y); + } + + 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"); } } - #endregion } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/GOFBBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/GOFBBlockCipher.cs index 4ad7f35..04381ee 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/GOFBBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/GOFBBlockCipher.cs @@ -2,8 +2,8 @@ #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.Modes { @@ -11,8 +11,8 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes * implements the GOST 28147 OFB counter mode (GCTR). */ public class GOfbBlockCipher - : IBlockCipher - { + : IBlockCipherMode + { private byte[] IV; private byte[] ofbV; private byte[] ofbOutV; @@ -48,15 +48,12 @@ public GOfbBlockCipher( 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; - } + public IBlockCipher UnderlyingCipher => cipher; /** * Initialise the cipher and, possibly, the initialisation vector (IV). @@ -133,41 +130,17 @@ 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) + 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"); - } + Check.DataLength(input, inOff, blockSize, "input buffer too short"); + Check.OutputLength(output, outOff, blockSize, "output buffer too short"); if (firstStep) { firstStep = false; cipher.ProcessBlock(ofbV, 0, ofbOutV, 0); - N3 = bytesToint(ofbOutV, 0); - N4 = bytesToint(ofbOutV, 4); + N3 = (int)Pack.LE_To_UInt32(ofbOutV, 0); + N4 = (int)Pack.LE_To_UInt32(ofbOutV, 4); } N3 += C2; N4 += C1; @@ -178,8 +151,8 @@ public int ProcessBlock( N4++; } } - intTobytes(N3, ofbV, 0); - intTobytes(N4, ofbV, 4); + Pack.UInt32_To_LE((uint)N3, ofbV, 0); + Pack.UInt32_To_LE((uint)N4, ofbV, 4); cipher.ProcessBlock(ofbV, 0, ofbOutV, 0); @@ -201,6 +174,52 @@ public int ProcessBlock( return blockSize; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessBlock(ReadOnlySpan input, Span output) + { + Check.DataLength(input, blockSize, "input buffer too short"); + Check.OutputLength(output, blockSize, "output buffer too short"); + + if (firstStep) + { + firstStep = false; + cipher.ProcessBlock(ofbV, ofbOutV); + N3 = (int)Pack.LE_To_UInt32(ofbOutV, 0); + N4 = (int)Pack.LE_To_UInt32(ofbOutV, 4); + } + N3 += C2; + N4 += C1; + if (N4 < C1) // addition is mod (2**32 - 1) + { + if (N4 > 0) + { + N4++; + } + } + Pack.UInt32_To_LE((uint)N3, ofbV, 0); + Pack.UInt32_To_LE((uint)N4, ofbV, 4); + + cipher.ProcessBlock(ofbV, ofbOutV); + + // + // XOR the ofbV with the plaintext producing the cipher text (and + // the next input block). + // + for (int i = 0; i < blockSize; i++) + { + output[i] = (byte)(ofbOutV[i] ^ input[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; + } +#endif + /** * reset the feedback vector back to the IV and reset the underlying * cipher. @@ -208,29 +227,6 @@ public int ProcessBlock( 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; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/GcmSivBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/GcmSivBlockCipher.cs index d231b28..5e5cecc 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/GcmSivBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/GcmSivBlockCipher.cs @@ -3,7 +3,6 @@ using System; using System.IO; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes.Gcm; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; @@ -39,17 +38,17 @@ public class GcmSivBlockCipher * The maximum data length (AEAD/PlainText). Due to implementation constraints this is restricted to the maximum * array length (https://programming.guide/java/array-maximum-length.html) minus the BUFLEN to allow for the MAC */ - private static readonly int MAX_DATALEN = Int32.MaxValue - 8 - BUFLEN; + private static readonly int MAX_DATALEN = int.MaxValue - 8 - BUFLEN; /** * The top bit mask. */ - private static readonly byte MASK = (byte)0x80; + private static readonly byte MASK = 0x80; /** * The addition constant. */ - private static readonly byte ADD = (byte)0xE1; + private static readonly byte ADD = 0xE1; /** * The initialisation flag. @@ -125,7 +124,7 @@ public class GcmSivBlockCipher * Constructor. */ public GcmSivBlockCipher() - : this(new AesEngine()) + : this(AesUtilities.CreateEngine()) { } @@ -158,10 +157,7 @@ public GcmSivBlockCipher(IBlockCipher pCipher, IGcmMultiplier pMultiplier) theDataHasher = new GcmSivHasher(this); } - public virtual IBlockCipher GetUnderlyingCipher() - { - return theCipher; - } + public virtual IBlockCipher UnderlyingCipher => theCipher; public virtual int GetBlockSize() { @@ -172,8 +168,8 @@ public virtual void Init(bool pEncrypt, ICipherParameters cipherParameters) { /* Set defaults */ byte[] myInitialAEAD = null; - byte[] myNonce = null; - KeyParameter myKey = null; + byte[] myNonce; + KeyParameter myKey; /* Access parameters */ if (cipherParameters is AeadParameters) @@ -208,8 +204,7 @@ public virtual void Init(bool pEncrypt, ICipherParameters cipherParameters) byte[] k = myKey.GetKey(); - if (k.Length != BUFLEN - && k.Length != (BUFLEN << 1)) + if (k.Length != BUFLEN && k.Length != (BUFLEN << 1)) { throw new ArgumentException("Invalid key"); } @@ -220,14 +215,11 @@ public virtual void Init(bool pEncrypt, ICipherParameters cipherParameters) theNonce = myNonce; /* Initialise the keys */ - deriveKeys(myKey); + DeriveKeys(myKey); ResetStreams(); } - public virtual string AlgorithmName - { - get { return theCipher.AlgorithmName + "-GCM-SIV"; } - } + public virtual string AlgorithmName => theCipher.AlgorithmName + "-GCM-SIV"; /** * check AEAD status. @@ -248,7 +240,7 @@ private void CheckAeadStatus(int pLen) } /* Make sure that we haven't breached AEAD data limit */ - if ((long)theAEADHasher.getBytesProcessed() + Int64.MinValue > (MAX_DATALEN - pLen) + Int64.MinValue) + if ((long)theAEADHasher.getBytesProcessed() + long.MinValue > (MAX_DATALEN - pLen) + long.MinValue) { throw new InvalidOperationException("AEAD byte count exceeded"); } @@ -281,8 +273,7 @@ private void CheckStatus(int pLen) dataLimit += BUFLEN; currBytes = theEncData.Length; } - if (currBytes + System.Int64.MinValue - > (dataLimit - pLen) + System.Int64.MinValue) + if (currBytes + long.MinValue > (dataLimit - pLen) + long.MinValue) { throw new InvalidOperationException("byte count exceeded"); } @@ -294,20 +285,34 @@ public virtual void ProcessAadByte(byte pByte) CheckAeadStatus(1); /* Process the aead */ - theAEADHasher.updateHash(pByte); + theAEADHasher.UpdateHash(pByte); } public virtual void ProcessAadBytes(byte[] pData, int pOffset, int pLen) { + Check.DataLength(pData, pOffset, pLen, "input buffer too short"); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ProcessAadBytes(pData.AsSpan(pOffset, pLen)); +#else /* Check that we can supply AEAD */ CheckAeadStatus(pLen); - /* Check input buffer */ - CheckBuffer(pData, pOffset, pLen, false); + /* Process the aead */ + theAEADHasher.UpdateHash(pData, pOffset, pLen); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void ProcessAadBytes(ReadOnlySpan input) + { + /* Check that we can supply AEAD */ + CheckAeadStatus(input.Length); /* Process the aead */ - theAEADHasher.updateHash(pData, pOffset, pLen); + theAEADHasher.UpdateHash(input); } +#endif public virtual int ProcessByte(byte pByte, byte[] pOutput, int pOutOffset) { @@ -318,7 +323,7 @@ public virtual int ProcessByte(byte pByte, byte[] pOutput, int pOutOffset) if (forEncryption) { thePlain.WriteByte(pByte); - theDataHasher.updateHash(pByte); + theDataHasher.UpdateHash(pByte); } else { @@ -329,19 +334,43 @@ public virtual int ProcessByte(byte pByte, byte[] pOutput, int pOutOffset) return 0; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessByte(byte input, Span output) + { + /* Check that we have initialised */ + CheckStatus(1); + + /* Store the data */ + if (forEncryption) + { + thePlain.WriteByte(input); + theDataHasher.UpdateHash(input); + } + else + { + theEncData.WriteByte(input); + } + + /* No data returned */ + return 0; + } +#endif + public virtual int ProcessBytes(byte[] pData, int pOffset, int pLen, byte[] pOutput, int pOutOffset) { + Check.DataLength(pData, pOffset, pLen, "input buffer too short"); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ProcessBytes(pData.AsSpan(pOffset, pLen), Spans.FromNullable(pOutput, pOutOffset)); +#else /* Check that we have initialised */ CheckStatus(pLen); - /* Check input buffer */ - CheckBuffer(pData, pOffset, pLen, false); - /* Store the data */ if (forEncryption) { thePlain.Write(pData, pOffset, pLen); - theDataHasher.updateHash(pData, pOffset, pLen); + theDataHasher.UpdateHash(pData, pOffset, pLen); } else { @@ -350,27 +379,52 @@ public virtual int ProcessBytes(byte[] pData, int pOffset, int pLen, byte[] pOut /* No data returned */ return 0; +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBytes(ReadOnlySpan input, Span output) + { + /* Check that we have initialised */ + CheckStatus(input.Length); + + /* Store the data */ + if (forEncryption) + { + thePlain.Write(input); + theDataHasher.UpdateHash(input); + } + else + { + theEncData.Write(input); + } + + /* No data returned */ + return 0; + } +#endif + public virtual int DoFinal(byte[] pOutput, int pOffset) { + Check.OutputLength(pOutput, pOffset, GetOutputSize(0), "output buffer too short"); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(pOutput.AsSpan(pOffset)); +#else /* Check that we have initialised */ CheckStatus(0); - /* Check output buffer */ - CheckBuffer(pOutput, pOffset, GetOutputSize(0), true); - /* If we are encrypting */ if (forEncryption) { /* Derive the tag */ - byte[] myTag = calculateTag(); + byte[] myTag = CalculateTag(); /* encrypt the plain text */ - int myDataLen = BUFLEN + encryptPlain(myTag, pOutput, pOffset); + int myDataLen = BUFLEN + EncryptPlain(myTag, pOutput, pOffset); /* Add the tag to the output */ - Array.Copy(myTag, 0, pOutput, pOffset + (int)thePlain.Length, BUFLEN); + Array.Copy(myTag, 0, pOutput, pOffset + Convert.ToInt32(thePlain.Length), BUFLEN); /* Reset the streams */ ResetStreams(); @@ -381,7 +435,7 @@ public virtual int DoFinal(byte[] pOutput, int pOffset) else { /* decrypt to plain text */ - decryptPlain(); + DecryptPlain(); /* Release plain text */ int myDataLen = Streams.WriteBufTo(thePlain, pOutput, pOffset); @@ -390,8 +444,54 @@ public virtual int DoFinal(byte[] pOutput, int pOffset) ResetStreams(); return myDataLen; } +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int DoFinal(Span output) + { + /* Check that we have initialised */ + CheckStatus(0); + + Check.OutputLength(output, GetOutputSize(0), "output buffer too short"); + + /* If we are encrypting */ + if (forEncryption) + { + /* Derive the tag */ + byte[] myTag = CalculateTag(); + + /* encrypt the plain text */ + int myDataLen = BUFLEN + EncryptPlain(myTag, output); + + /* Add the tag to the output */ + myTag.AsSpan(0, BUFLEN).CopyTo(output[Convert.ToInt32(thePlain.Length)..]); + + /* Reset the streams */ + ResetStreams(); + return myDataLen; + + /* else we are decrypting */ + } + else + { + /* decrypt to plain text */ + DecryptPlain(); + + /* Release plain text */ + if (!thePlain.TryGetBuffer(out var buffer)) + throw new InvalidOperationException(); + + buffer.AsSpan().CopyTo(output); + int myDataLen = buffer.Count; + + /* Reset the streams */ + ResetStreams(); + return myDataLen; + } + } +#endif + public virtual byte[] GetMac() { throw new InvalidOperationException(); @@ -406,9 +506,9 @@ public virtual int GetOutputSize(int pLen) { if (forEncryption) { - return (int)(pLen + thePlain.Length + BUFLEN); + return pLen + Convert.ToInt32(thePlain.Length) + BUFLEN; } - int myCurr = (int)(pLen + theEncData.Length); + int myCurr = pLen + Convert.ToInt32(theEncData.Length); return myCurr > BUFLEN ? myCurr - BUFLEN : 0; } @@ -425,8 +525,9 @@ private void ResetStreams() /* Clear the plainText buffer */ if (thePlain != null) { - thePlain.Position = 0L; - Streams.WriteZeroes(thePlain, thePlain.Capacity); + int count = Convert.ToInt32(thePlain.Length); + Array.Clear(thePlain.GetBuffer(), 0, count); + thePlain.SetLength(0); } /* Reset hashers */ @@ -442,7 +543,7 @@ private void ResetStreams() Arrays.Fill(theGHash, (byte)0); if (theInitialAEAD != null) { - theAEADHasher.updateHash(theInitialAEAD, 0, theInitialAEAD.Length); + theAEADHasher.UpdateHash(theInitialAEAD, 0, theInitialAEAD.Length); } } @@ -456,46 +557,46 @@ private static int bufLength(byte[] pBuffer) return pBuffer == null ? 0 : pBuffer.Length; } - /** - * Check buffer. - * @param pBuffer the buffer - * @param pOffset the offset - * @param pLen the length - * @param pOutput is this an output buffer? - */ - private static void CheckBuffer(byte[] pBuffer, int pOffset, int pLen, bool pOutput) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int EncryptPlain(byte[] pCounter, Span target) { - /* Access lengths */ - int myBufLen = bufLength(pBuffer); - int myLast = pOffset + pLen; + byte[] thePlainBuf = thePlain.GetBuffer(); + int thePlainLen = Convert.ToInt32(thePlain.Length); - /* Check for negative values and buffer overflow */ - bool badLen = pLen < 0 || pOffset < 0 || myLast < 0; - if (badLen || myLast > myBufLen) + byte[] mySrc = thePlainBuf; + byte[] myCounter = Arrays.Clone(pCounter); + myCounter[BUFLEN - 1] |= MASK; + byte[] myMask = new byte[BUFLEN]; + long myRemaining = thePlainLen; + int myOff = 0; + + /* While we have data to process */ + while (myRemaining > 0) { - throw pOutput - ? new OutputLengthException("Output buffer too short.") - : new DataLengthException("Input buffer too short."); + /* Generate the next mask */ + theCipher.ProcessBlock(myCounter, 0, myMask, 0); + + /* Xor data into mask */ + int myLen = (int)System.Math.Min(BUFLEN, myRemaining); + xorBlock(myMask, mySrc, myOff, myLen); + + /* Copy encrypted data to output */ + myMask.AsSpan(0, myLen).CopyTo(target[myOff..]); + + /* Adjust counters */ + myRemaining -= myLen; + myOff += myLen; + incrementCounter(myCounter); } - } - /** - * encrypt data stream. - * @param pCounter the counter - * @param pTarget the target buffer - * @param pOffset the target offset - * @return the length of data encrypted - */ - private int encryptPlain(byte[] pCounter, byte[] pTarget, int pOffset) - { - /* Access buffer and length */ -#if PORTABLE || NETFX_CORE - byte[] thePlainBuf = thePlain.ToArray(); - int thePlainLen = thePlainBuf.Length; + /* Return the amount of data processed */ + return thePlainLen; + } #else + private int EncryptPlain(byte[] pCounter, byte[] pTarget, int pOffset) + { byte[] thePlainBuf = thePlain.GetBuffer(); - int thePlainLen = (int)thePlain.Length; -#endif + int thePlainLen = Convert.ToInt32(thePlain.Length); byte[] mySrc = thePlainBuf; byte[] myCounter = Arrays.Clone(pCounter); @@ -526,21 +627,12 @@ private int encryptPlain(byte[] pCounter, byte[] pTarget, int pOffset) /* Return the amount of data processed */ return thePlainLen; } +#endif - /** - * decrypt data stream. - * @throws InvalidCipherTextException on data too short or mac check failed - */ - private void decryptPlain() + private void DecryptPlain() { - /* Access buffer and length */ -#if PORTABLE || NETFX_CORE - byte[] theEncDataBuf = theEncData.ToArray(); - int theEncDataLen = theEncDataBuf.Length; -#else byte[] theEncDataBuf = theEncData.GetBuffer(); - int theEncDataLen = (int)theEncData.Length; -#endif + int theEncDataLen = Convert.ToInt32(theEncData.Length); byte[] mySrc = theEncDataBuf; int myRemaining = theEncDataLen - BUFLEN; @@ -570,7 +662,7 @@ private void decryptPlain() /* Write data to plain dataStream */ thePlain.Write(myMask, 0, myLen); - theDataHasher.updateHash(myMask, 0, myLen); + theDataHasher.UpdateHash(myMask, 0, myLen); /* Adjust counters */ myRemaining -= myLen; @@ -579,7 +671,7 @@ private void decryptPlain() } /* Derive and check the tag */ - byte[] myTag = calculateTag(); + byte[] myTag = CalculateTag(); if (!Arrays.ConstantTimeAreEqual(myTag, myExpected)) { Reset(); @@ -591,7 +683,7 @@ private void decryptPlain() * calculate tag. * @return the calculated tag */ - private byte[] calculateTag() + private byte[] CalculateTag() { /* Complete the hash */ theDataHasher.completeHash(); @@ -651,13 +743,6 @@ private void gHASH(byte[] pNext) theMultiplier.MultiplyH(theGHash); } - /** - * Byte reverse a buffer. - * @param pInput the input buffer - * @param pOffset the offset - * @param pLength the length of data (<= BUFLEN) - * @param pOutput the output buffer - */ private static void fillReverse(byte[] pInput, int pOffset, int pLength, byte[] pOutput) { /* Loop through the buffer */ @@ -668,6 +753,18 @@ private static void fillReverse(byte[] pInput, int pOffset, int pLength, byte[] } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void fillReverse(ReadOnlySpan input, Span output) + { + /* Loop through the buffer */ + for (int i = 0, j = BUFLEN - 1; i < input.Length; i++, j--) + { + /* Copy byte */ + output[j] = input[i]; + } + } +#endif + /** * xor a full block buffer. * @param pLeft the left operand and result @@ -740,7 +837,7 @@ private static void mulX(byte[] pValue) * Derive Keys. * @param pKey the keyGeneration key */ - private void deriveKeys(KeyParameter pKey) + private void DeriveKeys(KeyParameter pKey) { /* Create the buffers */ byte[] myIn = new byte[BUFLEN]; @@ -857,10 +954,10 @@ internal void Reset() * update hash. * @param pByte the byte */ - internal void updateHash(byte pByte) + internal void UpdateHash(byte pByte) { theByte[0] = pByte; - updateHash(theByte, 0, 1); + UpdateHash(theByte, 0, 1); } /** @@ -869,7 +966,7 @@ internal void updateHash(byte pByte) * @param pOffset the offset within the buffer * @param pLen the length of data */ - internal void updateHash(byte[] pBuffer, int pOffset, int pLen) + internal void UpdateHash(byte[] pBuffer, int pOffset, int pLen) { /* If we should process the cache */ int mySpace = BUFLEN - numActive; @@ -896,8 +993,8 @@ internal void updateHash(byte[] pBuffer, int pOffset, int pLen) parent.gHASH(parent.theReverse); /* Adjust counters */ - numProcessed += mySpace; - myRemaining -= mySpace; + numProcessed += BUFLEN; + myRemaining -= BUFLEN; } /* If we have remaining data */ @@ -912,6 +1009,49 @@ internal void updateHash(byte[] pBuffer, int pOffset, int pLen) numHashed += (ulong)pLen; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal void UpdateHash(ReadOnlySpan buffer) + { + int pLen = buffer.Length; + + /* If we should process the cache */ + int mySpace = BUFLEN - numActive; + if (numActive > 0 && buffer.Length >= mySpace) + { + /* Copy data into the cache and hash it */ + buffer[..mySpace].CopyTo(theBuffer.AsSpan(numActive)); + fillReverse(theBuffer, parent.theReverse); + parent.gHASH(parent.theReverse); + + /* Adjust counters */ + buffer = buffer[mySpace..]; + numActive = 0; + } + + /* While we have full blocks */ + while (buffer.Length >= BUFLEN) + { + /* Access the next data */ + fillReverse(buffer[..BUFLEN], parent.theReverse); + parent.gHASH(parent.theReverse); + + /* Adjust counters */ + buffer = buffer[BUFLEN..]; + } + + /* If we have remaining data */ + if (!buffer.IsEmpty) + { + /* Copy data into the cache */ + buffer.CopyTo(theBuffer.AsSpan(numActive)); + numActive += buffer.Length; + } + + /* Adjust the number of bytes processed */ + numHashed += (ulong)pLen; + } +#endif + /** * complete hash. */ diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/IAeadBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/IAeadBlockCipher.cs index 0a8ff13..f87abec 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/IAeadBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/IAeadBlockCipher.cs @@ -12,7 +12,7 @@ public interface IAeadBlockCipher int GetBlockSize(); /// The block cipher underlying this algorithm. - IBlockCipher GetUnderlyingCipher(); + IBlockCipher UnderlyingCipher { get; } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/IAeadCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/IAeadCipher.cs index 9636d2d..68b4ebd 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/IAeadCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/IAeadCipher.cs @@ -43,6 +43,13 @@ public interface IAeadCipher /// The number of bytes to be processed. void ProcessAadBytes(byte[] inBytes, int inOff, int len); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// Add a span 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 span containing the data. + void ProcessAadBytes(ReadOnlySpan input); +#endif + /** * Encrypt/decrypt a single byte. * @@ -54,6 +61,10 @@ public interface IAeadCipher */ int ProcessByte(byte input, byte[] outBytes, int outOff); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int ProcessByte(byte input, Span output); +#endif + /** * Process a block of bytes from in putting the result into out. * @@ -67,6 +78,10 @@ public interface IAeadCipher */ int ProcessBytes(byte[] inBytes, int inOff, int len, byte[] outBytes, int outOff); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int ProcessBytes(ReadOnlySpan input, Span output); +#endif + /** * Finish the operation either appending or verifying the MAC at the end of the data. * @@ -78,6 +93,10 @@ public interface IAeadCipher */ int DoFinal(byte[] outBytes, int outOff); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int DoFinal(Span output); +#endif + /** * Return the value of the MAC associated with the last stream processed. * diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/IBlockCipherMode.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/IBlockCipherMode.cs new file mode 100644 index 0000000..ba90386 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/IBlockCipherMode.cs @@ -0,0 +1,23 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes +{ + public interface IBlockCipherMode + : IBlockCipher + { + /// Return the underlying this cipher mode. + IBlockCipher UnderlyingCipher { get; } + + /// Indicates whether this cipher mode can handle partial blocks. + bool IsPartialBlockOkay { get; } + + /// + /// Reset the cipher mode to the same state as it was after the last init (if there was one). + /// + void Reset(); + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/IBlockCipherMode.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/IBlockCipherMode.cs.meta new file mode 100644 index 0000000..58d562a --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/IBlockCipherMode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cdd6a50d059b6a947b9d90efa82a31ff +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/KCcmBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/KCcmBlockCipher.cs index ea5e579..27c0601 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/KCcmBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/KCcmBlockCipher.cs @@ -9,7 +9,8 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes { - public class KCcmBlockCipher: IAeadBlockCipher + public class KCcmBlockCipher + : IAeadBlockCipher { private static readonly int BYTES_IN_INT = 4; private static readonly int BITS_IN_BYTE = 8; @@ -132,23 +133,14 @@ public virtual void Init(bool forEncryption, ICipherParameters parameters) } } - public virtual String AlgorithmName - { - get - { - return engine.AlgorithmName + "/KCCM"; - } - } + public virtual string AlgorithmName => engine.AlgorithmName + "/KCCM"; public virtual int GetBlockSize() { return engine.GetBlockSize(); } - public virtual IBlockCipher GetUnderlyingCipher() - { - return engine; - } + public virtual IBlockCipher UnderlyingCipher => engine; public virtual void ProcessAadByte(byte input) { @@ -160,6 +152,13 @@ public virtual void ProcessAadBytes(byte[] input, int inOff, int len) associatedText.Write(input, inOff, len); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void ProcessAadBytes(ReadOnlySpan input) + { + associatedText.Write(input); + } +#endif + private void ProcessAAD(byte[] assocText, int assocOff, int assocLen, int dataLen) { if (assocLen - assocOff < engine.GetBlockSize()) @@ -229,6 +228,15 @@ public virtual int ProcessByte(byte input, byte[] output, int outOff) return 0; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessByte(byte input, Span output) + { + data.WriteByte(input); + + return 0; + } +#endif + public virtual int ProcessBytes(byte[] input, int inOff, int inLen, byte[] output, int outOff) { Check.DataLength(input, inOff, inLen, "input buffer too short"); @@ -238,22 +246,29 @@ public virtual int ProcessBytes(byte[] input, int inOff, int inLen, byte[] outpu return 0; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBytes(ReadOnlySpan input, Span output) + { + data.Write(input); + + return 0; + } +#endif + 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 NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ProcessPacket(input.AsSpan(inOff, len), output.AsSpan(outOff)); +#else 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 aadLen = Convert.ToInt32(associatedText.Length); - int dataLen = forEncryption ? (int)data.Length : ((int)data.Length - macSize); + int dataLen = Convert.ToInt32(data.Length) - (forEncryption ? 0 : macSize); ProcessAAD(aad, 0, aadLen, dataLen); } @@ -268,7 +283,7 @@ public int ProcessPacket(byte[] input, int inOff, int len, byte[] output, int ou int totalLength = len; while (totalLength > 0) { - ProcessBlock(input, inOff, len, output, outOff); + ProcessBlock(input, inOff, output, outOff); totalLength -= engine.GetBlockSize(); inOff += engine.GetBlockSize(); outOff += engine.GetBlockSize(); @@ -302,7 +317,7 @@ public int ProcessPacket(byte[] input, int inOff, int len, byte[] output, int ou for (int blockNum = 0; blockNum input, Span output) { + int len = input.Length; + Check.OutputLength(output, len, "output buffer too short"); + + if (associatedText.Length > 0) + { + byte[] aad = associatedText.GetBuffer(); + int aadLen = Convert.ToInt32(associatedText.Length); + + int dataLen = Convert.ToInt32(data.Length) - (forEncryption ? 0 : macSize); + + ProcessAAD(aad, 0, aadLen, dataLen); + } + + int blockSize = engine.GetBlockSize(), index = 0; + if (forEncryption) + { + Check.DataLength(len % blockSize != 0, "partial blocks not supported"); + + CalculateMac(input); + engine.ProcessBlock(nonce, s); + + int totalLength = len; + while (totalLength > 0) + { + ProcessBlock(input[index..], output[index..]); + totalLength -= blockSize; + index += blockSize; + } + + for (int byteIndex = 0; byteIndex < counter.Length; byteIndex++) + { + s[byteIndex] += counter[byteIndex]; + } + + engine.ProcessBlock(s, buffer); + + for (int byteIndex = 0; byteIndex < macSize; byteIndex++) + { + output[index + byteIndex] = (byte)(buffer[byteIndex] ^ macBlock[byteIndex]); + } + + Array.Copy(macBlock, 0, mac, 0, macSize); + Reset(); + + return len + macSize; + } + else + { + Check.DataLength((len - macSize) % blockSize != 0, "partial blocks not supported"); + + engine.ProcessBlock(nonce, 0, s, 0); + + int blocks = len / engine.GetBlockSize(); + + for (int blockNum = 0; blockNum < blocks; blockNum++) + { + ProcessBlock(input[index..], output[index..]); + index += blockSize; + } + + if (len > index) + { + for (int byteIndex = 0; byteIndex < counter.Length; byteIndex++) + { + s[byteIndex] += counter[byteIndex]; + } + + engine.ProcessBlock(s, buffer); + + for (int byteIndex = 0; byteIndex < macSize; byteIndex++) + { + output[index + byteIndex] = (byte)(buffer[byteIndex] ^ input[index + byteIndex]); + } + index += macSize; + } + + for (int byteIndex = 0; byteIndex < counter.Length; byteIndex++) + { + s[byteIndex] += counter[byteIndex]; + } + + engine.ProcessBlock(s, buffer); + + output[(index - macSize)..index].CopyTo(buffer); + + CalculateMac(output[..(index - macSize)]); + + Array.Copy(macBlock, 0, mac, 0, macSize); + + Span calculatedMac = macSize <= 64 + ? stackalloc byte[macSize] + : new byte[macSize]; + + calculatedMac.CopyFrom(buffer); + + if (!Arrays.ConstantTimeAreEqual(mac.AsSpan(0, macSize), calculatedMac)) + throw new InvalidCipherTextException("mac check failed"); + + Reset(); + + return len - macSize; + } + } +#endif + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void CalculateMac(ReadOnlySpan authText) + { + int blockSize = engine.GetBlockSize(); + + while (!authText.IsEmpty) + { + for (int byteIndex = 0; byteIndex < blockSize; byteIndex++) + { + macBlock[byteIndex] ^= authText[byteIndex]; + } + + engine.ProcessBlock(macBlock, macBlock); + + authText = authText[blockSize..]; + } + } + + private void ProcessBlock(ReadOnlySpan input, Span output) + { for (int byteIndex = 0; byteIndex < counter.Length; byteIndex++) { s[byteIndex] += counter[byteIndex]; } - engine.ProcessBlock(s, 0, buffer, 0); + engine.ProcessBlock(s, buffer); - for (int byteIndex = 0; byteIndex < engine.GetBlockSize(); byteIndex++) + int blockSize = engine.GetBlockSize(); + for (int byteIndex = 0; byteIndex < blockSize; byteIndex++) { - output[outOff + byteIndex] = (byte)(buffer[byteIndex] ^ input[inOff + byteIndex]); + output[byteIndex] = (byte)(buffer[byteIndex] ^ input[byteIndex]); } } - +#else private void CalculateMac(byte[] authText, int authOff, int len) { + int blockSize = engine.GetBlockSize(); int totalLen = len; while (totalLen > 0) { - for (int byteIndex = 0; byteIndex < engine.GetBlockSize(); byteIndex++) + for (int byteIndex = 0; byteIndex < blockSize; byteIndex++) { macBlock[byteIndex] ^= authText[authOff + byteIndex]; } engine.ProcessBlock(macBlock, 0, macBlock, 0); - totalLen -= engine.GetBlockSize(); - authOff += engine.GetBlockSize(); + totalLen -= blockSize; + authOff += blockSize; } } + private void ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) + { + + for (int byteIndex = 0; byteIndex < counter.Length; byteIndex++) + { + s[byteIndex] += counter[byteIndex]; + } + + engine.ProcessBlock(s, 0, buffer, 0); + + for (int byteIndex = 0; byteIndex < engine.GetBlockSize(); byteIndex++) + { + output[outOff + byteIndex] = (byte)(buffer[byteIndex] ^ input[inOff + byteIndex]); + } + } +#endif + public virtual int DoFinal(byte[] output, int outOff) { -#if PORTABLE || NETFX_CORE - byte[] buf = data.ToArray(); - int bufLen = buf.Length; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(output.AsSpan(outOff)); #else byte[] buf = data.GetBuffer(); - int bufLen = (int)data.Length; -#endif + int bufLen = Convert.ToInt32(data.Length); int len = ProcessPacket(buf, 0, bufLen, output, outOff); Reset(); return len; +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int DoFinal(Span output) + { + byte[] buf = data.GetBuffer(); + int bufLen = Convert.ToInt32(data.Length); + + int len = ProcessPacket(buf.AsSpan(0, bufLen), output); + + Reset(); + + return len; + } +#endif + public virtual byte[] GetMac() { return Arrays.Clone(mac); @@ -478,7 +652,7 @@ private byte getFlag(bool authTextPresents, int macSize) break; } - String binaryNb = Convert.ToString(Nb_ - 1, 2); + string binaryNb = Convert.ToString(Nb_ - 1, 2); while (binaryNb.Length < 4) { binaryNb = new StringBuilder(binaryNb).Insert(0, "0").ToString(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/KCtrBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/KCtrBlockCipher.cs index e593508..520638b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/KCtrBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/KCtrBlockCipher.cs @@ -9,7 +9,8 @@ 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 + public class KCtrBlockCipher + : IStreamCipher, IBlockCipherMode { private byte[] IV; private byte[] ofbV; @@ -42,10 +43,8 @@ public KCtrBlockCipher(IBlockCipher cipher) * * @return the underlying block cipher that we are wrapping. */ - public IBlockCipher GetUnderlyingCipher() - { - return cipher; - } + public IBlockCipher UnderlyingCipher => 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. @@ -120,26 +119,31 @@ public byte ReturnByte(byte 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"); - } + Check.DataLength(input, inOff, len, "input buffer too small"); + Check.OutputLength(output, outOff, len, "output buffer too short"); int inStart = inOff; int inEnd = inOff + len; int outStart = outOff; - while (inStart input, Span output) + { + Check.OutputLength(output, input.Length, "output buffer too short"); + + for (int i = 0; i < input.Length; ++i) + { + output[i] = CalculateByte(input[i]); + } + } +#endif + protected byte CalculateByte(byte b) { if (byteCount == 0) @@ -178,20 +182,28 @@ protected byte CalculateByte(byte b) */ public int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { - if (input.Length - inOff< GetBlockSize()) - { - throw new DataLengthException("Input buffer too short"); - } - if (output.Length - outOff< GetBlockSize()) - { - throw new DataLengthException("Output buffer too short"); - } + int blockSize = GetBlockSize(); + Check.DataLength(input, inOff, blockSize, "input buffer too short"); + Check.OutputLength(output, outOff, blockSize, "output buffer too short"); - ProcessBytes(input, inOff, GetBlockSize(), output, outOff); + ProcessBytes(input, inOff, blockSize, output, outOff); - return GetBlockSize(); + return blockSize; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessBlock(ReadOnlySpan input, Span output) + { + int blockSize = GetBlockSize(); + Check.DataLength(input, blockSize, "input buffer too short"); + Check.OutputLength(output, blockSize, "output buffer too short"); + + ProcessBytes(input[..blockSize], output); + + return blockSize; + } +#endif + /** * reset the chaining vector back to the IV and reset the underlying * cipher. @@ -202,7 +214,6 @@ public void Reset() { cipher.ProcessBlock(IV, 0, ofbV, 0); } - cipher.Reset(); byteCount = 0; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/OCBBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/OCBBlockCipher.cs index 6bee467..67cdd0d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/OCBBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/OCBBlockCipher.cs @@ -1,26 +1,27 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes { - /** - * An implementation of RFC 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.

- */ + /// An implementation of RFC 7253 on The OCB + /// Authenticated-Encryption Algorithm. + /// + /// For those still concerned about the original patents around this, please see: + /// https://mailarchive.ietf.org/arch/msg/cfrg/qLTveWOdTJcLn4HP3ev-vrj05Vg/ + /// Text reproduced below: + /// + /// Phillip Rogaway<rogaway@cs.ucdavis.edu> Sat, 27 February 2021 02:46 UTC + /// + /// I can confirm that I have abandoned all OCB patents and placed into the public domain all OCB-related IP of + /// mine. While I have been telling people this for quite some time, I don't think I ever made a proper announcement + /// to the CFRG or on the OCB webpage. Consider that done. + /// + /// public class OcbBlockCipher : IAeadBlockCipher { @@ -40,7 +41,7 @@ public class OcbBlockCipher * KEY-DEPENDENT */ // NOTE: elements are lazily calculated - private IList L; + private IList L; private byte[] L_Asterisk, L_Dollar; /* @@ -82,15 +83,9 @@ public OcbBlockCipher(IBlockCipher hashCipher, IBlockCipher mainCipher) this.mainCipher = mainCipher; } - public virtual IBlockCipher GetUnderlyingCipher() - { - return mainCipher; - } + public virtual string AlgorithmName => mainCipher.AlgorithmName + "/OCB"; - public virtual string AlgorithmName - { - get { return mainCipher.AlgorithmName + "/OCB"; } - } + public virtual IBlockCipher UnderlyingCipher => mainCipher; public virtual void Init(bool forEncryption, ICipherParameters parameters) { @@ -101,10 +96,8 @@ public virtual void Init(bool forEncryption, ICipherParameters parameters) KeyParameter keyParameter; byte[] N; - if (parameters is AeadParameters) + if (parameters is AeadParameters aeadParameters) { - AeadParameters aeadParameters = (AeadParameters) parameters; - N = aeadParameters.GetNonce(); initialAssociatedText = aeadParameters.GetAssociatedText(); @@ -115,10 +108,8 @@ public virtual void Init(bool forEncryption, ICipherParameters parameters) macSize = macSizeBits / 8; keyParameter = aeadParameters.Key; } - else if (parameters is ParametersWithIV) + else if (parameters is ParametersWithIV parametersWithIV) { - ParametersWithIV parametersWithIV = (ParametersWithIV) parameters; - N = parametersWithIV.GetIV(); initialAssociatedText = null; macSize = 16; @@ -163,7 +154,7 @@ public virtual void Init(bool forEncryption, ICipherParameters parameters) this.L_Dollar = OCB_double(L_Asterisk); - this.L = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + this.L = new List(); this.L.Add(OCB_double(L_Dollar)); /* @@ -289,6 +280,20 @@ public virtual void ProcessAadBytes(byte[] input, int off, int len) } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void ProcessAadBytes(ReadOnlySpan input) + { + for (int i = 0; i < input.Length; ++i) + { + hashBlock[hashBlockPos] = input[i]; + if (++hashBlockPos == hashBlock.Length) + { + ProcessHashBlock(); + } + } + } +#endif + public virtual int ProcessByte(byte input, byte[] output, int outOff) { mainBlock[mainBlockPos] = input; @@ -300,8 +305,24 @@ public virtual int ProcessByte(byte input, byte[] output, int outOff) return 0; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessByte(byte input, Span output) + { + mainBlock[mainBlockPos] = input; + if (++mainBlockPos == mainBlock.Length) + { + ProcessMainBlock(output); + return BLOCK_SIZE; + } + return 0; + } +#endif + public virtual int ProcessBytes(byte[] input, int inOff, int len, byte[] output, int outOff) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ProcessBytes(input.AsSpan(inOff, len), Spans.FromNullable(output, outOff)); +#else int resultLen = 0; for (int i = 0; i < len; ++i) @@ -314,11 +335,35 @@ public virtual int ProcessBytes(byte[] input, int inOff, int len, byte[] output, } } + return resultLen; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBytes(ReadOnlySpan input, Span output) + { + int len = input.Length; + int resultLen = 0; + + for (int i = 0; i < len; ++i) + { + mainBlock[mainBlockPos] = input[i]; + if (++mainBlockPos == mainBlock.Length) + { + ProcessMainBlock(output[resultLen..]); + resultLen += BLOCK_SIZE; + } + } + return resultLen; } +#endif public virtual int DoFinal(byte[] output, int outOff) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DoFinal(output.AsSpan(outOff)); +#else /* * For decryption, get the tag from the end of the message */ @@ -359,7 +404,7 @@ public virtual int DoFinal(byte[] output, int outOff) Xor(mainBlock, Pad); - Check.OutputLength(output, outOff, mainBlockPos, "Output buffer too short"); + Check.OutputLength(output, outOff, mainBlockPos, "output buffer too short"); Array.Copy(mainBlock, 0, output, outOff, mainBlockPos); if (!forEncryption) @@ -387,7 +432,7 @@ public virtual int DoFinal(byte[] output, int outOff) if (forEncryption) { - Check.OutputLength(output, outOff, resultLen + macSize, "Output buffer too short"); + Check.OutputLength(output, outOff, resultLen + macSize, "output buffer too short"); // Append tag to the message Array.Copy(macBlock, 0, output, outOff + resultLen, macSize); @@ -402,8 +447,99 @@ public virtual int DoFinal(byte[] output, int outOff) Reset(false); + return resultLen; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int DoFinal(Span output) + { + /* + * 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, mainBlockPos, "output buffer too short"); + mainBlock.AsSpan(0, mainBlockPos).CopyTo(output); + + 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) + { + // Append tag to the message + Check.OutputLength(output, resultLen + macSize, "output buffer too short"); + macBlock.AsSpan(0, macSize).CopyTo(output[resultLen..]); + 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; } +#endif public virtual void Reset() { @@ -422,9 +558,9 @@ protected virtual byte[] GetLSub(int n) { while (n >= L.Count) { - L.Add(OCB_double((byte[]) L[L.Count - 1])); + L.Add(OCB_double(L[L.Count - 1])); } - return (byte[])L[n]; + return L[n]; } protected virtual void ProcessHashBlock() @@ -466,11 +602,40 @@ protected virtual void ProcessMainBlock(byte[] output, int outOff) } } - protected virtual void Reset(bool clearMac) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + protected virtual void ProcessMainBlock(Span output) { - hashCipher.Reset(); - mainCipher.Reset(); + Check.DataLength(output, 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); + + mainBlock.AsSpan(0, BLOCK_SIZE).CopyTo(output); + + if (!forEncryption) + { + Xor(Checksum, mainBlock); + Array.Copy(mainBlock, BLOCK_SIZE, mainBlock, 0, macSize); + mainBlockPos = macSize; + } + } +#endif + + protected virtual void Reset(bool clearMac) + { Clear(hashBlock); Clear(mainBlock); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/OfbBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/OfbBlockCipher.cs index 5b31da6..cb9eeea 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/OfbBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/OfbBlockCipher.cs @@ -10,7 +10,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes * implements a Output-FeedBack (OFB) mode on top of a simple cipher. */ public class OfbBlockCipher - : IBlockCipher + : IBlockCipherMode { private byte[] IV; private byte[] ofbV; @@ -43,10 +43,7 @@ public OfbBlockCipher( * * @return the underlying block cipher that we are wrapping. */ - public IBlockCipher GetUnderlyingCipher() - { - return cipher; - } + public IBlockCipher UnderlyingCipher => cipher; /** * Initialise the cipher and, possibly, the initialisation vector (IV). @@ -63,9 +60,8 @@ public void Init( bool forEncryption, //ignored by this OFB mode ICipherParameters parameters) { - if (parameters is ParametersWithIV) + if (parameters is ParametersWithIV ivParam) { - ParametersWithIV ivParam = (ParametersWithIV)parameters; byte[] iv = ivParam.GetIV(); if (iv.Length < IV.Length) @@ -120,36 +116,38 @@ 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) + public int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { - if ((inOff + blockSize) > input.Length) - { - throw new DataLengthException("input buffer too short"); - } + Check.DataLength(input, inOff, blockSize, "input buffer too short"); + Check.OutputLength(output, outOff, blockSize, "output buffer too short"); + + cipher.ProcessBlock(ofbV, 0, ofbOutV, 0); - if ((outOff + blockSize) > output.Length) + // + // XOR the ofbV with the plaintext producing the cipher text (and + // the next input block). + // + for (int i = 0; i < blockSize; i++) { - throw new DataLengthException("output buffer too short"); + output[outOff + i] = (byte)(ofbOutV[i] ^ input[inOff + i]); } - cipher.ProcessBlock(ofbV, 0, ofbOutV, 0); + // + // 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; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessBlock(ReadOnlySpan input, Span output) + { + Check.DataLength(input, blockSize, "input buffer too short"); + Check.OutputLength(output, blockSize, "output buffer too short"); + + cipher.ProcessBlock(ofbV, ofbOutV); // // XOR the ofbV with the plaintext producing the cipher text (and @@ -157,7 +155,7 @@ public int ProcessBlock( // for (int i = 0; i < blockSize; i++) { - output[outOff + i] = (byte)(ofbOutV[i] ^ input[inOff + i]); + output[i] = (byte)(ofbOutV[i] ^ input[i]); } // @@ -168,6 +166,7 @@ public int ProcessBlock( return blockSize; } +#endif /** * reset the feedback vector back to the IV and reset the underlying @@ -176,11 +175,8 @@ public int ProcessBlock( public void Reset() { Array.Copy(IV, 0, ofbV, 0, IV.Length); - - cipher.Reset(); } } - } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/OpenPgpCfbBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/OpenPgpCfbBlockCipher.cs index 9321372..24ff92f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/OpenPgpCfbBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/OpenPgpCfbBlockCipher.cs @@ -16,7 +16,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes *

*/ public class OpenPgpCfbBlockCipher - : IBlockCipher + : IBlockCipherMode { private byte[] IV; private byte[] FR; @@ -45,15 +45,12 @@ public OpenPgpCfbBlockCipher( 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; - } + public IBlockCipher UnderlyingCipher => cipher; /** * return the algorithm name and mode. @@ -81,29 +78,29 @@ 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) + public int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { - return (forEncryption) ? EncryptBlock(input, inOff, output, outOff) : DecryptBlock(input, inOff, output, outOff); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return forEncryption + ? EncryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)) + : DecryptBlock(input.AsSpan(inOff), output.AsSpan(outOff)); +#else + return forEncryption + ? EncryptBlock(input, inOff, output, outOff) + : DecryptBlock(input, inOff, output, outOff); +#endif } - /** +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int ProcessBlock(ReadOnlySpan input, Span output) + { + return forEncryption + ? EncryptBlock(input, output) + : DecryptBlock(input, output); + } +#endif + + /** * reset the chaining vector back to the IV and reset the underlying * cipher. */ @@ -112,8 +109,6 @@ public void Reset() count = 0; Array.Copy(IV, 0, FR, 0, FR.Length); - - cipher.Reset(); } /** @@ -127,15 +122,12 @@ public void Reset() * @exception ArgumentException if the parameters argument is * inappropriate. */ - public void Init( - bool forEncryption, - ICipherParameters parameters) + public void Init(bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; - if (parameters is ParametersWithIV) + if (parameters is ParametersWithIV ivParam) { - ParametersWithIV ivParam = (ParametersWithIV)parameters; byte[] iv = ivParam.GetIV(); if (iv.Length < IV.Length) @@ -171,34 +163,132 @@ 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 NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int EncryptBlock(ReadOnlySpan input, Span output) { - if ((inOff + blockSize) > input.Length) + Check.DataLength(input, blockSize, "input buffer too short"); + Check.OutputLength(output, blockSize, "output buffer too short"); + + if (count > blockSize) { - throw new DataLengthException("input buffer too short"); + FR[blockSize - 2] = output[0] = EncryptByte(input[0], blockSize - 2); + FR[blockSize - 1] = output[1] = EncryptByte(input[1], blockSize - 1); + + cipher.ProcessBlock(FR, FRE); + + for (int n = 2; n < blockSize; n++) + { + FR[n - 2] = output[n] = EncryptByte(input[n], n - 2); + } } + else if (count == 0) + { + cipher.ProcessBlock(FR, FRE); - if ((outOff + blockSize) > outBytes.Length) + for (int n = 0; n < blockSize; n++) + { + FR[n] = output[n] = EncryptByte(input[n], n); + } + + count += blockSize; + } + else if (count == blockSize) { - throw new DataLengthException("output buffer too short"); + cipher.ProcessBlock(FR, FRE); + + output[0] = EncryptByte(input[0], 0); + output[1] = EncryptByte(input[1], 1); + + // + // do reset + // + Array.Copy(FR, 2, FR, 0, blockSize - 2); + output[..2].CopyTo(FR.AsSpan(blockSize - 2)); + + cipher.ProcessBlock(FR, FRE); + + for (int n = 2; n < blockSize; n++) + { + FR[n - 2] = output[n] = EncryptByte(input[n], n - 2); + } + + count += blockSize; } + return blockSize; + } + + private int DecryptBlock(ReadOnlySpan input, Span output) + { + Check.DataLength(input, blockSize, "input buffer too short"); + Check.OutputLength(output, blockSize, "output buffer too short"); + + if (count > blockSize) + { + byte inVal = input[0]; + FR[blockSize - 2] = inVal; + output[0] = EncryptByte(inVal, blockSize - 2); + + inVal = input[1]; + FR[blockSize - 1] = inVal; + output[1] = EncryptByte(inVal, blockSize - 1); + + cipher.ProcessBlock(FR, FRE); + + for (int n = 2; n < blockSize; n++) + { + inVal = input[n]; + FR[n - 2] = inVal; + output[n] = EncryptByte(inVal, n - 2); + } + } + else if (count == 0) + { + cipher.ProcessBlock(FR, FRE); + + for (int n = 0; n < blockSize; n++) + { + FR[n] = input[n]; + output[n] = EncryptByte(input[n], n); + } + + count += blockSize; + } + else if (count == blockSize) + { + cipher.ProcessBlock(FR, 0, FRE, 0); + + byte inVal1 = input[0]; + byte inVal2 = input[1]; + output[0] = EncryptByte(inVal1, 0); + output[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[n]; + FR[n - 2] = inVal; + output[n] = EncryptByte(inVal, n - 2); + } + + count += blockSize; + } + + return blockSize; + } +#else + private int EncryptBlock(byte[] input, int inOff, byte[] outBytes, int outOff) + { + Check.DataLength(input, inOff, blockSize, "input buffer too short"); + Check.OutputLength(outBytes, outOff, blockSize, "output buffer too short"); + if (count > blockSize) { FR[blockSize - 2] = outBytes[outOff] = EncryptByte(input[inOff], blockSize - 2); @@ -248,33 +338,10 @@ private int EncryptBlock( 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) + 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"); - } + Check.DataLength(input, inOff, blockSize, "input buffer too short"); + Check.OutputLength(outBytes, outOff, blockSize, "output buffer too short"); if (count > blockSize) { @@ -302,7 +369,7 @@ private int DecryptBlock( for (int n = 0; n < blockSize; n++) { FR[n] = input[inOff + n]; - outBytes[n] = EncryptByte(input[inOff + n], n); + outBytes[outOff + n] = EncryptByte(input[inOff + n], n); } count += blockSize; @@ -335,6 +402,7 @@ private int DecryptBlock( return blockSize; } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/SicBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/SicBlockCipher.cs index 014d29c..a556c23 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/SicBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/SicBlockCipher.cs @@ -14,7 +14,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes * block cipher. */ public class SicBlockCipher - : IBlockCipher + : IBlockCipherMode { private readonly IBlockCipher cipher; private readonly int blockSize; @@ -41,10 +41,7 @@ public SicBlockCipher(IBlockCipher cipher) * * @return the underlying block cipher that we are wrapping. */ - public virtual IBlockCipher GetUnderlyingCipher() - { - return cipher; - } + public IBlockCipher UnderlyingCipher => cipher; public virtual void Init( bool forEncryption, //ignored by this CTR mode @@ -87,11 +84,7 @@ public virtual int GetBlockSize() return cipher.GetBlockSize(); } - public virtual int ProcessBlock( - byte[] input, - int inOff, - byte[] output, - int outOff) + public virtual int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { cipher.ProcessBlock(counter, 0, counterOut, 0); @@ -112,11 +105,33 @@ public virtual int ProcessBlock( return counter.Length; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ProcessBlock(ReadOnlySpan input, Span output) + { + 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[i] = (byte)(counterOut[i] ^ input[i]); + } + + // Increment the counter + int j = counter.Length; + while (--j >= 0 && ++counter[j] == 0) + { + } + + return counter.Length; + } +#endif + public virtual void Reset() { Arrays.Fill(counter, (byte)0); Array.Copy(IV, 0, counter, 0, IV.Length); - cipher.Reset(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/BasicGcmExponentiator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/BasicGcmExponentiator.cs index e1cdc94..4f46941 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/BasicGcmExponentiator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/BasicGcmExponentiator.cs @@ -2,41 +2,39 @@ #pragma warning disable using System; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; - namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes.Gcm { public class BasicGcmExponentiator : IGcmExponentiator { - private ulong[] x; + private GcmUtilities.FieldElement x; public void Init(byte[] x) { - this.x = GcmUtilities.AsUlongs(x); + GcmUtilities.AsFieldElement(x, out this.x); } public void ExponentiateX(long pow, byte[] output) { - // Initial value is little-endian 1 - ulong[] y = GcmUtilities.OneAsUlongs(); + GcmUtilities.FieldElement y; + GcmUtilities.One(out y); if (pow > 0) { - ulong[] powX = Arrays.Clone(x); + GcmUtilities.FieldElement powX = x; do { if ((pow & 1L) != 0) { - GcmUtilities.Multiply(y, powX); + GcmUtilities.Multiply(ref y, ref powX); } - GcmUtilities.Square(powX, powX); + GcmUtilities.Square(ref powX); pow >>= 1; } while (pow > 0); } - GcmUtilities.AsBytes(y, output); + GcmUtilities.AsBytes(ref y, output); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/BasicGcmMultiplier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/BasicGcmMultiplier.cs index 8f26bd4..3370fd0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/BasicGcmMultiplier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/BasicGcmMultiplier.cs @@ -7,18 +7,18 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes.Gcm public class BasicGcmMultiplier : IGcmMultiplier { - private ulong[] H; + private GcmUtilities.FieldElement H; public void Init(byte[] H) { - this.H = GcmUtilities.AsUlongs(H); + GcmUtilities.AsFieldElement(H, out this.H); } public void MultiplyH(byte[] x) { - ulong[] t = GcmUtilities.AsUlongs(x); - GcmUtilities.Multiply(t, H); - GcmUtilities.AsBytes(t, x); + GcmUtilities.AsFieldElement(x, out var T); + GcmUtilities.Multiply(ref T, ref H); + GcmUtilities.AsBytes(ref T, x); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/GcmUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/GcmUtilities.cs index 8a088a7..8452cdc 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/GcmUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/GcmUtilities.cs @@ -1,6 +1,14 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Diagnostics; +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER +using System.Runtime.CompilerServices; +#endif +#if NETCOREAPP3_0_OR_GREATER +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; @@ -8,213 +16,120 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes.Gcm { - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] - internal static class GcmUtilities + internal abstract class GcmUtilities { - private const uint E1 = 0xe1000000; - private const ulong E1UL = (ulong)E1 << 32; - - 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) + internal struct FieldElement { - Pack.BE_To_UInt64(x, 0, z); + internal ulong n0, n1; } - internal static void AsUlongs(byte[] x, ulong[] z, int zOff) - { - Pack.BE_To_UInt64(x, 0, z, zOff, 2); - } + private const uint E1 = 0xe1000000; + private const ulong E1UL = (ulong)E1 << 32; - internal static void Copy(uint[] x, uint[] z) + internal static void One(out FieldElement x) { - z[0] = x[0]; - z[1] = x[1]; - z[2] = x[2]; - z[3] = x[3]; + x.n0 = 1UL << 63; + x.n1 = 0UL; } - internal static void Copy(ulong[] x, ulong[] z) +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif + internal static void AsBytes(ulong x0, ulong x1, byte[] z) { - z[0] = x[0]; - z[1] = x[1]; + Pack.UInt64_To_BE(x0, z, 0); + Pack.UInt64_To_BE(x1, z, 8); } - internal static void Copy(ulong[] x, int xOff, ulong[] z, int zOff) +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif + internal static void AsBytes(ref FieldElement x, byte[] z) { - z[zOff + 0] = x[xOff + 0]; - z[zOff + 1] = x[xOff + 1]; + AsBytes(x.n0, x.n1, z); } - internal static void DivideP(ulong[] x, ulong[] z) +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif + internal static void AsFieldElement(byte[] x, out FieldElement z) { - ulong x0 = x[0], x1 = x[1]; - ulong m = (ulong)((long)x0 >> 63); - x0 ^= (m & E1UL); - z[0] = (x0 << 1) | (x1 >> 63); - z[1] = (x1 << 1) | (ulong)(-(long)m); + z.n0 = Pack.BE_To_UInt64(x, 0); + z.n1 = Pack.BE_To_UInt64(x, 8); } - internal static void DivideP(ulong[] x, int xOff, ulong[] z, int zOff) + internal static void DivideP(ref FieldElement x, out FieldElement z) { - ulong x0 = x[xOff + 0], x1 = x[xOff + 1]; + ulong x0 = x.n0, x1 = x.n1; ulong m = (ulong)((long)x0 >> 63); x0 ^= (m & E1UL); - z[zOff + 0] = (x0 << 1) | (x1 >> 63); - z[zOff + 1] = (x1 << 1) | (ulong)(-(long)m); + z.n0 = (x0 << 1) | (x1 >> 63); + z.n1 = (x1 << 1) | (ulong)(-(long)m); } internal static void Multiply(byte[] x, byte[] y) { - ulong[] t1 = AsUlongs(x); - ulong[] t2 = AsUlongs(y); - Multiply(t1, t2); - AsBytes(t1, x); + AsFieldElement(x, out FieldElement X); + AsFieldElement(y, out FieldElement Y); + Multiply(ref X, ref Y); + AsBytes(ref X, x); } - internal static void Multiply(uint[] x, uint[] y) + internal static void Multiply(ref FieldElement x, ref FieldElement y) { - uint y0 = y[0], y1 = y[1], y2 = y[2], y3 = y[3]; - uint z0 = 0, z1 = 0, z2 = 0, z3 = 0; + ulong z0, z1, z2, z3; - for (int i = 0; i < 4; ++i) +#if NETCOREAPP3_0_OR_GREATER + if (Pclmulqdq.IsSupported) { - int bits = (int)x[i]; - for (int j = 0; j < 32; ++j) - { - uint m1 = (uint)(bits >> 31); bits <<= 1; - z0 ^= y0 & m1; - z1 ^= y1 & m1; - z2 ^= y2 & m1; - z3 ^= y3 & m1; - - uint m2 = (uint)((int)(y3 << 31) >> 8); - y3 = (y3 >> 1) | (y2 << 31); - y2 = (y2 >> 1) | (y1 << 31); - y1 = (y1 >> 1) | (y0 << 31); - y0 = (y0 >> 1) ^ (m2 & E1); - } + var X = Vector128.Create(x.n1, x.n0); + var Y = Vector128.Create(y.n1, y.n0); + + var Z0 = Pclmulqdq.CarrylessMultiply(X, Y, 0x00); + var Z1 = Sse2.Xor( + Pclmulqdq.CarrylessMultiply(X, Y, 0x01), + Pclmulqdq.CarrylessMultiply(X, Y, 0x10)); + var Z2 = Pclmulqdq.CarrylessMultiply(X, Y, 0x11); + + ulong t3 = Z0.GetElement(0); + ulong t2 = Z0.GetElement(1) ^ Z1.GetElement(0); + ulong t1 = Z2.GetElement(0) ^ Z1.GetElement(1); + ulong t0 = Z2.GetElement(1); + + z0 = (t0 << 1) | (t1 >> 63); + z1 = (t1 << 1) | (t2 >> 63); + z2 = (t2 << 1) | (t3 >> 63); + z3 = (t3 << 1); + } + else +#endif + { + /* + * "Three-way recursion" as described in "Batch binary Edwards", Daniel J. Bernstein. + * + * Without access to the high part of a 64x64 product x * y, we use a bit reversal to calculate it: + * rev(x) * rev(y) == rev((x * y) << 1) + */ + + ulong x0 = x.n0, x1 = x.n1; + ulong y0 = y.n0, y1 = y.n1; + ulong x0r = Longs.Reverse(x0), x1r = Longs.Reverse(x1); + ulong y0r = Longs.Reverse(y0), y1r = Longs.Reverse(y1); + + ulong h0 = Longs.Reverse(ImplMul64(x0r, y0r)); + ulong h1 = ImplMul64(x0, y0) << 1; + ulong h2 = Longs.Reverse(ImplMul64(x1r, y1r)); + ulong h3 = ImplMul64(x1, y1) << 1; + ulong h4 = Longs.Reverse(ImplMul64(x0r ^ x1r, y0r ^ y1r)); + ulong h5 = ImplMul64(x0 ^ x1, y0 ^ y1) << 1; + + z0 = h0; + z1 = h1 ^ h0 ^ h2 ^ h4; + z2 = h2 ^ h1 ^ h3 ^ h5; + z3 = h3; } - x[0] = z0; - x[1] = z1; - x[2] = z2; - x[3] = z3; - } - - internal static void Multiply(ulong[] x, ulong[] y) - { - //ulong x0 = x[0], x1 = x[1]; - //ulong y0 = y[0], y1 = y[1]; - //ulong z0 = 0, z1 = 0, z2 = 0; - - //for (int j = 0; j < 64; ++j) - //{ - // ulong m0 = (ulong)((long)x0 >> 63); x0 <<= 1; - // z0 ^= y0 & m0; - // z1 ^= y1 & m0; - - // ulong m1 = (ulong)((long)x1 >> 63); x1 <<= 1; - // z1 ^= y0 & m1; - // z2 ^= y1 & m1; - - // ulong c = (ulong)((long)(y1 << 63) >> 8); - // y1 = (y1 >> 1) | (y0 << 63); - // y0 = (y0 >> 1) ^ (c & E1UL); - //} - - //z0 ^= z2 ^ (z2 >> 1) ^ (z2 >> 2) ^ (z2 >> 7); - //z1 ^= (z2 << 63) ^ (z2 << 62) ^ (z2 << 57); - - //x[0] = z0; - //x[1] = z1; - - /* - * "Three-way recursion" as described in "Batch binary Edwards", Daniel J. Bernstein. - * - * Without access to the high part of a 64x64 product x * y, we use a bit reversal to calculate it: - * rev(x) * rev(y) == rev((x * y) << 1) - */ - - ulong x0 = x[0], x1 = x[1]; - ulong y0 = y[0], y1 = y[1]; - ulong x0r = Longs.Reverse(x0), x1r = Longs.Reverse(x1); - ulong y0r = Longs.Reverse(y0), y1r = Longs.Reverse(y1); - - ulong h0 = Longs.Reverse(ImplMul64(x0r, y0r)); - ulong h1 = ImplMul64(x0, y0) << 1; - ulong h2 = Longs.Reverse(ImplMul64(x1r, y1r)); - ulong h3 = ImplMul64(x1, y1) << 1; - ulong h4 = Longs.Reverse(ImplMul64(x0r ^ x1r, y0r ^ y1r)); - ulong h5 = ImplMul64(x0 ^ x1, y0 ^ y1) << 1; - - ulong z0 = h0; - ulong z1 = h1 ^ h0 ^ h2 ^ h4; - ulong z2 = h2 ^ h1 ^ h3 ^ h5; - ulong z3 = h3; + Debug.Assert(z3 << 63 == 0); z1 ^= z3 ^ (z3 >> 1) ^ (z3 >> 2) ^ (z3 >> 7); // z2 ^= (z3 << 63) ^ (z3 << 62) ^ (z3 << 57); @@ -223,155 +138,61 @@ internal static void Multiply(ulong[] x, ulong[] y) z0 ^= z2 ^ (z2 >> 1) ^ (z2 >> 2) ^ (z2 >> 7); z1 ^= (z2 << 63) ^ (z2 << 62) ^ (z2 << 57); - x[0] = z0; - x[1] = z1; - } - - internal static void MultiplyP(uint[] x) - { - uint x0 = x[0], x1 = x[1], x2 = x[2], x3 = x[3]; - uint m = (uint)((int)(x3 << 31) >> 31); - x[0] = (x0 >> 1) ^ (m & E1); - x[1] = (x1 >> 1) | (x0 << 31); - x[2] = (x2 >> 1) | (x1 << 31); - x[3] = (x3 >> 1) | (x2 << 31); + x.n0 = z0; + x.n1 = z1; } - internal static void MultiplyP(uint[] x, uint[] z) + internal static void MultiplyP7(ref FieldElement x) { - uint x0 = x[0], x1 = x[1], x2 = x[2], x3 = x[3]; - uint m = (uint)((int)(x3 << 31) >> 31); - z[0] = (x0 >> 1) ^ (m & E1); - z[1] = (x1 >> 1) | (x0 << 31); - z[2] = (x2 >> 1) | (x1 << 31); - z[3] = (x3 >> 1) | (x2 << 31); - } - - internal static void MultiplyP(ulong[] x) - { - ulong x0 = x[0], x1 = x[1]; - ulong m = (ulong)((long)(x1 << 63) >> 63); - x[0] = (x0 >> 1) ^ (m & E1UL); - x[1] = (x1 >> 1) | (x0 << 63); - } - - internal static void MultiplyP(ulong[] x, ulong[] z) - { - ulong x0 = x[0], x1 = x[1]; - ulong m = (ulong)((long)(x1 << 63) >> 63); - z[0] = (x0 >> 1) ^ (m & E1UL); - z[1] = (x1 >> 1) | (x0 << 63); - } - - internal static void MultiplyP3(ulong[] x, ulong[] z) - { - ulong x0 = x[0], x1 = x[1]; - ulong c = x1 << 61; - z[0] = (x0 >> 3) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); - z[1] = (x1 >> 3) | (x0 << 61); - } - - internal static void MultiplyP3(ulong[] x, int xOff, ulong[] z, int zOff) - { - ulong x0 = x[xOff + 0], x1 = x[xOff + 1]; - ulong c = x1 << 61; - z[zOff + 0] = (x0 >> 3) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); - z[zOff + 1] = (x1 >> 3) | (x0 << 61); - } - - internal static void MultiplyP4(ulong[] x, ulong[] z) - { - ulong x0 = x[0], x1 = x[1]; - ulong c = x1 << 60; - z[0] = (x0 >> 4) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); - z[1] = (x1 >> 4) | (x0 << 60); - } - - internal static void MultiplyP4(ulong[] x, int xOff, ulong[] z, int zOff) - { - ulong x0 = x[xOff + 0], x1 = x[xOff + 1]; - ulong c = x1 << 60; - z[zOff + 0] = (x0 >> 4) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); - z[zOff + 1] = (x1 >> 4) | (x0 << 60); - } - - internal static void MultiplyP7(ulong[] x, ulong[] z) - { - ulong x0 = x[0], x1 = x[1]; - ulong c = x1 << 57; - z[0] = (x0 >> 7) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); - z[1] = (x1 >> 7) | (x0 << 57); - } - - internal static void MultiplyP7(ulong[] x, int xOff, ulong[] z, int zOff) - { - ulong x0 = x[xOff + 0], x1 = x[xOff + 1]; + ulong x0 = x.n0, x1 = x.n1; ulong c = x1 << 57; - z[zOff + 0] = (x0 >> 7) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); - z[zOff + 1] = (x1 >> 7) | (x0 << 57); - } - - internal static void MultiplyP8(uint[] x) - { - uint x0 = x[0], x1 = x[1], x2 = x[2], x3 = x[3]; - uint c = x3 << 24; - x[0] = (x0 >> 8) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); - x[1] = (x1 >> 8) | (x0 << 24); - x[2] = (x2 >> 8) | (x1 << 24); - x[3] = (x3 >> 8) | (x2 << 24); + x.n0 = (x0 >> 7) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); + x.n1 = (x1 >> 7) | (x0 << 57); } - internal static void MultiplyP8(uint[] x, uint[] y) + internal static void MultiplyP8(ref FieldElement x) { - uint x0 = x[0], x1 = x[1], x2 = x[2], x3 = x[3]; - uint c = x3 << 24; - y[0] = (x0 >> 8) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); - y[1] = (x1 >> 8) | (x0 << 24); - y[2] = (x2 >> 8) | (x1 << 24); - y[3] = (x3 >> 8) | (x2 << 24); - } - - internal static void MultiplyP8(ulong[] x) - { - ulong x0 = x[0], x1 = x[1]; + ulong x0 = x.n0, x1 = x.n1; ulong c = x1 << 56; - x[0] = (x0 >> 8) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); - x[1] = (x1 >> 8) | (x0 << 56); + x.n0 = (x0 >> 8) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); + x.n1 = (x1 >> 8) | (x0 << 56); } - internal static void MultiplyP8(ulong[] x, ulong[] y) + internal static void MultiplyP8(ref FieldElement x, out FieldElement y) { - ulong x0 = x[0], x1 = x[1]; + ulong x0 = x.n0, x1 = x.n1; ulong c = x1 << 56; - y[0] = (x0 >> 8) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); - y[1] = (x1 >> 8) | (x0 << 56); + y.n0 = (x0 >> 8) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); + y.n1 = (x1 >> 8) | (x0 << 56); } - internal static void MultiplyP8(ulong[] x, int xOff, ulong[] y, int yOff) + internal static void MultiplyP16(ref FieldElement x) { - ulong x0 = x[xOff + 0], x1 = x[xOff + 1]; - ulong c = x1 << 56; - y[yOff + 0] = (x0 >> 8) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); - y[yOff + 1] = (x1 >> 8) | (x0 << 56); + ulong x0 = x.n0, x1 = x.n1; + ulong c = x1 << 48; + x.n0 = (x0 >> 16) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); + x.n1 = (x1 >> 16) | (x0 << 48); } - internal static void Square(ulong[] x, ulong[] z) + internal static void Square(ref FieldElement x) { - ulong[] t = new ulong[4]; - Interleave.Expand64To128Rev(x[0], t, 0); - Interleave.Expand64To128Rev(x[1], t, 2); + ulong z1 = Interleave.Expand64To128Rev(x.n0, out ulong z0); + ulong z3 = Interleave.Expand64To128Rev(x.n1, out ulong z2); - ulong z0 = t[0], z1 = t[1], z2 = t[2], z3 = t[3]; + Debug.Assert(z3 << 63 == 0); z1 ^= z3 ^ (z3 >> 1) ^ (z3 >> 2) ^ (z3 >> 7); // z2 ^= (z3 << 63) ^ (z3 << 62) ^ (z3 << 57); z2 ^= (z3 << 62) ^ (z3 << 57); + Debug.Assert(z2 << 63 == 0); + z0 ^= z2 ^ (z2 >> 1) ^ (z2 >> 2) ^ (z2 >> 7); - z1 ^= (z2 << 63) ^ (z2 << 62) ^ (z2 << 57); +// z1 ^= (z2 << 63) ^ (z2 << 62) ^ (z2 << 57); + z1 ^= (z2 << 62) ^ (z2 << 57); - z[0] = z0; - z[1] = z1; + x.n0 = z0; + x.n1 = z1; } internal static void Xor(byte[] x, byte[] y) @@ -400,19 +221,6 @@ internal static void Xor(byte[] x, byte[] y, int yOff) 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) @@ -429,58 +237,40 @@ internal static void Xor(byte[] x, int xOff, byte[] y, int yOff, int len) } } - internal static void Xor(byte[] x, byte[] y, byte[] z) + internal static void Xor(ref FieldElement x, ref FieldElement y) { - 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); + x.n0 ^= y.n0; + x.n1 ^= y.n1; } - internal static void Xor(uint[] x, uint[] y) + internal static void Xor(ref FieldElement x, ref FieldElement y, out FieldElement z) { - x[0] ^= y[0]; - x[1] ^= y[1]; - x[2] ^= y[2]; - x[3] ^= y[3]; + z.n0 = x.n0 ^ y.n0; + z.n1 = x.n1 ^ y.n1; } - internal static void Xor(uint[] x, uint[] y, uint[] z) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal static void Xor(Span x, ReadOnlySpan y) { - 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, int xOff, ulong[] y, int yOff) - { - x[xOff + 0] ^= y[yOff + 0]; - x[xOff + 1] ^= y[yOff + 1]; - } - - internal static void Xor(ulong[] x, ulong[] y, ulong[] z) - { - z[0] = x[0] ^ y[0]; - z[1] = x[1] ^ y[1]; + 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(ulong[] x, int xOff, ulong[] y, int yOff, ulong[] z, int zOff) + internal static void Xor(Span x, ReadOnlySpan y, int len) { - z[zOff + 0] = x[xOff + 0] ^ y[yOff + 0]; - z[zOff + 1] = x[xOff + 1] ^ y[yOff + 1]; + for (int i = 0; i < len; ++i) + { + x[i] ^= y[i]; + } } +#endif private static ulong ImplMul64(ulong x, ulong y) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/Tables1kGcmExponentiator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/Tables1kGcmExponentiator.cs index f341e2d..540e814 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/Tables1kGcmExponentiator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/Tables1kGcmExponentiator.cs @@ -1,9 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; - -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; +using System.Collections.Generic; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes.Gcm { @@ -12,34 +10,37 @@ public class Tables1kGcmExponentiator { // A lookup table of the power-of-two powers of 'x' // - lookupPowX2[i] = x^(2^i) - private IList lookupPowX2; + private IList lookupPowX2; public void Init(byte[] x) { - ulong[] y = GcmUtilities.AsUlongs(x); - if (lookupPowX2 != null && Arrays.AreEqual(y, (ulong[])lookupPowX2[0])) + GcmUtilities.FieldElement y; + GcmUtilities.AsFieldElement(x, out y); + if (lookupPowX2 != null && y.Equals(lookupPowX2[0])) return; - lookupPowX2 = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(8); + lookupPowX2 = new List(8); lookupPowX2.Add(y); } public void ExponentiateX(long pow, byte[] output) { - ulong[] y = GcmUtilities.OneAsUlongs(); + GcmUtilities.FieldElement y; + GcmUtilities.One(out y); int bit = 0; while (pow > 0) { if ((pow & 1L) != 0) { EnsureAvailable(bit); - GcmUtilities.Multiply(y, (ulong[])lookupPowX2[bit]); + GcmUtilities.FieldElement powX2 = (GcmUtilities.FieldElement)lookupPowX2[bit]; + GcmUtilities.Multiply(ref y, ref powX2); } ++bit; pow >>= 1; } - GcmUtilities.AsBytes(y, output); + GcmUtilities.AsBytes(ref y, output); } private void EnsureAvailable(int bit) @@ -47,12 +48,11 @@ private void EnsureAvailable(int bit) int count = lookupPowX2.Count; if (count <= bit) { - ulong[] tmp = (ulong[])lookupPowX2[count - 1]; + GcmUtilities.FieldElement powX2 = (GcmUtilities.FieldElement)lookupPowX2[count - 1]; do { - tmp = Arrays.Clone(tmp); - GcmUtilities.Square(tmp, tmp); - lookupPowX2.Add(tmp); + GcmUtilities.Square(ref powX2); + lookupPowX2.Add(powX2); } while (++count <= bit); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/Tables4kGcmMultiplier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/Tables4kGcmMultiplier.cs index d8162a7..10b611e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/Tables4kGcmMultiplier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/Tables4kGcmMultiplier.cs @@ -11,13 +11,13 @@ public class Tables4kGcmMultiplier : IGcmMultiplier { private byte[] H; - private ulong[] T; + private GcmUtilities.FieldElement[] T; public void Init(byte[] H) { if (T == null) { - T = new ulong[512]; + T = new GcmUtilities.FieldElement[256]; } else if (Arrays.AreEqual(this.H, H)) { @@ -29,44 +29,42 @@ public void Init(byte[] H) // T[0] = 0 // T[1] = H.p^7 - GcmUtilities.AsUlongs(this.H, T, 2); - GcmUtilities.MultiplyP7(T, 2, T, 2); + GcmUtilities.AsFieldElement(this.H, out T[1]); + GcmUtilities.MultiplyP7(ref T[1]); - for (int n = 2; n < 256; n += 2) + for (int n = 1; n < 128; ++n) { // T[2.n] = T[n].p^-1 - GcmUtilities.DivideP(T, n, T, n << 1); + GcmUtilities.DivideP(ref T[n], out T[n << 1]); // T[2.n + 1] = T[2.n] + T[1] - GcmUtilities.Xor(T, n << 1, T, 2, T, (n + 1) << 1); + GcmUtilities.Xor(ref T[n << 1], ref T[1], out T[(n << 1) + 1]); } } public void MultiplyH(byte[] x) { - //ulong[] z = new ulong[2]; - //GcmUtilities.Copy(T, x[15] << 1, z, 0); + //GcmUtilities.FieldElement z = T[x[15]]; //for (int i = 14; i >= 0; --i) //{ - // GcmUtilities.MultiplyP8(z); - // GcmUtilities.Xor(z, 0, T, x[i] << 1); + // GcmUtilities.MultiplyP8(ref z); + // GcmUtilities.Xor(ref z, ref T[x[i]]); //} - //Pack.UInt64_To_BE(z, x, 0); + //GcmUtilities.AsBytes(ref z, x); - int pos = x[15] << 1; - ulong z0 = T[pos + 0], z1 = T[pos + 1]; + int pos = x[15]; + ulong z0 = T[pos].n0, z1 = T[pos].n1; for (int i = 14; i >= 0; --i) { - pos = x[i] << 1; + pos = x[i]; ulong c = z1 << 56; - z1 = T[pos + 1] ^ ((z1 >> 8) | (z0 << 56)); - z0 = T[pos + 0] ^ (z0 >> 8) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); + z1 = T[pos].n1 ^ ((z1 >> 8) | (z0 << 56)); + z0 = T[pos].n0 ^ (z0 >> 8) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); } - Pack.UInt64_To_BE(z0, x, 0); - Pack.UInt64_To_BE(z1, x, 8); + GcmUtilities.AsBytes(z0, z1, x); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/Tables64kGcmMultiplier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/Tables64kGcmMultiplier.cs index cb1c36c..f1d5dc9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/Tables64kGcmMultiplier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/Tables64kGcmMultiplier.cs @@ -11,13 +11,13 @@ public class Tables64kGcmMultiplier : IGcmMultiplier { private byte[] H; - private ulong[][] T; + private GcmUtilities.FieldElement[][] T; public void Init(byte[] H) { if (T == null) { - T = new ulong[16][]; + T = new GcmUtilities.FieldElement[16][]; } else if (Arrays.AreEqual(this.H, H)) { @@ -28,56 +28,55 @@ public void Init(byte[] H) for (int i = 0; i < 16; ++i) { - ulong[] t = T[i] = new ulong[512]; + GcmUtilities.FieldElement[] t = T[i] = new GcmUtilities.FieldElement[256]; // t[0] = 0 if (i == 0) { // t[1] = H.p^7 - GcmUtilities.AsUlongs(this.H, t, 2); - GcmUtilities.MultiplyP7(t, 2, t, 2); - } + GcmUtilities.AsFieldElement(this.H, out t[1]); + GcmUtilities.MultiplyP7(ref t[1]); + } else - { + { // t[1] = T[i-1][1].p^8 - GcmUtilities.MultiplyP8(T[i - 1], 2, t, 2); + GcmUtilities.MultiplyP8(ref T[i - 1][1], out t[1]); } - for (int n = 2; n < 256; n += 2) + for (int n = 1; n < 128; ++n) { // t[2.n] = t[n].p^-1 - GcmUtilities.DivideP(t, n, t, n << 1); + GcmUtilities.DivideP(ref t[n], out t[n << 1]); // t[2.n + 1] = t[2.n] + t[1] - GcmUtilities.Xor(t, n << 1, t, 2, t, (n + 1) << 1); + GcmUtilities.Xor(ref t[n << 1], ref t[1], out t[(n << 1) + 1]); } } } public void MultiplyH(byte[] x) { - //ulong[] z = new ulong[2]; - //for (int i = 15; i >= 0; --i) + //GcmUtilities.FieldElement z = T[15][x[15]]; + //for (int i = 14; i >= 0; --i) //{ - // GcmUtilities.Xor(z, 0, T[i], x[i] << 1); + // GcmUtilities.Xor(ref z, ref T[i][x[i]]); //} - //Pack.UInt64_To_BE(z, x, 0); + //GcmUtilities.AsBytes(ref z, x); - ulong[] t = T[15]; - int tPos = x[15] << 1; - ulong z0 = t[tPos + 0], z1 = t[tPos + 1]; + GcmUtilities.FieldElement[] t = T[15]; + int tPos = x[15]; + ulong z0 = t[tPos].n0, z1 = t[tPos].n1; for (int i = 14; i >= 0; --i) { t = T[i]; - tPos = x[i] << 1; - z0 ^= t[tPos + 0]; - z1 ^= t[tPos + 1]; + tPos = x[i]; + z0 ^= t[tPos].n0; + z1 ^= t[tPos].n1; } - Pack.UInt64_To_BE(z0, x, 0); - Pack.UInt64_To_BE(z1, x, 8); + GcmUtilities.AsBytes(z0, z1, x); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/Tables8kGcmMultiplier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/Tables8kGcmMultiplier.cs index f47ddd2..d05c629 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/Tables8kGcmMultiplier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/modes/gcm/Tables8kGcmMultiplier.cs @@ -7,21 +7,17 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes.Gcm { - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] public sealed class Tables8kGcmMultiplier : IGcmMultiplier { private byte[] H; - private ulong[][] T; + private GcmUtilities.FieldElement[][] T; public void Init(byte[] H) { if (T == null) { - T = new ulong[32][]; + T = new GcmUtilities.FieldElement[2][]; } else if (Arrays.AreEqual(this.H, H)) { @@ -30,31 +26,31 @@ public void Init(byte[] H) this.H = Arrays.Clone(H); - for (int i = 0; i < 32; ++i) + for (int i = 0; i < 2; ++i) { - ulong[] t = T[i] = new ulong[32]; + GcmUtilities.FieldElement[] t = T[i] = new GcmUtilities.FieldElement[256]; // t[0] = 0 if (i == 0) - { - // t[1] = H.p^3 - GcmUtilities.AsUlongs(this.H, t, 2); - GcmUtilities.MultiplyP3(t, 2, t, 2); - } + { + // t[1] = H.p^7 + GcmUtilities.AsFieldElement(this.H, out t[1]); + GcmUtilities.MultiplyP7(ref t[1]); + } else - { - // t[1] = T[i-1][1].p^4 - GcmUtilities.MultiplyP4(T[i - 1], 2, t, 2); - } + { + // t[1] = T[i-1][1].p^8 + GcmUtilities.MultiplyP8(ref T[i - 1][1], out t[1]); + } - for (int n = 2; n < 16; n += 2) - { + for (int n = 1; n < 128; ++n) + { // t[2.n] = t[n].p^-1 - GcmUtilities.DivideP(t, n, t, n << 1); + GcmUtilities.DivideP(ref t[n], out t[n << 1]); // t[2.n + 1] = t[2.n] + t[1] - GcmUtilities.Xor(t, n << 1, t, 2, t, (n + 1) << 1); + GcmUtilities.Xor(ref t[n << 1], ref t[1], out t[(n << 1) + 1]); } } } @@ -62,27 +58,34 @@ public void Init(byte[] H) public void MultiplyH(byte[] x) { - //ulong[] z = new ulong[2]; - //for (int i = 15; i >= 0; --i) + GcmUtilities.FieldElement[] T0 = T[0], T1 = T[1]; + + //GcmUtilities.FieldElement z; + //GcmUtilities.Xor(ref T0[x[14]], ref T1[x[15]], out z); + //for (int i = 12; i >= 0; i -= 2) //{ - // GcmUtilities.Xor(z, 0, T[i + i + 1], (x[i] & 0x0F) << 1); - // GcmUtilities.Xor(z, 0, T[i + i], (x[i] & 0xF0) >> 3); + // GcmUtilities.MultiplyP16(ref z); + // GcmUtilities.Xor(ref z, ref T0[x[i]]); + // GcmUtilities.Xor(ref z, ref T1[x[i + 1]]); //} - //Pack.UInt64_To_BE(z, x, 0); + //GcmUtilities.AsBytes(ref z, x); - ulong z0 = 0, z1 = 0; + int vPos = x[15]; + int uPos = x[14]; + ulong z1 = T0[uPos].n1 ^ T1[vPos].n1; + ulong z0 = T0[uPos].n0 ^ T1[vPos].n0; - for (int i = 15; i >= 0; --i) - { - ulong[] tu = T[i + i + 1], tv = T[i + i]; - int uPos = (x[i] & 0x0F) << 1, vPos = (x[i] & 0xF0) >> 3; + for (int i = 12; i >= 0; i -= 2) + { + vPos = x[i + 1]; + uPos = x[i]; + + ulong c = z1 << 48; + z1 = T0[uPos].n1 ^ T1[vPos].n1 ^ ((z1 >> 16) | (z0 << 48)); + z0 = T0[uPos].n0 ^ T1[vPos].n0 ^ (z0 >> 16) ^ c ^ (c >> 1) ^ (c >> 2) ^ (c >> 7); + } - z0 ^= tu[uPos + 0] ^ tv[vPos + 0]; - z1 ^= tu[uPos + 1] ^ tv[vPos + 1]; - } - - Pack.UInt64_To_BE(z0, x, 0); - Pack.UInt64_To_BE(z1, x, 8); + GcmUtilities.AsBytes(z0, z1, x); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/Asn1CipherBuilder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/Asn1CipherBuilder.cs index 16eba35..93cef2e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/Asn1CipherBuilder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/Asn1CipherBuilder.cs @@ -1,19 +1,15 @@ #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.Ntt; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509; using BestHTTP.SecureProtocol.Org.BouncyCastle.Cms; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators { @@ -24,10 +20,7 @@ public class Asn1CipherBuilderWithKey : ICipherBuilderWithKey public Asn1CipherBuilderWithKey(DerObjectIdentifier encryptionOID, int keySize, SecureRandom random) { - if (random == null) - { - random = new SecureRandom(); - } + random = CryptoServicesRegistrar.GetSecureRandom(random); CipherKeyGenerator keyGen = CipherKeyGeneratorFactory.CreateKeyGenerator(encryptionOID, random); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/Asn1DigestFactory.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/Asn1DigestFactory.cs index 4aca159..dec8804 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/Asn1DigestFactory.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/Asn1DigestFactory.cs @@ -10,14 +10,15 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators { - public class Asn1DigestFactory : IDigestFactory + public class Asn1DigestFactory + : IDigestFactory { public static Asn1DigestFactory Get(DerObjectIdentifier oid) { return new Asn1DigestFactory(DigestUtilities.GetDigest(oid), oid); } - public static Asn1DigestFactory Get(String mechanism) + public static Asn1DigestFactory Get(string mechanism) { DerObjectIdentifier oid = DigestUtilities.GetObjectIdentifier(mechanism); return new Asn1DigestFactory(DigestUtilities.GetDigest(oid), oid); @@ -42,13 +43,14 @@ public virtual int DigestLength get { return mDigest.GetDigestSize(); } } - public virtual IStreamCalculator CreateCalculator() + public virtual IStreamCalculator CreateCalculator() { return new DfDigestStream(mDigest); } } - internal class DfDigestStream : IStreamCalculator + internal class DfDigestStream + : IStreamCalculator { private readonly DigestSink mStream; @@ -62,7 +64,7 @@ public Stream Stream get { return mStream; } } - public object GetResult() + public SimpleBlockResult GetResult() { byte[] result = new byte[mStream.Digest.GetDigestSize()]; mStream.Digest.DoFinal(result, 0); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/Asn1KeyWrapper.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/Asn1KeyWrapper.cs index a3a800d..a336f00 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/Asn1KeyWrapper.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/Asn1KeyWrapper.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist; @@ -11,7 +11,6 @@ using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Encodings; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines; using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.X509; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators @@ -157,26 +156,24 @@ internal class KeyWrapperUtil // // Provider // - private static readonly IDictionary providerMap = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + private static readonly Dictionary m_providerMap = + new Dictionary(StringComparer.OrdinalIgnoreCase); static KeyWrapperUtil() - { - providerMap.Add("RSA/ECB/PKCS1PADDING", new RsaOaepWrapperProvider(OiwObjectIdentifiers.IdSha1)); - providerMap.Add("RSA/NONE/PKCS1PADDING", new RsaOaepWrapperProvider(OiwObjectIdentifiers.IdSha1)); - providerMap.Add("RSA/NONE/OAEPWITHSHA1ANDMGF1PADDING", new RsaOaepWrapperProvider(OiwObjectIdentifiers.IdSha1)); - providerMap.Add("RSA/NONE/OAEPWITHSHA224ANDMGF1PADDING", new RsaOaepWrapperProvider(NistObjectIdentifiers.IdSha224)); - providerMap.Add("RSA/NONE/OAEPWITHSHA256ANDMGF1PADDING", new RsaOaepWrapperProvider(NistObjectIdentifiers.IdSha256)); - providerMap.Add("RSA/NONE/OAEPWITHSHA384ANDMGF1PADDING", new RsaOaepWrapperProvider(NistObjectIdentifiers.IdSha384)); - providerMap.Add("RSA/NONE/OAEPWITHSHA512ANDMGF1PADDING", new RsaOaepWrapperProvider(NistObjectIdentifiers.IdSha512)); - providerMap.Add("RSA/NONE/OAEPWITHSHA256ANDMGF1WITHSHA1PADDING", new RsaOaepWrapperProvider(NistObjectIdentifiers.IdSha256, OiwObjectIdentifiers.IdSha1)); + m_providerMap.Add("RSA/ECB/PKCS1PADDING", new RsaOaepWrapperProvider(OiwObjectIdentifiers.IdSha1)); + m_providerMap.Add("RSA/NONE/PKCS1PADDING", new RsaOaepWrapperProvider(OiwObjectIdentifiers.IdSha1)); + m_providerMap.Add("RSA/NONE/OAEPWITHSHA1ANDMGF1PADDING", new RsaOaepWrapperProvider(OiwObjectIdentifiers.IdSha1)); + m_providerMap.Add("RSA/NONE/OAEPWITHSHA224ANDMGF1PADDING", new RsaOaepWrapperProvider(NistObjectIdentifiers.IdSha224)); + m_providerMap.Add("RSA/NONE/OAEPWITHSHA256ANDMGF1PADDING", new RsaOaepWrapperProvider(NistObjectIdentifiers.IdSha256)); + m_providerMap.Add("RSA/NONE/OAEPWITHSHA384ANDMGF1PADDING", new RsaOaepWrapperProvider(NistObjectIdentifiers.IdSha384)); + m_providerMap.Add("RSA/NONE/OAEPWITHSHA512ANDMGF1PADDING", new RsaOaepWrapperProvider(NistObjectIdentifiers.IdSha512)); + m_providerMap.Add("RSA/NONE/OAEPWITHSHA256ANDMGF1WITHSHA1PADDING", new RsaOaepWrapperProvider(NistObjectIdentifiers.IdSha256, OiwObjectIdentifiers.IdSha1)); } public static IKeyWrapper WrapperForName(string algorithm, ICipherParameters parameters) { - WrapperProvider provider = (WrapperProvider)providerMap[Strings.ToUpperCase(algorithm)]; - - if (provider == null) + if (!m_providerMap.TryGetValue(algorithm, out var provider)) throw new ArgumentException("could not resolve " + algorithm + " to a KeyWrapper"); return (IKeyWrapper)provider.CreateWrapper(true, parameters); @@ -184,8 +181,7 @@ public static IKeyWrapper WrapperForName(string algorithm, ICipherParameters par public static IKeyUnwrapper UnwrapperForName(string algorithm, ICipherParameters parameters) { - WrapperProvider provider = (WrapperProvider)providerMap[Strings.ToUpperCase(algorithm)]; - if (provider == null) + if (!m_providerMap.TryGetValue(algorithm, out var provider)) throw new ArgumentException("could not resolve " + algorithm + " to a KeyUnwrapper"); return (IKeyUnwrapper)provider.CreateWrapper(false, parameters); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/Asn1Signature.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/Asn1Signature.cs index 130526f..244d01b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/Asn1Signature.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/Asn1Signature.cs @@ -1,110 +1,110 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; -using System.IO; +using System.Collections.Generic; 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.Rosstandart; 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.Crypto.Signers; 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(); + private static readonly IDictionary m_algorithms = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly IDictionary m_exParams = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly HashSet 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("SHA-1WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha1WithRsaEncryption); - algorithms.Add("SHA1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption); - algorithms.Add("SHA-1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption); - algorithms.Add("SHA224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption); - algorithms.Add("SHA-224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption); - algorithms.Add("SHA224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption); - algorithms.Add("SHA-224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption); - algorithms.Add("SHA256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption); - algorithms.Add("SHA-256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption); - algorithms.Add("SHA256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption); - algorithms.Add("SHA-256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption); - algorithms.Add("SHA384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption); - algorithms.Add("SHA-384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption); - algorithms.Add("SHA384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption); - algorithms.Add("SHA-384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption); - algorithms.Add("SHA512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption); - algorithms.Add("SHA-512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption); - algorithms.Add("SHA512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption); - algorithms.Add("SHA-512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption); - algorithms.Add("SHA512(224)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); - algorithms.Add("SHA-512(224)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); - algorithms.Add("SHA512(224)WITHRSA", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); - algorithms.Add("SHA-512(224)WITHRSA", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); - algorithms.Add("SHA512(256)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); - algorithms.Add("SHA-512(256)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); - algorithms.Add("SHA512(256)WITHRSA", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); - algorithms.Add("SHA-512(256)WITHRSA", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); - algorithms.Add("SHA3-224WITHRSAENCRYPTION", NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_224); - algorithms.Add("SHA3-256WITHRSAENCRYPTION", NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_256); - algorithms.Add("SHA3-384WITHRSAENCRYPTION", NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_384); - algorithms.Add("SHA3-512WITHRSAENCRYPTION", NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_512); - algorithms.Add("SHA3-224WITHRSA", NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_224); - algorithms.Add("SHA3-256WITHRSA", NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_256); - algorithms.Add("SHA3-384WITHRSA", NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_384); - algorithms.Add("SHA3-512WITHRSA", NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_512); - 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); + m_algorithms.Add("MD2WITHRSAENCRYPTION", PkcsObjectIdentifiers.MD2WithRsaEncryption); + m_algorithms.Add("MD2WITHRSA", PkcsObjectIdentifiers.MD2WithRsaEncryption); + m_algorithms.Add("MD5WITHRSAENCRYPTION", PkcsObjectIdentifiers.MD5WithRsaEncryption); + m_algorithms.Add("MD5WITHRSA", PkcsObjectIdentifiers.MD5WithRsaEncryption); + m_algorithms.Add("SHA1WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha1WithRsaEncryption); + m_algorithms.Add("SHA-1WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha1WithRsaEncryption); + m_algorithms.Add("SHA1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption); + m_algorithms.Add("SHA-1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption); + m_algorithms.Add("SHA224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption); + m_algorithms.Add("SHA-224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption); + m_algorithms.Add("SHA224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption); + m_algorithms.Add("SHA-224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption); + m_algorithms.Add("SHA256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption); + m_algorithms.Add("SHA-256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption); + m_algorithms.Add("SHA256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption); + m_algorithms.Add("SHA-256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption); + m_algorithms.Add("SHA384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption); + m_algorithms.Add("SHA-384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption); + m_algorithms.Add("SHA384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption); + m_algorithms.Add("SHA-384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption); + m_algorithms.Add("SHA512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption); + m_algorithms.Add("SHA-512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption); + m_algorithms.Add("SHA512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption); + m_algorithms.Add("SHA-512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption); + m_algorithms.Add("SHA512(224)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); + m_algorithms.Add("SHA-512(224)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); + m_algorithms.Add("SHA512(224)WITHRSA", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); + m_algorithms.Add("SHA-512(224)WITHRSA", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); + m_algorithms.Add("SHA512(256)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); + m_algorithms.Add("SHA-512(256)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); + m_algorithms.Add("SHA512(256)WITHRSA", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); + m_algorithms.Add("SHA-512(256)WITHRSA", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); + m_algorithms.Add("SHA3-224WITHRSAENCRYPTION", NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_224); + m_algorithms.Add("SHA3-256WITHRSAENCRYPTION", NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_256); + m_algorithms.Add("SHA3-384WITHRSAENCRYPTION", NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_384); + m_algorithms.Add("SHA3-512WITHRSAENCRYPTION", NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_512); + m_algorithms.Add("SHA3-224WITHRSA", NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_224); + m_algorithms.Add("SHA3-256WITHRSA", NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_256); + m_algorithms.Add("SHA3-384WITHRSA", NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_384); + m_algorithms.Add("SHA3-512WITHRSA", NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_512); + m_algorithms.Add("SHA1WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss); + m_algorithms.Add("SHA224WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss); + m_algorithms.Add("SHA256WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss); + m_algorithms.Add("SHA384WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss); + m_algorithms.Add("SHA512WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss); + m_algorithms.Add("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160); + m_algorithms.Add("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160); + m_algorithms.Add("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128); + m_algorithms.Add("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128); + m_algorithms.Add("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256); + m_algorithms.Add("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256); + m_algorithms.Add("SHA1WITHDSA", X9ObjectIdentifiers.IdDsaWithSha1); + m_algorithms.Add("DSAWITHSHA1", X9ObjectIdentifiers.IdDsaWithSha1); + m_algorithms.Add("SHA224WITHDSA", NistObjectIdentifiers.DsaWithSha224); + m_algorithms.Add("SHA256WITHDSA", NistObjectIdentifiers.DsaWithSha256); + m_algorithms.Add("SHA384WITHDSA", NistObjectIdentifiers.DsaWithSha384); + m_algorithms.Add("SHA512WITHDSA", NistObjectIdentifiers.DsaWithSha512); + m_algorithms.Add("SHA1WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha1); + m_algorithms.Add("ECDSAWITHSHA1", X9ObjectIdentifiers.ECDsaWithSha1); + m_algorithms.Add("SHA224WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha224); + m_algorithms.Add("SHA256WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha256); + m_algorithms.Add("SHA384WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha384); + m_algorithms.Add("SHA512WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha512); + m_algorithms.Add("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94); + m_algorithms.Add("GOST3411WITHGOST3410-94", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94); + m_algorithms.Add("GOST3411WITHECGOST3410", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001); + m_algorithms.Add("GOST3411WITHECGOST3410-2001", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001); + m_algorithms.Add("GOST3411WITHGOST3410-2001", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001); + m_algorithms.Add("GOST3411-2012-256WITHECGOST3410", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256); + m_algorithms.Add("GOST3411-2012-256WITHECGOST3410-2012-256", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256); + m_algorithms.Add("GOST3411-2012-512WITHECGOST3410", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512); + m_algorithms.Add("GOST3411-2012-512WITHECGOST3410-2012-512", RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512); + + // + // 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); @@ -126,19 +126,19 @@ static X509Utilities() // explicit params // AlgorithmIdentifier sha1AlgId = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance); - exParams.Add("SHA1WITHRSAANDMGF1", CreatePssParams(sha1AlgId, 20)); + m_exParams.Add("SHA1WITHRSAANDMGF1", CreatePssParams(sha1AlgId, 20)); AlgorithmIdentifier sha224AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha224, DerNull.Instance); - exParams.Add("SHA224WITHRSAANDMGF1", CreatePssParams(sha224AlgId, 28)); + m_exParams.Add("SHA224WITHRSAANDMGF1", CreatePssParams(sha224AlgId, 28)); AlgorithmIdentifier sha256AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256, DerNull.Instance); - exParams.Add("SHA256WITHRSAANDMGF1", CreatePssParams(sha256AlgId, 32)); + m_exParams.Add("SHA256WITHRSAANDMGF1", CreatePssParams(sha256AlgId, 32)); AlgorithmIdentifier sha384AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha384, DerNull.Instance); - exParams.Add("SHA384WITHRSAANDMGF1", CreatePssParams(sha384AlgId, 48)); + m_exParams.Add("SHA384WITHRSAANDMGF1", CreatePssParams(sha384AlgId, 48)); AlgorithmIdentifier sha512AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha512, DerNull.Instance); - exParams.Add("SHA512WITHRSAANDMGF1", CreatePssParams(sha512AlgId, 64)); + m_exParams.Add("SHA512WITHRSAANDMGF1", CreatePssParams(sha512AlgId, 64)); } /** @@ -196,6 +196,14 @@ private static string GetDigestAlgName( { return "GOST3411"; } + else if (RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256.Equals(digestAlgOID)) + { + return "GOST3411-2012-256"; + } + else if (RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512.Equals(digestAlgOID)) + { + return "GOST3411-2012-512"; + } else { return digestAlgOID.Id; @@ -206,7 +214,7 @@ internal static string GetSignatureName(AlgorithmIdentifier sigAlgId) { Asn1Encodable parameters = sigAlgId.Parameters; - if (parameters != null && !derNull.Equals(parameters)) + if (parameters != null && !DerNull.Instance.Equals(parameters)) { if (sigAlgId.Algorithm.Equals(PkcsObjectIdentifiers.IdRsassaPss)) { @@ -236,41 +244,28 @@ private static RsassaPssParameters CreatePssParams( new DerInteger(1)); } - internal static DerObjectIdentifier GetAlgorithmOid( - string algorithmName) + internal static DerObjectIdentifier GetAlgorithmOid(string algorithmName) { - algorithmName = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithmName); - - if (algorithms.Contains(algorithmName)) - { - return (DerObjectIdentifier) algorithms[algorithmName]; - } + if (m_algorithms.TryGetValue(algorithmName, out var oid)) + return oid; return new DerObjectIdentifier(algorithmName); } - internal static AlgorithmIdentifier GetSigAlgID( - DerObjectIdentifier sigOid, - string 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]); - } + if (m_exParams.TryGetValue(algorithmName, out var explicitParameters)) + return new AlgorithmIdentifier(sigOid, explicitParameters); return new AlgorithmIdentifier(sigOid, DerNull.Instance); } - internal static IEnumerable GetAlgNames() + internal static IEnumerable GetAlgNames() { - return new EnumerableProxy(algorithms.Keys); + return CollectionUtilities.Proxy(m_algorithms.Keys); } } @@ -321,12 +316,12 @@ public Asn1SignatureFactory(string algorithm, AsymmetricKeyParameter privateKey, this.algID = X509Utilities.GetSigAlgID(sigOid, algorithm); } - public Object AlgorithmDetails + public object AlgorithmDetails { get { return this.algID; } } - public IStreamCalculator CreateCalculator() + public IStreamCalculator CreateCalculator() { ISigner signer = SignerUtilities.InitSigner(algorithm, true, privateKey, random); @@ -336,7 +331,7 @@ public IStreamCalculator CreateCalculator() /// /// Allows enumeration of the signature names supported by the verifier provider. /// - public static IEnumerable SignatureAlgNames + public static IEnumerable SignatureAlgNames { get { return X509Utilities.GetAlgNames(); } } @@ -378,14 +373,13 @@ public Asn1VerifierFactory(AlgorithmIdentifier algorithm, AsymmetricKeyParameter this.algID = algorithm; } - public Object AlgorithmDetails + public object AlgorithmDetails { get { return this.algID; } } - public IStreamCalculator CreateCalculator() + public IStreamCalculator CreateCalculator() { - ISigner verifier = SignerUtilities.InitSigner(X509Utilities.GetSignatureName(algID), false, publicKey, null); return new DefaultVerifierCalculator(verifier); @@ -408,7 +402,7 @@ public Asn1VerifierFactoryProvider(AsymmetricKeyParameter publicKey) this.publicKey = publicKey; } - public IVerifierFactory CreateVerifierFactory(Object algorithmDetails) + public IVerifierFactory CreateVerifierFactory(object algorithmDetails) { return new Asn1VerifierFactory((AlgorithmIdentifier)algorithmDetails, publicKey); } @@ -416,7 +410,7 @@ public IVerifierFactory CreateVerifierFactory(Object algorithmDetails) /// /// Allows enumeration of the signature names supported by the verifier provider. /// - public IEnumerable SignatureAlgNames + public IEnumerable SignatureAlgNames { get { return X509Utilities.GetAlgNames(); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/CmsContentEncryptorBuilder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/CmsContentEncryptorBuilder.cs index c6905e5..013269d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/CmsContentEncryptorBuilder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/CmsContentEncryptorBuilder.cs @@ -1,18 +1,12 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; -using System.IO; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Nist; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ntt; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509; using BestHTTP.SecureProtocol.Org.BouncyCastle.Cms; -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.Crypto; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators; @@ -20,7 +14,8 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Operators { public class CmsContentEncryptorBuilder { - private static readonly IDictionary KeySizes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + private static readonly IDictionary KeySizes = + new Dictionary(); static CmsContentEncryptorBuilder() { @@ -35,12 +30,7 @@ static CmsContentEncryptorBuilder() private static int GetKeySize(DerObjectIdentifier oid) { - if (KeySizes.Contains(oid)) - { - return (int)KeySizes[oid]; - } - - return -1; + return KeySizes.TryGetValue(oid, out var keySize) ? keySize : -1; } private readonly DerObjectIdentifier encryptionOID; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/DefaultSignatureCalculator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/DefaultSignatureCalculator.cs index 4ed3ece..9eb113b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/DefaultSignatureCalculator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/DefaultSignatureCalculator.cs @@ -8,7 +8,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators { public class DefaultSignatureCalculator - : IStreamCalculator + : IStreamCalculator { private readonly SignerSink mSignerSink; @@ -22,7 +22,7 @@ public Stream Stream get { return mSignerSink; } } - public object GetResult() + public IBlockResult GetResult() { return new DefaultSignatureResult(mSignerSink.Signer); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/DefaultSignatureResult.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/DefaultSignatureResult.cs index 3d89f99..07e77e2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/DefaultSignatureResult.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/DefaultSignatureResult.cs @@ -25,6 +25,15 @@ public int Collect(byte[] sig, int sigOff) signature.CopyTo(sig, sigOff); return signature.Length; } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int Collect(Span destination) + { + byte[] result = Collect(); + result.CopyTo(destination); + return result.Length; + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/DefaultVerifierCalculator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/DefaultVerifierCalculator.cs index aa0a319..34675eb 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/DefaultVerifierCalculator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/operators/DefaultVerifierCalculator.cs @@ -8,7 +8,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators { public class DefaultVerifierCalculator - : IStreamCalculator + : IStreamCalculator { private readonly SignerSink mSignerSink; @@ -22,7 +22,7 @@ public Stream Stream get { return mSignerSink; } } - public object GetResult() + public IVerifier GetResult() { return new DefaultVerifierResult(mSignerSink.Signer); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/BlockCipherPadding.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/BlockCipherPadding.cs index 33d32ec..0454b34 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/BlockCipherPadding.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/BlockCipherPadding.cs @@ -1,47 +1,3 @@ #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/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/BlockCipherPadding.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/BlockCipherPadding.cs.meta index 8e84b31..2179569 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/BlockCipherPadding.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/BlockCipherPadding.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 4f24f6689dd124343ab88b53bbef3e26 +guid: 1991c05f84991634492c5a5943316444 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/IBlockCipherPadding.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/IBlockCipherPadding.cs new file mode 100644 index 0000000..bf6dc9c --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/IBlockCipherPadding.cs @@ -0,0 +1,47 @@ +#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.Paddings +{ + /// Block cipher padders are expected to conform to this interface. + public interface IBlockCipherPadding + { + /// Initialise the padder. + /// A source of randomness, if any required. + void Init(SecureRandom random); + + /// The name of the algorithm this padder implements. + string PaddingName { get; } + + /// Add padding to the passed in block. + /// the block to add padding to. + /// the offset into the block the padding is to start at. + /// the number of bytes of padding added. + int AddPadding(byte[] input, int inOff); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// Add padding to the passed in block. + /// the block to add padding to. + /// the offset into the block the padding is to start at. + /// the number of bytes of padding added. + int AddPadding(Span block, int position); +#endif + + /// Determine the length of padding present in the passed in block. + /// the block to check padding for. + /// the number of bytes of padding present. + int PadCount(byte[] input); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// Determine the length of padding present in the passed in block. + /// the block to check padding for. + /// the number of bytes of padding present. + int PadCount(ReadOnlySpan block); +#endif + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/IBlockCipherPadding.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/IBlockCipherPadding.cs.meta new file mode 100644 index 0000000..64c1e3a --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/IBlockCipherPadding.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: caf3bb6373773f848a9296be6ae067d0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/ISO10126d2Padding.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/ISO10126d2Padding.cs index 313b322..314be34 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/ISO10126d2Padding.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/ISO10126d2Padding.cs @@ -1,9 +1,8 @@ #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; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings { @@ -24,7 +23,7 @@ public void Init( SecureRandom random) //throws ArgumentException { - this.random = (random != null) ? random : new SecureRandom(); + this.random = CryptoServicesRegistrar.GetSecureRandom(random); } /** @@ -37,44 +36,58 @@ 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) + public int AddPadding(byte[] input, int inOff) { - byte code = (byte)(input.Length - inOff); - - while (inOff < (input.Length - 1)) + int count = input.Length - inOff; + if (count > 1) { - input[inOff] = (byte)random.NextInt(); - inOff++; + random.NextBytes(input, inOff, count - 1); } + input[input.Length - 1] = (byte)count; - input[inOff] = code; + return count; + } - return code; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int AddPadding(Span block, int position) + { + int count = block.Length - position; + if (count > 1) + { + random.NextBytes(block[position..(block.Length - 1)]); + } + block[block.Length - 1] = (byte)count; + + return count; } +#endif - /** - * return the number of pad bytes present in the block. - */ public int PadCount(byte[] input) - //throws InvalidCipherTextException { - int count = input[input.Length - 1] & 0xff; + int count = input[input.Length -1]; + int position = input.Length - count; - if (count > input.Length) - { + int failed = (position | (count - 1)) >> 31; + if (failed != 0) throw new InvalidCipherTextException("pad block corrupted"); - } return count; } - } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int PadCount(ReadOnlySpan block) + { + int count = block[block.Length - 1]; + int position = block.Length - count; + + int failed = (position | (count - 1)) >> 31; + if (failed != 0) + throw new InvalidCipherTextException("pad block corrupted"); + + return count; + } +#endif + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/ISO7816d4Padding.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/ISO7816d4Padding.cs index 18206dc..22805a3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/ISO7816d4Padding.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/ISO7816d4Padding.cs @@ -35,49 +35,67 @@ 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) + public int AddPadding(byte[] input, int inOff) { - int added = (input.Length - inOff); + int count = input.Length - inOff; - input[inOff]= (byte) 0x80; - inOff ++; - - while (inOff < input.Length) + input[inOff]= 0x80; + while (++inOff < input.Length) { - input[inOff] = (byte) 0; - inOff++; + input[inOff] = 0x00; } - return added; + return count; } - /** - * return the number of pad bytes present in the block. - */ - public int PadCount( - byte[] input) - { - int count = input.Length - 1; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int AddPadding(Span block, int position) + { + int count = block.Length - position; + block[position++] = 0x80; + block[position..].Fill(0x00); + return count; + } +#endif - while (count > 0 && input[count] == 0) + public int PadCount(byte[] input) + { + int position = -1, still00Mask = -1; + int i = input.Length; + while (--i >= 0) { - count--; + int next = input[i]; + int match00Mask = ((next ^ 0x00) - 1) >> 31; + int match80Mask = ((next ^ 0x80) - 1) >> 31; + position ^= (i ^ position) & still00Mask & match80Mask; + still00Mask &= match00Mask; } - - if (input[count] != (byte)0x80) - { + if (position < 0) throw new InvalidCipherTextException("pad block corrupted"); - } - return input.Length - count; + return input.Length - position; } - } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int PadCount(ReadOnlySpan block) + { + int position = -1, still00Mask = -1; + int i = block.Length; + while (--i >= 0) + { + int next = block[i]; + int match00Mask = ((next ^ 0x00) - 1) >> 31; + int match80Mask = ((next ^ 0x80) - 1) >> 31; + position ^= (i ^ position) & still00Mask & match80Mask; + still00Mask &= match00Mask; + } + if (position < 0) + throw new InvalidCipherTextException("pad block corrupted"); + + return block.Length - position; + } +#endif + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/PaddedBufferedBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/PaddedBufferedBlockCipher.cs index c68a5a7..f5d86ba 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/PaddedBufferedBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/PaddedBufferedBlockCipher.cs @@ -2,7 +2,7 @@ #pragma warning disable using System; -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.Security; @@ -18,22 +18,25 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings public class PaddedBufferedBlockCipher : BufferedBlockCipher { - private readonly IBlockCipherPadding padding; + private readonly IBlockCipherPadding padding; - /** + public PaddedBufferedBlockCipher(IBlockCipher cipher, IBlockCipherPadding padding) + : this(EcbBlockCipher.GetBlockCipherMode(cipher), 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) + public PaddedBufferedBlockCipher(IBlockCipherMode cipherMode, IBlockCipherPadding padding) { - this.cipher = cipher; + m_cipherMode = cipherMode; this.padding = padding; - buf = new byte[cipher.GetBlockSize()]; + buf = new byte[m_cipherMode.GetBlockSize()]; bufOff = 0; } @@ -42,9 +45,10 @@ public PaddedBufferedBlockCipher( * * @param cipher the underlying block cipher this buffering object wraps. */ - public PaddedBufferedBlockCipher( - IBlockCipher cipher) - : this(cipher, new Pkcs7Padding()) { } + public PaddedBufferedBlockCipher(IBlockCipherMode cipherMode) + : this(cipherMode, new Pkcs7Padding()) + { + } /** * initialise the cipher. @@ -55,23 +59,20 @@ public PaddedBufferedBlockCipher( * @exception ArgumentException if the parameters argument is * inappropriate. */ - public override void Init( - bool forEncryption, - ICipherParameters parameters) + public override void Init(bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; SecureRandom initRandom = null; - if (parameters is ParametersWithRandom) + if (parameters is ParametersWithRandom withRandom) { - ParametersWithRandom p = (ParametersWithRandom)parameters; - initRandom = p.Random; - parameters = p.Parameters; + initRandom = withRandom.Random; + parameters = withRandom.Parameters; } Reset(); padding.Init(initRandom); - cipher.Init(forEncryption, parameters); + m_cipherMode.Init(forEncryption, parameters); } /** @@ -112,8 +113,8 @@ public override int GetOutputSize( public override int GetUpdateOutputSize( int length) { - int total = length + bufOff; - int leftOver = total % buf.Length; + int total = length + bufOff; + int leftOver = total % buf.Length; if (leftOver == 0) { @@ -133,16 +134,29 @@ public override int GetUpdateOutputSize( * @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) + public override int ProcessByte(byte input, byte[] output, int outOff) + { + int resultLen = 0; + + if (bufOff == buf.Length) + { + resultLen = m_cipherMode.ProcessBlock(buf, 0, output, outOff); + bufOff = 0; + } + + buf[bufOff++] = input; + + return resultLen; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int ProcessByte(byte input, Span output) { int resultLen = 0; if (bufOff == buf.Length) { - resultLen = cipher.ProcessBlock(buf, 0, output, outOff); + resultLen = m_cipherMode.ProcessBlock(buf, output); bufOff = 0; } @@ -150,6 +164,7 @@ public override int ProcessByte( return resultLen; } +#endif /** * process an array of bytes, producing output if necessary. @@ -163,24 +178,17 @@ public override int ProcessByte( * @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) + 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"); + Check.OutputLength(output, outOff, outLength, "output buffer too short"); } int resultLen = 0; @@ -190,7 +198,7 @@ public override int ProcessBytes( { Array.Copy(input, inOff, buf, bufOff, gapLen); - resultLen += cipher.ProcessBlock(buf, 0, output, outOff); + resultLen = m_cipherMode.ProcessBlock(buf, 0, output, outOff); bufOff = 0; length -= gapLen; @@ -198,7 +206,7 @@ public override int ProcessBytes( while (length > buf.Length) { - resultLen += cipher.ProcessBlock(input, inOff, output, outOff + resultLen); + resultLen += m_cipherMode.ProcessBlock(input, inOff, output, outOff + resultLen); length -= blockSize; inOff += blockSize; @@ -212,7 +220,46 @@ public override int ProcessBytes( return resultLen; } - /** +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int ProcessBytes(ReadOnlySpan input, Span output) + { + int blockSize = GetBlockSize(); + int outLength = GetUpdateOutputSize(input.Length); + + if (outLength > 0) + { + Check.OutputLength(output, outLength, "output buffer too short"); + } + + int resultLen = 0; + int gapLen = buf.Length - bufOff; + + if (input.Length > gapLen) + { + input[..gapLen].CopyTo(buf.AsSpan(bufOff)); + + resultLen = m_cipherMode.ProcessBlock(buf, output); + + bufOff = 0; + input = input[gapLen..]; + + while (input.Length > buf.Length) + { + resultLen += m_cipherMode.ProcessBlock(input, output[resultLen..]); + + input = input[blockSize..]; + } + } + + input.CopyTo(buf.AsSpan(bufOff)); + + bufOff += input.Length; + + return resultLen; + } +#endif + + /** * 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. @@ -226,11 +273,9 @@ public override int ProcessBytes( * initialised. * @exception InvalidCipherTextException if padding is expected and not found. */ - public override int DoFinal( - byte[] output, - int outOff) - { - int blockSize = cipher.GetBlockSize(); + public override int DoFinal(byte[] output, int outOff) + { + int blockSize = m_cipherMode.GetBlockSize(); int resultLen = 0; if (forEncryption) @@ -244,13 +289,13 @@ public override int DoFinal( throw new OutputLengthException("output buffer too short"); } - resultLen = cipher.ProcessBlock(buf, 0, output, outOff); + resultLen = m_cipherMode.ProcessBlock(buf, 0, output, outOff); bufOff = 0; } padding.AddPadding(buf, bufOff); - resultLen += cipher.ProcessBlock(buf, 0, output, outOff + resultLen); + resultLen += m_cipherMode.ProcessBlock(buf, 0, output, outOff + resultLen); Reset(); } @@ -258,7 +303,7 @@ public override int DoFinal( { if (bufOff == blockSize) { - resultLen = cipher.ProcessBlock(buf, 0, buf, 0); + resultLen = m_cipherMode.ProcessBlock(buf, 0, buf, 0); bufOff = 0; } else @@ -282,8 +327,62 @@ public override int DoFinal( return resultLen; } - } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int DoFinal(Span output) + { + int blockSize = m_cipherMode.GetBlockSize(); + int resultLen = 0; + + if (forEncryption) + { + if (bufOff == blockSize) + { + if ((2 * blockSize) > output.Length) + { + Reset(); + + throw new OutputLengthException("output buffer too short"); + } + + resultLen = m_cipherMode.ProcessBlock(buf, output); + bufOff = 0; + } + + padding.AddPadding(buf, bufOff); + + resultLen += m_cipherMode.ProcessBlock(buf, output[resultLen..]); + + Reset(); + } + else + { + if (bufOff != blockSize) + { + Reset(); + + throw new DataLengthException("last block incomplete in decryption"); + } + + resultLen = m_cipherMode.ProcessBlock(buf, buf); + bufOff = 0; + + try + { + resultLen -= padding.PadCount(buf); + + buf.AsSpan(0, resultLen).CopyTo(output); + } + finally + { + Reset(); + } + } + + return resultLen; + } +#endif + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/Pkcs7Padding.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/Pkcs7Padding.cs index 2e1d4b6..0eeee52 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/Pkcs7Padding.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/Pkcs7Padding.cs @@ -34,47 +34,65 @@ 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) + public int AddPadding(byte[] input, int inOff) { - byte code = (byte)(input.Length - inOff); + int count = input.Length - inOff; + byte padValue = (byte)count; while (inOff < input.Length) { - input[inOff] = code; - inOff++; + input[inOff++] = padValue; } - return code; + return count; } - /** - * return the number of pad bytes present in the block. - */ - public int PadCount( - byte[] input) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int AddPadding(Span block, int position) + { + int count = block.Length - position; + byte padValue = (byte)count; + block[position..].Fill(padValue); + return count; + } +#endif + + public int PadCount(byte[] input) { - byte countAsByte = input[input.Length - 1]; - int count = countAsByte; + byte padValue = input[input.Length - 1]; + int count = padValue; + int position = input.Length - count; - if (count < 1 || count > input.Length) + int failed = (position | (count - 1)) >> 31; + for (int i = 0; i < input.Length; ++i) + { + failed |= (input[i] ^ padValue) & ~((i - position) >> 31); + } + if (failed != 0) throw new InvalidCipherTextException("pad block corrupted"); - for (int i = 2; i <= count; i++) + return count; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int PadCount(ReadOnlySpan block) + { + byte padValue = block[block.Length - 1]; + int count = padValue; + int position = block.Length - count; + + int failed = (position | (count - 1)) >> 31; + for (int i = 0; i < block.Length; ++i) { - if (input[input.Length - i] != countAsByte) - throw new InvalidCipherTextException("pad block corrupted"); + failed |= (block[i] ^ padValue) & ~((i - position) >> 31); } + if (failed != 0) + throw new InvalidCipherTextException("pad block corrupted"); return count; } +#endif } - } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/TbcPadding.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/TbcPadding.cs index 0ed6edc..04491be 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/TbcPadding.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/TbcPadding.cs @@ -1,7 +1,7 @@ #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 @@ -32,51 +32,73 @@ 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. - ///

- ///
+ /// add the pad bytes to the passed in block, returning the number of bytes added. + /// + /// This assumes that the last block of plain text is always passed to it inside . + /// i.e. if is zero, indicating the padding will fill the entire block,the value of + /// 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); - } + byte lastByte = inOff > 0 ? input[inOff - 1] : input[input.Length - 1]; + byte padValue = (byte)((lastByte & 1) - 1); while (inOff < input.Length) { - input[inOff] = code; - inOff++; + input[inOff++] = padValue; } return count; } - /// return the number of pad bytes present in the block. - public virtual int PadCount(byte[] input) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// add the pad bytes to the passed in block, returning the number of bytes added. + /// + /// This assumes that the last block of plain text is always passed to it inside . + /// i.e. if is zero, indicating the padding will fill the entire block,the value of + /// should be the same as the last block of plain text. + /// + public virtual int AddPadding(Span block, int position) { - byte code = input[input.Length - 1]; + byte lastByte = position > 0 ? block[position - 1] : block[block.Length - 1]; + byte padValue = (byte)((lastByte & 1) - 1); + + var padding = block[position..]; + padding.Fill(padValue); + return padding.Length; + } +#endif - int index = input.Length - 1; - while (index > 0 && input[index - 1] == code) + public virtual int PadCount(byte[] input) + { + int i = input.Length; + int code = input[--i], count = 1, countingMask = -1; + while (--i >= 0) { - index--; + int next = input[i]; + int matchMask = ((next ^ code) - 1) >> 31; + countingMask &= matchMask; + count -= countingMask; } + return count; + } - return input.Length - index; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int PadCount(ReadOnlySpan block) + { + int i = block.Length; + int code = block[--i], count = 1, countingMask = -1; + while (--i >= 0) + { + int next = block[i]; + int matchMask = ((next ^ code) - 1) >> 31; + countingMask &= matchMask; + count -= countingMask; + } + return count; } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/X923Padding.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/X923Padding.cs index 00296b1..843d790 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/X923Padding.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/X923Padding.cs @@ -2,8 +2,8 @@ #pragma warning disable using System; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings { @@ -37,49 +37,70 @@ 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) + public int AddPadding(byte[] input, int inOff) { - byte code = (byte)(input.Length - inOff); + int count = input.Length - inOff; + if (count > 1) + { + if (random == null) + { + Arrays.Fill(input, inOff, input.Length - 1, 0x00); + } + else + { + random.NextBytes(input, inOff, count - 1); + } + } + input[input.Length - 1] = (byte)count; + return count; + } - while (inOff < input.Length - 1) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int AddPadding(Span block, int position) + { + int count = block.Length - position; + if (count > 1) { + var body = block[position..(block.Length - 1)]; if (random == null) { - input[inOff] = 0; + body.Fill(0x00); } else { - input[inOff] = (byte)random.NextInt(); + random.NextBytes(body); } - inOff++; } + block[block.Length - 1] = (byte)count; + return count; + } +#endif + + public int PadCount(byte[] input) + { + int count = input[input.Length - 1]; + int position = input.Length - count; - input[inOff] = code; + int failed = (position | (count - 1)) >> 31; + if (failed != 0) + throw new InvalidCipherTextException("pad block corrupted"); - return code; + return count; } - /** - * return the number of pad bytes present in the block. - */ - public int PadCount( - byte[] input) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int PadCount(ReadOnlySpan block) { - int count = input[input.Length - 1] & 0xff; + int count = block[block.Length - 1]; + int position = block.Length - count; - if (count > input.Length) - { + int failed = (position | (count - 1)) >> 31; + if (failed != 0) throw new InvalidCipherTextException("pad block corrupted"); - } return count; } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/ZeroBytePadding.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/ZeroBytePadding.cs index 3033aef..352ba3f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/ZeroBytePadding.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/paddings/ZeroBytePadding.cs @@ -1,7 +1,7 @@ #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 @@ -30,42 +30,56 @@ 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) + public int AddPadding(byte[] input, int inOff) { - int added = (input.Length - inOff); + int added = input.Length - inOff; while (inOff < input.Length) { - input[inOff] = (byte) 0; - inOff++; + input[inOff++] = 0x00; } return added; } - /// return the number of pad bytes present in the block. - public int PadCount( - byte[] input) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int AddPadding(Span block, int position) { - int count = input.Length; + int count = block.Length - position; + block[position..].Fill(0x00); + return count; + } +#endif - while (count > 0) + public int PadCount(byte[] input) + { + int count = 0, still00Mask = -1; + int i = input.Length; + while (--i >= 0) { - if (input[count - 1] != 0) - { - break; - } - - count--; + int next = input[i]; + int match00Mask = ((next ^ 0x00) - 1) >> 31; + still00Mask &= match00Mask; + count -= still00Mask; } + return count; + } - return input.Length - count; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int PadCount(ReadOnlySpan block) + { + int count = 0, still00Mask = -1; + int i = block.Length; + while (--i >= 0) + { + int next = block[i]; + int match00Mask = ((next ^ 0x00) - 1) >> 31; + still00Mask &= match00Mask; + count -= still00Mask; + } + return count; } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Blake3Parameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Blake3Parameters.cs new file mode 100644 index 0000000..ebb096d --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Blake3Parameters.cs @@ -0,0 +1,62 @@ +#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 +{ + /// Blake3 Parameters. + public sealed class Blake3Parameters + : ICipherParameters + { + private const int KeyLen = 32; + + private byte[] m_theKey; + private byte[] m_theContext; + + /// Create a key parameter. + /// the context + /// the parameter + public static Blake3Parameters Context(byte[] pContext) + { + if (pContext == null) + throw new ArgumentNullException(nameof(pContext)); + + Blake3Parameters myParams = new Blake3Parameters(); + myParams.m_theContext = Arrays.Clone(pContext); + return myParams; + } + + /// Create a key parameter. + /// the key + /// the parameter + public static Blake3Parameters Key(byte[] pKey) + { + if (pKey == null) + throw new ArgumentNullException(nameof(pKey)); + if (pKey.Length != KeyLen) + throw new ArgumentException("Invalid key length", nameof(pKey)); + + Blake3Parameters myParams = new Blake3Parameters(); + myParams.m_theKey = Arrays.Clone(pKey); + return myParams; + } + + /// Obtain the key. + /// the key + public byte[] GetKey() => Arrays.Clone(m_theKey); + + /// Clear the key bytes. + public void ClearKey() + { + Arrays.Fill(m_theKey, 0); + } + + /// Obtain the salt. + /// the salt + public byte[] GetContext() => Arrays.Clone(m_theContext); + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Blake3Parameters.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Blake3Parameters.cs.meta new file mode 100644 index 0000000..d671705 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Blake3Parameters.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 60dacbbec400ae741a9e2ee85cc11106 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/DHKeyParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/DHKeyParameters.cs index afeef1d..8dc70ac 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/DHKeyParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/DHKeyParameters.cs @@ -59,7 +59,7 @@ public override bool Equals( protected bool Equals( DHKeyParameters other) { - return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(parameters, other.parameters) + return Org.BouncyCastle.Utilities.Platform.Equals(parameters, other.parameters) && base.Equals(other); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/DHParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/DHParameters.cs index 4f8d592..b064e6d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/DHParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/DHParameters.cs @@ -169,7 +169,7 @@ protected virtual bool Equals( { return p.Equals(other.p) && g.Equals(other.g) - && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(q, other.q); + && Org.BouncyCastle.Utilities.Platform.Equals(q, other.q); } public override int GetHashCode() diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/DesParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/DesParameters.cs index a43b013..07cb5ab 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/DesParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/DesParameters.cs @@ -137,6 +137,16 @@ public static void SetOddParity(byte[] bytes, int off, int len) bytes[off + i] = SetOddParity(bytes[off + i]); } } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void SetOddParity(Span bytes) + { + for (int i = 0; i < bytes.Length; i++) + { + bytes[i] = SetOddParity(bytes[i]); + } + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/DsaKeyParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/DsaKeyParameters.cs index 6511a09..a4c7236 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/DsaKeyParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/DsaKeyParameters.cs @@ -42,7 +42,7 @@ public override bool Equals( protected bool Equals( DsaKeyParameters other) { - return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(parameters, other.parameters) + return Org.BouncyCastle.Utilities.Platform.Equals(parameters, other.parameters) && base.Equals(other); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ECKeyParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ECKeyParameters.cs index c33e0c3..9c8112c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ECKeyParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ECKeyParameters.cs @@ -1,22 +1,29 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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" }; + // NB: Use a Dictionary so we can lookup the upper case version + private static readonly Dictionary Algorithms = + new Dictionary(StringComparer.OrdinalIgnoreCase) + { + { "EC", "EC" }, + { "ECDSA", "ECDSA" }, + { "ECDH", "ECDH" }, + { "ECDHC", "ECDHC" }, + { "ECGOST3410", "ECGOST3410" }, + { "ECMQV", "ECMQV" }, + }; private readonly string algorithm; private readonly ECDomainParameters parameters; @@ -106,9 +113,9 @@ internal ECKeyGenerationParameters CreateKeyGenerationParameters( 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"); + if (!Algorithms.TryGetValue(algorithm, out var upper)) + throw new ArgumentException("unrecognised algorithm: " + algorithm, nameof(algorithm)); + return upper; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ECPrivateKeyParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ECPrivateKeyParameters.cs index 174ff85..d478842 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ECPrivateKeyParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ECPrivateKeyParameters.cs @@ -20,15 +20,6 @@ public ECPrivateKeyParameters( { } - - public ECPrivateKeyParameters( - BigInteger d, - DerObjectIdentifier publicKeyParamSet) - : base("ECGOST3410", true, publicKeyParamSet) - { - this.d = Parameters.ValidatePrivateScalar(d); - } - public ECPrivateKeyParameters( string algorithm, BigInteger d, diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ECPublicKeyParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ECPublicKeyParameters.cs index c033a16..cb2f774 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ECPublicKeyParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ECPublicKeyParameters.cs @@ -20,15 +20,6 @@ public ECPublicKeyParameters( { } - - public ECPublicKeyParameters( - ECPoint q, - DerObjectIdentifier publicKeyParamSet) - : base("ECGOST3410", false, publicKeyParamSet) - { - this.q = ECDomainParameters.ValidatePublicPoint(Parameters.Curve, q); - } - public ECPublicKeyParameters( string algorithm, ECPoint q, diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Ed25519PrivateKeyParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Ed25519PrivateKeyParameters.cs index 7b7055b..3e284bb 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Ed25519PrivateKeyParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Ed25519PrivateKeyParameters.cs @@ -37,6 +37,17 @@ public Ed25519PrivateKeyParameters(byte[] buf, int off) Array.Copy(buf, off, data, 0, KeySize); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public Ed25519PrivateKeyParameters(ReadOnlySpan buf) + : base(true) + { + if (buf.Length != KeySize) + throw new ArgumentException("must have length " + KeySize, nameof(buf)); + + buf.CopyTo(data); + } +#endif + public Ed25519PrivateKeyParameters(Stream input) : base(true) { @@ -49,6 +60,13 @@ public void Encode(byte[] buf, int off) Array.Copy(data, 0, buf, off, KeySize); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Encode(Span buf) + { + data.CopyTo(buf); + } +#endif + public byte[] GetEncoded() { return Arrays.Clone(data); @@ -60,22 +78,21 @@ public Ed25519PublicKeyParameters GeneratePublicKey() { if (null == cachedPublicKey) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span publicKey = stackalloc byte[Ed25519.PublicKeySize]; + Ed25519.GeneratePublicKey(data, publicKey); + cachedPublicKey = new Ed25519PublicKeyParameters(publicKey); +#else byte[] publicKey = new byte[Ed25519.PublicKeySize]; Ed25519.GeneratePublicKey(data, 0, publicKey, 0); cachedPublicKey = new Ed25519PublicKeyParameters(publicKey, 0); +#endif } return cachedPublicKey; } } - - public void Sign(Ed25519.Algorithm algorithm, Ed25519PublicKeyParameters publicKey, byte[] ctx, byte[] msg, int msgOff, int msgLen, - byte[] sig, int sigOff) - { - Sign(algorithm, ctx, msg, msgOff, msgLen, sig, sigOff); - } - public void Sign(Ed25519.Algorithm algorithm, byte[] ctx, byte[] msg, int msgOff, int msgLen, byte[] sig, int sigOff) { @@ -117,7 +134,7 @@ public void Sign(Ed25519.Algorithm algorithm, byte[] ctx, byte[] msg, int msgOff private static byte[] Validate(byte[] buf) { if (buf.Length != KeySize) - throw new ArgumentException("must have length " + KeySize, "buf"); + throw new ArgumentException("must have length " + KeySize, nameof(buf)); return buf; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Ed25519PublicKeyParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Ed25519PublicKeyParameters.cs index 0425f56..45dc1f8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Ed25519PublicKeyParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Ed25519PublicKeyParameters.cs @@ -27,6 +27,17 @@ public Ed25519PublicKeyParameters(byte[] buf, int off) Array.Copy(buf, off, data, 0, KeySize); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public Ed25519PublicKeyParameters(ReadOnlySpan buf) + : base(false) + { + if (buf.Length != KeySize) + throw new ArgumentException("must have length " + KeySize, nameof(buf)); + + buf.CopyTo(data); + } +#endif + public Ed25519PublicKeyParameters(Stream input) : base(false) { @@ -39,6 +50,13 @@ public void Encode(byte[] buf, int off) Array.Copy(data, 0, buf, off, KeySize); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Encode(Span buf) + { + data.CopyTo(buf); + } +#endif + public byte[] GetEncoded() { return Arrays.Clone(data); @@ -47,7 +65,7 @@ public byte[] GetEncoded() private static byte[] Validate(byte[] buf) { if (buf.Length != KeySize) - throw new ArgumentException("must have length " + KeySize, "buf"); + throw new ArgumentException("must have length " + KeySize, nameof(buf)); return buf; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Ed448PrivateKeyParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Ed448PrivateKeyParameters.cs index 1a5a818..a9376cb 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Ed448PrivateKeyParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Ed448PrivateKeyParameters.cs @@ -37,6 +37,17 @@ public Ed448PrivateKeyParameters(byte[] buf, int off) Array.Copy(buf, off, data, 0, KeySize); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public Ed448PrivateKeyParameters(ReadOnlySpan buf) + : base(true) + { + if (buf.Length != KeySize) + throw new ArgumentException("must have length " + KeySize, nameof(buf)); + + buf.CopyTo(data); + } +#endif + public Ed448PrivateKeyParameters(Stream input) : base(true) { @@ -49,6 +60,13 @@ public void Encode(byte[] buf, int off) Array.Copy(data, 0, buf, off, KeySize); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Encode(Span buf) + { + data.CopyTo(buf); + } +#endif + public byte[] GetEncoded() { return Arrays.Clone(data); @@ -60,22 +78,21 @@ public Ed448PublicKeyParameters GeneratePublicKey() { if (null == cachedPublicKey) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span publicKey = stackalloc byte[Ed448.PublicKeySize]; + Ed448.GeneratePublicKey(data, publicKey); + cachedPublicKey = new Ed448PublicKeyParameters(publicKey); +#else byte[] publicKey = new byte[Ed448.PublicKeySize]; Ed448.GeneratePublicKey(data, 0, publicKey, 0); cachedPublicKey = new Ed448PublicKeyParameters(publicKey, 0); +#endif } return cachedPublicKey; } } - - public void Sign(Ed448.Algorithm algorithm, Ed448PublicKeyParameters publicKey, byte[] ctx, byte[] msg, int msgOff, int msgLen, - byte[] sig, int sigOff) - { - Sign(algorithm, ctx, msg, msgOff, msgLen, sig, sigOff); - } - public void Sign(Ed448.Algorithm algorithm, byte[] ctx, byte[] msg, int msgOff, int msgLen, byte[] sig, int sigOff) { @@ -109,7 +126,7 @@ public void Sign(Ed448.Algorithm algorithm, byte[] ctx, byte[] msg, int msgOff, private static byte[] Validate(byte[] buf) { if (buf.Length != KeySize) - throw new ArgumentException("must have length " + KeySize, "buf"); + throw new ArgumentException("must have length " + KeySize, nameof(buf)); return buf; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Ed448PublicKeyParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Ed448PublicKeyParameters.cs index 4a35fa9..0acd59e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Ed448PublicKeyParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/Ed448PublicKeyParameters.cs @@ -27,6 +27,17 @@ public Ed448PublicKeyParameters(byte[] buf, int off) Array.Copy(buf, off, data, 0, KeySize); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public Ed448PublicKeyParameters(ReadOnlySpan buf) + : base(false) + { + if (buf.Length != KeySize) + throw new ArgumentException("must have length " + KeySize, nameof(buf)); + + buf.CopyTo(data); + } +#endif + public Ed448PublicKeyParameters(Stream input) : base(false) { @@ -39,6 +50,13 @@ public void Encode(byte[] buf, int off) Array.Copy(data, 0, buf, off, KeySize); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Encode(Span buf) + { + data.CopyTo(buf); + } +#endif + public byte[] GetEncoded() { return Arrays.Clone(data); @@ -47,7 +65,7 @@ public byte[] GetEncoded() private static byte[] Validate(byte[] buf) { if (buf.Length != KeySize) - throw new ArgumentException("must have length " + KeySize, "buf"); + throw new ArgumentException("must have length " + KeySize, nameof(buf)); return buf; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ElGamalKeyParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ElGamalKeyParameters.cs index 04b6ae0..8536724 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ElGamalKeyParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ElGamalKeyParameters.cs @@ -42,7 +42,7 @@ public override bool Equals( protected bool Equals( ElGamalKeyParameters other) { - return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(parameters, other.parameters) + return Org.BouncyCastle.Utilities.Platform.Equals(parameters, other.parameters) && base.Equals(other); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/KdfParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/KdfParameters.cs index ed66588..5c65a86 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/KdfParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/KdfParameters.cs @@ -8,30 +8,28 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters /** * parameters for Key derivation functions for IEEE P1363a */ - public class KdfParameters : IDerivationParameters + public class KdfParameters + : IDerivationParameters { - byte[] iv; - byte[] shared; + private readonly byte[] m_iv; + private readonly byte[] m_shared; - public KdfParameters( - byte[] shared, - byte[] iv) + public KdfParameters(byte[] shared, byte[] iv) { - this.shared = shared; - this.iv = iv; + m_shared = shared; + m_iv = iv; } public byte[] GetSharedSecret() { - return shared; + return m_shared; } public byte[] GetIV() { - return iv; + return m_iv; } } - } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/KeyParameter.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/KeyParameter.cs index 8475f6e..8182b4c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/KeyParameter.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/KeyParameter.cs @@ -9,39 +9,41 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters public class KeyParameter : ICipherParameters { - private readonly byte[] key; + private readonly byte[] m_key; - public KeyParameter( - byte[] key) + public KeyParameter(byte[] key) { if (key == null) - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); - this.key = (byte[]) key.Clone(); + m_key = (byte[])key.Clone(); } - public KeyParameter( - byte[] key, - int keyOff, - int keyLen) + public KeyParameter(byte[] key, int keyOff, int keyLen) { if (key == null) - throw new ArgumentNullException("key"); + throw new ArgumentNullException(nameof(key)); if (keyOff < 0 || keyOff > key.Length) - throw new ArgumentOutOfRangeException("keyOff"); + throw new ArgumentOutOfRangeException(nameof(keyOff)); if (keyLen < 0 || keyLen > (key.Length - keyOff)) - throw new ArgumentOutOfRangeException("keyLen"); + throw new ArgumentOutOfRangeException(nameof(keyLen)); - this.key = new byte[keyLen]; - Array.Copy(key, keyOff, this.key, 0, keyLen); + m_key = new byte[keyLen]; + Array.Copy(key, keyOff, m_key, 0, keyLen); } - public byte[] GetKey() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public KeyParameter(ReadOnlySpan key) { - return (byte[]) key.Clone(); + m_key = key.ToArray(); } - } +#endif + public byte[] GetKey() + { + return (byte[])m_key.Clone(); + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/MgfParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/MgfParameters.cs index 51e86ab..1d4e38b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/MgfParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/MgfParameters.cs @@ -2,33 +2,44 @@ #pragma warning disable using System; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; + namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters { /// Parameters for mask derivation functions. - public class MgfParameters + public sealed class MgfParameters : IDerivationParameters { - private readonly byte[] seed; + private readonly byte[] m_seed; - public MgfParameters( - byte[] seed) + public MgfParameters(byte[] seed) : this(seed, 0, seed.Length) { } - public MgfParameters( - byte[] seed, - int off, - int len) + public MgfParameters(byte[] seed, int off, int len) { - this.seed = new byte[len]; - Array.Copy(seed, off, this.seed, 0, len); + m_seed = Arrays.CopyOfRange(seed, off, len); } - public byte[] GetSeed() + public byte[] GetSeed() { - return (byte[]) seed.Clone(); + return (byte[])m_seed.Clone(); } + + public void GetSeed(byte[] buffer, int offset) + { + m_seed.CopyTo(buffer, offset); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void GetSeed(Span output) + { + m_seed.CopyTo(output); + } +#endif + + public int SeedLength => m_seed.Length; } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/NaccacheSternKeyGenerationParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/NaccacheSternKeyGenerationParameters.cs index 71e9ce8..9517035 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/NaccacheSternKeyGenerationParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/NaccacheSternKeyGenerationParameters.cs @@ -49,32 +49,6 @@ public NaccacheSternKeyGenerationParameters( 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 - */ - - public NaccacheSternKeyGenerationParameters( - SecureRandom random, - int strength, - int certainty, - int countSmallPrimes, - bool debug) - : this(random, strength, certainty, countSmallPrimes) - { - } - /** * @return Returns the certainty. */ @@ -90,12 +64,6 @@ public int CountSmallPrimes { get { return countSmallPrimes; } } - - - public bool IsDebug - { - get { return false; } - } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/NaccacheSternPrivateKeyParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/NaccacheSternPrivateKeyParameters.cs index f21b1c0..84b089a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/NaccacheSternPrivateKeyParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/NaccacheSternPrivateKeyParameters.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; @@ -16,22 +16,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters 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 + private readonly IList smallPrimes; /** * Constructs a NaccacheSternPrivateKey @@ -52,7 +37,7 @@ public NaccacheSternPrivateKeyParameters( BigInteger g, BigInteger n, int lowerSigmaBound, - IList smallPrimes, + IList smallPrimes, BigInteger phiN) : base(true, g, n, lowerSigmaBound) { @@ -65,15 +50,7 @@ public BigInteger PhiN get { return phiN; } } -#if !(SILVERLIGHT || PORTABLE || NETFX_CORE) - - public ArrayList SmallPrimes - { - get { return new ArrayList(smallPrimes); } - } -#endif - - public IList SmallPrimesList + public IList SmallPrimesList { get { return smallPrimes; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ParametersWithID.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ParametersWithID.cs index cf57afd..f9c90ea 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ParametersWithID.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ParametersWithID.cs @@ -9,31 +9,34 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters public class ParametersWithID : ICipherParameters { - private readonly ICipherParameters parameters; - private readonly byte[] id; + private readonly ICipherParameters m_parameters; + private readonly byte[] m_id; - public ParametersWithID(ICipherParameters parameters, - byte[] id) + public ParametersWithID(ICipherParameters parameters, byte[] id) : this(parameters, id, 0, id.Length) { } - public ParametersWithID(ICipherParameters parameters, - byte[] id, int idOff, int idLen) + public ParametersWithID(ICipherParameters parameters, byte[] id, int idOff, int idLen) { - this.parameters = parameters; - this.id = Arrays.CopyOfRange(id, idOff, idOff + idLen); + m_parameters = parameters; + m_id = Arrays.CopyOfRange(id, idOff, idOff + idLen); } - public byte[] GetID() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public ParametersWithID(ICipherParameters parameters, ReadOnlySpan id) { - return id; + m_parameters = parameters; + m_id = id.ToArray(); } +#endif - public ICipherParameters Parameters + public byte[] GetID() { - get { return parameters; } + return m_id; } + + public ICipherParameters Parameters => m_parameters; } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ParametersWithIV.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ParametersWithIV.cs index ea03ebe..e46d3ce 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ParametersWithIV.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ParametersWithIV.cs @@ -9,35 +9,34 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters public class ParametersWithIV : ICipherParameters { - private readonly ICipherParameters parameters; - private readonly byte[] iv; + private readonly ICipherParameters m_parameters; + private readonly byte[] m_iv; - public ParametersWithIV(ICipherParameters parameters, - byte[] iv) + public ParametersWithIV(ICipherParameters parameters, byte[] iv) : this(parameters, iv, 0, iv.Length) { } - public ParametersWithIV(ICipherParameters parameters, - byte[] iv, int ivOff, int ivLen) + 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); + m_parameters = parameters; + m_iv = Arrays.CopyOfRange(iv, ivOff, ivOff + ivLen); } - public byte[] GetIV() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public ParametersWithIV(ICipherParameters parameters, ReadOnlySpan iv) { - return (byte[])iv.Clone(); + m_parameters = parameters; + m_iv = iv.ToArray(); } +#endif - public ICipherParameters Parameters + public byte[] GetIV() { - get { return parameters; } + return (byte[])m_iv.Clone(); } + + public ICipherParameters Parameters => m_parameters; } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ParametersWithRandom.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ParametersWithRandom.cs index a17922c..1bc36ce 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ParametersWithRandom.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ParametersWithRandom.cs @@ -9,43 +9,28 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters public class ParametersWithRandom : ICipherParameters { - private readonly ICipherParameters parameters; - private readonly SecureRandom random; + private readonly ICipherParameters m_parameters; + private readonly SecureRandom m_random; - public ParametersWithRandom( - ICipherParameters parameters, - SecureRandom random) + public ParametersWithRandom(ICipherParameters parameters) + : this(parameters, CryptoServicesRegistrar.GetSecureRandom()) { - 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()) + public ParametersWithRandom(ICipherParameters parameters, SecureRandom random) { - } - + if (parameters == null) + throw new ArgumentNullException(nameof(parameters)); + if (random == null) + throw new ArgumentNullException(nameof(random)); - public SecureRandom GetRandom() - { - return Random; + m_parameters = parameters; + m_random = random; } - public SecureRandom Random - { - get { return random; } - } + public ICipherParameters Parameters => m_parameters; - public ICipherParameters Parameters - { - get { return parameters; } - } + public SecureRandom Random => m_random; } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ParametersWithSalt.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ParametersWithSalt.cs index 84352f3..a4fd7b0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ParametersWithSalt.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/ParametersWithSalt.cs @@ -3,40 +3,43 @@ using System; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters { /// Cipher parameters with a fixed salt value associated with them. - public class ParametersWithSalt : ICipherParameters + public class ParametersWithSalt + : ICipherParameters { - private byte[] salt; - private ICipherParameters parameters; + private readonly ICipherParameters m_parameters; + private readonly byte[] m_salt; - public ParametersWithSalt(ICipherParameters parameters, byte[] salt):this(parameters, salt, 0, salt.Length) + 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); + m_parameters = parameters; + m_salt = Arrays.CopyOfRange(salt, saltOff, saltOff + saltLen); } - public byte[] GetSalt() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public ParametersWithSalt(ICipherParameters parameters, ReadOnlySpan salt) { - return salt; + m_parameters = parameters; + m_salt = salt.ToArray(); } +#endif - public ICipherParameters Parameters + public byte[] GetSalt() { - get - { - return parameters; - } + return m_salt; } + + public ICipherParameters Parameters => m_parameters; } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/RsaKeyParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/RsaKeyParameters.cs index dd2b1cf..57f8966 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/RsaKeyParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/RsaKeyParameters.cs @@ -4,6 +4,7 @@ using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters { @@ -25,6 +26,14 @@ private static BigInteger Validate(BigInteger modulus) if (!modulus.Gcd(SmallPrimesProduct).Equals(BigInteger.One)) throw new ArgumentException("RSA modulus has a small prime factor"); + int maxBitLength = AsInteger("BestHTTP.SecureProtocol.Org.BouncyCastle.Rsa.MaxSize", 15360); + + int modBitLength = modulus.BitLength; + if (maxBitLength < modBitLength) + { + throw new ArgumentException("modulus value out of range"); + } + // TODO: add additional primePower/Composite test - expensive!! return modulus; @@ -83,6 +92,18 @@ public override int GetHashCode() { return modulus.GetHashCode() ^ exponent.GetHashCode() ^ IsPrivate.GetHashCode(); } + + internal static int AsInteger(string envVariable, int defaultValue) + { + string v = Org.BouncyCastle.Utilities.Platform.GetEnvironmentVariable(envVariable); + + if (v == null) + { + return defaultValue; + } + + return int.Parse(v); + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/SkeinParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/SkeinParameters.cs index a93a8ac..b689ef5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/SkeinParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/SkeinParameters.cs @@ -1,11 +1,12 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.Globalization; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters { @@ -73,25 +74,24 @@ public class SkeinParameters ///
public const int PARAM_TYPE_OUTPUT = 63; - private IDictionary parameters; + private IDictionary m_parameters; public SkeinParameters() - : this(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable()) - + : this(new Dictionary()) { } - private SkeinParameters(IDictionary parameters) + private SkeinParameters(IDictionary parameters) { - this.parameters = parameters; + this.m_parameters = parameters; } /// /// Obtains a map of type (int) to value (byte[]) for the parameters tracked in this object. /// - public IDictionary GetParameters() + public IDictionary GetParameters() { - return parameters; + return m_parameters; } /// @@ -101,7 +101,7 @@ public IDictionary GetParameters() /// The key. public byte[] GetKey() { - return (byte[])parameters[PARAM_TYPE_KEY]; + return CollectionUtilities.GetValueOrNull(m_parameters, PARAM_TYPE_KEY); } /// @@ -110,7 +110,7 @@ public byte[] GetKey() /// public byte[] GetPersonalisation() { - return (byte[])parameters[PARAM_TYPE_PERSONALISATION]; + return CollectionUtilities.GetValueOrNull(m_parameters, PARAM_TYPE_PERSONALISATION); } /// @@ -119,7 +119,7 @@ public byte[] GetPersonalisation() /// public byte[] GetPublicKey() { - return (byte[])parameters[PARAM_TYPE_PUBLIC_KEY]; + return CollectionUtilities.GetValueOrNull(m_parameters, PARAM_TYPE_PUBLIC_KEY); } /// @@ -128,7 +128,7 @@ public byte[] GetPublicKey() /// public byte[] GetKeyIdentifier() { - return (byte[])parameters[PARAM_TYPE_KEY_IDENTIFIER]; + return CollectionUtilities.GetValueOrNull(m_parameters, PARAM_TYPE_KEY_IDENTIFIER); } /// @@ -137,7 +137,7 @@ public byte[] GetKeyIdentifier() /// public byte[] GetNonce() { - return (byte[])parameters[PARAM_TYPE_NONCE]; + return CollectionUtilities.GetValueOrNull(m_parameters, PARAM_TYPE_NONCE); } /// @@ -145,30 +145,21 @@ public byte[] GetNonce() /// public class Builder { - private IDictionary parameters = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + private Dictionary m_parameters; public Builder() { + m_parameters = new Dictionary(); } - public Builder(IDictionary paramsMap) + public Builder(IDictionary paramsMap) { - IEnumerator keys = paramsMap.Keys.GetEnumerator(); - while (keys.MoveNext()) - { - int key = (int)keys.Current; - parameters.Add(key, paramsMap[key]); - } + m_parameters = new Dictionary(paramsMap); } public Builder(SkeinParameters parameters) + : this(parameters.m_parameters) { - IEnumerator keys = parameters.parameters.Keys.GetEnumerator(); - while (keys.MoveNext()) - { - int key = (int)keys.Current; - this.parameters.Add(key, parameters.parameters[key]); - } } /// @@ -200,7 +191,7 @@ public Builder Set(int type, byte[] value) throw new ArgumentException("Parameter type " + PARAM_TYPE_CONFIG + " is reserved for internal use."); } - this.parameters.Add(type, value); + m_parameters.Add(type, value); return this; } @@ -236,14 +227,15 @@ public Builder SetPersonalisation(DateTime date, string emailAddress, string dis 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()); + using (var 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); + } + return Set(PARAM_TYPE_PERSONALISATION, bout.ToArray()); } catch (IOException e) { @@ -281,7 +273,7 @@ public Builder SetNonce(byte[] nonce) /// public SkeinParameters Build() { - return new SkeinParameters(parameters); + return new SkeinParameters(m_parameters); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/X25519PrivateKeyParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/X25519PrivateKeyParameters.cs index c2ca783..7d3edf3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/X25519PrivateKeyParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/X25519PrivateKeyParameters.cs @@ -35,6 +35,17 @@ public X25519PrivateKeyParameters(byte[] buf, int off) Array.Copy(buf, off, data, 0, KeySize); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public X25519PrivateKeyParameters(ReadOnlySpan buf) + : base(true) + { + if (buf.Length != KeySize) + throw new ArgumentException("must have length " + KeySize, nameof(buf)); + + buf.CopyTo(data); + } +#endif + public X25519PrivateKeyParameters(Stream input) : base(true) { @@ -47,6 +58,13 @@ public void Encode(byte[] buf, int off) Array.Copy(data, 0, buf, off, KeySize); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Encode(Span buf) + { + data.CopyTo(buf); + } +#endif + public byte[] GetEncoded() { return Arrays.Clone(data); @@ -54,23 +72,43 @@ public byte[] GetEncoded() public X25519PublicKeyParameters GeneratePublicKey() { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span publicKey = stackalloc byte[X25519.PointSize]; + X25519.GeneratePublicKey(data, publicKey); + return new X25519PublicKeyParameters(publicKey); +#else byte[] publicKey = new byte[X25519.PointSize]; X25519.GeneratePublicKey(data, 0, publicKey, 0); return new X25519PublicKeyParameters(publicKey, 0); +#endif } public void GenerateSecret(X25519PublicKeyParameters publicKey, byte[] buf, int off) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + GenerateSecret(publicKey, buf.AsSpan(off)); +#else 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"); +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void GenerateSecret(X25519PublicKeyParameters publicKey, Span buf) + { + Span encoded = stackalloc byte[X25519.PointSize]; + publicKey.Encode(encoded); + if (!X25519.CalculateAgreement(data, encoded, buf)) + throw new InvalidOperationException("X25519 agreement failed"); + } +#endif + private static byte[] Validate(byte[] buf) { if (buf.Length != KeySize) - throw new ArgumentException("must have length " + KeySize, "buf"); + throw new ArgumentException("must have length " + KeySize, nameof(buf)); return buf; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/X25519PublicKeyParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/X25519PublicKeyParameters.cs index bd450f1..21ffbc8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/X25519PublicKeyParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/X25519PublicKeyParameters.cs @@ -27,6 +27,17 @@ public X25519PublicKeyParameters(byte[] buf, int off) Array.Copy(buf, off, data, 0, KeySize); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public X25519PublicKeyParameters(ReadOnlySpan buf) + : base(false) + { + if (buf.Length != KeySize) + throw new ArgumentException("must have length " + KeySize, nameof(buf)); + + buf.CopyTo(data); + } +#endif + public X25519PublicKeyParameters(Stream input) : base(false) { @@ -39,6 +50,13 @@ public void Encode(byte[] buf, int off) Array.Copy(data, 0, buf, off, KeySize); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Encode(Span buf) + { + data.CopyTo(buf); + } +#endif + public byte[] GetEncoded() { return Arrays.Clone(data); @@ -47,7 +65,7 @@ public byte[] GetEncoded() private static byte[] Validate(byte[] buf) { if (buf.Length != KeySize) - throw new ArgumentException("must have length " + KeySize, "buf"); + throw new ArgumentException("must have length " + KeySize, nameof(buf)); return buf; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/X448PrivateKeyParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/X448PrivateKeyParameters.cs index 5210888..e63977e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/X448PrivateKeyParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/X448PrivateKeyParameters.cs @@ -35,6 +35,17 @@ public X448PrivateKeyParameters(byte[] buf, int off) Array.Copy(buf, off, data, 0, KeySize); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public X448PrivateKeyParameters(ReadOnlySpan buf) + : base(true) + { + if (buf.Length != KeySize) + throw new ArgumentException("must have length " + KeySize, nameof(buf)); + + buf.CopyTo(data); + } +#endif + public X448PrivateKeyParameters(Stream input) : base(true) { @@ -47,6 +58,13 @@ public void Encode(byte[] buf, int off) Array.Copy(data, 0, buf, off, KeySize); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Encode(Span buf) + { + data.CopyTo(buf); + } +#endif + public byte[] GetEncoded() { return Arrays.Clone(data); @@ -54,23 +72,43 @@ public byte[] GetEncoded() public X448PublicKeyParameters GeneratePublicKey() { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span publicKey = stackalloc byte[X448.PointSize]; + X448.GeneratePublicKey(data, publicKey); + return new X448PublicKeyParameters(publicKey); +#else byte[] publicKey = new byte[X448.PointSize]; X448.GeneratePublicKey(data, 0, publicKey, 0); return new X448PublicKeyParameters(publicKey, 0); +#endif } public void GenerateSecret(X448PublicKeyParameters publicKey, byte[] buf, int off) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + GenerateSecret(publicKey, buf.AsSpan(off)); +#else 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"); +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void GenerateSecret(X448PublicKeyParameters publicKey, Span buf) + { + Span encoded = stackalloc byte[X448.PointSize]; + publicKey.Encode(encoded); + if (!X448.CalculateAgreement(data, encoded, buf)) + throw new InvalidOperationException("X448 agreement failed"); + } +#endif + private static byte[] Validate(byte[] buf) { if (buf.Length != KeySize) - throw new ArgumentException("must have length " + KeySize, "buf"); + throw new ArgumentException("must have length " + KeySize, nameof(buf)); return buf; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/X448PublicKeyParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/X448PublicKeyParameters.cs index 4d72022..c2e4014 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/X448PublicKeyParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/parameters/X448PublicKeyParameters.cs @@ -27,6 +27,17 @@ public X448PublicKeyParameters(byte[] buf, int off) Array.Copy(buf, off, data, 0, KeySize); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public X448PublicKeyParameters(ReadOnlySpan buf) + : base(false) + { + if (buf.Length != KeySize) + throw new ArgumentException("must have length " + KeySize, nameof(buf)); + + buf.CopyTo(data); + } +#endif + public X448PublicKeyParameters(Stream input) : base(false) { @@ -39,6 +50,13 @@ public void Encode(byte[] buf, int off) Array.Copy(data, 0, buf, off, KeySize); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Encode(Span buf) + { + data.CopyTo(buf); + } +#endif + public byte[] GetEncoded() { return Arrays.Clone(data); @@ -47,7 +65,7 @@ public byte[] GetEncoded() private static byte[] Validate(byte[] buf) { if (buf.Length != KeySize) - throw new ArgumentException("must have length " + KeySize, "buf"); + throw new ArgumentException("must have length " + KeySize, nameof(buf)); return buf; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/BasicEntropySourceProvider.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/BasicEntropySourceProvider.cs index 0686621..d5f79bc 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/BasicEntropySourceProvider.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/BasicEntropySourceProvider.cs @@ -23,6 +23,9 @@ public class BasicEntropySourceProvider */ public BasicEntropySourceProvider(SecureRandom secureRandom, bool isPredictionResistant) { + if (secureRandom == null) + throw new ArgumentNullException(nameof(secureRandom)); + mSecureRandom = secureRandom; mPredictionResistant = isPredictionResistant; } @@ -48,6 +51,9 @@ private class BasicEntropySource internal BasicEntropySource(SecureRandom secureRandom, bool predictionResistant, int entropySize) { + if (secureRandom == null) + throw new ArgumentNullException(nameof(secureRandom)); + this.mSecureRandom = secureRandom; this.mPredictionResistant = predictionResistant; this.mEntropySize = entropySize; @@ -64,6 +70,15 @@ byte[] IEntropySource.GetEntropy() return SecureRandom.GetNextBytes(mSecureRandom, (mEntropySize + 7) / 8); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int IEntropySource.GetEntropy(Span output) + { + int length = (mEntropySize + 7) / 8; + mSecureRandom.NextBytes(output[..length]); + return length; + } +#endif + int IEntropySource.EntropySize { get { return mEntropySize; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/CryptoApiEntropySourceProvider.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/CryptoApiEntropySourceProvider.cs index f717ac6..a8350d3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/CryptoApiEntropySourceProvider.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/CryptoApiEntropySourceProvider.cs @@ -1,6 +1,5 @@ #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; @@ -59,6 +58,15 @@ byte[] IEntropySource.GetEntropy() return result; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int IEntropySource.GetEntropy(Span output) + { + int length = (mEntropySize + 7) / 8; + mRng.GetBytes(output[..length]); + return length; + } +#endif + int IEntropySource.EntropySize { get { return mEntropySize; } @@ -68,7 +76,5 @@ int IEntropySource.EntropySize } } } - -#endif #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/CryptoApiRandomGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/CryptoApiRandomGenerator.cs index 16366c5..c2816a0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/CryptoApiRandomGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/CryptoApiRandomGenerator.cs @@ -1,7 +1,5 @@ #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; @@ -10,40 +8,51 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng /// /// Uses RandomNumberGenerator.Create() to get randomness generator /// - public class CryptoApiRandomGenerator - : IRandomGenerator + public sealed class CryptoApiRandomGenerator + : IRandomGenerator, IDisposable { - private readonly RandomNumberGenerator rndProv; + private readonly RandomNumberGenerator m_randomNumberGenerator; public CryptoApiRandomGenerator() : this(RandomNumberGenerator.Create()) { } - public CryptoApiRandomGenerator(RandomNumberGenerator rng) + public CryptoApiRandomGenerator(RandomNumberGenerator randomNumberGenerator) { - this.rndProv = rng; + m_randomNumberGenerator = randomNumberGenerator ?? + throw new ArgumentNullException(nameof(randomNumberGenerator)); } #region IRandomGenerator Members - public virtual void AddSeedMaterial(byte[] seed) + public void AddSeedMaterial(byte[] seed) + { + // We don't care about the seed + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void AddSeedMaterial(ReadOnlySpan inSeed) { // We don't care about the seed } +#endif - public virtual void AddSeedMaterial(long seed) + public void AddSeedMaterial(long seed) { // We don't care about the seed } - public virtual void NextBytes(byte[] bytes) + public void NextBytes(byte[] bytes) { - rndProv.GetBytes(bytes); + m_randomNumberGenerator.GetBytes(bytes); } - public virtual void NextBytes(byte[] bytes, int start, int len) + public void NextBytes(byte[] bytes, int start, int len) { +#if NETCOREAPP2_0_OR_GREATER || NETSTANDARD2_0_OR_GREATER + m_randomNumberGenerator.GetBytes(bytes, start, len); +#else if (start < 0) throw new ArgumentException("Start offset cannot be negative", "start"); if (bytes.Length < (start + len)) @@ -59,12 +68,27 @@ public virtual void NextBytes(byte[] bytes, int start, int len) NextBytes(tmpBuf); Array.Copy(tmpBuf, 0, bytes, start, len); } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void NextBytes(Span bytes) + { + m_randomNumberGenerator.GetBytes(bytes); + } +#endif + + #endregion + + #region IDisposable Members + + public void Dispose() + { + m_randomNumberGenerator.Dispose(); } #endregion } } - -#endif #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/DigestRandomGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/DigestRandomGenerator.cs index 5b78243..adf57d3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/DigestRandomGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/DigestRandomGenerator.cs @@ -14,7 +14,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng * Internal access to the digest is synchronized so a single one of these can be shared. *

*/ - public class DigestRandomGenerator + public sealed class DigestRandomGenerator : IRandomGenerator { private const long CYCLE_COUNT = 10; @@ -25,8 +25,7 @@ public class DigestRandomGenerator private byte[] state; private byte[] seed; - public DigestRandomGenerator( - IDigest digest) + public DigestRandomGenerator(IDigest digest) { this.digest = digest; @@ -37,8 +36,7 @@ public DigestRandomGenerator( this.stateCounter = 1; } - public void AddSeedMaterial( - byte[] inSeed) + public void AddSeedMaterial(byte[] inSeed) { lock (this) { @@ -51,8 +49,22 @@ public void AddSeedMaterial( } } - public void AddSeedMaterial( - long rSeed) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void AddSeedMaterial(ReadOnlySpan inSeed) + { + lock (this) + { + if (!inSeed.IsEmpty) + { + DigestUpdate(inSeed); + } + DigestUpdate(seed); + DigestDoFinal(seed); + } + } +#endif + + public void AddSeedMaterial(long rSeed) { lock (this) { @@ -62,17 +74,16 @@ public void AddSeedMaterial( } } - public void NextBytes( - byte[] bytes) + public void NextBytes(byte[] bytes) { NextBytes(bytes, 0, bytes.Length); } - public void NextBytes( - byte[] bytes, - int start, - int len) + public void NextBytes(byte[] bytes, int start, int len) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + NextBytes(bytes.AsSpan(start, len)); +#else lock (this) { int stateOff = 0; @@ -90,7 +101,30 @@ public void NextBytes( bytes[i] = state[stateOff++]; } } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void NextBytes(Span bytes) + { + lock (this) + { + int stateOff = 0; + + GenerateState(); + + for (int i = 0; i < bytes.Length; ++i) + { + if (stateOff == state.Length) + { + GenerateState(); + stateOff = 0; + } + bytes[i] = state[stateOff++]; + } + } } +#endif private void CycleSeed() { @@ -112,23 +146,42 @@ private void GenerateState() } } - private void DigestAddCounter(long seedVal) - { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void DigestAddCounter(long seedVal) + { + Span bytes = stackalloc byte[8]; + Pack.UInt64_To_LE((ulong)seedVal, bytes); + digest.BlockUpdate(bytes); + } + + private void DigestUpdate(ReadOnlySpan inSeed) + { + digest.BlockUpdate(inSeed); + } + + private void DigestDoFinal(Span result) + { + digest.DoFinal(result); + } +#else + 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) + private void DigestUpdate(byte[] inSeed) { digest.BlockUpdate(inSeed, 0, inSeed.Length); } - private void DigestDoFinal(byte[] result) + private void DigestDoFinal(byte[] result) { digest.DoFinal(result, 0); } - } +#endif + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/IRandomGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/IRandomGenerator.cs index ebc5cbd..35f4087 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/IRandomGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/IRandomGenerator.cs @@ -11,9 +11,13 @@ public interface IRandomGenerator /// 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); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + void AddSeedMaterial(ReadOnlySpan seed); +#endif + + /// 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. @@ -24,6 +28,10 @@ public interface IRandomGenerator /// Index to start filling at. /// Length of segment to fill. void NextBytes(byte[] bytes, int start, int len); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + void NextBytes(Span bytes); +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/ReversedWindowGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/ReversedWindowGenerator.cs index 02e092e..3b1d777 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/ReversedWindowGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/ReversedWindowGenerator.cs @@ -1,102 +1,2 @@ #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/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/ReversedWindowGenerator.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/ReversedWindowGenerator.cs.meta index 659a1ce..e1f780f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/ReversedWindowGenerator.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/ReversedWindowGenerator.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 9c9b45d1f0973ac4a9db88250e6d0ebb +guid: d7aa93dd4975eb04d9800c845c274927 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/SP800SecureRandom.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/SP800SecureRandom.cs index a2e4d3a..2a1336d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/SP800SecureRandom.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/SP800SecureRandom.cs @@ -17,8 +17,9 @@ public class SP800SecureRandom private ISP80090Drbg mDrbg; - internal SP800SecureRandom(SecureRandom randomSource, IEntropySource entropySource, IDrbgProvider drbgProvider, bool predictionResistant) - : base((IRandomGenerator)null) + internal SP800SecureRandom(SecureRandom randomSource, IEntropySource entropySource, IDrbgProvider drbgProvider, + bool predictionResistant) + : base(null) { this.mRandomSource = randomSource; this.mEntropySource = entropySource; @@ -37,6 +38,19 @@ public override void SetSeed(byte[] seed) } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void SetSeed(Span seed) + { + lock (this) + { + if (mRandomSource != null) + { + this.mRandomSource.SetSeed(seed); + } + } + } +#endif + public override void SetSeed(long seed) { lock (this) @@ -51,6 +65,14 @@ public override void SetSeed(long seed) public override void NextBytes(byte[] bytes) { + NextBytes(bytes, 0, bytes.Length); + } + + public override void NextBytes(byte[] buf, int off, int len) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + NextBytes(buf.AsSpan(off, len)); +#else lock (this) { if (mDrbg == null) @@ -59,20 +81,34 @@ public override void NextBytes(byte[] bytes) } // check if a reseed is required... - if (mDrbg.Generate(bytes, null, mPredictionResistant) < 0) + if (mDrbg.Generate(buf, off, len, null, mPredictionResistant) < 0) { mDrbg.Reseed(null); - mDrbg.Generate(bytes, null, mPredictionResistant); + mDrbg.Generate(buf, off, len, null, mPredictionResistant); } } +#endif } - public override void NextBytes(byte[] buf, int off, int len) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void NextBytes(Span buffer) { - byte[] bytes = new byte[len]; - NextBytes(bytes); - Array.Copy(bytes, 0, buf, off, len); + lock (this) + { + if (mDrbg == null) + { + mDrbg = mDrbgProvider.Get(mEntropySource); + } + + // check if a reseed is required... + if (mDrbg.Generate(buffer, mPredictionResistant) < 0) + { + mDrbg.Reseed(ReadOnlySpan.Empty); + mDrbg.Generate(buffer, mPredictionResistant); + } + } } +#endif public override byte[] GenerateSeed(int numBytes) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/SP800SecureRandomBuilder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/SP800SecureRandomBuilder.cs index c7c9179..e6a8be1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/SP800SecureRandomBuilder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/SP800SecureRandomBuilder.cs @@ -28,7 +28,7 @@ public class SP800SecureRandomBuilder *

*/ public SP800SecureRandomBuilder() - : this(new SecureRandom(), false) + : this(CryptoServicesRegistrar.GetSecureRandom(), false) { } @@ -44,6 +44,9 @@ public SP800SecureRandomBuilder() */ public SP800SecureRandomBuilder(SecureRandom entropySource, bool predictionResistant) { + if (entropySource == null) + throw new ArgumentNullException(nameof(entropySource)); + this.mRandom = entropySource; this.mEntropySourceProvider = new BasicEntropySourceProvider(entropySource, predictionResistant); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/VMPCRandomGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/VMPCRandomGenerator.cs index b4840b0..fad4d00 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/VMPCRandomGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/VMPCRandomGenerator.cs @@ -6,11 +6,9 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng { - public class VmpcRandomGenerator + public sealed class VmpcRandomGenerator : IRandomGenerator { - private byte n = 0; - /// /// Permutation generated by code: /// @@ -30,88 +28,116 @@ public class VmpcRandomGenerator /// P[s & 0xff] = temp; /// } /// - private byte[] P = + private readonly byte[] P = { - (byte) 0xbb, (byte) 0x2c, (byte) 0x62, (byte) 0x7f, (byte) 0xb5, (byte) 0xaa, (byte) 0xd4, - (byte) 0x0d, (byte) 0x81, (byte) 0xfe, (byte) 0xb2, (byte) 0x82, (byte) 0xcb, (byte) 0xa0, (byte) 0xa1, - (byte) 0x08, (byte) 0x18, (byte) 0x71, (byte) 0x56, (byte) 0xe8, (byte) 0x49, (byte) 0x02, (byte) 0x10, - (byte) 0xc4, (byte) 0xde, (byte) 0x35, (byte) 0xa5, (byte) 0xec, (byte) 0x80, (byte) 0x12, (byte) 0xb8, - (byte) 0x69, (byte) 0xda, (byte) 0x2f, (byte) 0x75, (byte) 0xcc, (byte) 0xa2, (byte) 0x09, (byte) 0x36, - (byte) 0x03, (byte) 0x61, (byte) 0x2d, (byte) 0xfd, (byte) 0xe0, (byte) 0xdd, (byte) 0x05, (byte) 0x43, - (byte) 0x90, (byte) 0xad, (byte) 0xc8, (byte) 0xe1, (byte) 0xaf, (byte) 0x57, (byte) 0x9b, (byte) 0x4c, - (byte) 0xd8, (byte) 0x51, (byte) 0xae, (byte) 0x50, (byte) 0x85, (byte) 0x3c, (byte) 0x0a, (byte) 0xe4, - (byte) 0xf3, (byte) 0x9c, (byte) 0x26, (byte) 0x23, (byte) 0x53, (byte) 0xc9, (byte) 0x83, (byte) 0x97, - (byte) 0x46, (byte) 0xb1, (byte) 0x99, (byte) 0x64, (byte) 0x31, (byte) 0x77, (byte) 0xd5, (byte) 0x1d, - (byte) 0xd6, (byte) 0x78, (byte) 0xbd, (byte) 0x5e, (byte) 0xb0, (byte) 0x8a, (byte) 0x22, (byte) 0x38, - (byte) 0xf8, (byte) 0x68, (byte) 0x2b, (byte) 0x2a, (byte) 0xc5, (byte) 0xd3, (byte) 0xf7, (byte) 0xbc, - (byte) 0x6f, (byte) 0xdf, (byte) 0x04, (byte) 0xe5, (byte) 0x95, (byte) 0x3e, (byte) 0x25, (byte) 0x86, - (byte) 0xa6, (byte) 0x0b, (byte) 0x8f, (byte) 0xf1, (byte) 0x24, (byte) 0x0e, (byte) 0xd7, (byte) 0x40, - (byte) 0xb3, (byte) 0xcf, (byte) 0x7e, (byte) 0x06, (byte) 0x15, (byte) 0x9a, (byte) 0x4d, (byte) 0x1c, - (byte) 0xa3, (byte) 0xdb, (byte) 0x32, (byte) 0x92, (byte) 0x58, (byte) 0x11, (byte) 0x27, (byte) 0xf4, - (byte) 0x59, (byte) 0xd0, (byte) 0x4e, (byte) 0x6a, (byte) 0x17, (byte) 0x5b, (byte) 0xac, (byte) 0xff, - (byte) 0x07, (byte) 0xc0, (byte) 0x65, (byte) 0x79, (byte) 0xfc, (byte) 0xc7, (byte) 0xcd, (byte) 0x76, - (byte) 0x42, (byte) 0x5d, (byte) 0xe7, (byte) 0x3a, (byte) 0x34, (byte) 0x7a, (byte) 0x30, (byte) 0x28, - (byte) 0x0f, (byte) 0x73, (byte) 0x01, (byte) 0xf9, (byte) 0xd1, (byte) 0xd2, (byte) 0x19, (byte) 0xe9, - (byte) 0x91, (byte) 0xb9, (byte) 0x5a, (byte) 0xed, (byte) 0x41, (byte) 0x6d, (byte) 0xb4, (byte) 0xc3, - (byte) 0x9e, (byte) 0xbf, (byte) 0x63, (byte) 0xfa, (byte) 0x1f, (byte) 0x33, (byte) 0x60, (byte) 0x47, - (byte) 0x89, (byte) 0xf0, (byte) 0x96, (byte) 0x1a, (byte) 0x5f, (byte) 0x93, (byte) 0x3d, (byte) 0x37, - (byte) 0x4b, (byte) 0xd9, (byte) 0xa8, (byte) 0xc1, (byte) 0x1b, (byte) 0xf6, (byte) 0x39, (byte) 0x8b, - (byte) 0xb7, (byte) 0x0c, (byte) 0x20, (byte) 0xce, (byte) 0x88, (byte) 0x6e, (byte) 0xb6, (byte) 0x74, - (byte) 0x8e, (byte) 0x8d, (byte) 0x16, (byte) 0x29, (byte) 0xf2, (byte) 0x87, (byte) 0xf5, (byte) 0xeb, - (byte) 0x70, (byte) 0xe3, (byte) 0xfb, (byte) 0x55, (byte) 0x9f, (byte) 0xc6, (byte) 0x44, (byte) 0x4a, - (byte) 0x45, (byte) 0x7d, (byte) 0xe2, (byte) 0x6b, (byte) 0x5c, (byte) 0x6c, (byte) 0x66, (byte) 0xa9, - (byte) 0x8c, (byte) 0xee, (byte) 0x84, (byte) 0x13, (byte) 0xa7, (byte) 0x1e, (byte) 0x9d, (byte) 0xdc, - (byte) 0x67, (byte) 0x48, (byte) 0xba, (byte) 0x2e, (byte) 0xe6, (byte) 0xa4, (byte) 0xab, (byte) 0x7c, - (byte) 0x94, (byte) 0x00, (byte) 0x21, (byte) 0xef, (byte) 0xea, (byte) 0xbe, (byte) 0xca, (byte) 0x72, - (byte) 0x4f, (byte) 0x52, (byte) 0x98, (byte) 0x3f, (byte) 0xc2, (byte) 0x14, (byte) 0x7b, (byte) 0x3b, - (byte) 0x54 + 0xbb, 0x2c, 0x62, 0x7f, 0xb5, 0xaa, 0xd4, 0x0d, 0x81, 0xfe, 0xb2, 0x82, 0xcb, 0xa0, 0xa1, 0x08, + 0x18, 0x71, 0x56, 0xe8, 0x49, 0x02, 0x10, 0xc4, 0xde, 0x35, 0xa5, 0xec, 0x80, 0x12, 0xb8, 0x69, + 0xda, 0x2f, 0x75, 0xcc, 0xa2, 0x09, 0x36, 0x03, 0x61, 0x2d, 0xfd, 0xe0, 0xdd, 0x05, 0x43, 0x90, + 0xad, 0xc8, 0xe1, 0xaf, 0x57, 0x9b, 0x4c, 0xd8, 0x51, 0xae, 0x50, 0x85, 0x3c, 0x0a, 0xe4, 0xf3, + 0x9c, 0x26, 0x23, 0x53, 0xc9, 0x83, 0x97, 0x46, 0xb1, 0x99, 0x64, 0x31, 0x77, 0xd5, 0x1d, 0xd6, + 0x78, 0xbd, 0x5e, 0xb0, 0x8a, 0x22, 0x38, 0xf8, 0x68, 0x2b, 0x2a, 0xc5, 0xd3, 0xf7, 0xbc, 0x6f, + 0xdf, 0x04, 0xe5, 0x95, 0x3e, 0x25, 0x86, 0xa6, 0x0b, 0x8f, 0xf1, 0x24, 0x0e, 0xd7, 0x40, 0xb3, + 0xcf, 0x7e, 0x06, 0x15, 0x9a, 0x4d, 0x1c, 0xa3, 0xdb, 0x32, 0x92, 0x58, 0x11, 0x27, 0xf4, 0x59, + 0xd0, 0x4e, 0x6a, 0x17, 0x5b, 0xac, 0xff, 0x07, 0xc0, 0x65, 0x79, 0xfc, 0xc7, 0xcd, 0x76, 0x42, + 0x5d, 0xe7, 0x3a, 0x34, 0x7a, 0x30, 0x28, 0x0f, 0x73, 0x01, 0xf9, 0xd1, 0xd2, 0x19, 0xe9, 0x91, + 0xb9, 0x5a, 0xed, 0x41, 0x6d, 0xb4, 0xc3, 0x9e, 0xbf, 0x63, 0xfa, 0x1f, 0x33, 0x60, 0x47, 0x89, + 0xf0, 0x96, 0x1a, 0x5f, 0x93, 0x3d, 0x37, 0x4b, 0xd9, 0xa8, 0xc1, 0x1b, 0xf6, 0x39, 0x8b, 0xb7, + 0x0c, 0x20, 0xce, 0x88, 0x6e, 0xb6, 0x74, 0x8e, 0x8d, 0x16, 0x29, 0xf2, 0x87, 0xf5, 0xeb, 0x70, + 0xe3, 0xfb, 0x55, 0x9f, 0xc6, 0x44, 0x4a, 0x45, 0x7d, 0xe2, 0x6b, 0x5c, 0x6c, 0x66, 0xa9, 0x8c, + 0xee, 0x84, 0x13, 0xa7, 0x1e, 0x9d, 0xdc, 0x67, 0x48, 0xba, 0x2e, 0xe6, 0xa4, 0xab, 0x7c, 0x94, + 0x00, 0x21, 0xef, 0xea, 0xbe, 0xca, 0x72, 0x4f, 0x52, 0x98, 0x3f, 0xc2, 0x14, 0x7b, 0x3b, 0x54, }; /// Value generated in the same way as P. - private byte s = (byte) 0xbe; + private byte s = 0xbe; + private byte n = 0; public VmpcRandomGenerator() { } - public virtual void AddSeedMaterial(byte[] seed) + public void AddSeedMaterial(byte[] seed) { for (int m = 0; m < seed.Length; m++) { - s = P[(s + P[n & 0xff] + seed[m]) & 0xff]; - byte temp = P[n & 0xff]; - P[n & 0xff] = P[s & 0xff]; - P[s & 0xff] = temp; - n = (byte) ((n + 1) & 0xff); + byte pn = P[n]; + s = P[(s + pn + seed[m]) & 0xff]; + P[n] = P[s]; + P[s] = pn; + n = (byte)(n + 1); + } + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void AddSeedMaterial(ReadOnlySpan seed) + { + for (int m = 0; m < seed.Length; m++) + { + byte pn = P[n]; + s = P[(s + pn + seed[m]) & 0xff]; + P[n] = P[s]; + P[s] = pn; + n = (byte)(n + 1); } } +#endif - public virtual void AddSeedMaterial(long seed) + public void AddSeedMaterial(long seed) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span bytes = stackalloc byte[8]; + Pack.UInt64_To_BE((ulong)seed, bytes); + AddSeedMaterial(bytes); +#else AddSeedMaterial(Pack.UInt64_To_BE((ulong)seed)); +#endif } - public virtual void NextBytes(byte[] bytes) + public void NextBytes(byte[] bytes) { NextBytes(bytes, 0, bytes.Length); } - public virtual void NextBytes(byte[] bytes, int start, int len) + public void NextBytes(byte[] bytes, int start, int len) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + NextBytes(bytes.AsSpan(start, len)); +#else lock (P) { int end = start + len; for (int i = start; i != end; i++) { - s = P[(s + P[n & 0xff]) & 0xff]; - bytes[i] = P[(P[(P[s & 0xff]) & 0xff] + 1) & 0xff]; - byte temp = P[n & 0xff]; - P[n & 0xff] = P[s & 0xff]; - P[s & 0xff] = temp; - n = (byte) ((n + 1) & 0xff); + byte pn = P[n]; + s = P[(s + pn) & 0xFF]; + byte ps = P[s]; + bytes[i] = P[(P[ps] + 1) & 0xFF]; + P[s] = pn; + P[n] = ps; + n = (byte)(n + 1); + } + } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void NextBytes(Span bytes) + { + lock (P) + { + for (int i = 0; i < bytes.Length; ++i) + { + byte pn = P[n]; + s = P[(s + pn) & 0xFF]; + byte ps = P[s]; + bytes[i] = P[(P[ps] + 1) & 0xFF]; + P[s] = pn; + P[n] = ps; + n = (byte)(n + 1); } } } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/X931Rng.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/X931Rng.cs index b4a4fd5..07115d7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/X931Rng.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/X931Rng.cs @@ -40,6 +40,66 @@ internal X931Rng(IBlockCipher engine, byte[] dateTimeVector, IEntropySource entr this.mR = new byte[engine.GetBlockSize()]; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal int Generate(Span output, bool predictionResistant) + { + int outputLen = output.Length; + + if (mR.Length == 8) // 64 bit block size + { + if (mReseedCounter > BLOCK64_RESEED_MAX) + return -1; + + if (outputLen > BLOCK64_MAX_BITS_REQUEST / 8) + throw new ArgumentException("Number of bits per request limited to " + BLOCK64_MAX_BITS_REQUEST, "output"); + } + else + { + if (mReseedCounter > BLOCK128_RESEED_MAX) + return -1; + + if (outputLen > BLOCK128_MAX_BITS_REQUEST / 8) + throw new ArgumentException("Number of bits per request limited to " + BLOCK128_MAX_BITS_REQUEST, "output"); + } + + if (predictionResistant || mV == null) + { + mV = mEntropySource.GetEntropy(); + if (mV.Length != mEngine.GetBlockSize()) + throw new InvalidOperationException("Insufficient entropy returned"); + } + + int m = outputLen / mR.Length; + + for (int i = 0; i < m; i++) + { + mEngine.ProcessBlock(mDT, mI); + Process(mR, mI, mV); + Process(mV, mR, mI); + + mR.CopyTo(output[(i * mR.Length)..]); + + Increment(mDT); + } + + int bytesToCopy = outputLen - m * mR.Length; + + if (bytesToCopy > 0) + { + mEngine.ProcessBlock(mDT, mI); + Process(mR, mI, mV); + Process(mV, mR, mI); + + mR.AsSpan(0, bytesToCopy).CopyTo(output[(m * mR.Length)..]); + + Increment(mDT); + } + + mReseedCounter++; + + return outputLen * 8; + } +#else /** * Populate a passed in array with random data. * @@ -48,14 +108,14 @@ internal X931Rng(IBlockCipher engine, byte[] dateTimeVector, IEntropySource entr * * @return number of bits generated, -1 if a reseed required. */ - internal int Generate(byte[] output, bool predictionResistant) + internal int Generate(byte[] output, int outputOff, int outputLen, bool predictionResistant) { if (mR.Length == 8) // 64 bit block size { if (mReseedCounter > BLOCK64_RESEED_MAX) return -1; - if (IsTooLarge(output, BLOCK64_MAX_BITS_REQUEST / 8)) + if (outputLen > BLOCK64_MAX_BITS_REQUEST / 8) throw new ArgumentException("Number of bits per request limited to " + BLOCK64_MAX_BITS_REQUEST, "output"); } else @@ -63,7 +123,7 @@ internal int Generate(byte[] output, bool predictionResistant) if (mReseedCounter > BLOCK128_RESEED_MAX) return -1; - if (IsTooLarge(output, BLOCK128_MAX_BITS_REQUEST / 8)) + if (outputLen > BLOCK128_MAX_BITS_REQUEST / 8) throw new ArgumentException("Number of bits per request limited to " + BLOCK128_MAX_BITS_REQUEST, "output"); } @@ -74,7 +134,7 @@ internal int Generate(byte[] output, bool predictionResistant) throw new InvalidOperationException("Insufficient entropy returned"); } - int m = output.Length / mR.Length; + int m = outputLen / mR.Length; for (int i = 0; i < m; i++) { @@ -82,12 +142,12 @@ internal int Generate(byte[] output, bool predictionResistant) Process(mR, mI, mV); Process(mV, mR, mI); - Array.Copy(mR, 0, output, i * mR.Length, mR.Length); + Array.Copy(mR, 0, output, outputOff + i * mR.Length, mR.Length); Increment(mDT); } - int bytesToCopy = (output.Length - m * mR.Length); + int bytesToCopy = outputLen - m * mR.Length; if (bytesToCopy > 0) { @@ -95,15 +155,16 @@ internal int Generate(byte[] output, bool predictionResistant) Process(mR, mI, mV); Process(mV, mR, mI); - Array.Copy(mR, 0, output, m * mR.Length, bytesToCopy); + Array.Copy(mR, 0, output, outputOff + m * mR.Length, bytesToCopy); Increment(mDT); } mReseedCounter++; - return output.Length; + return outputLen * 8; } +#endif /** * Reseed the RNG. @@ -139,11 +200,6 @@ private void Increment(byte[] val) break; } } - - private static bool IsTooLarge(byte[] bytes, int maxBytes) - { - return bytes != null && bytes.Length > maxBytes; - } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/X931SecureRandom.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/X931SecureRandom.cs index 9ce61d2..41666d6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/X931SecureRandom.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/X931SecureRandom.cs @@ -14,7 +14,7 @@ public class X931SecureRandom private readonly X931Rng mDrbg; internal X931SecureRandom(SecureRandom randomSource, X931Rng drbg, bool predictionResistant) - : base((IRandomGenerator)null) + : base(null) { this.mRandomSource = randomSource; this.mDrbg = drbg; @@ -32,6 +32,19 @@ public override void SetSeed(byte[] seed) } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void SetSeed(Span seed) + { + lock (this) + { + if (mRandomSource != null) + { + this.mRandomSource.SetSeed(seed); + } + } + } +#endif + public override void SetSeed(long seed) { lock (this) @@ -46,23 +59,40 @@ public override void SetSeed(long seed) public override void NextBytes(byte[] bytes) { + NextBytes(bytes, 0, bytes.Length); + } + + public override void NextBytes(byte[] buf, int off, int len) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + NextBytes(buf.AsSpan(off, len)); +#else lock (this) { // check if a reseed is required... - if (mDrbg.Generate(bytes, mPredictionResistant) < 0) + if (mDrbg.Generate(buf, off, len, mPredictionResistant) < 0) { mDrbg.Reseed(); - mDrbg.Generate(bytes, mPredictionResistant); + mDrbg.Generate(buf, off, len, mPredictionResistant); } } +#endif } - public override void NextBytes(byte[] buf, int off, int len) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void NextBytes(Span buffer) { - byte[] bytes = new byte[len]; - NextBytes(bytes); - Array.Copy(bytes, 0, buf, off, len); + lock (this) + { + // check if a reseed is required... + if (mDrbg.Generate(buffer, mPredictionResistant) < 0) + { + mDrbg.Reseed(); + mDrbg.Generate(buffer, mPredictionResistant); + } + } } +#endif public override byte[] GenerateSeed(int numBytes) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/X931SecureRandomBuilder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/X931SecureRandomBuilder.cs index f23fdeb..6842a74 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/X931SecureRandomBuilder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/X931SecureRandomBuilder.cs @@ -25,7 +25,7 @@ public class X931SecureRandomBuilder *

*/ public X931SecureRandomBuilder() - : this(new SecureRandom(), false) + : this(CryptoServicesRegistrar.GetSecureRandom(), false) { } @@ -41,6 +41,9 @@ public X931SecureRandomBuilder() */ public X931SecureRandomBuilder(SecureRandom entropySource, bool predictionResistant) { + if (entropySource == null) + throw new ArgumentNullException(nameof(entropySource)); + this.mRandom = entropySource; this.mEntropySourceProvider = new BasicEntropySourceProvider(mRandom, predictionResistant); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/CtrSP800Drbg.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/CtrSP800Drbg.cs index 2a93e19..c2736dd 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/CtrSP800Drbg.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/CtrSP800Drbg.cs @@ -3,6 +3,7 @@ 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; @@ -11,7 +12,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng.Drbg /** * A SP800-90A CTR DRBG. */ - public class CtrSP800Drbg + public sealed class CtrSP800Drbg : ISP80090Drbg { private static readonly long TDEA_RESEED_MAX = 1L << (32 - 1); @@ -61,20 +62,19 @@ public CtrSP800Drbg(IBlockCipher engine, int keySizeInBits, int securityStrength mSeedLength = keySizeInBits + engine.GetBlockSize() * 8; mIsTdea = IsTdea(engine); - byte[] entropy = GetEntropy(); // Get_entropy_input - - CTR_DRBG_Instantiate_algorithm(entropy, nonce, personalizationString); + CTR_DRBG_Instantiate_algorithm(nonce, personalizationString); } - private void CTR_DRBG_Instantiate_algorithm(byte[] entropy, byte[] nonce, byte[] personalisationString) + private void CTR_DRBG_Instantiate_algorithm(byte[] nonce, byte[] personalisationString) { - byte[] seedMaterial = Arrays.ConcatenateAll(entropy, nonce, personalisationString); - byte[] seed = Block_Cipher_df(seedMaterial, mSeedLength); + byte[] entropy = GetEntropy(); // Get_entropy_input + byte[] seedMaterial = Arrays.ConcatenateAll(entropy, nonce, personalisationString); + byte[] seed = BlockCipherDF(seedMaterial, mSeedLength / 8); - int outlen = mEngine.GetBlockSize(); + int blockSize = mEngine.GetBlockSize(); mKey = new byte[(mKeySizeInBits + 7) / 8]; - mV = new byte[outlen]; + mV = new byte[blockSize]; // mKey & mV are modified by this call CTR_DRBG_Update(seed, mKey, mV); @@ -82,55 +82,130 @@ private void CTR_DRBG_Instantiate_algorithm(byte[] entropy, byte[] nonce, byte[] mReseedCounter = 1; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void CTR_DRBG_Update(ReadOnlySpan seed, Span key, Span v) + { + int seedLength = seed.Length; + Span temp = seedLength <= 256 + ? stackalloc byte[seedLength] + : new byte[seedLength]; + + int blockSize = mEngine.GetBlockSize(); + Span block = blockSize <= 64 + ? stackalloc byte[blockSize] + : new byte[blockSize]; + + mEngine.Init(true, ExpandToKeyParameter(key)); + for (int i = 0; i * blockSize < seed.Length; ++i) + { + AddOneTo(v); + mEngine.ProcessBlock(v, block); + + int bytesToCopy = System.Math.Min(blockSize, temp.Length - i * blockSize); + block[..bytesToCopy].CopyTo(temp[(i * blockSize)..]); + } + + XorWith(seed, temp); + + key.CopyFrom(temp); + v.CopyFrom(temp[key.Length..]); + } +#else private void CTR_DRBG_Update(byte[] seed, byte[] key, byte[] v) { - byte[] temp = new byte[seed.Length]; + 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) + mEngine.Init(true, ExpandToKeyParameter(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); - + int bytesToCopy = System.Math.Min(outLen, temp.Length - i * outLen); Array.Copy(outputBlock, 0, temp, i * outLen, bytesToCopy); ++i; } - XOR(temp, seed, temp, 0); + 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); + } +#endif + + private void CTR_DRBG_Reseed_algorithm(byte[] additionalInput) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + CTR_DRBG_Reseed_algorithm(Spans.FromNullableReadOnly(additionalInput)); +#else + byte[] seedMaterial = Arrays.Concatenate(GetEntropy(), additionalInput); - seedMaterial = Block_Cipher_df(seedMaterial, mSeedLength); + seedMaterial = BlockCipherDF(seedMaterial, mSeedLength / 8); CTR_DRBG_Update(seedMaterial, mKey, mV); mReseedCounter = 1; - } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void CTR_DRBG_Reseed_algorithm(ReadOnlySpan additionalInput) + { + int entropyLength = GetEntropyLength(); + int seedLength = entropyLength + additionalInput.Length; + + Span seedMaterial = seedLength <= 256 + ? stackalloc byte[seedLength] + : new byte[seedLength]; + + GetEntropy(seedMaterial[..entropyLength]); + additionalInput.CopyTo(seedMaterial[entropyLength..]); - private void XOR(byte[] output, byte[] a, byte[] b, int bOff) + seedMaterial = BlockCipherDF(seedMaterial, mSeedLength / 8); + + CTR_DRBG_Update(seedMaterial, mKey, mV); + + mReseedCounter = 1; + } +#endif + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void Xor(ReadOnlySpan x, ReadOnlySpan y, Span z) + { + for (int i = 0; i < z.Length; ++i) + { + z[i] = (byte)(x[i] ^ y[i]); + } + } + + private void XorWith(ReadOnlySpan x, Span z) + { + for (int i = 0; i < z.Length; ++i) + { + z[i] ^= x[i]; + } + } +#else + 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]); } } +#endif - private void AddOneTo(byte[] longer) - { - uint carry = 1; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void AddOneTo(Span longer) +#else + private void AddOneTo(byte[] longer) +#endif + { + uint carry = 1; int i = longer.Length; while (--i >= 0) { @@ -148,83 +223,101 @@ private byte[] GetEntropy() return entropy; } - // -- Internal state migration --- +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int GetEntropy(Span output) + { + int length = mEntropySource.GetEntropy(output); + if (length < (mSecurityStrength + 7) / 8) + throw new InvalidOperationException("Insufficient entropy provided by entropy source"); + return length; + } + + private int GetEntropyLength() + { + return (mEntropySource.EntropySize + 7) / 8; + } +#endif + + // -- Internal state migration --- - private static readonly byte[] K_BITS = Hex.DecodeStrict("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"); + private static readonly byte[] K_BITS = Hex.DecodeStrict( + "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 + // 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[] BlockCipherDF(byte[] input, int N) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return BlockCipherDF(input.AsSpan(), N); +#else + int outLen = mEngine.GetBlockSize(); + int L = input.Length; // already in bytes + // 4 S = L || N || input || 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; + Pack.UInt32_To_BE((uint)L, S, 0); + Pack.UInt32_To_BE((uint)N, S, 4); + Array.Copy(input, 0, S, 8, L); + S[8 + L] = 0x80; // S already padded with zeros byte[] temp = new byte[mKeySizeInBits / 8 + outLen]; @@ -235,16 +328,15 @@ private byte[] Block_Cipher_df(byte[] inputString, int bitLength) int i = 0; byte[] K = new byte[mKeySizeInBits / 8]; Array.Copy(K_BITS, 0, K, 0, K.Length); + var K1 = ExpandToKeyParameter(K); + mEngine.Init(true, K1); while (i*outLen*8 < mKeySizeInBits + outLen *8) { - copyIntToByteArray(IV, i, 0); - BCC(bccOut, K, IV, S); + Pack.UInt32_To_BE((uint)i, IV, 0); + BCC(bccOut, IV, S); - int bytesToCopy = ((temp.Length - i * outLen) > outLen) - ? outLen - : (temp.Length - i * outLen); - + int bytesToCopy = System.Math.Min(outLen, temp.Length - i * outLen); Array.Copy(bccOut, 0, temp, i * outLen, bytesToCopy); ++i; } @@ -253,39 +345,120 @@ private byte[] Block_Cipher_df(byte[] inputString, int bitLength) Array.Copy(temp, 0, K, 0, K.Length); Array.Copy(temp, K.Length, X, 0, X.Length); - temp = new byte[bitLength / 2]; + temp = new byte[N]; i = 0; - mEngine.Init(true, new KeyParameter(ExpandKey(K))); + mEngine.Init(true, ExpandToKeyParameter(K)); while (i * outLen < temp.Length) { mEngine.ProcessBlock(X, 0, X, 0); - int bytesToCopy = ((temp.Length - i * outLen) > outLen) - ? outLen - : (temp.Length - i * outLen); - + int bytesToCopy = System.Math.Min(outLen, temp.Length - i * outLen); Array.Copy(X, 0, temp, i * outLen, bytesToCopy); i++; } return temp; - } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private byte[] BlockCipherDF(ReadOnlySpan input, int N) + { + int blockSize = mEngine.GetBlockSize(); + int L = input.Length; // already in bytes + // 4 S = L || N || input || 0x80 + int sLen = 4 + 4 + L + 1; + int blockLen = ((sLen + blockSize - 1) / blockSize) * blockSize; + Span S = blockLen <= 256 + ? stackalloc byte[blockLen] + : new byte[blockLen]; + Pack.UInt32_To_BE((uint)L, S); + Pack.UInt32_To_BE((uint)N, S[4..]); + input.CopyTo(S[8..]); + S[8 + L] = 0x80; + // S already padded with zeros + + int keySize = mKeySizeInBits / 8; + int tempSize = keySize + blockSize; + Span temp = tempSize <= 128 + ? stackalloc byte[tempSize] + : new byte[tempSize]; + + Span bccOut = blockSize <= 64 + ? stackalloc byte[blockSize] + : new byte[blockSize]; + + Span IV = blockSize <= 64 + ? stackalloc byte[blockSize] + : new byte[blockSize]; + + var K1 = ExpandToKeyParameter(K_BITS.AsSpan(0, keySize)); + mEngine.Init(true, K1); + + for (int i = 0; i * blockSize < tempSize; ++i) + { + Pack.UInt32_To_BE((uint)i, IV); + BCC(bccOut, IV, S); - /* - * 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 bytesToCopy = System.Math.Min(blockSize, tempSize - i * blockSize); + bccOut[..bytesToCopy].CopyTo(temp[(i * blockSize)..]); + } + + var K2 = ExpandToKeyParameter(temp[..keySize]); + mEngine.Init(true, K2); + var X = temp[keySize..]; + + byte[] result = new byte[N]; + for (int i = 0; i * blockSize < result.Length; ++i) + { + mEngine.ProcessBlock(X, X); + + int bytesToCopy = System.Math.Min(blockSize, result.Length - i * blockSize); + X[..bytesToCopy].CopyTo(result.AsSpan(i * blockSize)); + } + return result; + } +#endif + + /* + * 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. + */ +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void BCC(Span bccOut, ReadOnlySpan iV, ReadOnlySpan data) + { + int blockSize = mEngine.GetBlockSize(); + + Span chainingValue = blockSize <= 64 + ? stackalloc byte[blockSize] + : new byte[blockSize]; + Span inputBlock = blockSize <= 64 + ? stackalloc byte[blockSize] + : new byte[blockSize]; + + mEngine.ProcessBlock(iV, chainingValue); + + int n = data.Length / blockSize; + for (int i = 0; i < n; i++) + { + Xor(chainingValue, data[(i * blockSize)..], inputBlock); + mEngine.ProcessBlock(inputBlock, chainingValue); + } + + bccOut.CopyFrom(chainingValue); + } +#else + private void BCC(byte[] bccOut, byte[] iV, byte[] data) { int outlen = mEngine.GetBlockSize(); byte[] chainingValue = new byte[outlen]; // initial values = 0 @@ -293,33 +466,24 @@ private void BCC(byte[] bccOut, byte[] k, byte[] iV, byte[] data) 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); + Xor(inputBlock, chainingValue, data, i*outlen); mEngine.ProcessBlock(inputBlock, 0, chainingValue, 0); } Array.Copy(chainingValue, 0, bccOut, 0, bccOut.Length); } +#endif - 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 + public int BlockSize { get { return mV.Length * 8; } } @@ -333,14 +497,20 @@ public int BlockSize * * @return number of bits generated, -1 if a reseed required. */ - public int Generate(byte[] output, byte[] additionalInput, bool predictionResistant) + public int Generate(byte[] output, int outputOff, int outputLen, byte[] additionalInput, + bool predictionResistant) { - if (mIsTdea) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return additionalInput == null + ? Generate(output.AsSpan(outputOff, outputLen), predictionResistant) + : GenerateWithInput(output.AsSpan(outputOff, outputLen), additionalInput.AsSpan(), predictionResistant); +#else + if (mIsTdea) { if (mReseedCounter > TDEA_RESEED_MAX) return -1; - if (DrbgUtilities.IsTooLarge(output, TDEA_MAX_BITS_REQUEST / 8)) + if (outputLen > TDEA_MAX_BITS_REQUEST / 8) throw new ArgumentException("Number of bits per request limited to " + TDEA_MAX_BITS_REQUEST, "output"); } else @@ -348,7 +518,7 @@ public int Generate(byte[] output, byte[] additionalInput, bool predictionResist if (mReseedCounter > AES_RESEED_MAX) return -1; - if (DrbgUtilities.IsTooLarge(output, AES_MAX_BITS_REQUEST / 8)) + if (outputLen > AES_MAX_BITS_REQUEST / 8) throw new ArgumentException("Number of bits per request limited to " + AES_MAX_BITS_REQUEST, "output"); } @@ -360,7 +530,7 @@ public int Generate(byte[] output, byte[] additionalInput, bool predictionResist if (additionalInput != null) { - additionalInput = Block_Cipher_df(additionalInput, mSeedLength); + additionalInput = BlockCipherDF(additionalInput, mSeedLength / 8); CTR_DRBG_Update(additionalInput, mKey, mV); } else @@ -370,13 +540,11 @@ public int Generate(byte[] output, byte[] additionalInput, bool predictionResist byte[] tmp = new byte[mV.Length]; - mEngine.Init(true, new KeyParameter(ExpandKey(mKey))); + mEngine.Init(true, ExpandToKeyParameter(mKey)); - for (int i = 0; i <= output.Length / tmp.Length; i++) + for (int i = 0, limit = outputLen / tmp.Length; i <= limit; i++) { - int bytesToCopy = ((output.Length - i * tmp.Length) > tmp.Length) - ? tmp.Length - : (output.Length - i * mV.Length); + int bytesToCopy = System.Math.Min(tmp.Length, outputLen - i * tmp.Length); if (bytesToCopy != 0) { @@ -384,7 +552,7 @@ public int Generate(byte[] output, byte[] additionalInput, bool predictionResist mEngine.ProcessBlock(mV, 0, tmp, 0); - Array.Copy(tmp, 0, output, i * tmp.Length, bytesToCopy); + Array.Copy(tmp, 0, output, outputOff + i * tmp.Length, bytesToCopy); } } @@ -392,19 +560,127 @@ public int Generate(byte[] output, byte[] additionalInput, bool predictionResist mReseedCounter++; - return output.Length * 8; - } + return outputLen * 8; +#endif + } - /** +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int Generate(Span output, bool predictionResistant) + { + int outputLen = output.Length; + if (mIsTdea) + { + if (mReseedCounter > TDEA_RESEED_MAX) + return -1; + + if (outputLen > 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 (outputLen > 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(ReadOnlySpan.Empty); + } + + byte[] seed = new byte[mSeedLength / 8]; + + return ImplGenerate(seed, output); + } + + public int GenerateWithInput(Span output, ReadOnlySpan additionalInput, bool predictionResistant) + { + int outputLen = output.Length; + if (mIsTdea) + { + if (mReseedCounter > TDEA_RESEED_MAX) + return -1; + + if (outputLen > 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 (outputLen > AES_MAX_BITS_REQUEST / 8) + throw new ArgumentException("Number of bits per request limited to " + AES_MAX_BITS_REQUEST, "output"); + } + + int seedLength = mSeedLength / 8; + byte[] seed; + if (predictionResistant) + { + CTR_DRBG_Reseed_algorithm(additionalInput); + seed = new byte[seedLength]; + } + else + { + seed = BlockCipherDF(additionalInput, seedLength); + CTR_DRBG_Update(seed, mKey, mV); + } + + return ImplGenerate(seed, output); + } + + private int ImplGenerate(ReadOnlySpan seed, Span output) + { + byte[] tmp = new byte[mV.Length]; + + mEngine.Init(true, ExpandToKeyParameter(mKey)); + + int outputLen = output.Length; + for (int i = 0, limit = outputLen / tmp.Length; i <= limit; i++) + { + int bytesToCopy = System.Math.Min(tmp.Length, outputLen - i * tmp.Length); + + if (bytesToCopy != 0) + { + AddOneTo(mV); + + mEngine.ProcessBlock(mV, 0, tmp, 0); + + tmp[..bytesToCopy].CopyTo(output[(i * tmp.Length)..]); + } + } + + CTR_DRBG_Update(seed, mKey, mV); + + mReseedCounter++; + + return outputLen * 8; + } +#endif + + /** * Reseed the DRBG. * * @param additionalInput additional input to be added to the DRBG in this step. */ - public void Reseed(byte[] additionalInput) + public void Reseed(byte[] additionalInput) { - CTR_DRBG_Reseed_algorithm(additionalInput); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Reseed(Spans.FromNullableReadOnly(additionalInput)); +#else + CTR_DRBG_Reseed_algorithm(additionalInput); +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Reseed(ReadOnlySpan additionalInput) + { + CTR_DRBG_Reseed_algorithm(additionalInput); + } +#endif + private bool IsTdea(IBlockCipher cipher) { return cipher.AlgorithmName.Equals("DESede") || cipher.AlgorithmName.Equals("TDEA"); @@ -424,26 +700,39 @@ private int GetMaxSecurityStrength(IBlockCipher cipher, int keySizeInBits) return -1; } - private byte[] ExpandKey(byte[] key) + private KeyParameter ExpandToKeyParameter(byte[] key) { - if (mIsTdea) - { - // expand key to 192 bits. - byte[] tmp = new byte[24]; + if (!mIsTdea) + return new KeyParameter(key); - PadKey(key, 0, tmp, 0); - PadKey(key, 7, tmp, 8); - PadKey(key, 14, tmp, 16); + // expand key to 192 bits. + byte[] tmp = new byte[24]; - return tmp; - } - else - { - return key; - } - } + PadKey(key, 0, tmp, 0); + PadKey(key, 7, tmp, 8); + PadKey(key, 14, tmp, 16); - /** + return new KeyParameter(tmp); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private KeyParameter ExpandToKeyParameter(ReadOnlySpan key) + { + if (!mIsTdea) + return new KeyParameter(key); + + // expand key to 192 bits. + Span tmp = stackalloc byte[24]; + + PadKey(key, tmp); + PadKey(key[7..], tmp[8..]); + PadKey(key[14..], tmp[16..]); + + return new KeyParameter(tmp); + } +#endif + + /** * Pad out a key for TDEA, setting odd parity for each byte. * * @param keyMaster @@ -464,7 +753,23 @@ private void PadKey(byte[] keyMaster, int keyOff, byte[] tmp, int tmpOff) DesParameters.SetOddParity(tmp, tmpOff, 8); } - } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void PadKey(ReadOnlySpan keyMaster, Span tmp) + { + tmp[0] = (byte)(keyMaster[0] & 0xFE); + tmp[1] = (byte)((keyMaster[0] << 7) | ((keyMaster[1] & 0xfc) >> 1)); + tmp[2] = (byte)((keyMaster[1] << 6) | ((keyMaster[2] & 0xf8) >> 2)); + tmp[3] = (byte)((keyMaster[2] << 5) | ((keyMaster[3] & 0xf0) >> 3)); + tmp[4] = (byte)((keyMaster[3] << 4) | ((keyMaster[4] & 0xe0) >> 4)); + tmp[5] = (byte)((keyMaster[4] << 3) | ((keyMaster[5] & 0xc0) >> 5)); + tmp[6] = (byte)((keyMaster[5] << 2) | ((keyMaster[6] & 0x80) >> 6)); + tmp[7] = (byte)(keyMaster[6] << 1); + + DesParameters.SetOddParity(tmp[..8]); + } +#endif + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/DrbgUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/DrbgUtilities.cs index f3ef1ca..90c29ae 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/DrbgUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/DrbgUtilities.cs @@ -1,105 +1,113 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng.Drbg { internal class DrbgUtilities { - private static readonly IDictionary maxSecurityStrengths = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + private static readonly IDictionary MaxSecurityStrengths = + new Dictionary(StringComparer.OrdinalIgnoreCase); static DrbgUtilities() { - maxSecurityStrengths.Add("SHA-1", 128); + 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-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); + MaxSecurityStrengths.Add("SHA-512/224", 192); + MaxSecurityStrengths.Add("SHA-512/256", 256); } internal static int GetMaxSecurityStrength(IDigest d) { - return (int)maxSecurityStrengths[d.AlgorithmName]; + return MaxSecurityStrengths[d.AlgorithmName]; } internal static int GetMaxSecurityStrength(IMac m) { string name = m.AlgorithmName; - return (int)maxSecurityStrengths[name.Substring(0, name.IndexOf("/"))]; + return 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(); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal static void HashDF(IDigest digest, ReadOnlySpan seedMaterial, int seedLength, Span output) +#else + internal static void HashDF(IDigest digest, byte[] seedMaterial, int seedLength, byte[] output) +#endif + { + // 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. + int outputLength = (seedLength + 7) / 8; + + int digestSize = digest.GetDigestSize(); + int len = outputLength / digestSize; int counter = 1; - byte[] dig = new byte[digest.GetDigestSize()]; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span dig = digestSize <= 128 + ? stackalloc byte[digestSize] + : new byte[digestSize]; + Span header = stackalloc byte[5]; + Pack.UInt32_To_BE((uint)seedLength, header[1..]); +#else + byte[] dig = new byte[digestSize]; + byte[] header = new byte[5]; + Pack.UInt32_To_BE((uint)seedLength, header, 1); +#endif - for (int i = 0; i <= len; i++) + for (int i = 0; i <= len; i++, counter++) { - 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++; - } + header[0] = (byte)counter; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + digest.BlockUpdate(header); + digest.BlockUpdate(seedMaterial); + digest.DoFinal(dig); + + int bytesToCopy = System.Math.Min(digestSize, outputLength - i * digestSize); + dig[..bytesToCopy].CopyTo(output[(i * digestSize)..]); +#else + digest.BlockUpdate(header, 0, header.Length); + digest.BlockUpdate(seedMaterial, 0, seedMaterial.Length); + digest.DoFinal(dig, 0); + + int bytesToCopy = System.Math.Min(digestSize, outputLength - i * digestSize); + Array.Copy(dig, 0, output, i * digestSize, bytesToCopy); +#endif + } - // do a left shift to get rid of excess bits. - if (seedLength % 8 != 0) + // 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++) + for (int i = 0; i != outputLength; i++) { - uint b = temp[i]; - temp[i] = (byte)((b >> shift) | (carry << (8 - shift))); + uint b = output[i]; + output[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; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/HMacSP800Drbg.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/HMacSP800Drbg.cs index 445c314..a4367d0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/HMacSP800Drbg.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/HMacSP800Drbg.cs @@ -10,7 +10,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng.Drbg /** * A SP800-90A HMAC DRBG. */ - public class HMacSP800Drbg + public sealed class HMacSP800Drbg : ISP80090Drbg { private readonly static long RESEED_MAX = 1L << (48 - 1); @@ -35,7 +35,8 @@ public class HMacSP800Drbg * @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) + 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"); @@ -58,12 +59,41 @@ public HMacSP800Drbg(IMac hMac, int securityStrength, IEntropySource entropySour mReseedCounter = 1; } - private void hmac_DRBG_Update(byte[] seedMaterial) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void hmac_DRBG_Update() + { + hmac_DRBG_Update_Func(ReadOnlySpan.Empty, 0x00); + } + + private void hmac_DRBG_Update(ReadOnlySpan seedMaterial) + { + hmac_DRBG_Update_Func(seedMaterial, 0x00); + hmac_DRBG_Update_Func(seedMaterial, 0x01); + } + + private void hmac_DRBG_Update_Func(ReadOnlySpan seedMaterial, byte vValue) + { + mHMac.Init(new KeyParameter(mK)); + + mHMac.BlockUpdate(mV); + mHMac.Update(vValue); + if (!seedMaterial.IsEmpty) + { + mHMac.BlockUpdate(seedMaterial); + } + mHMac.DoFinal(mK); + + mHMac.Init(new KeyParameter(mK)); + mHMac.BlockUpdate(mV); + mHMac.DoFinal(mV); + } +#else + private void hmac_DRBG_Update(byte[] seedMaterial) { - hmac_DRBG_Update_Func(seedMaterial, (byte)0x00); + hmac_DRBG_Update_Func(seedMaterial, 0x00); if (seedMaterial != null) { - hmac_DRBG_Update_Func(seedMaterial, (byte)0x01); + hmac_DRBG_Update_Func(seedMaterial, 0x01); } } @@ -86,13 +116,14 @@ private void hmac_DRBG_Update_Func(byte[] seedMaterial, byte vValue) mHMac.DoFinal(mV, 0); } +#endif - /** + /** * Return the block size (in bits) of the DRBG. * * @return the number of bits produced on each round of the DRBG. */ - public int BlockSize + public int BlockSize { get { return mV.Length * 8; } } @@ -106,17 +137,21 @@ public int BlockSize * * @return number of bits generated, -1 if a reseed required. */ - public int Generate(byte[] output, byte[] additionalInput, bool predictionResistant) + public int Generate(byte[] output, int outputOff, int outputLen, byte[] additionalInput, + bool predictionResistant) { - int numberOfBits = output.Length * 8; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return additionalInput == null + ? Generate(output.AsSpan(outputOff, outputLen), predictionResistant) + : GenerateWithInput(output.AsSpan(outputOff, outputLen), additionalInput.AsSpan(), predictionResistant); +#else + int numberOfBits = outputLen * 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) { @@ -131,9 +166,9 @@ public int Generate(byte[] output, byte[] additionalInput, bool predictionResist } // 3. - byte[] rv = new byte[output.Length]; + byte[] rv = new byte[outputLen]; - int m = output.Length / mV.Length; + int m = outputLen / mV.Length; mHMac.Init(new KeyParameter(mK)); @@ -157,26 +192,137 @@ public int Generate(byte[] output, byte[] additionalInput, bool predictionResist mReseedCounter++; - Array.Copy(rv, 0, output, 0, output.Length); + Array.Copy(rv, 0, output, outputOff, outputLen); return numberOfBits; +#endif } - /** +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int Generate(Span output, 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(ReadOnlySpan.Empty); + } + + // 3. + ImplGenerate(output); + + hmac_DRBG_Update(); + + mReseedCounter++; + + return numberOfBits; + } + + public int GenerateWithInput(Span output, ReadOnlySpan 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); + } + else + { + // 2. + hmac_DRBG_Update(additionalInput); + } + + // 3. + ImplGenerate(output); + + if (predictionResistant) + { + hmac_DRBG_Update(); + } + else + { + hmac_DRBG_Update(additionalInput); + } + + mReseedCounter++; + + return numberOfBits; + } + + private void ImplGenerate(Span output) + { + int outputLen = output.Length; + int m = outputLen / mV.Length; + + mHMac.Init(new KeyParameter(mK)); + + for (int i = 0; i < m; i++) + { + mHMac.BlockUpdate(mV); + mHMac.DoFinal(mV); + + mV.CopyTo(output[(i * mV.Length)..]); + } + + int remaining = outputLen - m * mV.Length; + if (remaining > 0) + { + mHMac.BlockUpdate(mV); + mHMac.DoFinal(mV); + + mV[..remaining].CopyTo(output[(m * mV.Length)..]); + } + } +#endif + + /** * Reseed the DRBG. * * @param additionalInput additional input to be added to the DRBG in this step. */ - public void Reseed(byte[] additionalInput) + public void Reseed(byte[] additionalInput) { - byte[] entropy = GetEntropy(); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Reseed(Spans.FromNullableReadOnly(additionalInput)); +#else + byte[] entropy = GetEntropy(); byte[] seedMaterial = Arrays.Concatenate(entropy, additionalInput); hmac_DRBG_Update(seedMaterial); mReseedCounter = 1; +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Reseed(ReadOnlySpan additionalInput) + { + int entropyLength = GetEntropyLength(); + int seedMaterialLength = entropyLength + additionalInput.Length; + Span seedMaterial = seedMaterialLength <= 256 + ? stackalloc byte[seedMaterialLength] + : new byte[seedMaterialLength]; + GetEntropy(seedMaterial); + additionalInput.CopyTo(seedMaterial[entropyLength..]); + + hmac_DRBG_Update(seedMaterial); + + mReseedCounter = 1; + } +#endif + private byte[] GetEntropy() { byte[] entropy = mEntropySource.GetEntropy(); @@ -184,7 +330,22 @@ private byte[] GetEntropy() throw new InvalidOperationException("Insufficient entropy provided by entropy source"); return entropy; } - } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int GetEntropy(Span output) + { + int length = mEntropySource.GetEntropy(output); + if (length < (mSecurityStrength + 7) / 8) + throw new InvalidOperationException("Insufficient entropy provided by entropy source"); + return length; + } + + private int GetEntropyLength() + { + return (mEntropySource.EntropySize + 7) / 8; + } +#endif + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/HashSP800Drbg.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/HashSP800Drbg.cs index 7d244fc..aabb227 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/HashSP800Drbg.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/HashSP800Drbg.cs @@ -1,8 +1,9 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng.Drbg @@ -10,7 +11,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Prng.Drbg /** * A SP800-90A Hash DRBG. */ - public class HashSP800Drbg + public sealed class HashSP800Drbg : ISP80090Drbg { private readonly static byte[] ONE = { 0x01 }; @@ -18,17 +19,18 @@ public class HashSP800Drbg 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(); + private static readonly IDictionary SeedLens = + new Dictionary(StringComparer.OrdinalIgnoreCase); 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); + 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; @@ -61,7 +63,7 @@ public HashSP800Drbg(IDigest digest, int securityStrength, IEntropySource entrop mDigest = digest; mEntropySource = entropySource; mSecurityStrength = securityStrength; - mSeedLength = (int)seedlens[digest.AlgorithmName]; + mSeedLength = SeedLens[digest.AlgorithmName]; // 1. seed_material = entropy_input || nonce || personalization_string. // 2. seed = Hash_df (seed_material, seedlen). @@ -73,12 +75,13 @@ public HashSP800Drbg(IDigest digest, int securityStrength, IEntropySource entrop byte[] entropy = GetEntropy(); byte[] seedMaterial = Arrays.ConcatenateAll(entropy, nonce, personalizationString); - byte[] seed = DrbgUtilities.HashDF(mDigest, seedMaterial, mSeedLength); + mV = new byte[(mSeedLength + 7) / 8]; + DrbgUtilities.HashDF(mDigest, seedMaterial, mSeedLength, mV); - mV = seed; byte[] subV = new byte[mV.Length + 1]; Array.Copy(mV, 0, subV, 1, mV.Length); - mC = DrbgUtilities.HashDF(mDigest, subV, mSeedLength); + mC = new byte[(mSeedLength + 7) / 8]; + DrbgUtilities.HashDF(mDigest, subV, mSeedLength, mC); mReseedCounter = 1; } @@ -90,7 +93,7 @@ public HashSP800Drbg(IDigest digest, int securityStrength, IEntropySource entrop */ public int BlockSize { - get { return mDigest.GetDigestSize () * 8; } + get { return mDigest.GetDigestSize() * 8; } } /** @@ -102,22 +105,28 @@ public int BlockSize * * @return number of bits generated, -1 if a reseed required. */ - public int Generate(byte[] output, byte[] additionalInput, bool predictionResistant) + public int Generate(byte[] output, int outputOff, int outputLen, 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 NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return additionalInput == null + ? Generate(output.AsSpan(outputOff, outputLen), predictionResistant) + : GenerateWithInput(output.AsSpan(outputOff, outputLen), additionalInput.AsSpan(), predictionResistant); +#else + // 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 = outputLen * 8; if (numberOfBits > MAX_BITS_REQUEST) throw new ArgumentException("Number of bits per request limited to " + MAX_BITS_REQUEST, "output"); @@ -137,7 +146,6 @@ public int Generate(byte[] output, byte[] additionalInput, bool predictionResist 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); @@ -145,7 +153,7 @@ public int Generate(byte[] output, byte[] additionalInput, bool predictionResist } // 3. - byte[] rv = hashgen(mV, numberOfBits); + byte[] rv = Hashgen(mV, outputLen); // 4. byte[] subH = new byte[mV.Length + 1]; @@ -157,22 +165,129 @@ public int Generate(byte[] output, byte[] additionalInput, bool predictionResist // 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; + Pack.UInt32_To_BE((uint)mReseedCounter, c); AddTo(mV, c); mReseedCounter++; - Array.Copy(rv, 0, output, 0, output.Length); + Array.Copy(rv, 0, output, outputOff, outputLen); return numberOfBits; - } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int Generate(Span output, 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(ReadOnlySpan.Empty); + } + + return ImplGenerate(output); + } + + public int GenerateWithInput(Span output, ReadOnlySpan 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); + } + else + { + // 2. + mDigest.Update(0x02); + mDigest.BlockUpdate(mV); + mDigest.BlockUpdate(additionalInput); + + int digestSize = mDigest.GetDigestSize(); + Span w = digestSize <= 128 + ? stackalloc byte[digestSize] + : new byte[digestSize]; + mDigest.DoFinal(w); - private byte[] GetEntropy() + AddTo(mV, w); + } + + return ImplGenerate(output); + } + + private int ImplGenerate(Span output) + { + // 3. + Hashgen(mV, output); + + // 4. + mDigest.Update(0x03); + mDigest.BlockUpdate(mV); + + int digestSize = mDigest.GetDigestSize(); + Span H = digestSize <= 128 + ? stackalloc byte[digestSize] + : new byte[digestSize]; + mDigest.DoFinal(H); + + // 5. + AddTo(mV, H); + AddTo(mV, mC); + + Span c = stackalloc byte[4]; + Pack.UInt32_To_BE((uint)mReseedCounter, c); + + AddTo(mV, c); + + mReseedCounter++; + + return output.Length * 8; + } +#endif + + private byte[] GetEntropy() { byte[] entropy = mEntropySource.GetEntropy(); if (entropy.Length < (mSecurityStrength + 7) / 8) @@ -180,18 +295,37 @@ private byte[] GetEntropy() 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) - { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int GetEntropy(Span output) + { + int length = mEntropySource.GetEntropy(output); + if (length < (mSecurityStrength + 7) / 8) + throw new InvalidOperationException("Insufficient entropy provided by entropy source"); + return length; + } + + private int GetEntropyLength() + { + return (mEntropySource.EntropySize + 7) / 8; + } +#endif + + // this will always add the shorter length byte array mathematically to the + // longer length byte array. + // be careful.... +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void AddTo(Span longer, ReadOnlySpan shorter) +#else + private void AddTo(byte[] longer, byte[] shorter) +#endif + { int off = longer.Length - shorter.Length; uint carry = 0; int i = shorter.Length; while (--i >= 0) { - carry += (uint)longer[off + i] + (uint)shorter[i]; + carry += (uint)longer[off + i] + shorter[i]; longer[off + i] = (byte)carry; carry >>= 8; } @@ -212,80 +346,157 @@ private void AddTo(byte[] longer, byte[] shorter) */ 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(); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Reseed(Spans.FromNullableReadOnly(additionalInput)); +#else + // 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); + DrbgUtilities.HashDF(mDigest, seedMaterial, mSeedLength, mV); - 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); + DrbgUtilities.HashDF(mDigest, subV, mSeedLength, mC); mReseedCounter = 1; +#endif } - private byte[] Hash(byte[] input) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Reseed(ReadOnlySpan additionalInput) { - byte[] hash = new byte[mDigest.GetDigestSize()]; - DoHash(input, hash); - return hash; + // 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. + int entropyLength = GetEntropyLength(); + + int seedMaterialLength = 1 + mV.Length + entropyLength + additionalInput.Length; + Span seedMaterial = seedMaterialLength <= 256 + ? stackalloc byte[seedMaterialLength] + : new byte[seedMaterialLength]; + + seedMaterial[0] = 0x01; + mV.CopyTo(seedMaterial[1..]); + GetEntropy(seedMaterial[(1 + mV.Length)..]); + additionalInput.CopyTo(seedMaterial[(1 + mV.Length + entropyLength)..]); + + DrbgUtilities.HashDF(mDigest, seedMaterial, mSeedLength, mV); + + int subVLength = 1 + mV.Length; + Span subV = subVLength <= 128 + ? stackalloc byte[subVLength] + : new byte[subVLength]; + subV[0] = 0x00; + mV.CopyTo(subV[1..]); + + DrbgUtilities.HashDF(mDigest, subV, mSeedLength, mC); + + mReseedCounter = 1; } +#endif - private void DoHash(byte[] input, byte[] output) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void DoHash(ReadOnlySpan input, Span output) + { + mDigest.BlockUpdate(input); + mDigest.DoFinal(output); + } +#else + private void DoHash(byte[] input, byte[] output) { mDigest.BlockUpdate(input, 0, input.Length); mDigest.DoFinal(output, 0); } + private byte[] Hash(byte[] input) + { + byte[] hash = new byte[mDigest.GetDigestSize()]; + DoHash(input, hash); + return hash; + } +#endif + // 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) + // 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. +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void Hashgen(ReadOnlySpan input, Span output) { int digestSize = mDigest.GetDigestSize(); - int m = (lengthInBits / 8) / digestSize; + int m = output.Length / digestSize; - byte[] data = new byte[input.Length]; - Array.Copy(input, 0, data, 0, input.Length); + int dataSize = input.Length; + Span data = dataSize <= 256 + ? stackalloc byte[input.Length] + : new byte[input.Length]; + input.CopyTo(data); - byte[] W = new byte[lengthInBits / 8]; + Span dig = digestSize <= 128 + ? stackalloc byte[digestSize] + : new byte[digestSize]; - 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); + int bytesToCopy = System.Math.Min(digestSize, output.Length - i * digestSize); + dig[..bytesToCopy].CopyTo(output[(i * digestSize)..]); + AddTo(data, ONE); + } + } +#else + private byte[] Hashgen(byte[] input, int length) + { + int digestSize = mDigest.GetDigestSize(); + int m = length / digestSize; + + byte[] data = (byte[])input.Clone(); + byte[] W = new byte[length]; + + byte[] dig = new byte[digestSize]; + for (int i = 0; i <= m; i++) + { + DoHash(data, dig); + + int bytesToCopy = System.Math.Min(digestSize, length - i * digestSize); + Array.Copy(dig, 0, W, i * digestSize, bytesToCopy); AddTo(data, ONE); } return W; - } - } + } +#endif + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/ISP80090Drbg.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/ISP80090Drbg.cs index b48b7fe..a6f9493 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/ISP80090Drbg.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/prng/drbg/ISP80090Drbg.cs @@ -16,7 +16,7 @@ public interface ISP80090Drbg */ int BlockSize { get; } - /** + /** * Populate a passed in array with random data. * * @param output output array for generated bits. @@ -25,15 +25,25 @@ public interface ISP80090Drbg * * @return number of bits generated, -1 if a reseed required. */ - int Generate(byte[] output, byte[] additionalInput, bool predictionResistant); + int Generate(byte[] output, int outputOff, int outputLen, byte[] additionalInput, bool predictionResistant); - /** +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int Generate(Span output, bool predictionResistant); + + int GenerateWithInput(Span output, ReadOnlySpan additionalInput, bool predictionResistant); +#endif + + /** * Reseed the DRBG. * * @param additionalInput additional input to be added to the DRBG in this step. */ - void Reseed(byte[] additionalInput); - } + void Reseed(byte[] additionalInput); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + void Reseed(ReadOnlySpan additionalInput); +#endif + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/DsaDigestSigner.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/DsaDigestSigner.cs index 3bae7b6..7d66f3f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/DsaDigestSigner.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/DsaDigestSigner.cs @@ -16,19 +16,12 @@ public class DsaDigestSigner private readonly IDsaEncoding encoding; private bool forSigning; - public DsaDigestSigner( - IDsa dsa, - IDigest digest) + public DsaDigestSigner(IDsa dsa, IDigest digest) + : this(dsa, digest, StandardDsaEncoding.Instance) { - this.dsa = dsa; - this.digest = digest; - this.encoding = StandardDsaEncoding.Instance; } - public DsaDigestSigner( - IDsaExt dsa, - IDigest digest, - IDsaEncoding encoding) + public DsaDigestSigner(IDsa dsa, IDigest digest, IDsaEncoding encoding) { this.dsa = dsa; this.digest = digest; @@ -40,17 +33,14 @@ public virtual string AlgorithmName get { return digest.AlgorithmName + "with" + dsa.AlgorithmName; } } - public virtual void Init( - bool forSigning, - ICipherParameters parameters) + public virtual void Init(bool forSigning, ICipherParameters parameters) { this.forSigning = forSigning; AsymmetricKeyParameter k; - - if (parameters is ParametersWithRandom) + if (parameters is ParametersWithRandom withRandom) { - k = (AsymmetricKeyParameter)((ParametersWithRandom)parameters).Parameters; + k = (AsymmetricKeyParameter)withRandom.Parameters; } else { @@ -68,31 +58,24 @@ public virtual void Init( dsa.Init(forSigning, parameters); } - /** - * update the internal digest with the byte b - */ - public virtual void Update( - byte input) + 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) + public virtual void BlockUpdate(byte[] input, int inOff, int inLen) { - digest.BlockUpdate(input, inOff, length); + digest.BlockUpdate(input, inOff, inLen); } - /** - * Generate a signature for the message we've been loaded with using - * the key we were initialised with. - */ - public virtual byte[] GenerateSignature() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) + { + digest.BlockUpdate(input); + } +#endif + + public virtual byte[] GenerateSignature() { if (!forSigning) throw new InvalidOperationException("DSADigestSigner not initialised for signature generation."); @@ -112,9 +95,7 @@ public virtual byte[] GenerateSignature() } } - /// true if the internal state represents the signature described in the passed in array. - public virtual bool VerifySignature( - byte[] signature) + public virtual bool VerifySignature(byte[] signature) { if (forSigning) throw new InvalidOperationException("DSADigestSigner not initialised for verification"); @@ -134,7 +115,6 @@ public virtual bool VerifySignature( } } - /// Reset the internal state public virtual void Reset() { digest.Reset(); @@ -142,7 +122,7 @@ public virtual void Reset() protected virtual BigInteger GetOrder() { - return dsa is IDsaExt ? ((IDsaExt)dsa).Order : null; + return dsa.Order; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/DsaSigner.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/DsaSigner.cs index 367c699..dff1c6e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/DsaSigner.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/DsaSigner.cs @@ -14,7 +14,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers * Cryptography", pages 452 - 453. */ public class DsaSigner - : IDsaExt + : IDsa { protected readonly IDsaKCalculator kCalculator; @@ -157,7 +157,7 @@ protected virtual BigInteger CalculateE(BigInteger n, byte[] message) protected virtual SecureRandom InitSecureRandom(bool needed, SecureRandom provided) { - return !needed ? null : (provided != null) ? provided : new SecureRandom(); + return !needed ? null : CryptoServicesRegistrar.GetSecureRandom(provided); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/ECDsaSigner.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/ECDsaSigner.cs index ff7fca1..4f1f424 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/ECDsaSigner.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/ECDsaSigner.cs @@ -2,7 +2,6 @@ #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; @@ -16,7 +15,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers * EC-DSA as described in X9.62 */ public class ECDsaSigner - : IDsaExt + : IDsa { private static readonly BigInteger Eight = BigInteger.ValueOf(8); @@ -242,7 +241,7 @@ protected virtual ECFieldElement GetDenominator(int coordinateSystem, ECPoint p) protected virtual SecureRandom InitSecureRandom(bool needed, SecureRandom provided) { - return !needed ? null : (provided != null) ? provided : new SecureRandom(); + return !needed ? null : CryptoServicesRegistrar.GetSecureRandom(provided); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/ECGOST3410Signer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/ECGOST3410Signer.cs index bba4ba4..4f5bd99 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/ECGOST3410Signer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/ECGOST3410Signer.cs @@ -2,7 +2,6 @@ #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; @@ -16,7 +15,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers * GOST R 34.10-2001 Signature Algorithm */ public class ECGost3410Signer - : IDsaExt + : IDsa { private ECKeyParameters key; private SecureRandom random; @@ -27,44 +26,37 @@ public virtual string AlgorithmName get { return key.AlgorithmName; } } - public virtual void Init( - bool forSigning, - ICipherParameters parameters) + public virtual void Init(bool forSigning, ICipherParameters parameters) { this.forSigning = forSigning; if (forSigning) { - if (parameters is ParametersWithRandom) + if (parameters is ParametersWithRandom rParam) { - ParametersWithRandom rParam = (ParametersWithRandom)parameters; - this.random = rParam.Random; parameters = rParam.Parameters; } else { - this.random = new SecureRandom(); + this.random = CryptoServicesRegistrar.GetSecureRandom(); } - if (!(parameters is ECPrivateKeyParameters)) + if (!(parameters is ECPrivateKeyParameters ecPrivateKeyParameters)) throw new InvalidKeyException("EC private key required for signing"); - this.key = (ECPrivateKeyParameters) parameters; + this.key = ecPrivateKeyParameters; } else { - if (!(parameters is ECPublicKeyParameters)) + if (!(parameters is ECPublicKeyParameters ecPublicKeyParameters)) throw new InvalidKeyException("EC public key required for verification"); - this.key = (ECPublicKeyParameters)parameters; + this.key = ecPublicKeyParameters; } } - public virtual BigInteger Order - { - get { return key.Parameters.N; } - } + public virtual BigInteger Order => key.Parameters.N; /** * generate a signature for the given message using the key we were @@ -73,13 +65,10 @@ public virtual BigInteger Order * * @param message the message that will be verified later. */ - public virtual BigInteger[] GenerateSignature( - byte[] message) + public virtual BigInteger[] GenerateSignature(byte[] message) { if (!forSigning) - { throw new InvalidOperationException("not initialized for signing"); - } byte[] mRev = Arrays.Reverse(message); // conversion is little-endian BigInteger e = new BigInteger(1, mRev); @@ -88,7 +77,7 @@ public virtual BigInteger[] GenerateSignature( BigInteger n = ec.N; BigInteger d = ((ECPrivateKeyParameters)key).D; - BigInteger r, s = null; + BigInteger r, s; ECMultiplier basePointMultiplier = CreateBasePointMultiplier(); @@ -99,7 +88,7 @@ public virtual BigInteger[] GenerateSignature( { do { - k = new BigInteger(n.BitLength, random); + k = BigIntegers.CreateRandomBigInteger(n.BitLength, random); } while (k.SignValue == 0); @@ -109,7 +98,7 @@ public virtual BigInteger[] GenerateSignature( } while (r.SignValue == 0); - s = (k.Multiply(e)).Add(d.Multiply(r)).Mod(n); + s = k.Multiply(e).Add(d.Multiply(r)).Mod(n); } while (s.SignValue == 0); @@ -121,15 +110,10 @@ public virtual BigInteger[] GenerateSignature( * 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) + public virtual bool VerifySignature(byte[] message, BigInteger r, BigInteger s) { if (forSigning) - { throw new InvalidOperationException("not initialized for verification"); - } byte[] mRev = Arrays.Reverse(message); // conversion is little-endian BigInteger e = new BigInteger(1, mRev); @@ -137,20 +121,16 @@ public virtual bool VerifySignature( // 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 = BigIntegers.ModOddInverseVar(n, e); BigInteger z1 = s.Multiply(v).Mod(n); - BigInteger z2 = (n.Subtract(r)).Multiply(v).Mod(n); + BigInteger z2 = n.Subtract(r).Multiply(v).Mod(n); ECPoint G = key.Parameters.G; // P ECPoint Q = ((ECPublicKeyParameters)key).Q; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/ECNRSigner.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/ECNRSigner.cs index 03fa64b..dbbfdb6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/ECNRSigner.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/ECNRSigner.cs @@ -15,7 +15,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers * EC-NR as described in IEEE 1363-2000 */ public class ECNRSigner - : IDsaExt + : IDsa { private bool forSigning; private ECKeyParameters key; @@ -26,24 +26,20 @@ public virtual string AlgorithmName get { return "ECNR"; } } - public virtual void Init( - bool forSigning, - ICipherParameters parameters) + public virtual void Init(bool forSigning, ICipherParameters parameters) { this.forSigning = forSigning; if (forSigning) { - if (parameters is ParametersWithRandom) + if (parameters is ParametersWithRandom rParam) { - ParametersWithRandom rParam = (ParametersWithRandom) parameters; - this.random = rParam.Random; parameters = rParam.Parameters; } else { - this.random = new SecureRandom(); + this.random = CryptoServicesRegistrar.GetSecureRandom(); } if (!(parameters is ECPrivateKeyParameters)) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed25519Signer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed25519Signer.cs index 36c5017..71516bf 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed25519Signer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed25519Signer.cs @@ -5,8 +5,6 @@ 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 { @@ -56,6 +54,13 @@ public virtual void BlockUpdate(byte[] buf, int off, int len) buffer.Write(buf, off, len); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) + { + buffer.Write(input); + } +#endif + public virtual byte[] GenerateSignature() { if (!forSigning || null == privateKey) @@ -83,13 +88,9 @@ internal byte[] GenerateSignature(Ed25519PrivateKeyParameters privateKey) { lock (this) { -#if PORTABLE || NETFX_CORE - byte[] buf = ToArray(); - int count = buf.Length; -#else byte[] buf = GetBuffer(); - int count = (int)Position; -#endif + int count = Convert.ToInt32(Length); + byte[] signature = new byte[Ed25519PrivateKeyParameters.SignatureSize]; privateKey.Sign(Ed25519.Algorithm.Ed25519, null, buf, 0, count, signature, 0); Reset(); @@ -107,13 +108,9 @@ internal bool VerifySignature(Ed25519PublicKeyParameters publicKey, byte[] signa lock (this) { -#if PORTABLE || NETFX_CORE - byte[] buf = ToArray(); - int count = buf.Length; -#else byte[] buf = GetBuffer(); - int count = (int)Position; -#endif + int count = Convert.ToInt32(Length); + byte[] pk = publicKey.GetEncoded(); bool result = Ed25519.Verify(signature, 0, pk, 0, buf, 0, count); Reset(); @@ -125,14 +122,9 @@ 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; + int count = Convert.ToInt32(Length); + Array.Clear(GetBuffer(), 0, count); + SetLength(0); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed25519ctxSigner.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed25519ctxSigner.cs index b82ac56..a23a063 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed25519ctxSigner.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed25519ctxSigner.cs @@ -6,7 +6,6 @@ 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 { @@ -58,6 +57,13 @@ public virtual void BlockUpdate(byte[] buf, int off, int len) buffer.Write(buf, off, len); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) + { + buffer.Write(input); + } +#endif + public virtual byte[] GenerateSignature() { if (!forSigning || null == privateKey) @@ -85,13 +91,9 @@ internal byte[] GenerateSignature(Ed25519PrivateKeyParameters privateKey, byte[] { lock (this) { -#if PORTABLE || NETFX_CORE - byte[] buf = ToArray(); - int count = buf.Length; -#else byte[] buf = GetBuffer(); - int count = (int)Position; -#endif + int count = Convert.ToInt32(Length); + byte[] signature = new byte[Ed25519PrivateKeyParameters.SignatureSize]; privateKey.Sign(Ed25519.Algorithm.Ed25519ctx, ctx, buf, 0, count, signature, 0); Reset(); @@ -109,13 +111,9 @@ internal bool VerifySignature(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 + int count = Convert.ToInt32(Length); + byte[] pk = publicKey.GetEncoded(); bool result = Ed25519.Verify(signature, 0, pk, 0, ctx, buf, 0, count); Reset(); @@ -127,14 +125,9 @@ 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; + int count = Convert.ToInt32(Length); + Array.Clear(GetBuffer(), 0, count); + SetLength(0); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed25519phSigner.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed25519phSigner.cs index 9f93f38..f7e3849 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed25519phSigner.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed25519phSigner.cs @@ -57,6 +57,13 @@ public virtual void BlockUpdate(byte[] buf, int off, int len) prehash.BlockUpdate(buf, off, len); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) + { + prehash.BlockUpdate(input); + } +#endif + public virtual byte[] GenerateSignature() { if (!forSigning || null == privateKey) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed448Signer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed448Signer.cs index bccc861..ff4d0fa 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed448Signer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed448Signer.cs @@ -6,7 +6,6 @@ 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 { @@ -58,6 +57,13 @@ public virtual void BlockUpdate(byte[] buf, int off, int len) buffer.Write(buf, off, len); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) + { + buffer.Write(input); + } +#endif + public virtual byte[] GenerateSignature() { if (!forSigning || null == privateKey) @@ -85,13 +91,9 @@ internal byte[] GenerateSignature(Ed448PrivateKeyParameters privateKey, byte[] c { lock (this) { -#if PORTABLE || NETFX_CORE - byte[] buf = ToArray(); - int count = buf.Length; -#else byte[] buf = GetBuffer(); - int count = (int)Position; -#endif + int count = Convert.ToInt32(Length); + byte[] signature = new byte[Ed448PrivateKeyParameters.SignatureSize]; privateKey.Sign(Ed448.Algorithm.Ed448, ctx, buf, 0, count, signature, 0); Reset(); @@ -109,13 +111,9 @@ internal bool VerifySignature(Ed448PublicKeyParameters publicKey, byte[] ctx, by lock (this) { -#if PORTABLE || NETFX_CORE - byte[] buf = ToArray(); - int count = buf.Length; -#else byte[] buf = GetBuffer(); - int count = (int)Position; -#endif + int count = Convert.ToInt32(Length); + byte[] pk = publicKey.GetEncoded(); bool result = Ed448.Verify(signature, 0, pk, 0, ctx, buf, 0, count); Reset(); @@ -127,14 +125,9 @@ 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; + int count = Convert.ToInt32(Length); + Array.Clear(GetBuffer(), 0, count); + SetLength(0); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed448phSigner.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed448phSigner.cs index a71a0d5..ca5a427 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed448phSigner.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Ed448phSigner.cs @@ -57,13 +57,20 @@ public virtual void BlockUpdate(byte[] buf, int off, int len) prehash.BlockUpdate(buf, off, len); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) + { + prehash.BlockUpdate(input); + } +#endif + 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)) + if (Ed448.PrehashSize != prehash.OutputFinal(msg, 0, Ed448.PrehashSize)) throw new InvalidOperationException("Prehash digest failed"); byte[] signature = new byte[Ed448PrivateKeyParameters.SignatureSize]; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/GOST3410DigestSigner.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/GOST3410DigestSigner.cs index b77b9e1..dcdb74a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/GOST3410DigestSigner.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/GOST3410DigestSigner.cs @@ -1,12 +1,7 @@ #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; @@ -22,11 +17,7 @@ public class Gost3410DigestSigner private int halfSize; private bool forSigning; - - - public Gost3410DigestSigner( - IDsa signer, - IDigest digest) + public Gost3410DigestSigner(IDsa signer, IDigest digest) { this.dsaSigner = signer; this.digest = digest; @@ -41,9 +32,7 @@ public virtual string AlgorithmName get { return digest.AlgorithmName + "with" + dsaSigner.AlgorithmName; } } - public virtual void Init( - bool forSigning, - ICipherParameters parameters) + public virtual void Init(bool forSigning, ICipherParameters parameters) { this.forSigning = forSigning; @@ -73,30 +62,23 @@ public virtual void Init( dsaSigner.Init(forSigning, parameters); } - /** - * update the internal digest with the byte b - */ - public virtual void Update( - byte input) + 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) + public virtual void BlockUpdate(byte[] input, int inOff, int inLen) + { + digest.BlockUpdate(input, inOff, inLen); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) { - digest.BlockUpdate(input, inOff, length); + digest.BlockUpdate(input); } +#endif - /** - * Generate a signature for the message we've been loaded with using - * the key we were initialised with. - */ public virtual byte[] GenerateSignature() { if (!forSigning) @@ -123,9 +105,7 @@ public virtual byte[] GenerateSignature() } } - /// true if the internal state represents the signature described in the passed in array. - public virtual bool VerifySignature( - byte[] signature) + public virtual bool VerifySignature(byte[] signature) { if (forSigning) throw new InvalidOperationException("DSADigestSigner not initialised for verification"); @@ -147,7 +127,6 @@ public virtual bool VerifySignature( return dsaSigner.VerifySignature(hash, R, S); } - /// Reset the internal state public virtual void Reset() { digest.Reset(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/GOST3410Signer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/GOST3410Signer.cs index fa89891..36655e8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/GOST3410Signer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/GOST3410Signer.cs @@ -13,7 +13,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers * Gost R 34.10-94 Signature Algorithm */ public class Gost3410Signer - : IDsaExt + : IDsa { private Gost3410KeyParameters key; private SecureRandom random; @@ -23,22 +23,18 @@ public virtual string AlgorithmName get { return "GOST3410"; } } - public virtual void Init( - bool forSigning, - ICipherParameters parameters) + public virtual void Init(bool forSigning, ICipherParameters parameters) { if (forSigning) { - if (parameters is ParametersWithRandom) + if (parameters is ParametersWithRandom rParam) { - ParametersWithRandom rParam = (ParametersWithRandom)parameters; - this.random = rParam.Random; parameters = rParam.Parameters; } else { - this.random = new SecureRandom(); + this.random = CryptoServicesRegistrar.GetSecureRandom(); } if (!(parameters is Gost3410PrivateKeyParameters)) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/GenericSigner.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/GenericSigner.cs index abf14d9..372c61a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/GenericSigner.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/GenericSigner.cs @@ -61,26 +61,23 @@ public virtual void Init(bool forSigning, ICipherParameters parameters) 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) + public virtual void BlockUpdate(byte[] input, int inOff, int inLen) { - digest.BlockUpdate(input, inOff, length); + digest.BlockUpdate(input, inOff, inLen); } - /** - * Generate a signature for the message we've been loaded with using the key - * we were initialised with. - */ +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) + { + digest.BlockUpdate(input); + } +#endif + public virtual byte[] GenerateSignature() { if (!forSigning) @@ -92,10 +89,6 @@ public virtual byte[] GenerateSignature() 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) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/HMacDsaKCalculator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/HMacDsaKCalculator.cs index a8cb7ca..12cec18 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/HMacDsaKCalculator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/HMacDsaKCalculator.cs @@ -48,54 +48,58 @@ 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]; + Arrays.Fill(V, 0x01); + Arrays.Fill(K, 0); BigInteger mInt = BitsToInt(message); - if (mInt.CompareTo(n) >= 0) { mInt = mInt.Subtract(n); } - byte[] mVal = BigIntegers.AsUnsignedByteArray(mInt); + int size = BigIntegers.GetUnsignedByteLength(n); - Array.Copy(mVal, 0, m, m.Length - mVal.Length, mVal.Length); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int xmSize = size * 2; + Span xm = xmSize <= 512 + ? stackalloc byte[xmSize] + : new byte[xmSize]; + BigIntegers.AsUnsignedByteArray(d, xm[..size]); + BigIntegers.AsUnsignedByteArray(mInt, xm[size..]); +#else + byte[] x = BigIntegers.AsUnsignedByteArray(size, d); + byte[] m = BigIntegers.AsUnsignedByteArray(size, mInt); +#endif hMac.Init(new KeyParameter(K)); hMac.BlockUpdate(V, 0, V.Length); - hMac.Update((byte)0x00); + hMac.Update(0x00); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + hMac.BlockUpdate(xm); +#else hMac.BlockUpdate(x, 0, x.Length); hMac.BlockUpdate(m, 0, m.Length); - +#endif + InitAdditionalInput0(hMac); 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.Update(0x01); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + hMac.BlockUpdate(xm); +#else hMac.BlockUpdate(x, 0, x.Length); hMac.BlockUpdate(m, 0, m.Length); - +#endif hMac.DoFinal(K, 0); hMac.Init(new KeyParameter(K)); - hMac.BlockUpdate(V, 0, V.Length); - hMac.DoFinal(V, 0); } @@ -110,7 +114,6 @@ public virtual BigInteger NextK() while (tOff < t.Length) { hMac.BlockUpdate(V, 0, V.Length); - hMac.DoFinal(V, 0); int len = System.Math.Min(t.Length - tOff, V.Length); @@ -121,23 +124,34 @@ public virtual BigInteger NextK() 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.Update(0x00); hMac.DoFinal(K, 0); hMac.Init(new KeyParameter(K)); - hMac.BlockUpdate(V, 0, V.Length); - hMac.DoFinal(V, 0); } } + /// Supports use of additional input. + /// + /// RFC 6979 3.6. Additional data may be added to the input of HMAC [..]. A use case may be a protocol that + /// requires a non-deterministic signature algorithm on a system that does not have access to a high-quality + /// random source. It suffices that the additional data[..] is non-repeating(e.g., a signature counter or a + /// monotonic clock) to ensure "random-looking" signatures are indistinguishable, in a cryptographic way, from + /// plain (EC)DSA signatures. + /// + /// By default there is no additional input. Override this method to supply additional input, bearing in mind + /// that this calculator may be used for many signatures. + /// + /// The to which the additional input should be added. + protected virtual void InitAdditionalInput0(HMac hmac0) + { + } + private BigInteger BitsToInt(byte[] t) { BigInteger v = new BigInteger(1, t); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Iso9796d2PssSigner.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Iso9796d2PssSigner.cs index e7772e5..ca6cd24 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Iso9796d2PssSigner.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Iso9796d2PssSigner.cs @@ -1,9 +1,7 @@ #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; @@ -28,23 +26,6 @@ public byte[] GetRecoveredMessage() return recoveredMessage; } - - public const int TrailerImplicit = 0xBC; - - public const int TrailerRipeMD160 = 0x31CC; - - public const int TrailerRipeMD128 = 0x32CC; - - public const int TrailerSha1 = 0x33CC; - - public const int TrailerSha256 = 0x34CC; - - public const int TrailerSha512 = 0x35CC; - - public const int TrailerSha384 = 0x36CC; - - public const int TrailerWhirlpool = 0x37CC; - private IDigest digest; private IAsymmetricBlockCipher cipher; @@ -130,42 +111,36 @@ public virtual string AlgorithmName /// if wrong parameter type or a fixed /// salt is passed in which is the wrong length. /// - public virtual void Init( - bool forSigning, - ICipherParameters parameters) + public virtual void Init(bool forSigning, ICipherParameters parameters) { RsaKeyParameters kParam; - if (parameters is ParametersWithRandom) + if (parameters is ParametersWithRandom withRandom) { - ParametersWithRandom p = (ParametersWithRandom) parameters; - - kParam = (RsaKeyParameters) p.Parameters; + kParam = (RsaKeyParameters)withRandom.Parameters; if (forSigning) { - random = p.Random; + random = withRandom.Random; } } - else if (parameters is ParametersWithSalt) + else if (parameters is ParametersWithSalt withSalt) { if (!forSigning) - throw new ArgumentException("ParametersWithSalt only valid for signing", "parameters"); + throw new ArgumentException("ParametersWithSalt only valid for signing", nameof(parameters)); - ParametersWithSalt p = (ParametersWithSalt) parameters; - - kParam = (RsaKeyParameters) p.Parameters; - standardSalt = p.GetSalt(); + kParam = (RsaKeyParameters)withSalt.Parameters; + standardSalt = withSalt.GetSalt(); if (standardSalt.Length != saltLength) throw new ArgumentException("Fixed salt is of wrong length"); } else { - kParam = (RsaKeyParameters) parameters; + kParam = (RsaKeyParameters)parameters; if (forSigning) { - random = new SecureRandom(); + random = CryptoServicesRegistrar.GetSecureRandom(); } } @@ -311,28 +286,47 @@ public virtual void Update( } } - /// update the internal digest with the byte array in - public virtual void BlockUpdate( - byte[] input, - int inOff, - int length) + public virtual void BlockUpdate(byte[] input, int inOff, int inLen) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BlockUpdate(input.AsSpan(inOff, inLen)); +#else if (preSig == null) { - while (length > 0 && messageLength < mBuf.Length) + while (inLen > 0 && messageLength < mBuf.Length) { this.Update(input[inOff]); inOff++; - length--; + inLen--; } } - if (length > 0) + if (inLen > 0) { - digest.BlockUpdate(input, inOff, length); + digest.BlockUpdate(input, inOff, inLen); } +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) + { + if (preSig == null) + { + while (!input.IsEmpty && messageLength < mBuf.Length) + { + this.Update(input[0]); + input = input[1..]; + } + } + + if (!input.IsEmpty) + { + digest.BlockUpdate(input); + } + } +#endif + /// reset the internal state public virtual void Reset() { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Iso9796d2Signer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Iso9796d2Signer.cs index 4a909c9..3ad22be 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Iso9796d2Signer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/Iso9796d2Signer.cs @@ -1,10 +1,7 @@ #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; @@ -23,23 +20,6 @@ public byte[] GetRecoveredMessage() return recoveredMessage; } - - public const int TrailerImplicit = 0xBC; - - public const int TrailerRipeMD160 = 0x31CC; - - public const int TrailerRipeMD128 = 0x32CC; - - public const int TrailerSha1 = 0x33CC; - - public const int TrailerSha256 = 0x34CC; - - public const int TrailerSha512 = 0x35CC; - - public const int TrailerSha384 = 0x36CC; - - public const int TrailerWhirlpool = 0x37CC; - private IDigest digest; private IAsymmetricBlockCipher cipher; @@ -240,9 +220,7 @@ public virtual void UpdateWithRecoveredMessage( recoveredMessage.CopyTo(mBuf, 0); } - /// update the internal digest with the byte b - public virtual void Update( - byte input) + public virtual void Update(byte input) { digest.Update(input); @@ -254,26 +232,42 @@ public virtual void Update( messageLength++; } - /// update the internal digest with the byte array in - public virtual void BlockUpdate( - byte[] input, - int inOff, - int length) + public virtual void BlockUpdate(byte[] input, int inOff, int inLen) { - while (length > 0 && messageLength < mBuf.Length) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BlockUpdate(input.AsSpan(inOff, inLen)); +#else + while (inLen > 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--; + inLen--; } - digest.BlockUpdate(input, inOff, length); - messageLength += length; + if (inLen > 0) + { + digest.BlockUpdate(input, inOff, inLen); + messageLength += inLen; + } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) + { + while (!input.IsEmpty && messageLength < mBuf.Length) + { + this.Update(input[0]); + input = input[1..]; + } + + if (!input.IsEmpty) + { + digest.BlockUpdate(input); + messageLength += input.Length; + } } +#endif /// reset the internal state public virtual void Reset() diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/IsoTrailers.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/IsoTrailers.cs index b388c2a..c54451b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/IsoTrailers.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/IsoTrailers.cs @@ -1,11 +1,7 @@ #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; +using System.Collections.Generic; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers { @@ -23,9 +19,9 @@ public class IsoTrailers public const int TRAILER_SHA512_224 = 0x39CC; public const int TRAILER_SHA512_256 = 0x40CC; - private static IDictionary CreateTrailerMap() + private static IDictionary CreateTrailerMap() { - IDictionary trailers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + var trailers = new Dictionary(StringComparer.OrdinalIgnoreCase); trailers.Add("RIPEMD128", TRAILER_RIPEMD128); trailers.Add("RIPEMD160", TRAILER_RIPEMD160); @@ -40,20 +36,20 @@ private static IDictionary CreateTrailerMap() trailers.Add("Whirlpool", TRAILER_WHIRLPOOL); - return CollectionUtilities.ReadOnly(trailers); + return trailers; } // IDictionary is (string -> Int32) - private static readonly IDictionary trailerMap = CreateTrailerMap(); + private static readonly IDictionary TrailerMap = CreateTrailerMap(); public static int GetTrailer(IDigest digest) { - return (int)trailerMap[digest.AlgorithmName]; + return TrailerMap[digest.AlgorithmName]; } public static bool NoTrailerAvailable(IDigest digest) { - return !trailerMap.Contains(digest.AlgorithmName); + return !TrailerMap.ContainsKey(digest.AlgorithmName); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/PssSigner.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/PssSigner.cs index d106581..8f088d4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/PssSigner.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/PssSigner.cs @@ -17,7 +17,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers public class PssSigner : ISigner { - public const byte TrailerImplicit = (byte)0xBC; + public const byte TrailerImplicit = 0xBC; private readonly IDigest contentDigest1, contentDigest2; private readonly IDigest mgfDigest; @@ -35,23 +35,23 @@ public class PssSigner private byte[] block; private byte trailer; - public static PssSigner CreateRawSigner( - IAsymmetricBlockCipher cipher, - IDigest digest) + 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) + 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 static PssSigner CreateRawSigner(IAsymmetricBlockCipher cipher, IDigest contentDigest, IDigest mgfDigest, + byte[] salt, byte trailer) + { + return new PssSigner(cipher, new NullDigest(), contentDigest, mgfDigest, salt.Length, salt, trailer); + } + public PssSigner( IAsymmetricBlockCipher cipher, IDigest digest) @@ -154,22 +154,18 @@ public virtual string AlgorithmName get { return mgfDigest.AlgorithmName + "withRSAandMGF1"; } } - public virtual void Init( - bool forSigning, - ICipherParameters parameters) + public virtual void Init(bool forSigning, ICipherParameters parameters) { - if (parameters is ParametersWithRandom) + if (parameters is ParametersWithRandom withRandom) { - ParametersWithRandom p = (ParametersWithRandom) parameters; - - parameters = p.Parameters; - random = p.Random; + parameters = withRandom.Parameters; + random = withRandom.Random; } else { if (forSigning) { - random = new SecureRandom(); + random = CryptoServicesRegistrar.GetSecureRandom(); } } @@ -178,11 +174,11 @@ public virtual void Init( RsaKeyParameters kParam; if (parameters is RsaBlindingParameters) { - kParam = ((RsaBlindingParameters) parameters).PublicKey; + kParam = ((RsaBlindingParameters)parameters).PublicKey; } else { - kParam = (RsaKeyParameters) parameters; + kParam = (RsaKeyParameters)parameters; } emBits = kParam.Modulus.BitLength - 1; @@ -200,33 +196,33 @@ private void ClearBlock( Array.Clear(block, 0, block.Length); } - /// update the internal digest with the byte b - public virtual void Update( - byte input) + 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) + public virtual void BlockUpdate(byte[] input, int inOff, int inLen) { - contentDigest1.BlockUpdate(input, inOff, length); + contentDigest1.BlockUpdate(input, inOff, inLen); } - /// reset the internal state +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) + { + contentDigest1.BlockUpdate(input); + } +#endif + 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() { + if (contentDigest1.GetDigestSize() != hLen) + throw new InvalidOperationException(); + contentDigest1.DoFinal(mDash, mDash.Length - hLen - sLen); if (sLen != 0) @@ -267,13 +263,12 @@ public virtual byte[] GenerateSignature() return b; } - /// return true if the internal state represents the signature described - /// in the passed in array. - /// - public virtual bool VerifySignature( - byte[] signature) + public virtual bool VerifySignature(byte[] signature) { - contentDigest1.DoFinal(mDash, mDash.Length - hLen - sLen); + if (contentDigest1.GetDigestSize() != hLen) + throw new InvalidOperationException(); + + contentDigest1.DoFinal(mDash, mDash.Length - hLen - sLen); byte[] b = cipher.ProcessBlock(signature, 0, signature.Length); Arrays.Fill(block, 0, block.Length - b.Length, 0); @@ -361,7 +356,7 @@ private byte[] MaskGeneratorFunction( { byte[] mask = new byte[length]; mgfDigest.BlockUpdate(Z, zOff, zLen); - ((IXof)mgfDigest).DoFinal(mask, 0, mask.Length); + ((IXof)mgfDigest).OutputFinal(mask, 0, mask.Length); return mask; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/RsaDigestSigner.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/RsaDigestSigner.cs index 8d65131..251b7e3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/RsaDigestSigner.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/RsaDigestSigner.cs @@ -1,22 +1,19 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; -using System.IO; -using System.Text; +using System.Collections.Generic; 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; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers { @@ -28,36 +25,37 @@ public class RsaDigestSigner private readonly IDigest digest; private bool forSigning; - private static readonly IDictionary oidMap = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + private static readonly IDictionary OidMap = + new Dictionary(StringComparer.OrdinalIgnoreCase); /// /// 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["SHA-512/224"] = NistObjectIdentifiers.IdSha512_224; - oidMap["SHA-512/256"] = NistObjectIdentifiers.IdSha512_256; - oidMap["SHA3-224"] = NistObjectIdentifiers.IdSha3_224; - oidMap["SHA3-256"] = NistObjectIdentifiers.IdSha3_256; - oidMap["SHA3-384"] = NistObjectIdentifiers.IdSha3_384; - oidMap["SHA3-512"] = NistObjectIdentifiers.IdSha3_512; - - oidMap["MD2"] = PkcsObjectIdentifiers.MD2; - oidMap["MD4"] = PkcsObjectIdentifiers.MD4; - oidMap["MD5"] = PkcsObjectIdentifiers.MD5; + 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["SHA-512/224"] = NistObjectIdentifiers.IdSha512_224; + OidMap["SHA-512/256"] = NistObjectIdentifiers.IdSha512_256; + OidMap["SHA3-224"] = NistObjectIdentifiers.IdSha3_224; + OidMap["SHA3-256"] = NistObjectIdentifiers.IdSha3_256; + OidMap["SHA3-384"] = NistObjectIdentifiers.IdSha3_384; + OidMap["SHA3-512"] = NistObjectIdentifiers.IdSha3_512; + + OidMap["MD2"] = PkcsObjectIdentifiers.MD2; + OidMap["MD4"] = PkcsObjectIdentifiers.MD4; + OidMap["MD5"] = PkcsObjectIdentifiers.MD5; } public RsaDigestSigner(IDigest digest) - : this(digest, (DerObjectIdentifier)oidMap[digest.AlgorithmName]) + : this(digest, CollectionUtilities.GetValueOrNull(OidMap, digest.AlgorithmName)) { } @@ -126,30 +124,23 @@ public virtual void Init( rsaEngine.Init(forSigning, parameters); } - /** - * update the internal digest with the byte b - */ - public virtual void Update( - byte input) + 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) + public virtual void BlockUpdate(byte[] input, int inOff, int inLen) { - digest.BlockUpdate(input, inOff, length); + digest.BlockUpdate(input, inOff, inLen); } - /** - * Generate a signature for the message we've been loaded with using - * the key we were initialised with. - */ +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) + { + digest.BlockUpdate(input); + } +#endif + public virtual byte[] GenerateSignature() { if (!forSigning) @@ -162,12 +153,7 @@ public virtual byte[] GenerateSignature() 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) + public virtual bool VerifySignature(byte[] signature) { if (forSigning) throw new InvalidOperationException("RsaDigestSigner not initialised for verification"); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/SM2Signer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/SM2Signer.cs index 2602103..0150038 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/SM2Signer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/SM2Signer.cs @@ -74,10 +74,8 @@ public virtual void Init(bool forSigning, ICipherParameters parameters) if (forSigning) { - if (baseParam is ParametersWithRandom) + if (baseParam is ParametersWithRandom rParam) { - ParametersWithRandom rParam = (ParametersWithRandom)baseParam; - ecKey = (ECKeyParameters)rParam.Parameters; ecParams = ecKey.Parameters; kCalculator.Init(ecParams.N, rParam.Random); @@ -86,7 +84,7 @@ public virtual void Init(bool forSigning, ICipherParameters parameters) { ecKey = (ECKeyParameters)baseParam; ecParams = ecKey.Parameters; - kCalculator.Init(ecParams.N, new SecureRandom()); + kCalculator.Init(ecParams.N, CryptoServicesRegistrar.GetSecureRandom()); } pubPoint = CreateBasePointMultiplier().Multiply(ecParams.G, ((ECPrivateKeyParameters)ecKey).D).Normalize(); } @@ -108,11 +106,18 @@ public virtual void Update(byte b) digest.Update(b); } - public virtual void BlockUpdate(byte[] buf, int off, int len) + public virtual void BlockUpdate(byte[] input, int inOff, int inLen) { - digest.BlockUpdate(buf, off, len); + digest.BlockUpdate(input, inOff, inLen); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) + { + digest.BlockUpdate(input); + } +#endif + public virtual bool VerifySignature(byte[] signature) { try diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/X931Signer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/X931Signer.cs index 605b6de..c631768 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/X931Signer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/signers/X931Signer.cs @@ -1,11 +1,11 @@ #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; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Zlib; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers { @@ -22,25 +22,6 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers public class X931Signer : ISigner { - - 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; - private IDigest digest; private IAsymmetricBlockCipher cipher; private RsaKeyParameters kParam; @@ -104,46 +85,34 @@ public virtual void Init(bool forSigning, ICipherParameters parameters) Reset(); } - /// clear possible sensitive data - private void ClearBlock(byte[] block) + public virtual void Update(byte b) { - Array.Clear(block, 0, block.Length); + digest.Update(b); } - /** - * update the internal digest with the byte b - */ - public virtual void Update(byte b) + public virtual void BlockUpdate(byte[] input, int inOff, int inLen) { - digest.Update(b); + digest.BlockUpdate(input, inOff, inLen); } - /** - * update the internal digest with the byte array in - */ - public virtual void BlockUpdate(byte[] input, int off, int len) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void BlockUpdate(ReadOnlySpan input) { - digest.BlockUpdate(input, off, len); + digest.BlockUpdate(input); } +#endif - /** - * 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); + Arrays.Fill(block, 0x00); t = t.Min(kParam.Modulus.Subtract(t)); @@ -178,10 +147,6 @@ private void CreateSignatureBlock() 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 @@ -215,12 +180,20 @@ public virtual bool VerifySignature(byte[] signature) CreateSignatureBlock(); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int fBlockSize = block.Length; + Span fBlock = fBlockSize <= 512 + ? stackalloc byte[fBlockSize] + : new byte[fBlockSize]; + BigIntegers.AsUnsignedByteArray(f, fBlock); +#else byte[] fBlock = BigIntegers.AsUnsignedByteArray(block.Length, f); +#endif bool rv = Arrays.ConstantTimeAreEqual(block, fBlock); - ClearBlock(block); - ClearBlock(fBlock); + Arrays.Fill(block, 0x00); + Arrays.Fill(fBlock, 0x00); return rv; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/util/BasicAlphabetMapper.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/util/BasicAlphabetMapper.cs index d056343..8fbbbe1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/util/BasicAlphabetMapper.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/util/BasicAlphabetMapper.cs @@ -1,9 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; - -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; +using System.Collections.Generic; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities { @@ -14,8 +12,8 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities public class BasicAlphabetMapper : IAlphabetMapper { - private readonly IDictionary indexMap = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private readonly IDictionary charMap = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + private readonly IDictionary m_indexMap = new Dictionary(); + private readonly IList m_charMap = new List(); /** * Base constructor. @@ -36,30 +34,32 @@ public BasicAlphabetMapper(char[] alphabet) { for (int i = 0; i != alphabet.Length; i++) { - if (indexMap.Contains(alphabet[i])) - { + if (m_indexMap.ContainsKey(alphabet[i])) throw new ArgumentException("duplicate key detected in alphabet: " + alphabet[i]); - } - indexMap.Add(alphabet[i], i); - charMap.Add(i, alphabet[i]); + + m_indexMap.Add(alphabet[i], i); + m_charMap.Add(alphabet[i]); } } public int Radix { - get { return indexMap.Count; } + get { return m_charMap.Count; } } public byte[] ConvertToIndexes(char[] input) { byte[] outBuf; - if (indexMap.Count <= 256) + if (m_charMap.Count <= 256) { outBuf = new byte[input.Length]; for (int i = 0; i != input.Length; i++) { - outBuf[i] = (byte)(int)indexMap[input[i]]; + if (!m_indexMap.TryGetValue(input[i], out var idx)) + throw new InvalidOperationException(); + + outBuf[i] = (byte)idx; } } else @@ -67,9 +67,11 @@ public byte[] ConvertToIndexes(char[] input) outBuf = new byte[input.Length * 2]; for (int i = 0; i != input.Length; i++) { - int idx = (int)indexMap[input[i]]; - outBuf[i * 2] = (byte)((idx >> 8) & 0xff); - outBuf[i * 2 + 1] = (byte)(idx & 0xff); + if (!m_indexMap.TryGetValue(input[i], out var idx)) + throw new InvalidOperationException(); + + outBuf[i * 2 + 0] = (byte)(idx >> 8); + outBuf[i * 2 + 1] = (byte)idx; } } @@ -80,12 +82,12 @@ public char[] ConvertToChars(byte[] input) { char[] outBuf; - if (charMap.Count <= 256) + if (m_charMap.Count <= 256) { outBuf = new char[input.Length]; for (int i = 0; i != input.Length; i++) { - outBuf[i] = (char)charMap[input[i] & 0xff]; + outBuf[i] = m_charMap[input[i]]; } } else @@ -98,7 +100,7 @@ public char[] ConvertToChars(byte[] input) outBuf = new char[input.Length / 2]; for (int i = 0; i != input.Length; i += 2) { - outBuf[i / 2] = (char)charMap[((input[i] << 8) & 0xff00) | (input[i + 1] & 0xff)]; + outBuf[i / 2] = m_charMap[(input[i] << 8) | input[i + 1]]; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/util/CipherFactory.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/util/CipherFactory.cs index 66f4b05..0199689 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/util/CipherFactory.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/util/CipherFactory.cs @@ -112,13 +112,13 @@ public static object CreateContentCipher(bool forEncryption, ICipherParameters e private static BufferedBlockCipher CreateCipher(DerObjectIdentifier algorithm) { - IBlockCipher cipher; + IBlockCipherMode cipher; if (NistObjectIdentifiers.IdAes128Cbc.Equals(algorithm) || NistObjectIdentifiers.IdAes192Cbc.Equals(algorithm) || NistObjectIdentifiers.IdAes256Cbc.Equals(algorithm)) { - cipher = new CbcBlockCipher(new AesEngine()); + cipher = new CbcBlockCipher(AesUtilities.CreateEngine()); } else if (PkcsObjectIdentifiers.DesEde3Cbc.Equals(algorithm)) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/util/CipherKeyGeneratorFactory.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/util/CipherKeyGeneratorFactory.cs index 0bf8a22..6b98021 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/util/CipherKeyGeneratorFactory.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/util/CipherKeyGeneratorFactory.cs @@ -13,12 +13,8 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities { - public class CipherKeyGeneratorFactory + public static class CipherKeyGeneratorFactory { - private CipherKeyGeneratorFactory() - { - } - /** * Create a key generator for the passed in Object Identifier. * diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/util/Pack.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/util/Pack.cs index 750366b..60e6c19 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/util/Pack.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/crypto/util/Pack.cs @@ -1,34 +1,44 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ +using System.Buffers.Binary; +#endif +using System.Diagnostics; +using System.Runtime.CompilerServices; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities { - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] internal static class Pack { internal static void UInt16_To_BE(ushort n, byte[] bs) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BinaryPrimitives.WriteUInt16BigEndian(bs, n); +#else bs[0] = (byte)(n >> 8); - bs[1] = (byte)(n); + bs[1] = (byte)n; +#endif } internal static void UInt16_To_BE(ushort n, byte[] bs, int off) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BinaryPrimitives.WriteUInt16BigEndian(bs.AsSpan(off), n); +#else bs[off] = (byte)(n >> 8); - bs[off + 1] = (byte)(n); + bs[off + 1] = (byte)n; +#endif } - //internal static ushort BE_To_UInt16(byte[] bs) - //{ - // for (int i = 0; i < ns.Length; ++i) - // { - // UInt16_To_BE(ns[i], bs, off); - // off += 2; - // } - //} + internal static void UInt16_To_BE(ushort[] ns, byte[] bs, int off) + { + for (int i = 0; i < ns.Length; ++i) + { + UInt16_To_BE(ns[i], bs, off); + off += 2; + } + } internal static void UInt16_To_BE(ushort[] ns, int nsOff, int nsLen, byte[] bs, int bsOff) { @@ -60,9 +70,13 @@ internal static byte[] UInt16_To_BE(ushort[] ns, int nsOff, int nsLen) internal static ushort BE_To_UInt16(byte[] bs, int off) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return BinaryPrimitives.ReadUInt16BigEndian(bs.AsSpan(off)); +#else uint n = (uint)bs[off] << 8 - | (uint)bs[off + 1]; + | bs[off + 1]; return (ushort)n; +#endif } internal static void BE_To_UInt16(byte[] bs, int bsOff, ushort[] ns, int nsOff) @@ -82,7 +96,7 @@ internal static ushort[] BE_To_UInt16(byte[] bs, int off, int len) ushort[] ns = new ushort[len / 2]; for (int i = 0; i < len; i += 2) - { + { BE_To_UInt16(bs, off + i, ns, i >> 1); } return ns; @@ -90,18 +104,26 @@ internal static ushort[] BE_To_UInt16(byte[] bs, int off, int len) internal static void UInt32_To_BE(uint n, byte[] bs) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BinaryPrimitives.WriteUInt32BigEndian(bs, n); +#else bs[0] = (byte)(n >> 24); bs[1] = (byte)(n >> 16); bs[2] = (byte)(n >> 8); - bs[3] = (byte)(n); + bs[3] = (byte)n; +#endif } internal static void UInt32_To_BE(uint n, byte[] bs, int off) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BinaryPrimitives.WriteUInt32BigEndian(bs.AsSpan(off), n); +#else bs[off] = (byte)(n >> 24); bs[off + 1] = (byte)(n >> 16); bs[off + 2] = (byte)(n >> 8); - bs[off + 3] = (byte)(n); + bs[off + 3] = (byte)n; +#endif } internal static void UInt32_To_BE(uint[] ns, byte[] bs, int off) @@ -138,18 +160,39 @@ internal static byte[] UInt32_To_BE(uint[] ns) internal static uint BE_To_UInt32(byte[] bs) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return BinaryPrimitives.ReadUInt32BigEndian(bs); +#else return (uint)bs[0] << 24 | (uint)bs[1] << 16 | (uint)bs[2] << 8 - | (uint)bs[3]; + | bs[3]; +#endif } internal static uint BE_To_UInt32(byte[] bs, int off) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return BinaryPrimitives.ReadUInt32BigEndian(bs.AsSpan(off)); +#else return (uint)bs[off] << 24 | (uint)bs[off + 1] << 16 | (uint)bs[off + 2] << 8 - | (uint)bs[off + 3]; + | bs[off + 3]; +#endif + } + + internal static uint BE_To_UInt32_Partial(byte[] bs, int off, int len) + { + Debug.Assert(1 <= len && len <= 4); + + uint result = bs[off]; + for (int i = 1; i < len; ++i) + { + result <<= 8; + result |= bs[off + i]; + } + return result; } internal static void BE_To_UInt32(byte[] bs, int off, uint[] ns) @@ -179,14 +222,22 @@ internal static byte[] UInt64_To_BE(ulong n) internal static void UInt64_To_BE(ulong n, byte[] bs) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BinaryPrimitives.WriteUInt64BigEndian(bs, n); +#else UInt32_To_BE((uint)(n >> 32), bs); - UInt32_To_BE((uint)(n), bs, 4); + UInt32_To_BE((uint)n, bs, 4); +#endif } internal static void UInt64_To_BE(ulong n, byte[] bs, int off) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BinaryPrimitives.WriteUInt64BigEndian(bs.AsSpan(off), n); +#else UInt32_To_BE((uint)(n >> 32), bs, off); - UInt32_To_BE((uint)(n), bs, off + 4); + UInt32_To_BE((uint)n, bs, off + 4); +#endif } internal static byte[] UInt64_To_BE(ulong[] ns) @@ -208,17 +259,45 @@ internal static void UInt64_To_BE(ulong[] ns, byte[] bs, int off) internal static void UInt64_To_BE(ulong[] ns, int nsOff, int nsLen, byte[] bs, int bsOff) { for (int i = 0; i < nsLen; ++i) - { + { UInt64_To_BE(ns[nsOff + i], bs, bsOff); bsOff += 8; } } + internal static ulong BE_To_UInt64(byte[] bs) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return BinaryPrimitives.ReadUInt64BigEndian(bs); +#else + uint hi = BE_To_UInt32(bs); + uint lo = BE_To_UInt32(bs, 4); + return ((ulong)hi << 32) | (ulong)lo; +#endif + } + internal static ulong BE_To_UInt64(byte[] bs, int off) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return BinaryPrimitives.ReadUInt64BigEndian(bs.AsSpan(off)); +#else uint hi = BE_To_UInt32(bs, off); uint lo = BE_To_UInt32(bs, off + 4); return ((ulong)hi << 32) | (ulong)lo; +#endif + } + + internal static ulong BE_To_UInt64_Partial(byte[] bs, int off, int len) + { + Debug.Assert(1 <= len && len <= 8); + + ulong result = bs[off]; + for (int i = 1; i < len; ++i) + { + result <<= 8; + result |= bs[off + i]; + } + return result; } internal static void BE_To_UInt64(byte[] bs, int off, ulong[] ns) @@ -238,31 +317,54 @@ internal static void BE_To_UInt64(byte[] bs, int bsOff, ulong[] ns, int nsOff, i bsOff += 8; } } - + internal static void UInt16_To_LE(ushort n, byte[] bs) { - bs[0] = (byte)(n); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BinaryPrimitives.WriteUInt16LittleEndian(bs, n); +#else + bs[0] = (byte)n; bs[1] = (byte)(n >> 8); +#endif } internal static void UInt16_To_LE(ushort n, byte[] bs, int off) { - bs[off] = (byte)(n); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BinaryPrimitives.WriteUInt16LittleEndian(bs.AsSpan(off), n); +#else + bs[off] = (byte)n; bs[off + 1] = (byte)(n >> 8); +#endif + } + + internal static byte[] UInt16_To_LE(ushort n) + { + byte[] bs = new byte[2]; + UInt16_To_LE(n, bs, 0); + return bs; } internal static ushort LE_To_UInt16(byte[] bs) { - uint n = (uint)bs[0] +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return BinaryPrimitives.ReadUInt16LittleEndian(bs); +#else + uint n = bs[0] | (uint)bs[1] << 8; return (ushort)n; +#endif } internal static ushort LE_To_UInt16(byte[] bs, int off) { - uint n = (uint)bs[off] +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return BinaryPrimitives.ReadUInt16LittleEndian(bs.AsSpan(off)); +#else + uint n = bs[off] | (uint)bs[off + 1] << 8; return (ushort)n; +#endif } internal static byte[] UInt32_To_LE(uint n) @@ -274,18 +376,27 @@ internal static byte[] UInt32_To_LE(uint n) internal static void UInt32_To_LE(uint n, byte[] bs) { - bs[0] = (byte)(n); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BinaryPrimitives.WriteUInt32LittleEndian(bs, n); +#else + bs[0] = (byte)n; bs[1] = (byte)(n >> 8); bs[2] = (byte)(n >> 16); bs[3] = (byte)(n >> 24); +#endif } + [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void UInt32_To_LE(uint n, byte[] bs, int off) { - bs[off] = (byte)(n); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BinaryPrimitives.WriteUInt32LittleEndian(bs.AsSpan(off), n); +#else + bs[off] = (byte)n; bs[off + 1] = (byte)(n >> 8); bs[off + 2] = (byte)(n >> 16); bs[off + 3] = (byte)(n >> 24); +#endif } internal static byte[] UInt32_To_LE(uint[] ns) @@ -312,21 +423,37 @@ internal static void UInt32_To_LE(uint[] ns, int nsOff, int nsLen, byte[] bs, in bsOff += 4; } } - + + internal static uint LE_To_UInt24(byte[] bs, int off) + { + return bs[off] + | (uint)bs[off + 1] << 8 + | (uint)bs[off + 2] << 16; + } + internal static uint LE_To_UInt32(byte[] bs) { - return (uint)bs[0] +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return BinaryPrimitives.ReadUInt32LittleEndian(bs); +#else + return bs[0] | (uint)bs[1] << 8 | (uint)bs[2] << 16 | (uint)bs[3] << 24; +#endif } + [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static uint LE_To_UInt32(byte[] bs, int off) { - return (uint)bs[off] +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return BinaryPrimitives.ReadUInt32LittleEndian(bs.AsSpan(off)); +#else + return bs[off] | (uint)bs[off + 1] << 8 | (uint)bs[off + 2] << 16 | (uint)bs[off + 3] << 24; +#endif } internal static void LE_To_UInt32(byte[] bs, int off, uint[] ns) @@ -367,14 +494,22 @@ internal static byte[] UInt64_To_LE(ulong n) internal static void UInt64_To_LE(ulong n, byte[] bs) { - UInt32_To_LE((uint)(n), bs); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BinaryPrimitives.WriteUInt64LittleEndian(bs, n); +#else + UInt32_To_LE((uint)n, bs); UInt32_To_LE((uint)(n >> 32), bs, 4); +#endif } internal static void UInt64_To_LE(ulong n, byte[] bs, int off) { - UInt32_To_LE((uint)(n), bs, off); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + BinaryPrimitives.WriteUInt64LittleEndian(bs.AsSpan(off), n); +#else + UInt32_To_LE((uint)n, bs, off); UInt32_To_LE((uint)(n >> 32), bs, off + 4); +#endif } internal static byte[] UInt64_To_LE(ulong[] ns) @@ -404,16 +539,24 @@ internal static void UInt64_To_LE(ulong[] ns, int nsOff, int nsLen, byte[] bs, i internal static ulong LE_To_UInt64(byte[] bs) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return BinaryPrimitives.ReadUInt64LittleEndian(bs); +#else uint lo = LE_To_UInt32(bs); uint hi = LE_To_UInt32(bs, 4); return ((ulong)hi << 32) | (ulong)lo; +#endif } internal static ulong LE_To_UInt64(byte[] bs, int off) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return BinaryPrimitives.ReadUInt64LittleEndian(bs.AsSpan(off)); +#else uint lo = LE_To_UInt32(bs, off); uint hi = LE_To_UInt32(bs, off + 4); return ((ulong)hi << 32) | (ulong)lo; +#endif } internal static void LE_To_UInt64(byte[] bs, int off, ulong[] ns) @@ -433,6 +576,184 @@ internal static void LE_To_UInt64(byte[] bs, int bsOff, ulong[] ns, int nsOff, i bsOff += 8; } } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static uint BE_To_UInt32(ReadOnlySpan bs) + { + return BinaryPrimitives.ReadUInt32BigEndian(bs); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void BE_To_UInt32(ReadOnlySpan bs, Span ns) + { + for (int i = 0; i < ns.Length; ++i) + { + ns[i] = BE_To_UInt32(bs); + bs = bs[4..]; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static uint BE_To_UInt32_Partial(ReadOnlySpan bs) + { + int len = bs.Length; + Debug.Assert(1 <= len && len <= 4); + + uint result = bs[0]; + for (int i = 1; i < len; ++i) + { + result <<= 8; + result |= bs[i]; + } + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static ulong BE_To_UInt64(ReadOnlySpan bs) + { + return BinaryPrimitives.ReadUInt64BigEndian(bs); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void BE_To_UInt64(ReadOnlySpan bs, Span ns) + { + for (int i = 0; i < ns.Length; ++i) + { + ns[i] = BE_To_UInt64(bs); + bs = bs[8..]; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static ulong BE_To_UInt64_Partial(ReadOnlySpan bs) + { + int len = bs.Length; + Debug.Assert(1 <= len && len <= 8); + + ulong result = bs[0]; + for (int i = 1; i < len; ++i) + { + result <<= 8; + result |= bs[i]; + } + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static ushort LE_To_UInt16(ReadOnlySpan bs) + { + return BinaryPrimitives.ReadUInt16LittleEndian(bs); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static uint LE_To_UInt32(ReadOnlySpan bs) + { + return BinaryPrimitives.ReadUInt32LittleEndian(bs); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void LE_To_UInt32(ReadOnlySpan bs, Span ns) + { + for (int i = 0; i < ns.Length; ++i) + { + ns[i] = LE_To_UInt32(bs); + bs = bs[4..]; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static ulong LE_To_UInt64(ReadOnlySpan bs) + { + return BinaryPrimitives.ReadUInt64LittleEndian(bs); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void LE_To_UInt64(ReadOnlySpan bs, Span ns) + { + for (int i = 0; i < ns.Length; ++i) + { + ns[i] = LE_To_UInt64(bs); + bs = bs[8..]; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void UInt16_To_BE(ushort n, Span bs) + { + BinaryPrimitives.WriteUInt16BigEndian(bs, n); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void UInt16_To_LE(ushort n, Span bs) + { + BinaryPrimitives.WriteUInt16LittleEndian(bs, n); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void UInt32_To_BE(uint n, Span bs) + { + BinaryPrimitives.WriteUInt32BigEndian(bs, n); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void UInt32_To_BE(ReadOnlySpan ns, Span bs) + { + for (int i = 0; i < ns.Length; ++i) + { + UInt32_To_BE(ns[i], bs); + bs = bs[4..]; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void UInt32_To_LE(uint n, Span bs) + { + BinaryPrimitives.WriteUInt32LittleEndian(bs, n); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void UInt32_To_LE(ReadOnlySpan ns, Span bs) + { + for (int i = 0; i < ns.Length; ++i) + { + UInt32_To_LE(ns[i], bs); + bs = bs[4..]; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void UInt64_To_BE(ulong n, Span bs) + { + BinaryPrimitives.WriteUInt64BigEndian(bs, n); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void UInt64_To_BE(ReadOnlySpan ns, Span bs) + { + for (int i = 0; i < ns.Length; ++i) + { + UInt64_To_BE(ns[i], bs); + bs = bs[8..]; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void UInt64_To_LE(ulong n, Span bs) + { + BinaryPrimitives.WriteUInt64LittleEndian(bs, n); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void UInt64_To_LE(ReadOnlySpan ns, Span bs) + { + for (int i = 0; i < ns.Length; ++i) + { + UInt64_To_LE(ns[i], bs); + bs = bs[8..]; + } + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/BigInteger.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/BigInteger.cs index 804295f..6e292aa 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/BigInteger.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/BigInteger.cs @@ -1,20 +1,23 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.Diagnostics; using System.Globalization; +#if NETCOREAPP3_0_OR_GREATER +using System.Numerics; +#endif +using System.Runtime.Serialization; using System.Text; - +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math { -#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE) [Serializable] -#endif - public class BigInteger + public sealed class BigInteger + : IComparable, IEquatable { // The first few odd primes /* @@ -139,26 +142,7 @@ 1231 1237 1249 1259 1277 1279 1283 1289 public static readonly BigInteger Four; public static readonly BigInteger Ten; - //private readonly static byte[] BitCountTable = - //{ - // 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, - // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - // 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 - //}; - +#if !NETCOREAPP3_0_OR_GREATER private readonly static byte[] BitLengthTable = { 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, @@ -178,19 +162,18 @@ 1231 1237 1249 1259 1277 1279 1283 1289 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }; +#endif // TODO Parse radix-2 64 bits at a time and radix-8 63 bits at a time private const int chunk2 = 1, chunk8 = 1, chunk10 = 19, chunk16 = 16; private static readonly BigInteger radix2, radix2E, radix8, radix8E, radix10, radix10E, radix16, radix16E; - private static readonly SecureRandom RandomSource = new SecureRandom(); - /* * These are the threshold bit-lengths (of an exponent) where we increase the window size. * They are calculated according to the expected savings in multiplications. * Some squares will also be saved on average, but we offset these against the extra storage costs. */ - private static readonly int[] ExpWindowThresholds = { 7, 25, 81, 241, 673, 1793, 4609, Int32.MaxValue }; + private static readonly int[] ExpWindowThresholds = { 7, 25, 81, 241, 673, 1793, 4609, int.MaxValue }; private const int BitsPerByte = 8; private const int BitsPerInt = 32; @@ -241,19 +224,27 @@ static BigInteger() private int[] magnitude; // array of ints with [0] being the most significant private int sign; // -1 means -ve; +1 means +ve; 0 means 0; + + [NonSerialized] private int nBits = -1; // cache BitCount() value + [NonSerialized] private int nBitLength = -1; // cache BitLength() value - private int mQuote = 0; // -m^(-1) mod b, b = 2^32 (see Montgomery mult.), 0 when uninitialised - private static int GetByteLength( - int nBits) + [OnDeserialized] + private void OnDeserialized(StreamingContext context) + { + this.nBits = -1; + this.nBitLength = -1; + } + + private static int GetByteLength(int nBits) { return (nBits + BitsPerByte - 1) / BitsPerByte; } public static BigInteger Arbitrary(int sizeInBits) { - return new BigInteger(sizeInBits, RandomSource); + return new BigInteger(sizeInBits, SecureRandom.ArbitraryRandom); } private BigInteger( @@ -363,7 +354,7 @@ public BigInteger( } // strip leading zeros from the string str - while (index < str.Length && Int32.Parse(str[index].ToString(), style) == 0) + while (index < str.Length && int.Parse(str[index].ToString(), style) == 0) { index++; } @@ -475,7 +466,7 @@ public BigInteger( // { // char c = value[index]; // string s = c.ToString(); -// int i = Int32.Parse(s, style); +// int i = int.Parse(s, style); // // b = b.Multiply(r).Add(ValueOf(i)); // index++; @@ -518,7 +509,14 @@ public BigInteger( else { int numBytes = end - iBval; + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span inverse = numBytes <= 512 + ? stackalloc byte[numBytes] + : new byte[numBytes]; +#else byte[] inverse = new byte[numBytes]; +#endif int index = 0; while (index < numBytes) @@ -535,7 +533,7 @@ public BigInteger( inverse[index]++; - this.magnitude = MakeMagnitude(inverse, 0, inverse.Length); + this.magnitude = MakeMagnitude(inverse); } } else @@ -546,24 +544,26 @@ public BigInteger( } } - private static int[] MakeMagnitude( - byte[] bytes, - int offset, - int length) + private static int[] MakeMagnitude(byte[] bytes) + { + return MakeMagnitude(bytes, 0, bytes.Length); + } + + private static int[] MakeMagnitude(byte[] bytes, int offset, int length) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return MakeMagnitude(bytes.AsSpan(offset, length)); +#else int end = offset + length; // strip leading zeros int firstSignificant; - for (firstSignificant = offset; firstSignificant < end - && bytes[firstSignificant] == 0; firstSignificant++) + for (firstSignificant = offset; firstSignificant < end && bytes[firstSignificant] == 0; firstSignificant++) { } if (firstSignificant >= end) - { return ZeroMagnitude; - } int nInts = (end - firstSignificant + 3) / BytesPerInt; int bCount = (end - firstSignificant) % BytesPerInt; @@ -573,10 +573,59 @@ private static int[] MakeMagnitude( } if (nInts < 1) + return ZeroMagnitude; + + int[] mag = new int[nInts]; + + int v = 0; + int magnitudeIndex = 0; + for (int i = firstSignificant; i < end; ++i) { + v <<= 8; + v |= bytes[i] & 0xff; + bCount--; + if (bCount <= 0) + { + mag[magnitudeIndex] = v; + magnitudeIndex++; + bCount = BytesPerInt; + v = 0; + } + } + + if (magnitudeIndex < mag.Length) + { + mag[magnitudeIndex] = v; + } + + return mag; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static int[] MakeMagnitude(ReadOnlySpan bytes) + { + int end = bytes.Length; + + // strip leading zeros + int firstSignificant; + for (firstSignificant = 0; firstSignificant < end && bytes[firstSignificant] == 0; firstSignificant++) + { + } + + if (firstSignificant >= end) return ZeroMagnitude; + + int nInts = (end - firstSignificant + 3) / BytesPerInt; + int bCount = (end - firstSignificant) % BytesPerInt; + if (bCount == 0) + { + bCount = BytesPerInt; } + if (nInts < 1) + return ZeroMagnitude; + int[] mag = new int[nInts]; int v = 0; @@ -602,19 +651,14 @@ private static int[] MakeMagnitude( return mag; } +#endif - public BigInteger( - int sign, - byte[] bytes) + public BigInteger(int sign, byte[] bytes) : this(sign, bytes, 0, bytes.Length) { } - public BigInteger( - int sign, - byte[] bytes, - int offset, - int length) + public BigInteger(int sign, byte[] bytes, int offset, int length) { if (sign < -1 || sign > 1) throw new FormatException("Invalid sign value"); @@ -632,6 +676,26 @@ public BigInteger( } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public BigInteger(int sign, ReadOnlySpan bytes) + { + if (sign < -1 || sign > 1) + throw new FormatException("Invalid sign value"); + + if (sign == 0) + { + this.sign = 0; + this.magnitude = ZeroMagnitude; + } + else + { + // copy bytes + this.magnitude = MakeMagnitude(bytes); + this.sign = this.magnitude.Length < 1 ? 0 : sign; + } + } +#endif + public BigInteger( int sizeInBits, Random random) @@ -650,14 +714,21 @@ public BigInteger( } int nBytes = GetByteLength(sizeInBits); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span b = nBytes <= 512 + ? stackalloc byte[nBytes] + : new byte[nBytes]; +#else byte[] b = new byte[nBytes]; +#endif random.NextBytes(b); // strip off any excess bits in the MSB int xBits = BitsPerByte * nBytes - sizeInBits; b[0] &= (byte)(255U >> xBits); - this.magnitude = MakeMagnitude(b, 0, b.Length); + this.magnitude = MakeMagnitude(b); this.sign = this.magnitude.Length < 1 ? 0 : 1; } @@ -681,7 +752,14 @@ public BigInteger( } int nBytes = GetByteLength(bitLength); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span b = nBytes <= 512 + ? stackalloc byte[nBytes] + : new byte[nBytes]; +#else byte[] b = new byte[nBytes]; +#endif int xBits = BitsPerByte * nBytes - bitLength; byte mask = (byte)(255U >> xBits); @@ -700,9 +778,8 @@ public BigInteger( // ensure the trailing bit is 1 (i.e. must be odd) b[nBytes - 1] |= 1; - this.magnitude = MakeMagnitude(b, 0, b.Length); + this.magnitude = MakeMagnitude(b); this.nBits = -1; - this.mQuote = 0; if (certainty < 1) break; @@ -902,6 +979,9 @@ public int BitCount public static int BitCnt(int i) { +#if NETCOREAPP3_0_OR_GREATER + return BitOperations.PopCount((uint)i); +#else uint u = (uint)i; u = u - ((u >> 1) & 0x55555555); u = (u & 0x33333333) + ((u >> 2) & 0x33333333); @@ -910,6 +990,7 @@ public static int BitCnt(int i) u += (u >> 16); u &= 0x3f; return (int)u; +#endif } private static int CalcBitLength(int sign, int indx, int[] mag) @@ -964,11 +1045,20 @@ public int BitLength } } - // - // BitLen(value) is the number of bits in value. - // - internal static int BitLen(int w) + private static int BitLen(byte b) { +#if NETCOREAPP3_0_OR_GREATER + return 32 - BitOperations.LeadingZeroCount((uint)b); +#else + return BitLengthTable[b]; +#endif + } + + private static int BitLen(int w) + { +#if NETCOREAPP3_0_OR_GREATER + return 32 - BitOperations.LeadingZeroCount((uint)w); +#else uint v = (uint)w; uint t = v >> 24; if (t != 0) @@ -980,6 +1070,7 @@ internal static int BitLen(int w) if (t != 0) return 8 + BitLengthTable[t]; return BitLengthTable[v]; +#endif } private bool QuickPow2Check() @@ -987,10 +1078,18 @@ private bool QuickPow2Check() return sign > 0 && nBits == 1; } - public int CompareTo( - object obj) + public int CompareTo(BigInteger other) { - return CompareTo((BigInteger)obj); + if (other == null) + return 1; + + return sign < other.sign + ? -1 + : sign > other.sign + ? 1 + : sign == 0 + ? 0 + : sign * CompareNoLeadingZeroes(0, magnitude, 0, other.magnitude); } /** @@ -1043,15 +1142,6 @@ private static int CompareNoLeadingZeroes( return 0; } - public int CompareTo( - BigInteger value) - { - return sign < value.sign ? -1 - : sign > value.sign ? 1 - : sign == 0 ? 0 - : sign * CompareNoLeadingZeroes(0, magnitude, 0, value.magnitude); - } - /** * return z = x / y - done in place (z value preserved, x contains the * remainder) @@ -1242,19 +1332,26 @@ public BigInteger[] DivideAndRemainder( return biggies; } - public override bool Equals( - object obj) + public override bool Equals(object obj) { if (obj == this) return true; - - BigInteger biggie = obj as BigInteger; - if (biggie == null) + if (!(obj is BigInteger biggie)) return false; return sign == biggie.sign && IsEqualMagnitude(biggie); } + public bool Equals(BigInteger other) + { + if (other == this) + return true; + if (other == null) + return false; + + return sign == other.sign && IsEqualMagnitude(other); + } + private bool IsEqualMagnitude(BigInteger x) { int[] xMag = x.magnitude; @@ -1368,7 +1465,7 @@ internal bool IsProbablePrime(int certainty, bool randomlySelected) if (n.Equals(One)) return false; - return n.CheckProbablePrime(certainty, RandomSource, randomlySelected); + return n.CheckProbablePrime(certainty, SecureRandom.ArbitraryRandom, randomlySelected); } private bool CheckProbablePrime(int certainty, Random random, bool randomlySelected) @@ -1664,7 +1761,7 @@ public BigInteger ModInverse( // if (F.Equals(One)) // { // BigInteger half = m.Add(One).ShiftRight(1); -// BigInteger halfK = half.ModPow(BigInteger.ValueOf(k), m); +// BigInteger halfK = half.ModPow(ValueOf(k), m); // return B.Multiply(halfK).Mod(m); // } // @@ -1711,13 +1808,13 @@ private BigInteger ModInversePow2(BigInteger m) int pow = m.BitLength - 1; - long inv64 = ModInverse64(LongValue); + long inv64 = (long)Raw.Mod.Inverse64((ulong)LongValue); if (pow < 64) { inv64 &= ((1L << pow) - 1); } - BigInteger x = BigInteger.ValueOf(inv64); + BigInteger x = ValueOf(inv64); if (pow > 64) { @@ -1741,33 +1838,6 @@ private BigInteger ModInversePow2(BigInteger m) return x; } - private static int ModInverse32(int d) - { - // Newton's method with initial estimate "correct to 4 bits" - Debug.Assert((d & 1) != 0); - int x = d + (((d + 1) & 4) << 1); // d.x == 1 mod 2**4 - Debug.Assert(((d * x) & 15) == 1); - x *= 2 - d * x; // d.x == 1 mod 2**8 - x *= 2 - d * x; // d.x == 1 mod 2**16 - x *= 2 - d * x; // d.x == 1 mod 2**32 - Debug.Assert(d * x == 1); - return x; - } - - private static long ModInverse64(long d) - { - // Newton's method with initial estimate "correct to 4 bits" - Debug.Assert((d & 1L) != 0); - long x = d + (((d + 1L) & 4L) << 1); // d.x == 1 mod 2**4 - Debug.Assert(((d * x) & 15L) == 1L); - x *= 2 - d * x; // d.x == 1 mod 2**8 - x *= 2 - d * x; // d.x == 1 mod 2**16 - x *= 2 - d * x; // d.x == 1 mod 2**32 - x *= 2 - d * x; // d.x == 1 mod 2**64 - Debug.Assert(d * x == 1L); - return x; - } - /** * Calculate the numbers u1, u2, and u3 such that: * @@ -1901,7 +1971,7 @@ private static BigInteger ModPowBarrett(BigInteger b, BigInteger e, BigInteger m { mult = window & 0xFF; - int bits = lastZeroes + BitLengthTable[mult]; + int bits = lastZeroes + BitLen((byte)mult); for (int j = 0; j < bits; ++j) { y = ReduceBarrett(y.Square(), m, mr, yu); @@ -2026,7 +2096,7 @@ private static BigInteger ModPowMonty(BigInteger b, BigInteger e, BigInteger m, { mult = window & 0xFF; - int bits = lastZeroes + BitLengthTable[mult]; + int bits = lastZeroes + BitLen((byte)mult); for (int j = 0; j < bits; ++j) { SquareMonty(yAccum, yVal, m.magnitude, mDash, smallMontyModulus); @@ -2111,11 +2181,19 @@ private static int[] GetWindowList(int[] mag, int extraBits) private static int CreateWindowEntry(int mult, int zeroes) { + Debug.Assert(mult > 0); + +#if NETCOREAPP3_0_OR_GREATER + int tz = BitOperations.TrailingZeroCount(mult); + mult >>= tz; + zeroes += tz; +#else while ((mult & 1) == 0) { mult >>= 1; ++zeroes; } +#endif return mult | (zeroes << 8); } @@ -2234,18 +2312,13 @@ private static int[] Multiply(int[] x, int[] y, int[] z) */ private int GetMQuote() { - if (mQuote != 0) - { - return mQuote; // already calculated - } - Debug.Assert(this.sign > 0); int d = -magnitude[magnitude.Length - 1]; Debug.Assert((d & 1) != 0); - return mQuote = ModInverse32(d); + return (int)Raw.Mod.Inverse32((uint)d); } private static void MontgomeryReduce(int[] x, int[] m, uint mDash) // mDash = -m^(-1) mod b @@ -2541,7 +2614,7 @@ public BigInteger NextProbablePrime() BigInteger n = Inc().SetBit(0); - while (!n.CheckProbablePrime(100, RandomSource, false)) + while (!n.CheckProbablePrime(100, SecureRandom.ArbitraryRandom, false)) { n = n.Add(Two); } @@ -2572,7 +2645,7 @@ public BigInteger Pow(int exp) if (QuickPow2Check()) { long powOf2 = (long)exp * (BitLength - 1); - if (powOf2 > Int32.MaxValue) + if (powOf2 > int.MaxValue) { throw new ArithmeticException("Result too large"); } @@ -2790,7 +2863,7 @@ private int[] LastNBits( int excessBits = (numWords << 5) - n; if (excessBits > 0) { - result[0] &= (int)(UInt32.MaxValue >> excessBits); + result[0] &= (int)(uint.MaxValue >> excessBits); } return result; @@ -3102,18 +3175,41 @@ private static int[] doSubBigLil( return Subtract(0, res, 0, lilMag); } + public int GetLengthofByteArray() + { + return GetByteLength(BitLength + 1); + } + + public int GetLengthofByteArrayUnsigned() + { + return GetByteLength(sign < 0 ? BitLength + 1 : BitLength); + } + public byte[] ToByteArray() { return ToByteArray(false); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void ToByteArray(Span output) + { + ToByteArray(false, output); + } +#endif + public byte[] ToByteArrayUnsigned() { return ToByteArray(true); } - private byte[] ToByteArray( - bool unsigned) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void ToByteArrayUnsigned(Span output) + { + ToByteArray(true, output); + } +#endif + + private byte[] ToByteArray(bool unsigned) { if (sign == 0) return unsigned ? ZeroEncoding : new byte[1]; @@ -3133,10 +3229,8 @@ private byte[] ToByteArray( while (magIndex > 1) { uint mag = (uint) magnitude[--magIndex]; - bytes[--bytesIndex] = (byte) mag; - bytes[--bytesIndex] = (byte)(mag >> 8); - bytes[--bytesIndex] = (byte)(mag >> 16); - bytes[--bytesIndex] = (byte)(mag >> 24); + bytesIndex -= 4; + Pack.UInt32_To_BE(mag, bytes, bytesIndex); } uint lastMag = (uint) magnitude[0]; @@ -3161,10 +3255,8 @@ private byte[] ToByteArray( carry = (++mag == uint.MinValue); } - bytes[--bytesIndex] = (byte) mag; - bytes[--bytesIndex] = (byte)(mag >> 8); - bytes[--bytesIndex] = (byte)(mag >> 16); - bytes[--bytesIndex] = (byte)(mag >> 24); + bytesIndex -= 4; + Pack.UInt32_To_BE(mag, bytes, bytesIndex); } uint lastMag = (uint) magnitude[0]; @@ -3192,6 +3284,86 @@ private byte[] ToByteArray( return bytes; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void ToByteArray(bool unsigned, Span output) + { + if (sign == 0) + { + if (!unsigned) + { + output[0] = 0; + } + return; + } + + int nBits = (unsigned && sign > 0) ? BitLength : BitLength + 1; + + int nBytes = GetByteLength(nBits); + if (nBytes > output.Length) + throw new ArgumentException("insufficient space", nameof(output)); + + int magIndex = magnitude.Length; + int bytesIndex = nBytes; + + if (sign > 0) + { + while (magIndex > 1) + { + uint mag = (uint) magnitude[--magIndex]; + bytesIndex -= 4; + Pack.UInt32_To_BE(mag, output[bytesIndex..]); + } + + uint lastMag = (uint)magnitude[0]; + while (lastMag > byte.MaxValue) + { + output[--bytesIndex] = (byte)lastMag; + lastMag >>= 8; + } + + output[--bytesIndex] = (byte)lastMag; + } + else // sign < 0 + { + bool carry = true; + + while (magIndex > 1) + { + uint mag = ~((uint)magnitude[--magIndex]); + + if (carry) + { + carry = (++mag == uint.MinValue); + } + + bytesIndex -= 4; + Pack.UInt32_To_BE(mag, output[bytesIndex..]); + } + + uint lastMag = (uint)magnitude[0]; + + if (carry) + { + // Never wraps because magnitude[0] != 0 + --lastMag; + } + + while (lastMag > byte.MaxValue) + { + output[--bytesIndex] = (byte)~lastMag; + lastMag >>= 8; + } + + output[--bytesIndex] = (byte)~lastMag; + + if (bytesIndex > 0) + { + output[--bytesIndex] = byte.MaxValue; + } + } + } +#endif + public override string ToString() { return ToString(10); @@ -3260,7 +3432,7 @@ public string ToString(int radix) int mask = (1 << 30) - 1; BigInteger u = this.Abs(); int bits = u.BitLength; - IList S = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var S = new List(); while (bits > 30) { S.Add(Convert.ToString(u.IntValue & mask, 8)); @@ -3270,7 +3442,7 @@ public string ToString(int radix) sb.Append(Convert.ToString(u.IntValue, 8)); for (int i = S.Count - 1; i >= 0; --i) { - AppendZeroExtendedString(sb, (string)S[i], 10); + AppendZeroExtendedString(sb, S[i], 10); } break; } @@ -3296,8 +3468,8 @@ public string ToString(int radix) } // TODO Could cache the moduli for each radix (soft reference?) - IList moduli = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); - BigInteger R = BigInteger.ValueOf(radix); + var moduli = new List(); + BigInteger R = ValueOf(radix); while (R.CompareTo(q) <= 0) { moduli.Add(R); @@ -3316,7 +3488,7 @@ public string ToString(int radix) return sb.ToString(); } - private static void ToString(StringBuilder sb, int radix, IList moduli, int scale, BigInteger pos) + private static void ToString(StringBuilder sb, int radix, IList moduli, int scale, BigInteger pos) { if (pos.BitLength < 64) { @@ -3332,7 +3504,7 @@ private static void ToString(StringBuilder sb, int radix, IList moduli, int scal return; } - BigInteger[] qr = pos.DivideAndRemainder((BigInteger)moduli[--scale]); + BigInteger[] qr = pos.DivideAndRemainder(moduli[--scale]); ToString(sb, radix, moduli, scale, qr[0]); ToString(sb, radix, moduli, scale, qr[1]); @@ -3416,6 +3588,9 @@ private int GetLowestSetBitMaskFirst(int firstWordMask) offset += 32; } +#if NETCOREAPP3_0_OR_GREATER + offset += BitOperations.TrailingZeroCount(word); +#else while ((word & 0xFF) == 0) { word >>= 8; @@ -3428,6 +3603,7 @@ private int GetLowestSetBitMaskFirst(int firstWordMask) ++offset; } +#endif return offset; } @@ -3619,7 +3795,6 @@ private BigInteger FlipExistingBit( int[] mag = (int[]) this.magnitude.Clone(); mag[mag.Length - 1 - (n >> 5)] ^= (1 << (n & 31)); // Flip bit - //mag[mag.Length - 1 - (n / 32)] ^= (1 << (n % 32)); return new BigInteger(this.sign, mag, false); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/Primes.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/Primes.cs index 9775cad..efe9038 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/Primes.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/Primes.cs @@ -3,15 +3,14 @@ using System; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math { - /** - * Utility methods for generating primes and testing for primality. - */ - public abstract class Primes + /// Utility methods for generating primes and testing for primality. + public static class Primes { public static readonly int SmallFactorLimit = 211; @@ -19,12 +18,10 @@ public abstract class Primes private static readonly BigInteger Two = BigInteger.Two; private static readonly BigInteger Three = BigInteger.Three; - /** - * Used to return the output from the - * {@linkplain Primes#enhancedMRProbablePrimeTest(BigInteger, SecureRandom, int) Enhanced - * Miller-Rabin Probabilistic Primality Test} - */ - public class MROutput + /// Used to return the output from the + /// + /// Enhanced Miller-Rabin Probabilistic Primality Test + public sealed class MROutput { internal static MROutput ProbablyPrime() { @@ -41,115 +38,83 @@ internal static MROutput ProvablyCompositeNotPrimePower() return new MROutput(true, null); } - private readonly bool mProvablyComposite; - private readonly BigInteger mFactor; + private readonly bool m_provablyComposite; + private readonly BigInteger m_factor; private MROutput(bool provablyComposite, BigInteger factor) { - this.mProvablyComposite = provablyComposite; - this.mFactor = factor; + m_provablyComposite = provablyComposite; + m_factor = factor; } - public BigInteger Factor - { - get { return mFactor; } - } + public BigInteger Factor => m_factor; - public bool IsProvablyComposite - { - get { return mProvablyComposite; } - } + public bool IsProvablyComposite => m_provablyComposite; - public bool IsNotPrimePower - { - get { return mProvablyComposite && mFactor == null; } - } + public bool IsNotPrimePower => m_provablyComposite && m_factor == null; } - /** - * Used to return the output from the {@linkplain Primes#generateSTRandomPrime(Digest, int, byte[]) Shawe-Taylor Random_Prime Routine} - */ - public class STOutput + /// Used to return the output from the + /// Shawe-Taylor Random_Prime Routine + public sealed class STOutput { - private readonly BigInteger mPrime; - private readonly byte[] mPrimeSeed; - private readonly int mPrimeGenCounter; + private readonly BigInteger m_prime; + private readonly byte[] m_primeSeed; + private readonly int m_primeGenCounter; internal STOutput(BigInteger prime, byte[] primeSeed, int primeGenCounter) { - this.mPrime = prime; - this.mPrimeSeed = primeSeed; - this.mPrimeGenCounter = primeGenCounter; + m_prime = prime; + m_primeSeed = primeSeed; + m_primeGenCounter = primeGenCounter; } - public BigInteger Prime - { - get { return mPrime; } - } + public BigInteger Prime => m_prime; - public byte[] PrimeSeed - { - get { return mPrimeSeed; } - } + public byte[] PrimeSeed => m_primeSeed; - public int PrimeGenCounter - { - get { return mPrimeGenCounter; } - } + public int PrimeGenCounter => m_primeGenCounter; } - /** - * FIPS 186-4 C.6 Shawe-Taylor Random_Prime Routine - * - * Construct a provable prime number using a hash function. - * - * @param hash - * the {@link Digest} instance to use (as "Hash()"). Cannot be null. - * @param length - * the length (in bits) of the prime to be generated. Must be at least 2. - * @param inputSeed - * the seed to be used for the generation of the requested prime. Cannot be null or - * empty. - * @return an {@link STOutput} instance containing the requested prime. - */ + /// FIPS 186-4 C.6 Shawe-Taylor Random_Prime Routine. + /// Construct a provable prime number using a hash function. + /// The instance to use (as "Hash()"). Cannot be null. + /// The length (in bits) of the prime to be generated. Must be at least 2. + /// The seed to be used for the generation of the requested prime. Cannot be null or + /// empty. + /// An instance containing the requested prime. public static STOutput GenerateSTRandomPrime(IDigest hash, int length, byte[] inputSeed) { if (hash == null) - throw new ArgumentNullException("hash"); + throw new ArgumentNullException(nameof(hash)); if (length < 2) - throw new ArgumentException("must be >= 2", "length"); + throw new ArgumentException("must be >= 2", nameof(length)); if (inputSeed == null) - throw new ArgumentNullException("inputSeed"); + throw new ArgumentNullException(nameof(inputSeed)); if (inputSeed.Length == 0) - throw new ArgumentException("cannot be empty", "inputSeed"); + throw new ArgumentException("cannot be empty", nameof(inputSeed)); return ImplSTRandomPrime(hash, length, Arrays.Clone(inputSeed)); } - /** - * FIPS 186-4 C.3.2 Enhanced Miller-Rabin Probabilistic Primality Test - * - * Run several iterations of the Miller-Rabin algorithm with randomly-chosen bases. This is an - * alternative to {@link #isMRProbablePrime(BigInteger, SecureRandom, int)} that provides more - * information about a composite candidate, which may be useful when generating or validating - * RSA moduli. - * - * @param candidate - * the {@link BigInteger} instance to test for primality. - * @param random - * the source of randomness to use to choose bases. - * @param iterations - * the number of randomly-chosen bases to perform the test for. - * @return an {@link MROutput} instance that can be further queried for details. - */ + /// FIPS 186-4 C.3.2 Enhanced Miller-Rabin Probabilistic Primality Test. + /// + /// Run several iterations of the Miller-Rabin algorithm with randomly-chosen bases. This is an alternative to + /// that provides more information about a + /// composite candidate, which may be useful when generating or validating RSA moduli. + /// + /// The instance to test for primality. + /// The source of randomness to use to choose bases. + /// The number of randomly-chosen bases to perform the test for. + /// An instance that can be further queried for details. public static MROutput EnhancedMRProbablePrimeTest(BigInteger candidate, SecureRandom random, int iterations) { - CheckCandidate(candidate, "candidate"); + CheckCandidate(candidate, nameof(candidate)); if (random == null) - throw new ArgumentNullException("random"); + throw new ArgumentNullException(nameof(random)); if (iterations < 1) - throw new ArgumentException("must be > 0", "iterations"); + throw new ArgumentException("must be > 0", nameof(iterations)); if (candidate.BitLength == 2) return MROutput.ProbablyPrime(); @@ -182,7 +147,7 @@ public static MROutput EnhancedMRProbablePrimeTest(BigInteger candidate, SecureR BigInteger x = z; for (int j = 1; j < a; ++j) { - z = z.ModPow(Two, w); + z = z.Square().Mod(w); if (z.Equals(wSubOne)) { @@ -201,7 +166,7 @@ public static MROutput EnhancedMRProbablePrimeTest(BigInteger candidate, SecureR if (!z.Equals(One)) { x = z; - z = z.ModPow(Two, w); + z = z.Square().Mod(w); if (!z.Equals(One)) { @@ -221,46 +186,34 @@ public static MROutput EnhancedMRProbablePrimeTest(BigInteger candidate, SecureR return MROutput.ProbablyPrime(); } - /** - * A fast check for small divisors, up to some implementation-specific limit. - * - * @param candidate - * the {@link BigInteger} instance to test for division by small factors. - * - * @return true if the candidate is found to have any small factors, - * false otherwise. - */ + /// A fast check for small divisors, up to some implementation-specific limit. + /// The instance to test for division by small factors. + /// true if the candidate is found to have any small factors, false otherwise. public static bool HasAnySmallFactors(BigInteger candidate) { - CheckCandidate(candidate, "candidate"); + CheckCandidate(candidate, nameof(candidate)); return ImplHasAnySmallFactors(candidate); } - /** - * FIPS 186-4 C.3.1 Miller-Rabin Probabilistic Primality Test - * - * Run several iterations of the Miller-Rabin algorithm with randomly-chosen bases. - * - * @param candidate - * the {@link BigInteger} instance to test for primality. - * @param random - * the source of randomness to use to choose bases. - * @param iterations - * the number of randomly-chosen bases to perform the test for. - * @return false if any witness to compositeness is found amongst the chosen bases - * (so candidate is definitely NOT prime), or else true - * (indicating primality with some probability dependent on the number of iterations - * that were performed). - */ + /// FIPS 186-4 C.3.1 Miller-Rabin Probabilistic Primality Test. + /// Run several iterations of the Miller-Rabin algorithm with randomly-chosen bases. + /// The instance to test for primality. + /// The source of randomness to use to choose bases. + /// The number of randomly-chosen bases to perform the test for. + /// + /// false if any witness to compositeness is found amongst the chosen bases (so + /// is definitely NOT prime), or else true (indicating primality with some + /// probability dependent on the number of iterations that were performed). + /// public static bool IsMRProbablePrime(BigInteger candidate, SecureRandom random, int iterations) { - CheckCandidate(candidate, "candidate"); + CheckCandidate(candidate, nameof(candidate)); if (random == null) - throw new ArgumentException("cannot be null", "random"); + throw new ArgumentException("cannot be null", nameof(random)); if (iterations < 1) - throw new ArgumentException("must be > 0", "iterations"); + throw new ArgumentException("must be > 0", nameof(iterations)); if (candidate.BitLength == 2) return true; @@ -285,25 +238,19 @@ public static bool IsMRProbablePrime(BigInteger candidate, SecureRandom random, return true; } - /** - * FIPS 186-4 C.3.1 Miller-Rabin Probabilistic Primality Test (to a fixed base). - * - * Run a single iteration of the Miller-Rabin algorithm against the specified base. - * - * @param candidate - * the {@link BigInteger} instance to test for primality. - * @param baseValue - * the base value to use for this iteration. - * @return false if the specified base is a witness to compositeness (so - * candidate is definitely NOT prime), or else true. - */ + /// FIPS 186-4 C.3.1 Miller-Rabin Probabilistic Primality Test (to a fixed base). + /// Run a single iteration of the Miller-Rabin algorithm against the specified base. + /// The instance to test for primality. + /// The base value to use for this iteration. + /// false if is a witness to compositeness (so + /// is definitely NOT prime), or else true. public static bool IsMRProbablePrimeToBase(BigInteger candidate, BigInteger baseValue) { - CheckCandidate(candidate, "candidate"); - CheckCandidate(baseValue, "baseValue"); + CheckCandidate(candidate, nameof(candidate)); + CheckCandidate(baseValue, nameof(baseValue)); if (baseValue.CompareTo(candidate.Subtract(One)) >= 0) - throw new ArgumentException("must be < ('candidate' - 1)", "baseValue"); + throw new ArgumentException("must be < ('candidate' - 1)", nameof(baseValue)); if (candidate.BitLength == 2) return true; @@ -413,59 +360,52 @@ private static bool ImplMRProbablePrimeToBase(BigInteger w, BigInteger wSubOne, if (z.Equals(One) || z.Equals(wSubOne)) return true; - bool result = false; - for (int j = 1; j < a; ++j) { - z = z.ModPow(Two, w); + z = z.Square().Mod(w); if (z.Equals(wSubOne)) - { - result = true; - break; - } + return true; if (z.Equals(One)) return false; } - return result; + return false; } private static STOutput ImplSTRandomPrime(IDigest d, int length, byte[] primeSeed) { int dLen = d.GetDigestSize(); + int cLen = System.Math.Max(4, dLen); if (length < 33) { int primeGenCounter = 0; - byte[] c0 = new byte[dLen]; - byte[] c1 = new byte[dLen]; + byte[] c0 = new byte[cLen]; + byte[] c1 = new byte[cLen]; for (;;) { - Hash(d, primeSeed, c0, 0); + Hash(d, primeSeed, c0, cLen - dLen); Inc(primeSeed, 1); - Hash(d, primeSeed, c1, 0); + Hash(d, primeSeed, c1, cLen - dLen); Inc(primeSeed, 1); - uint c = Extract32(c0) ^ Extract32(c1); - c &= (uint.MaxValue >> (32 - length)); + uint c = Pack.BE_To_UInt32(c0, cLen - 4) + ^ Pack.BE_To_UInt32(c1, cLen - 4); + c &= uint.MaxValue >> (32 - length); c |= (1U << (length - 1)) | 1U; ++primeGenCounter; if (IsPrime32(c)) - { - return new STOutput(BigInteger.ValueOf((long)c), primeSeed, primeGenCounter); - } + return new STOutput(BigInteger.ValueOf(c), primeSeed, primeGenCounter); if (primeGenCounter > (4 * length)) - { throw new InvalidOperationException("Too many iterations in Shawe-Taylor Random_Prime Routine"); - } } } @@ -510,7 +450,11 @@ private static STOutput ImplSTRandomPrime(IDigest d, int length, byte[] primeSee * * NOTE: 'primeSeed' is still incremented as if we performed the full check! */ - if (!ImplHasAnySmallFactors(c)) + if (ImplHasAnySmallFactors(c)) + { + Inc(primeSeed, iterations + 1); + } + else { BigInteger a = HashGen(d, primeSeed, iterations + 1); a = a.Mod(c.Subtract(Three)).Add(Two); @@ -521,19 +465,11 @@ private static STOutput ImplSTRandomPrime(IDigest d, int length, byte[] primeSee BigInteger z = a.ModPow(tx2, c); if (c.Gcd(z.Subtract(One)).Equals(One) && z.ModPow(c0, c).Equals(One)) - { return new STOutput(c, primeSeed, primeGenCounter); - } - } - else - { - Inc(primeSeed, iterations + 1); } if (primeGenCounter >= ((4 * length) + oldCounter)) - { throw new InvalidOperationException("Too many iterations in Shawe-Taylor Random_Prime Routine"); - } dt += 2; c = c.Add(c0x2); @@ -541,20 +477,6 @@ private static STOutput ImplSTRandomPrime(IDigest d, int length, byte[] primeSee } } - private static uint Extract32(byte[] bs) - { - uint result = 0; - - int count = System.Math.Min(4, bs.Length); - for (int i = 0; i < count; ++i) - { - uint b = bs[bs.Length - (i + 1)]; - result |= (b << (8 * i)); - } - - return result; - } - private static void Hash(IDigest d, byte[] input, byte[] output, int outPos) { d.BlockUpdate(input, 0, input.Length); @@ -592,19 +514,15 @@ private static bool IsPrime32(uint x) * Use wheel factorization with 2, 3, 5 to select trial divisors. */ - if (x <= 5) - { - return x == 2 || x == 3 || x == 5; - } + if (x < 32) + return ((1 << (int)x) & 0b0010_0000_1000_1010_0010_1000_1010_1100) != 0; - if ((x & 1) == 0 || (x % 3) == 0 || (x % 5) == 0) - { + if (((1 << (int)(x % 30U)) & 0b1010_0000_1000_1010_0010_1000_1000_0010U) == 0) return false; - } uint[] ds = new uint[]{ 1, 7, 11, 13, 17, 19, 23, 29 }; uint b = 0; - for (int pos = 1; ; pos = 0) + for (int pos = 1;; pos = 0) { /* * Trial division by wheel-selected divisors @@ -613,18 +531,15 @@ private static bool IsPrime32(uint x) { uint d = b + ds[pos]; if (x % d == 0) - { - return x < 30; - } + return false; + ++pos; } b += 30; if ((b >> 16 != 0) || (b * b >= x)) - { return true; - } } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/ECAlgorithms.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/ECAlgorithms.cs index e4bf5be..566ed33 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/ECAlgorithms.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/ECAlgorithms.cs @@ -215,9 +215,18 @@ public static ECPoint CleanPoint(ECCurve c, ECPoint p) { ECCurve cp = p.Curve; if (!c.Equals(cp)) - throw new ArgumentException("Point must be on the same curve", "p"); - + throw new ArgumentException("Point must be on the same curve", nameof(p)); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int encodedLength = p.GetEncodedLength(false); + Span encoding = encodedLength <= 512 + ? stackalloc byte[encodedLength] + : new byte[encodedLength]; + p.EncodeTo(false, encoding); + return c.DecodePoint(encoding); +#else return c.DecodePoint(p.GetEncoded(false)); +#endif } internal static ECPoint ImplCheckResult(ECPoint p) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/ECCurve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/ECCurve.cs index a09f951..42ebf6e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/ECCurve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/ECCurve.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Abc; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Endo; @@ -114,39 +114,21 @@ public virtual ECPoint ValidatePoint(BigInteger x, BigInteger y) { ECPoint p = CreatePoint(x, y); if (!p.IsValid()) - { throw new ArgumentException("Invalid point coordinates"); - } - return p; - } - - public virtual ECPoint ValidatePoint(BigInteger x, BigInteger y, bool withCompression) - { - ECPoint p = CreatePoint(x, y, withCompression); - if (!p.IsValid()) - { - throw new ArgumentException("Invalid point coordinates"); - } return p; } public virtual ECPoint CreatePoint(BigInteger x, BigInteger y) { - return CreatePoint(x, y, false); - } - - - public virtual ECPoint CreatePoint(BigInteger x, BigInteger y, bool withCompression) - { - return CreateRawPoint(FromBigInteger(x), FromBigInteger(y), withCompression); + return CreateRawPoint(FromBigInteger(x), FromBigInteger(y)); } protected abstract ECCurve CloneCurve(); - protected internal abstract ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression); + protected internal abstract ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y); - protected internal abstract ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression); + protected internal abstract ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs); protected virtual ECMultiplier CreateDefaultMultiplier() { @@ -168,7 +150,7 @@ public virtual PreCompInfo GetPreCompInfo(ECPoint point, string name) { CheckPoint(point); - IDictionary table; + IDictionary table; lock (point) { table = point.m_preCompTable; @@ -179,7 +161,7 @@ public virtual PreCompInfo GetPreCompInfo(ECPoint point, string name) lock (table) { - return (PreCompInfo)table[name]; + return table.TryGetValue(name, out var preCompInfo) ? preCompInfo : null; } } @@ -199,19 +181,19 @@ public virtual PreCompInfo Precompute(ECPoint point, string name, IPreCompCallba { CheckPoint(point); - IDictionary table; + IDictionary table; lock (point) { table = point.m_preCompTable; if (null == table) { - point.m_preCompTable = table = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(4); + point.m_preCompTable = table = new Dictionary(); } } lock (table) { - PreCompInfo existing = (PreCompInfo)table[name]; + PreCompInfo existing = table.TryGetValue(name, out var preCompInfo) ? preCompInfo : null; PreCompInfo result = callback.Precompute(existing); if (result != existing) @@ -237,7 +219,7 @@ public virtual ECPoint ImportPoint(ECPoint p) // TODO Default behaviour could be improved if the two curves have the same coordinate system by copying any Z coordinates. p = p.Normalize(); - return CreatePoint(p.XCoord.ToBigInteger(), p.YCoord.ToBigInteger(), p.IsCompressed); + return CreatePoint(p.XCoord.ToBigInteger(), p.YCoord.ToBigInteger()); } /** @@ -456,75 +438,152 @@ public virtual ECMultiplier GetMultiplier() */ public virtual ECPoint DecodePoint(byte[] encoded) { - ECPoint p = null; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return DecodePoint(encoded.AsSpan()); +#else + ECPoint p; int expectedLength = (FieldSize + 7) / 8; byte type = encoded[0]; switch (type) { - case 0x00: // infinity - { - if (encoded.Length != 1) - throw new ArgumentException("Incorrect length for infinity encoding", "encoded"); + case 0x00: // infinity + { + if (encoded.Length != 1) + throw new ArgumentException("Incorrect length for infinity encoding", "encoded"); - p = Infinity; - break; - } + p = Infinity; + break; + } - case 0x02: // compressed - case 0x03: // compressed - { - if (encoded.Length != (expectedLength + 1)) - throw new ArgumentException("Incorrect length for compressed encoding", "encoded"); + case 0x02: // compressed + case 0x03: // compressed + { + if (encoded.Length != (expectedLength + 1)) + throw new ArgumentException("Incorrect length for compressed encoding", "encoded"); - int yTilde = type & 1; - BigInteger X = new BigInteger(1, encoded, 1, expectedLength); + int yTilde = type & 1; + BigInteger X = new BigInteger(1, encoded, 1, expectedLength); - p = DecompressPoint(yTilde, X); - if (!p.ImplIsValid(true, true)) - throw new ArgumentException("Invalid point"); + p = DecompressPoint(yTilde, X); + if (!p.ImplIsValid(true, true)) + throw new ArgumentException("Invalid point"); - break; - } + break; + } - case 0x04: // uncompressed - { - if (encoded.Length != (2 * expectedLength + 1)) - throw new ArgumentException("Incorrect length for uncompressed encoding", "encoded"); + case 0x04: // uncompressed + { + if (encoded.Length != (2 * expectedLength + 1)) + throw new ArgumentException("Incorrect length for uncompressed encoding", "encoded"); - BigInteger X = new BigInteger(1, encoded, 1, expectedLength); - BigInteger Y = new BigInteger(1, encoded, 1 + expectedLength, expectedLength); + BigInteger X = new BigInteger(1, encoded, 1, expectedLength); + BigInteger Y = new BigInteger(1, encoded, 1 + expectedLength, expectedLength); - p = ValidatePoint(X, Y); - break; - } + p = ValidatePoint(X, Y); + break; + } - case 0x06: // hybrid - case 0x07: // hybrid - { - if (encoded.Length != (2 * expectedLength + 1)) - throw new ArgumentException("Incorrect length for hybrid encoding", "encoded"); + case 0x06: // hybrid + case 0x07: // hybrid + { + if (encoded.Length != (2 * expectedLength + 1)) + throw new ArgumentException("Incorrect length for hybrid encoding", "encoded"); - BigInteger X = new BigInteger(1, encoded, 1, expectedLength); - BigInteger Y = new BigInteger(1, encoded, 1 + expectedLength, expectedLength); + BigInteger X = new BigInteger(1, encoded, 1, expectedLength); + BigInteger Y = new BigInteger(1, encoded, 1 + expectedLength, expectedLength); - if (Y.TestBit(0) != (type == 0x07)) - throw new ArgumentException("Inconsistent Y coordinate in hybrid encoding", "encoded"); + if (Y.TestBit(0) != (type == 0x07)) + throw new ArgumentException("Inconsistent Y coordinate in hybrid encoding", "encoded"); - p = ValidatePoint(X, Y); - break; - } + p = ValidatePoint(X, Y); + break; + } - default: - throw new FormatException("Invalid point encoding " + type); + default: + throw new FormatException("Invalid point encoding " + type); } if (type != 0x00 && p.IsInfinity) throw new ArgumentException("Invalid infinity encoding", "encoded"); return p; +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual ECPoint DecodePoint(ReadOnlySpan encoded) + { + ECPoint p; + int expectedLength = (FieldSize + 7) / 8; + + byte type = encoded[0]; + switch (type) + { + case 0x00: // infinity + { + if (encoded.Length != 1) + throw new ArgumentException("Incorrect length for infinity encoding", "encoded"); + + p = Infinity; + break; + } + + case 0x02: // compressed + case 0x03: // compressed + { + if (encoded.Length != (expectedLength + 1)) + throw new ArgumentException("Incorrect length for compressed encoding", "encoded"); + + int yTilde = type & 1; + BigInteger X = new BigInteger(1, encoded[1..]); + + p = DecompressPoint(yTilde, X); + if (!p.ImplIsValid(true, true)) + throw new ArgumentException("Invalid point"); + + break; + } + + case 0x04: // uncompressed + { + if (encoded.Length != (2 * expectedLength + 1)) + throw new ArgumentException("Incorrect length for uncompressed encoding", "encoded"); + + BigInteger X = new BigInteger(1, encoded[1..(1 + expectedLength)]); + BigInteger Y = new BigInteger(1, encoded[(1 + expectedLength)..]); + + p = ValidatePoint(X, Y); + break; + } + + case 0x06: // hybrid + case 0x07: // hybrid + { + if (encoded.Length != (2 * expectedLength + 1)) + throw new ArgumentException("Incorrect length for hybrid encoding", "encoded"); + + BigInteger X = new BigInteger(1, encoded[1..(1 + expectedLength)]); + BigInteger Y = new BigInteger(1, encoded[(1 + expectedLength)..]); + + if (Y.TestBit(0) != (type == 0x07)) + throw new ArgumentException("Inconsistent Y coordinate in hybrid encoding", "encoded"); + + p = ValidatePoint(X, Y); + break; + } + + default: + throw new FormatException("Invalid point encoding " + type); + } + + if (type != 0x00 && p.IsInfinity) + throw new ArgumentException("Invalid infinity encoding", "encoded"); + + return p; + } +#endif + private class DefaultLookupTable : AbstractECLookupTable { @@ -585,7 +644,7 @@ private ECPoint CreatePoint(byte[] x, byte[] y) { ECFieldElement X = m_outer.FromBigInteger(new BigInteger(1, x)); ECFieldElement Y = m_outer.FromBigInteger(new BigInteger(1, y)); - return m_outer.CreateRawPoint(X, Y, false); + return m_outer.CreateRawPoint(X, Y); } } } @@ -645,7 +704,7 @@ protected override ECPoint DecompressPoint(int yTilde, BigInteger X1) y = y.Negate(); } - return CreateRawPoint(x, y, true); + return CreateRawPoint(x, y); } private static BigInteger ImplRandomFieldElement(SecureRandom r, BigInteger p) @@ -679,6 +738,8 @@ public class FpCurve { private const int FP_DEFAULT_COORDS = COORD_JACOBIAN_MODIFIED; + private static readonly HashSet KnownQs = new HashSet(); + protected readonly BigInteger m_q, m_r; protected readonly FpPoint m_infinity; @@ -689,11 +750,41 @@ public FpCurve(BigInteger q, BigInteger a, BigInteger b) } public FpCurve(BigInteger q, BigInteger a, BigInteger b, BigInteger order, BigInteger cofactor) + : this(q, a, b, order, cofactor, false) + { + } + + internal FpCurve(BigInteger q, BigInteger a, BigInteger b, BigInteger order, BigInteger cofactor, bool isInternal) : base(q) { + if (!isInternal) + { + bool unknownQ; + lock (KnownQs) unknownQ = !KnownQs.Contains(q); + + if (unknownQ) + { + int maxBitLength = AsInteger("BestHTTP.SecureProtocol.Org.BouncyCastle.EC.Fp_MaxSize", 1042); // 2 * 521 + int certainty = AsInteger("BestHTTP.SecureProtocol.Org.BouncyCastle.EC.Fp_Certainty", 100); + + int qBitLength = q.BitLength; + if (maxBitLength < qBitLength) + throw new ArgumentException("Fp q value out of range"); + + if (Primes.HasAnySmallFactors(q) || + !Primes.IsMRProbablePrime(q, SecureRandom.ArbitraryRandom, + GetNumberOfIterations(qBitLength, certainty))) + { + throw new ArgumentException("Fp q value not prime"); + } + } + } + + lock (KnownQs) KnownQs.Add(q); this.m_q = q; + this.m_r = FpFieldElement.CalculateResidue(q); - this.m_infinity = new FpPoint(this, null, null, false); + this.m_infinity = new FpPoint(this, null, null); this.m_a = FromBigInteger(a); this.m_b = FromBigInteger(b); @@ -702,18 +793,13 @@ public FpCurve(BigInteger q, BigInteger a, BigInteger b, BigInteger order, BigIn this.m_coord = FP_DEFAULT_COORDS; } - - protected FpCurve(BigInteger q, BigInteger r, ECFieldElement a, ECFieldElement b) - : this(q, r, a, b, null, null) - { - } - - protected FpCurve(BigInteger q, BigInteger r, ECFieldElement a, ECFieldElement b, BigInteger order, BigInteger cofactor) + internal FpCurve(BigInteger q, BigInteger r, ECFieldElement a, ECFieldElement b, BigInteger order, + BigInteger cofactor) : base(q) { this.m_q = q; this.m_r = r; - this.m_infinity = new FpPoint(this, null, null, false); + this.m_infinity = new FpPoint(this, null, null); this.m_a = a; this.m_b = b; @@ -758,17 +844,20 @@ public override int FieldSize public override ECFieldElement FromBigInteger(BigInteger x) { + if (x == null || x.SignValue < 0 || x.CompareTo(m_q) >= 0) + throw new ArgumentException("value invalid for Fp field element", "x"); + return new FpFieldElement(this.m_q, this.m_r, x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new FpPoint(this, x, y, withCompression); + return new FpPoint(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new FpPoint(this, x, y, zs, withCompression); + return new FpPoint(this, x, y, zs); } public override ECPoint ImportPoint(ECPoint p) @@ -783,8 +872,7 @@ public override ECPoint ImportPoint(ECPoint p) return new FpPoint(this, FromBigInteger(p.RawXCoord.ToBigInteger()), FromBigInteger(p.RawYCoord.ToBigInteger()), - new ECFieldElement[] { FromBigInteger(p.GetZCoord(0).ToBigInteger()) }, - p.IsCompressed); + new ECFieldElement[] { FromBigInteger(p.GetZCoord(0).ToBigInteger()) }); default: break; } @@ -792,6 +880,50 @@ public override ECPoint ImportPoint(ECPoint p) return base.ImportPoint(p); } + + private int GetNumberOfIterations(int bits, int certainty) + { + /* + * NOTE: We enforce a minimum 'certainty' of 100 for bits >= 1024 (else 80). Where the + * certainty is higher than the FIPS 186-4 tables (C.2/C.3) cater to, extra iterations + * are added at the "worst case rate" for the excess. + */ + if (bits >= 1536) + { + return certainty <= 100 ? 3 + : certainty <= 128 ? 4 + : 4 + (certainty - 128 + 1) / 2; + } + else if (bits >= 1024) + { + return certainty <= 100 ? 4 + : certainty <= 112 ? 5 + : 5 + (certainty - 112 + 1) / 2; + } + else if (bits >= 512) + { + return certainty <= 80 ? 5 + : certainty <= 100 ? 7 + : 7 + (certainty - 100 + 1) / 2; + } + else + { + return certainty <= 80 ? 40 + : 40 + (certainty - 80 + 1) / 2; + } + } + + int AsInteger(string envVariable, int defaultValue) + { + string v = Org.BouncyCastle.Utilities.Platform.GetEnvironmentVariable(envVariable); + + if (v == null) + { + return defaultValue; + } + + return int.Parse(v); + } } public abstract class AbstractF2mCurve @@ -811,32 +943,11 @@ public static BigInteger Inverse(int m, int[] ks, BigInteger x) private static IFiniteField BuildField(int m, int k1, int k2, int k3) { - if (k1 == 0) - { - throw new ArgumentException("k1 must be > 0"); - } - - if (k2 == 0) - { - if (k3 != 0) - { - throw new ArgumentException("k3 must be 0 if k2 == 0"); - } - - return FiniteFields.GetBinaryExtensionField(new int[]{ 0, k1, m }); - } - - if (k2 <= k1) - { - throw new ArgumentException("k2 must be > k1"); - } - - if (k3 <= k2) - { - throw new ArgumentException("k3 must be > k2"); - } + int[] exponents = (k2 | k3) == 0 + ? new int[]{ 0, k1, m } + : new int[]{ 0, k1, k2, k3, m }; - return FiniteFields.GetBinaryExtensionField(new int[]{ 0, k1, k2, k3, m }); + return FiniteFields.GetBinaryExtensionField(exponents); } protected AbstractF2mCurve(int m, int k1, int k2, int k3) @@ -844,8 +955,7 @@ protected AbstractF2mCurve(int m, int k1, int k2, int k3) { } - - public override ECPoint CreatePoint(BigInteger x, BigInteger y, bool withCompression) + public override ECPoint CreatePoint(BigInteger x, BigInteger y) { ECFieldElement X = FromBigInteger(x), Y = FromBigInteger(y); @@ -872,7 +982,7 @@ public override ECPoint CreatePoint(BigInteger x, BigInteger y, bool withCompres } } - return CreateRawPoint(X, Y, withCompression); + return CreateRawPoint(X, Y); } public override bool IsValidFieldElement(BigInteger x) @@ -937,7 +1047,7 @@ protected override ECPoint DecompressPoint(int yTilde, BigInteger X1) if (yp == null) throw new ArgumentException("Invalid point compression"); - return CreateRawPoint(xp, yp, true); + return CreateRawPoint(xp, yp); } /** @@ -1192,15 +1302,8 @@ public F2mCurve( * @param cofactor The cofactor of the elliptic curve, i.e. * #Ea(F2m) = h * n. */ - public F2mCurve( - int m, - int k1, - int k2, - int k3, - BigInteger a, - BigInteger b, - BigInteger order, - BigInteger cofactor) + public F2mCurve(int m, int k1, int k2, int k3, BigInteger a, BigInteger b, BigInteger order, + BigInteger cofactor) : base(m, k1, k2, k3) { this.m = m; @@ -1209,31 +1312,15 @@ public F2mCurve( this.k3 = k3; this.m_order = order; this.m_cofactor = cofactor; - this.m_infinity = new F2mPoint(this, null, null, false); - - if (k1 == 0) - throw new ArgumentException("k1 must be > 0"); - - if (k2 == 0) - { - if (k3 != 0) - throw new ArgumentException("k3 must be 0 if k2 == 0"); - } - else - { - if (k2 <= k1) - throw new ArgumentException("k2 must be > k1"); - - if (k3 <= k2) - throw new ArgumentException("k3 must be > k2"); - } + this.m_infinity = new F2mPoint(this, null, null); this.m_a = FromBigInteger(a); this.m_b = FromBigInteger(b); this.m_coord = F2M_DEFAULT_COORDS; } - protected F2mCurve(int m, int k1, int k2, int k3, ECFieldElement a, ECFieldElement b, BigInteger order, BigInteger cofactor) + internal F2mCurve(int m, int k1, int k2, int k3, ECFieldElement a, ECFieldElement b, BigInteger order, + BigInteger cofactor) : base(m, k1, k2, k3) { this.m = m; @@ -1242,8 +1329,8 @@ protected F2mCurve(int m, int k1, int k2, int k3, ECFieldElement a, ECFieldEleme this.k3 = k3; this.m_order = order; this.m_cofactor = cofactor; + this.m_infinity = new F2mPoint(this, null, null); - this.m_infinity = new F2mPoint(this, null, null, false); this.m_a = a; this.m_b = b; this.m_coord = F2M_DEFAULT_COORDS; @@ -1284,17 +1371,24 @@ public override int FieldSize public override ECFieldElement FromBigInteger(BigInteger x) { - return new F2mFieldElement(this.m, this.k1, this.k2, this.k3, x); + if (x == null || x.SignValue < 0 || x.BitLength > m) + throw new ArgumentException("value invalid for F2m field element", "x"); + + int[] ks = (k2 | k3) == 0 + ? new int[]{ k1 } + : new int[]{ k1, k2, k3 }; + + return new F2mFieldElement(m, ks, new LongArray(x)); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new F2mPoint(this, x, y, withCompression); + return new F2mPoint(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new F2mPoint(this, x, y, zs, withCompression); + return new F2mPoint(this, x, y, zs); } public override ECPoint Infinity @@ -1336,7 +1430,7 @@ public override ECLookupTable CreateCacheSafeLookupTable(ECPoint[] points, int o { int FE_LONGS = (m + 63) / 64; - long[] table = new long[len * FE_LONGS * 2]; + ulong[] table = new ulong[len * FE_LONGS * 2]; { int pos = 0; for (int i = 0; i < len; ++i) @@ -1354,10 +1448,10 @@ private class DefaultF2mLookupTable : AbstractECLookupTable { private readonly F2mCurve m_outer; - private readonly long[] m_table; + private readonly ulong[] m_table; private readonly int m_size; - internal DefaultF2mLookupTable(F2mCurve outer, long[] table, int size) + internal DefaultF2mLookupTable(F2mCurve outer, ulong[] table, int size) { this.m_outer = outer; this.m_table = table; @@ -1372,12 +1466,12 @@ public override int Size public override ECPoint Lookup(int index) { int FE_LONGS = (m_outer.m + 63) / 64; - long[] x = new long[FE_LONGS], y = new long[FE_LONGS]; + ulong[] x = new ulong[FE_LONGS], y = new ulong[FE_LONGS]; int pos = 0; for (int i = 0; i < m_size; ++i) { - long MASK =((i ^ index) - 1) >> 31; + ulong MASK = (ulong)(long)(((i ^ index) - 1) >> 31); for (int j = 0; j < FE_LONGS; ++j) { @@ -1394,7 +1488,7 @@ public override ECPoint Lookup(int index) public override ECPoint LookupVar(int index) { int FE_LONGS = (m_outer.m + 63) / 64; - long[] x = new long[FE_LONGS], y = new long[FE_LONGS]; + ulong[] x = new ulong[FE_LONGS], y = new ulong[FE_LONGS]; int pos = index * FE_LONGS * 2; for (int j = 0; j < FE_LONGS; ++j) @@ -1406,14 +1500,16 @@ public override ECPoint LookupVar(int index) return CreatePoint(x, y); } - private ECPoint CreatePoint(long[] x, long[] y) + private ECPoint CreatePoint(ulong[] x, ulong[] y) { int m = m_outer.m; - int[] ks = m_outer.IsTrinomial() ? new int[] { m_outer.k1 } : new int[] { m_outer.k1, m_outer.k2, m_outer.k3 }; + int[] ks = m_outer.IsTrinomial() + ? new int[]{ m_outer.k1 } + : new int[]{ m_outer.k1, m_outer.k2, m_outer.k3 }; ECFieldElement X = new F2mFieldElement(m, ks, new LongArray(x)); ECFieldElement Y = new F2mFieldElement(m, ks, new LongArray(y)); - return m_outer.CreateRawPoint(X, Y, false); + return m_outer.CreateRawPoint(X, Y); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/ECFieldElement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/ECFieldElement.cs index f68f8d0..9688ac1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/ECFieldElement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/ECFieldElement.cs @@ -98,8 +98,25 @@ public override string ToString() public virtual byte[] GetEncoded() { - return BigIntegers.AsUnsignedByteArray((FieldSize + 7) / 8, ToBigInteger()); + return BigIntegers.AsUnsignedByteArray(GetEncodedLength(), ToBigInteger()); } + + public virtual int GetEncodedLength() + { + return (FieldSize + 7) / 8; + } + + public virtual void EncodeTo(byte[] buf, int off) + { + BigIntegers.AsUnsignedByteArray(ToBigInteger(), buf, off, GetEncodedLength()); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void EncodeTo(Span buf) + { + BigIntegers.AsUnsignedByteArray(ToBigInteger(), buf[..GetEncodedLength()]); + } +#endif } public abstract class AbstractFpFieldElement @@ -130,17 +147,8 @@ internal static BigInteger CalculateResidue(BigInteger p) return null; } - - public FpFieldElement(BigInteger q, BigInteger x) - : this(q, CalculateResidue(q), x) - { - } - internal FpFieldElement(BigInteger q, BigInteger r, BigInteger x) { - if (x == null || x.SignValue < 0 || x.CompareTo(q) >= 0) - throw new ArgumentException("value invalid in Fp field element", "x"); - this.q = q; this.r = r; this.x = x; @@ -273,7 +281,7 @@ public override ECFieldElement Sqrt() return this; if (!q.TestBit(0)) - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("even value of q"); + throw new NotImplementedException("even value of q"); if (q.TestBit(1)) // q == 4m + 3 { @@ -651,71 +659,6 @@ public class F2mFieldElement */ internal LongArray x; - /** - * Constructor for Ppb. - * @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). - * @param x The BigInteger representing the value of the field element. - */ - - public F2mFieldElement( - int m, - int k1, - int k2, - int k3, - BigInteger x) - { - if (x == null || x.SignValue < 0 || x.BitLength > m) - throw new ArgumentException("value invalid in F2m field element", "x"); - - if ((k2 == 0) && (k3 == 0)) - { - this.representation = Tpb; - this.ks = new int[] { k1 }; - } - else - { - if (k2 >= k3) - throw new ArgumentException("k2 must be smaller than k3"); - if (k2 <= 0) - throw new ArgumentException("k2 must be larger than 0"); - - this.representation = Ppb; - this.ks = new int[] { k1, k2, k3 }; - } - - this.m = m; - this.x = new LongArray(x); - } - - /** - * Constructor for Tpb. - * @param m The exponent m of - * F2m. - * @param k The integer k where xm + - * xk + 1 represents the reduction - * polynomial f(z). - * @param x The BigInteger representing the value of the field element. - */ - - public F2mFieldElement( - int m, - int k, - BigInteger x) - : this(m, k, 0, 0, x) - { - // Set k1 to k, and set k2 and k3 to 0 - } - internal F2mFieldElement(int m, int[] ks, LongArray x) { this.m = m; @@ -844,9 +787,9 @@ public override ECFieldElement MultiplyPlusProduct(ECFieldElement b, ECFieldElem LongArray ab = ax.Multiply(bx, m, ks); LongArray xy = xx.Multiply(yx, m, ks); - if (ab == ax || ab == bx) + if (LongArray.AreAliased(ref ab, ref ax) || LongArray.AreAliased(ref ab, ref bx)) { - ab = (LongArray)ab.Copy(); + ab = ab.Copy(); } ab.AddShiftedByWords(xy, 0); @@ -886,9 +829,9 @@ public override ECFieldElement SquarePlusProduct(ECFieldElement x, ECFieldElemen LongArray aa = ax.Square(m, ks); LongArray xy = xx.Multiply(yx, m, ks); - if (aa == ax) + if (LongArray.AreAliased(ref aa, ref ax)) { - aa = (LongArray)aa.Copy(); + aa = aa.Copy(); } aa.AddShiftedByWords(xy, 0); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/ECPoint.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/ECPoint.cs index 69f56ca..feec822 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/ECPoint.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/ECPoint.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.Text; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Multiplier; @@ -14,8 +14,6 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC */ public abstract class ECPoint { - private static readonly SecureRandom Random = new SecureRandom(); - protected static ECFieldElement[] EMPTY_ZS = new ECFieldElement[0]; protected static ECFieldElement[] GetInitialZCoords(ECCurve curve) @@ -52,23 +50,20 @@ protected static ECFieldElement[] GetInitialZCoords(ECCurve curve) protected internal readonly ECCurve m_curve; protected internal readonly ECFieldElement m_x, m_y; protected internal readonly ECFieldElement[] m_zs; - protected internal readonly bool m_withCompression; - // Dictionary is (string -> PreCompInfo) - protected internal IDictionary m_preCompTable = null; + protected internal IDictionary m_preCompTable = null; - protected ECPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : this(curve, x, y, GetInitialZCoords(curve), withCompression) + protected ECPoint(ECCurve curve, ECFieldElement x, ECFieldElement y) + : this(curve, x, y, GetInitialZCoords(curve)) { } - internal ECPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + internal ECPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { this.m_curve = curve; this.m_x = x; this.m_y = y; this.m_zs = zs; - this.m_withCompression = withCompression; } protected abstract bool SatisfiesCurveEquation(); @@ -251,10 +246,7 @@ public virtual ECPoint Normalize() * Any side-channel in the implementation of 'inverse' now only leaks information about * the value (z * b), and no longer reveals information about 'z' itself. */ - // TODO Add CryptoServicesRegistrar class and use here - //SecureRandom r = CryptoServicesRegistrar.GetSecureRandom(); - SecureRandom r = Random; - ECFieldElement b = m_curve.RandomFieldElementMult(r); + ECFieldElement b = m_curve.RandomFieldElementMult(SecureRandom.ArbitraryRandom); ECFieldElement zInv = z.Multiply(b).Invert().Multiply(b); return Normalize(zInv); } @@ -286,7 +278,7 @@ internal virtual ECPoint Normalize(ECFieldElement zInv) protected virtual ECPoint CreateScaledPoint(ECFieldElement sx, ECFieldElement sy) { - return Curve.CreateRawPoint(RawXCoord.Multiply(sx), RawYCoord.Multiply(sy), IsCompressed); + return Curve.CreateRawPoint(RawXCoord.Multiply(sx), RawYCoord.Multiply(sy)); } public bool IsInfinity @@ -294,11 +286,6 @@ public bool IsInfinity get { return m_x == null && m_y == null; } } - public bool IsCompressed - { - get { return m_withCompression; } - } - public bool IsValid() { return ImplIsValid(false, true); @@ -323,28 +310,28 @@ public virtual ECPoint ScaleX(ECFieldElement scale) { return IsInfinity ? this - : Curve.CreateRawPoint(RawXCoord.Multiply(scale), RawYCoord, RawZCoords, IsCompressed); + : Curve.CreateRawPoint(RawXCoord.Multiply(scale), RawYCoord, RawZCoords); } public virtual ECPoint ScaleXNegateY(ECFieldElement scale) { return IsInfinity ? this - : Curve.CreateRawPoint(RawXCoord.Multiply(scale), RawYCoord.Negate(), RawZCoords, IsCompressed); + : Curve.CreateRawPoint(RawXCoord.Multiply(scale), RawYCoord.Negate(), RawZCoords); } public virtual ECPoint ScaleY(ECFieldElement scale) { return IsInfinity ? this - : Curve.CreateRawPoint(RawXCoord, RawYCoord.Multiply(scale), RawZCoords, IsCompressed); + : Curve.CreateRawPoint(RawXCoord, RawYCoord.Multiply(scale), RawZCoords); } public virtual ECPoint ScaleYNegateX(ECFieldElement scale) { return IsInfinity ? this - : Curve.CreateRawPoint(RawXCoord.Negate(), RawYCoord.Multiply(scale), RawZCoords, IsCompressed); + : Curve.CreateRawPoint(RawXCoord.Negate(), RawYCoord.Multiply(scale), RawZCoords); } public override bool Equals(object obj) @@ -442,11 +429,19 @@ public override string ToString() public virtual byte[] GetEncoded() { - return GetEncoded(m_withCompression); + return GetEncoded(false); } public abstract byte[] GetEncoded(bool compressed); + public abstract int GetEncodedLength(bool compressed); + + public abstract void EncodeTo(bool compressed, byte[] buf, int off); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public abstract void EncodeTo(bool compressed, Span buf); +#endif + protected internal abstract bool CompressionYTilde { get; } public abstract ECPoint Add(ECPoint b); @@ -529,17 +524,13 @@ public PreCompInfo Precompute(PreCompInfo existing) public abstract class ECPointBase : ECPoint { - protected internal ECPointBase( - ECCurve curve, - ECFieldElement x, - ECFieldElement y, - bool withCompression) - : base(curve, x, y, withCompression) + protected internal ECPointBase(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - protected internal ECPointBase(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + protected internal ECPointBase(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -549,9 +540,7 @@ protected internal ECPointBase(ECCurve curve, ECFieldElement x, ECFieldElement y public override byte[] GetEncoded(bool compressed) { if (this.IsInfinity) - { return new byte[1]; - } ECPoint normed = Normalize(); @@ -576,6 +565,69 @@ public override byte[] GetEncoded(bool compressed) } } + public override int GetEncodedLength(bool compressed) + { + if (IsInfinity) + return 1; + + if (compressed) + return 1 + XCoord.GetEncodedLength(); + + return 1 + XCoord.GetEncodedLength() + YCoord.GetEncodedLength(); + } + + public override void EncodeTo(bool compressed, byte[] buf, int off) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + EncodeTo(compressed, buf.AsSpan(off)); +#else + if (IsInfinity) + { + buf[off] = 0x00; + return; + } + + ECPoint normed = Normalize(); + ECFieldElement X = normed.XCoord, Y = normed.YCoord; + + if (compressed) + { + buf[off] = (byte)(normed.CompressionYTilde ? 0x03 : 0x02); + X.EncodeTo(buf, off + 1); + return; + } + + buf[off] = 0x04; + X.EncodeTo(buf, off + 1); + Y.EncodeTo(buf, off + 1 + X.GetEncodedLength()); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void EncodeTo(bool compressed, Span buf) + { + if (IsInfinity) + { + buf[0] = 0x00; + return; + } + + ECPoint normed = Normalize(); + ECFieldElement X = normed.XCoord, Y = normed.YCoord; + + if (compressed) + { + buf[0] = (byte)(normed.CompressionYTilde ? 0x03 : 0x02); + X.EncodeTo(buf[1..]); + return; + } + + buf[0] = 0x04; + X.EncodeTo(buf[1..]); + Y.EncodeTo(buf[(1 + X.GetEncodedLength())..]); + } +#endif + /** * Multiplies this ECPoint by the given number. * @param k The multiplicator. @@ -590,13 +642,13 @@ public override ECPoint Multiply(BigInteger k) public abstract class AbstractFpPoint : ECPointBase { - protected AbstractFpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) + protected AbstractFpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - protected AbstractFpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + protected AbstractFpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -663,43 +715,21 @@ public override ECPoint Subtract(ECPoint b) public class FpPoint : AbstractFpPoint { - /** - * Create a point which encodes without point compression. - * - * @param curve the curve to use - * @param x affine x co-ordinate - * @param y affine y co-ordinate - */ - - public FpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) - { - } - - /** - * Create a point that encodes with or without point compression. - * - * @param curve the curve to use - * @param x affine x co-ordinate - * @param y affine y co-ordinate - * @param withCompression if true encode with point compression - */ - - public FpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) + internal FpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { if ((x == null) != (y == null)) throw new ArgumentException("Exactly one of the field elements is null"); } - internal FpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal FpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } protected override ECPoint Detach() { - return new FpPoint(null, AffineXCoord, AffineYCoord, false); + return new FpPoint(null, AffineXCoord, AffineYCoord); } public override ECFieldElement GetZCoord(int index) @@ -750,7 +780,7 @@ public override ECPoint Add(ECPoint b) ECFieldElement X3 = gamma.Square().Subtract(X1).Subtract(X2); ECFieldElement Y3 = gamma.Multiply(X1.Subtract(X3)).Subtract(Y1); - return new FpPoint(Curve, X3, Y3, IsCompressed); + return new FpPoint(Curve, X3, Y3); } case ECCurve.COORD_HOMOGENEOUS: @@ -792,7 +822,7 @@ public override ECPoint Add(ECPoint b) ECFieldElement Y3 = vSquaredV2.Subtract(A).MultiplyMinusProduct(u, u2, vCubed); ECFieldElement Z3 = vCubed.Multiply(w); - return new FpPoint(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed); + return new FpPoint(curve, X3, Y3, new ECFieldElement[] { Z3 }); } case ECCurve.COORD_JACOBIAN: @@ -922,7 +952,7 @@ public override ECPoint Add(ECPoint b) zs = new ECFieldElement[] { Z3 }; } - return new FpPoint(curve, X3, Y3, zs, IsCompressed); + return new FpPoint(curve, X3, Y3, zs); } default: @@ -957,7 +987,7 @@ public override ECPoint Twice() ECFieldElement X3 = gamma.Square().Subtract(Two(X1)); ECFieldElement Y3 = gamma.Multiply(X1.Subtract(X3)).Subtract(Y1); - return new FpPoint(Curve, X3, Y3, IsCompressed); + return new FpPoint(Curve, X3, Y3); } case ECCurve.COORD_HOMOGENEOUS: @@ -987,7 +1017,7 @@ public override ECPoint Twice() ECFieldElement _4sSquared = Z1IsOne ? Two(_2t) : _2s.Square(); ECFieldElement Z3 = Two(_4sSquared).Multiply(s); - return new FpPoint(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed); + return new FpPoint(curve, X3, Y3, new ECFieldElement[] { Z3 }); } case ECCurve.COORD_JACOBIAN: @@ -1046,7 +1076,7 @@ public override ECPoint Twice() // Alternative calculation of Z3 using fast square //ECFieldElement Z3 = doubleProductFromSquares(Y1, Z1, Y1Squared, Z1Squared); - return new FpPoint(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed); + return new FpPoint(curve, X3, Y3, new ECFieldElement[] { Z3 }); } case ECCurve.COORD_JACOBIAN_MODIFIED: @@ -1117,7 +1147,7 @@ public override ECPoint TwicePlus(ECPoint b) ECFieldElement X4 = (L2.Subtract(L1)).Multiply(L1.Add(L2)).Add(X2); ECFieldElement Y4 = (X1.Subtract(X4)).Multiply(L2).Subtract(Y1); - return new FpPoint(Curve, X4, Y4, IsCompressed); + return new FpPoint(Curve, X4, Y4); } case ECCurve.COORD_JACOBIAN_MODIFIED: { @@ -1166,7 +1196,7 @@ public override ECPoint ThreeTimes() ECFieldElement X4 = (L2.Subtract(L1)).Multiply(L1.Add(L2)).Add(X1); ECFieldElement Y4 = (X1.Subtract(X4)).Multiply(L2).Subtract(Y1); - return new FpPoint(Curve, X4, Y4, IsCompressed); + return new FpPoint(Curve, X4, Y4); } case ECCurve.COORD_JACOBIAN_MODIFIED: { @@ -1248,15 +1278,15 @@ public override ECPoint TimesPow2(int e) { case ECCurve.COORD_AFFINE: ECFieldElement zInv = Z1.Invert(), zInv2 = zInv.Square(), zInv3 = zInv2.Multiply(zInv); - return new FpPoint(curve, X1.Multiply(zInv2), Y1.Multiply(zInv3), IsCompressed); + return new FpPoint(curve, X1.Multiply(zInv2), Y1.Multiply(zInv3)); case ECCurve.COORD_HOMOGENEOUS: X1 = X1.Multiply(Z1); Z1 = Z1.Multiply(Z1.Square()); - return new FpPoint(curve, X1, Y1, new ECFieldElement[] { Z1 }, IsCompressed); + return new FpPoint(curve, X1, Y1, new ECFieldElement[] { Z1 }); case ECCurve.COORD_JACOBIAN: - return new FpPoint(curve, X1, Y1, new ECFieldElement[] { Z1 }, IsCompressed); + return new FpPoint(curve, X1, Y1, new ECFieldElement[] { Z1 }); case ECCurve.COORD_JACOBIAN_MODIFIED: - return new FpPoint(curve, X1, Y1, new ECFieldElement[] { Z1, W1 }, IsCompressed); + return new FpPoint(curve, X1, Y1, new ECFieldElement[] { Z1, W1 }); default: throw new InvalidOperationException("unsupported coordinate system"); } @@ -1302,10 +1332,10 @@ public override ECPoint Negate() if (ECCurve.COORD_AFFINE != coord) { - return new FpPoint(curve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed); + return new FpPoint(curve, RawXCoord, RawYCoord.Negate(), RawZCoords); } - return new FpPoint(curve, RawXCoord, RawYCoord.Negate(), IsCompressed); + return new FpPoint(curve, RawXCoord, RawYCoord.Negate()); } protected virtual ECFieldElement CalculateJacobianModifiedW(ECFieldElement Z, ECFieldElement ZSquared) @@ -1360,20 +1390,20 @@ protected virtual FpPoint TwiceJacobianModified(bool calculateW) ECFieldElement W3 = calculateW ? Two(_8T.Multiply(W1)) : null; ECFieldElement Z3 = Z1.IsOne ? _2Y1 : _2Y1.Multiply(Z1); - return new FpPoint(this.Curve, X3, Y3, new ECFieldElement[] { Z3, W3 }, IsCompressed); + return new FpPoint(this.Curve, X3, Y3, new ECFieldElement[] { Z3, W3 }); } } public abstract class AbstractF2mPoint : ECPointBase { - protected AbstractF2mPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) + protected AbstractF2mPoint(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - protected AbstractF2mPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + protected AbstractF2mPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -1513,7 +1543,7 @@ public override ECPoint ScaleX(ECFieldElement scale) ECFieldElement X2 = X.Multiply(scale); ECFieldElement L2 = L.Add(X).Divide(scale).Add(X2); - return Curve.CreateRawPoint(X, L2, RawZCoords, IsCompressed); + return Curve.CreateRawPoint(X, L2, RawZCoords); } case ECCurve.COORD_LAMBDA_PROJECTIVE: { @@ -1525,7 +1555,7 @@ public override ECPoint ScaleX(ECFieldElement scale) ECFieldElement L2 = L.Add(X).Add(X2); ECFieldElement Z2 = Z.Multiply(scale); - return Curve.CreateRawPoint(X, L2, new ECFieldElement[] { Z2 }, IsCompressed); + return Curve.CreateRawPoint(X, L2, new ECFieldElement[] { Z2 }); } default: { @@ -1554,7 +1584,7 @@ public override ECPoint ScaleY(ECFieldElement scale) // Y is actually Lambda (X + Y/X) here ECFieldElement L2 = L.Add(X).Multiply(scale).Add(X); - return Curve.CreateRawPoint(X, L2, RawZCoords, IsCompressed); + return Curve.CreateRawPoint(X, L2, RawZCoords); } default: { @@ -1593,14 +1623,14 @@ public virtual AbstractF2mPoint Tau() case ECCurve.COORD_LAMBDA_AFFINE: { ECFieldElement Y1 = this.RawYCoord; - return (AbstractF2mPoint)curve.CreateRawPoint(X1.Square(), Y1.Square(), IsCompressed); + return (AbstractF2mPoint)curve.CreateRawPoint(X1.Square(), Y1.Square()); } case ECCurve.COORD_HOMOGENEOUS: case ECCurve.COORD_LAMBDA_PROJECTIVE: { ECFieldElement Y1 = this.RawYCoord, Z1 = this.RawZCoords[0]; return (AbstractF2mPoint)curve.CreateRawPoint(X1.Square(), Y1.Square(), - new ECFieldElement[] { Z1.Square() }, IsCompressed); + new ECFieldElement[] { Z1.Square() }); } default: { @@ -1625,14 +1655,14 @@ public virtual AbstractF2mPoint TauPow(int pow) case ECCurve.COORD_LAMBDA_AFFINE: { ECFieldElement Y1 = this.RawYCoord; - return (AbstractF2mPoint)curve.CreateRawPoint(X1.SquarePow(pow), Y1.SquarePow(pow), IsCompressed); + return (AbstractF2mPoint)curve.CreateRawPoint(X1.SquarePow(pow), Y1.SquarePow(pow)); } case ECCurve.COORD_HOMOGENEOUS: case ECCurve.COORD_LAMBDA_PROJECTIVE: { ECFieldElement Y1 = this.RawYCoord, Z1 = this.RawZCoords[0]; return (AbstractF2mPoint)curve.CreateRawPoint(X1.SquarePow(pow), Y1.SquarePow(pow), - new ECFieldElement[] { Z1.SquarePow(pow) }, IsCompressed); + new ECFieldElement[] { Z1.SquarePow(pow) }); } default: { @@ -1648,33 +1678,8 @@ public virtual AbstractF2mPoint TauPow(int pow) public class F2mPoint : AbstractF2mPoint { - /** - * @param curve base curve - * @param x x point - * @param y y point - */ - - public F2mPoint( - ECCurve curve, - ECFieldElement x, - ECFieldElement y) - : this(curve, x, y, false) - { - } - - /** - * @param curve base curve - * @param x x point - * @param y y point - * @param withCompression true if encode with point compression. - */ - - public F2mPoint( - ECCurve curve, - ECFieldElement x, - ECFieldElement y, - bool withCompression) - : base(curve, x, y, withCompression) + internal F2mPoint(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { if ((x == null) != (y == null)) { @@ -1694,14 +1699,14 @@ public F2mPoint( } } - internal F2mPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal F2mPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } protected override ECPoint Detach() { - return new F2mPoint(null, AffineXCoord, AffineYCoord, false); + return new F2mPoint(null, AffineXCoord, AffineYCoord); } public override ECFieldElement YCoord @@ -1804,7 +1809,7 @@ public override ECPoint Add(ECPoint b) ECFieldElement X3 = L.Square().Add(L).Add(dx).Add(curve.A); ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); - return new F2mPoint(curve, X3, Y3, IsCompressed); + return new F2mPoint(curve, X3, Y3); } case ECCurve.COORD_HOMOGENEOUS: { @@ -1851,7 +1856,7 @@ public override ECPoint Add(ECPoint b) ECFieldElement Y3 = U.MultiplyPlusProduct(X1, V, Y1).MultiplyPlusProduct(VSqZ2, uv, A); ECFieldElement Z3 = VCu.Multiply(W); - return new F2mPoint(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed); + return new F2mPoint(curve, X3, Y3, new ECFieldElement[] { Z3 }); } case ECCurve.COORD_LAMBDA_PROJECTIVE: { @@ -1909,7 +1914,7 @@ public override ECPoint Add(ECPoint b) X3 = L.Square().Add(L).Add(X1).Add(curve.A); if (X3.IsZero) { - return new F2mPoint(curve, X3, curve.B.Sqrt(), IsCompressed); + return new F2mPoint(curve, X3, curve.B.Sqrt()); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); @@ -1926,7 +1931,7 @@ public override ECPoint Add(ECPoint b) X3 = AU1.Multiply(AU2); if (X3.IsZero) { - return new F2mPoint(curve, X3, curve.B.Sqrt(), IsCompressed); + return new F2mPoint(curve, X3, curve.B.Sqrt()); } ECFieldElement ABZ2 = A.Multiply(B); @@ -1944,7 +1949,7 @@ public override ECPoint Add(ECPoint b) } } - return new F2mPoint(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new F2mPoint(curve, X3, L3, new ECFieldElement[] { Z3 }); } default: { @@ -1983,7 +1988,7 @@ public override ECPoint Twice() ECFieldElement X3 = L1.Square().Add(L1).Add(curve.A); ECFieldElement Y3 = X1.SquarePlusProduct(X3, L1.AddOne()); - return new F2mPoint(curve, X3, Y3, IsCompressed); + return new F2mPoint(curve, X3, Y3); } case ECCurve.COORD_HOMOGENEOUS: { @@ -2004,7 +2009,7 @@ public override ECPoint Twice() ECFieldElement Y3 = X1Sq.Square().MultiplyPlusProduct(V, h, sv); ECFieldElement Z3 = V.Multiply(vSquared); - return new F2mPoint(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed); + return new F2mPoint(curve, X3, Y3, new ECFieldElement[] { Z3 }); } case ECCurve.COORD_LAMBDA_PROJECTIVE: { @@ -2018,7 +2023,7 @@ public override ECPoint Twice() ECFieldElement T = L1.Square().Add(L1Z1).Add(aZ1Sq); if (T.IsZero) { - return new F2mPoint(curve, T, curve.B.Sqrt(), IsCompressed); + return new F2mPoint(curve, T, curve.B.Sqrt()); } ECFieldElement X3 = T.Square(); @@ -2055,7 +2060,7 @@ public override ECPoint Twice() L3 = X1Z1.SquarePlusProduct(T, L1Z1).Add(X3).Add(Z3); } - return new F2mPoint(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new F2mPoint(curve, X3, L3, new ECFieldElement[] { Z3 }); } default: { @@ -2119,14 +2124,14 @@ public override ECPoint TwicePlus(ECPoint b) if (A.IsZero) { - return new F2mPoint(curve, A, curve.B.Sqrt(), IsCompressed); + return new F2mPoint(curve, A, curve.B.Sqrt()); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2plus1, Z3); - return new F2mPoint(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new F2mPoint(curve, X3, L3, new ECFieldElement[] { Z3 }); } default: { @@ -2152,23 +2157,23 @@ public override ECPoint Negate() case ECCurve.COORD_AFFINE: { ECFieldElement Y = this.RawYCoord; - return new F2mPoint(curve, X, Y.Add(X), IsCompressed); + return new F2mPoint(curve, X, Y.Add(X)); } case ECCurve.COORD_HOMOGENEOUS: { ECFieldElement Y = this.RawYCoord, Z = this.RawZCoords[0]; - return new F2mPoint(curve, X, Y.Add(X), new ECFieldElement[] { Z }, IsCompressed); + return new F2mPoint(curve, X, Y.Add(X), new ECFieldElement[] { Z }); } case ECCurve.COORD_LAMBDA_AFFINE: { ECFieldElement L = this.RawYCoord; - return new F2mPoint(curve, X, L.AddOne(), IsCompressed); + return new F2mPoint(curve, X, L.AddOne()); } case ECCurve.COORD_LAMBDA_PROJECTIVE: { // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; - return new F2mPoint(curve, X, L.Add(Z), new ECFieldElement[] { Z }, IsCompressed); + return new F2mPoint(curve, X, L.Add(Z), new ECFieldElement[] { Z }); } default: { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/LongArray.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/LongArray.cs index 52b3ccb..afdc3e0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/LongArray.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/LongArray.cs @@ -2,334 +2,53 @@ #pragma warning disable using System; using System.Text; - +using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC { - internal class LongArray + internal struct LongArray { - //private static long DEInterleave_MASK = 0x5555555555555555L; - - /* - * This expands 8 bit indices into 16 bit contents (high bit 14), by inserting 0s between bits. - * In a binary field, this operation is the same as squaring an 8 bit number. - */ - private static readonly ushort[] INTERLEAVE2_TABLE = new ushort[] - { - 0x0000, 0x0001, 0x0004, 0x0005, 0x0010, 0x0011, 0x0014, 0x0015, - 0x0040, 0x0041, 0x0044, 0x0045, 0x0050, 0x0051, 0x0054, 0x0055, - 0x0100, 0x0101, 0x0104, 0x0105, 0x0110, 0x0111, 0x0114, 0x0115, - 0x0140, 0x0141, 0x0144, 0x0145, 0x0150, 0x0151, 0x0154, 0x0155, - 0x0400, 0x0401, 0x0404, 0x0405, 0x0410, 0x0411, 0x0414, 0x0415, - 0x0440, 0x0441, 0x0444, 0x0445, 0x0450, 0x0451, 0x0454, 0x0455, - 0x0500, 0x0501, 0x0504, 0x0505, 0x0510, 0x0511, 0x0514, 0x0515, - 0x0540, 0x0541, 0x0544, 0x0545, 0x0550, 0x0551, 0x0554, 0x0555, - 0x1000, 0x1001, 0x1004, 0x1005, 0x1010, 0x1011, 0x1014, 0x1015, - 0x1040, 0x1041, 0x1044, 0x1045, 0x1050, 0x1051, 0x1054, 0x1055, - 0x1100, 0x1101, 0x1104, 0x1105, 0x1110, 0x1111, 0x1114, 0x1115, - 0x1140, 0x1141, 0x1144, 0x1145, 0x1150, 0x1151, 0x1154, 0x1155, - 0x1400, 0x1401, 0x1404, 0x1405, 0x1410, 0x1411, 0x1414, 0x1415, - 0x1440, 0x1441, 0x1444, 0x1445, 0x1450, 0x1451, 0x1454, 0x1455, - 0x1500, 0x1501, 0x1504, 0x1505, 0x1510, 0x1511, 0x1514, 0x1515, - 0x1540, 0x1541, 0x1544, 0x1545, 0x1550, 0x1551, 0x1554, 0x1555, - 0x4000, 0x4001, 0x4004, 0x4005, 0x4010, 0x4011, 0x4014, 0x4015, - 0x4040, 0x4041, 0x4044, 0x4045, 0x4050, 0x4051, 0x4054, 0x4055, - 0x4100, 0x4101, 0x4104, 0x4105, 0x4110, 0x4111, 0x4114, 0x4115, - 0x4140, 0x4141, 0x4144, 0x4145, 0x4150, 0x4151, 0x4154, 0x4155, - 0x4400, 0x4401, 0x4404, 0x4405, 0x4410, 0x4411, 0x4414, 0x4415, - 0x4440, 0x4441, 0x4444, 0x4445, 0x4450, 0x4451, 0x4454, 0x4455, - 0x4500, 0x4501, 0x4504, 0x4505, 0x4510, 0x4511, 0x4514, 0x4515, - 0x4540, 0x4541, 0x4544, 0x4545, 0x4550, 0x4551, 0x4554, 0x4555, - 0x5000, 0x5001, 0x5004, 0x5005, 0x5010, 0x5011, 0x5014, 0x5015, - 0x5040, 0x5041, 0x5044, 0x5045, 0x5050, 0x5051, 0x5054, 0x5055, - 0x5100, 0x5101, 0x5104, 0x5105, 0x5110, 0x5111, 0x5114, 0x5115, - 0x5140, 0x5141, 0x5144, 0x5145, 0x5150, 0x5151, 0x5154, 0x5155, - 0x5400, 0x5401, 0x5404, 0x5405, 0x5410, 0x5411, 0x5414, 0x5415, - 0x5440, 0x5441, 0x5444, 0x5445, 0x5450, 0x5451, 0x5454, 0x5455, - 0x5500, 0x5501, 0x5504, 0x5505, 0x5510, 0x5511, 0x5514, 0x5515, - 0x5540, 0x5541, 0x5544, 0x5545, 0x5550, 0x5551, 0x5554, 0x5555 - }; - - /* - * This expands 7 bit indices into 21 bit contents (high bit 18), by inserting 0s between bits. - */ - private static readonly int[] INTERLEAVE3_TABLE = new int[] - { - 0x00000, 0x00001, 0x00008, 0x00009, 0x00040, 0x00041, 0x00048, 0x00049, - 0x00200, 0x00201, 0x00208, 0x00209, 0x00240, 0x00241, 0x00248, 0x00249, - 0x01000, 0x01001, 0x01008, 0x01009, 0x01040, 0x01041, 0x01048, 0x01049, - 0x01200, 0x01201, 0x01208, 0x01209, 0x01240, 0x01241, 0x01248, 0x01249, - 0x08000, 0x08001, 0x08008, 0x08009, 0x08040, 0x08041, 0x08048, 0x08049, - 0x08200, 0x08201, 0x08208, 0x08209, 0x08240, 0x08241, 0x08248, 0x08249, - 0x09000, 0x09001, 0x09008, 0x09009, 0x09040, 0x09041, 0x09048, 0x09049, - 0x09200, 0x09201, 0x09208, 0x09209, 0x09240, 0x09241, 0x09248, 0x09249, - 0x40000, 0x40001, 0x40008, 0x40009, 0x40040, 0x40041, 0x40048, 0x40049, - 0x40200, 0x40201, 0x40208, 0x40209, 0x40240, 0x40241, 0x40248, 0x40249, - 0x41000, 0x41001, 0x41008, 0x41009, 0x41040, 0x41041, 0x41048, 0x41049, - 0x41200, 0x41201, 0x41208, 0x41209, 0x41240, 0x41241, 0x41248, 0x41249, - 0x48000, 0x48001, 0x48008, 0x48009, 0x48040, 0x48041, 0x48048, 0x48049, - 0x48200, 0x48201, 0x48208, 0x48209, 0x48240, 0x48241, 0x48248, 0x48249, - 0x49000, 0x49001, 0x49008, 0x49009, 0x49040, 0x49041, 0x49048, 0x49049, - 0x49200, 0x49201, 0x49208, 0x49209, 0x49240, 0x49241, 0x49248, 0x49249 - }; - - /* - * This expands 8 bit indices into 32 bit contents (high bit 28), by inserting 0s between bits. - */ - private static readonly int[] INTERLEAVE4_TABLE = new int[] - { - 0x00000000, 0x00000001, 0x00000010, 0x00000011, 0x00000100, 0x00000101, 0x00000110, 0x00000111, - 0x00001000, 0x00001001, 0x00001010, 0x00001011, 0x00001100, 0x00001101, 0x00001110, 0x00001111, - 0x00010000, 0x00010001, 0x00010010, 0x00010011, 0x00010100, 0x00010101, 0x00010110, 0x00010111, - 0x00011000, 0x00011001, 0x00011010, 0x00011011, 0x00011100, 0x00011101, 0x00011110, 0x00011111, - 0x00100000, 0x00100001, 0x00100010, 0x00100011, 0x00100100, 0x00100101, 0x00100110, 0x00100111, - 0x00101000, 0x00101001, 0x00101010, 0x00101011, 0x00101100, 0x00101101, 0x00101110, 0x00101111, - 0x00110000, 0x00110001, 0x00110010, 0x00110011, 0x00110100, 0x00110101, 0x00110110, 0x00110111, - 0x00111000, 0x00111001, 0x00111010, 0x00111011, 0x00111100, 0x00111101, 0x00111110, 0x00111111, - 0x01000000, 0x01000001, 0x01000010, 0x01000011, 0x01000100, 0x01000101, 0x01000110, 0x01000111, - 0x01001000, 0x01001001, 0x01001010, 0x01001011, 0x01001100, 0x01001101, 0x01001110, 0x01001111, - 0x01010000, 0x01010001, 0x01010010, 0x01010011, 0x01010100, 0x01010101, 0x01010110, 0x01010111, - 0x01011000, 0x01011001, 0x01011010, 0x01011011, 0x01011100, 0x01011101, 0x01011110, 0x01011111, - 0x01100000, 0x01100001, 0x01100010, 0x01100011, 0x01100100, 0x01100101, 0x01100110, 0x01100111, - 0x01101000, 0x01101001, 0x01101010, 0x01101011, 0x01101100, 0x01101101, 0x01101110, 0x01101111, - 0x01110000, 0x01110001, 0x01110010, 0x01110011, 0x01110100, 0x01110101, 0x01110110, 0x01110111, - 0x01111000, 0x01111001, 0x01111010, 0x01111011, 0x01111100, 0x01111101, 0x01111110, 0x01111111, - 0x10000000, 0x10000001, 0x10000010, 0x10000011, 0x10000100, 0x10000101, 0x10000110, 0x10000111, - 0x10001000, 0x10001001, 0x10001010, 0x10001011, 0x10001100, 0x10001101, 0x10001110, 0x10001111, - 0x10010000, 0x10010001, 0x10010010, 0x10010011, 0x10010100, 0x10010101, 0x10010110, 0x10010111, - 0x10011000, 0x10011001, 0x10011010, 0x10011011, 0x10011100, 0x10011101, 0x10011110, 0x10011111, - 0x10100000, 0x10100001, 0x10100010, 0x10100011, 0x10100100, 0x10100101, 0x10100110, 0x10100111, - 0x10101000, 0x10101001, 0x10101010, 0x10101011, 0x10101100, 0x10101101, 0x10101110, 0x10101111, - 0x10110000, 0x10110001, 0x10110010, 0x10110011, 0x10110100, 0x10110101, 0x10110110, 0x10110111, - 0x10111000, 0x10111001, 0x10111010, 0x10111011, 0x10111100, 0x10111101, 0x10111110, 0x10111111, - 0x11000000, 0x11000001, 0x11000010, 0x11000011, 0x11000100, 0x11000101, 0x11000110, 0x11000111, - 0x11001000, 0x11001001, 0x11001010, 0x11001011, 0x11001100, 0x11001101, 0x11001110, 0x11001111, - 0x11010000, 0x11010001, 0x11010010, 0x11010011, 0x11010100, 0x11010101, 0x11010110, 0x11010111, - 0x11011000, 0x11011001, 0x11011010, 0x11011011, 0x11011100, 0x11011101, 0x11011110, 0x11011111, - 0x11100000, 0x11100001, 0x11100010, 0x11100011, 0x11100100, 0x11100101, 0x11100110, 0x11100111, - 0x11101000, 0x11101001, 0x11101010, 0x11101011, 0x11101100, 0x11101101, 0x11101110, 0x11101111, - 0x11110000, 0x11110001, 0x11110010, 0x11110011, 0x11110100, 0x11110101, 0x11110110, 0x11110111, - 0x11111000, 0x11111001, 0x11111010, 0x11111011, 0x11111100, 0x11111101, 0x11111110, 0x11111111 - }; - - /* - * This expands 7 bit indices into 35 bit contents (high bit 30), by inserting 0s between bits. - */ - private static readonly int[] INTERLEAVE5_TABLE = new int[] { - 0x00000000, 0x00000001, 0x00000020, 0x00000021, 0x00000400, 0x00000401, 0x00000420, 0x00000421, - 0x00008000, 0x00008001, 0x00008020, 0x00008021, 0x00008400, 0x00008401, 0x00008420, 0x00008421, - 0x00100000, 0x00100001, 0x00100020, 0x00100021, 0x00100400, 0x00100401, 0x00100420, 0x00100421, - 0x00108000, 0x00108001, 0x00108020, 0x00108021, 0x00108400, 0x00108401, 0x00108420, 0x00108421, - 0x02000000, 0x02000001, 0x02000020, 0x02000021, 0x02000400, 0x02000401, 0x02000420, 0x02000421, - 0x02008000, 0x02008001, 0x02008020, 0x02008021, 0x02008400, 0x02008401, 0x02008420, 0x02008421, - 0x02100000, 0x02100001, 0x02100020, 0x02100021, 0x02100400, 0x02100401, 0x02100420, 0x02100421, - 0x02108000, 0x02108001, 0x02108020, 0x02108021, 0x02108400, 0x02108401, 0x02108420, 0x02108421, - 0x40000000, 0x40000001, 0x40000020, 0x40000021, 0x40000400, 0x40000401, 0x40000420, 0x40000421, - 0x40008000, 0x40008001, 0x40008020, 0x40008021, 0x40008400, 0x40008401, 0x40008420, 0x40008421, - 0x40100000, 0x40100001, 0x40100020, 0x40100021, 0x40100400, 0x40100401, 0x40100420, 0x40100421, - 0x40108000, 0x40108001, 0x40108020, 0x40108021, 0x40108400, 0x40108401, 0x40108420, 0x40108421, - 0x42000000, 0x42000001, 0x42000020, 0x42000021, 0x42000400, 0x42000401, 0x42000420, 0x42000421, - 0x42008000, 0x42008001, 0x42008020, 0x42008021, 0x42008400, 0x42008401, 0x42008420, 0x42008421, - 0x42100000, 0x42100001, 0x42100020, 0x42100021, 0x42100400, 0x42100401, 0x42100420, 0x42100421, - 0x42108000, 0x42108001, 0x42108020, 0x42108021, 0x42108400, 0x42108401, 0x42108420, 0x42108421 - }; - - /* - * This expands 9 bit indices into 63 bit (long) contents (high bit 56), by inserting 0s between bits. - */ - private static readonly long[] INTERLEAVE7_TABLE = new long[] - { - 0x0000000000000000L, 0x0000000000000001L, 0x0000000000000080L, 0x0000000000000081L, - 0x0000000000004000L, 0x0000000000004001L, 0x0000000000004080L, 0x0000000000004081L, - 0x0000000000200000L, 0x0000000000200001L, 0x0000000000200080L, 0x0000000000200081L, - 0x0000000000204000L, 0x0000000000204001L, 0x0000000000204080L, 0x0000000000204081L, - 0x0000000010000000L, 0x0000000010000001L, 0x0000000010000080L, 0x0000000010000081L, - 0x0000000010004000L, 0x0000000010004001L, 0x0000000010004080L, 0x0000000010004081L, - 0x0000000010200000L, 0x0000000010200001L, 0x0000000010200080L, 0x0000000010200081L, - 0x0000000010204000L, 0x0000000010204001L, 0x0000000010204080L, 0x0000000010204081L, - 0x0000000800000000L, 0x0000000800000001L, 0x0000000800000080L, 0x0000000800000081L, - 0x0000000800004000L, 0x0000000800004001L, 0x0000000800004080L, 0x0000000800004081L, - 0x0000000800200000L, 0x0000000800200001L, 0x0000000800200080L, 0x0000000800200081L, - 0x0000000800204000L, 0x0000000800204001L, 0x0000000800204080L, 0x0000000800204081L, - 0x0000000810000000L, 0x0000000810000001L, 0x0000000810000080L, 0x0000000810000081L, - 0x0000000810004000L, 0x0000000810004001L, 0x0000000810004080L, 0x0000000810004081L, - 0x0000000810200000L, 0x0000000810200001L, 0x0000000810200080L, 0x0000000810200081L, - 0x0000000810204000L, 0x0000000810204001L, 0x0000000810204080L, 0x0000000810204081L, - 0x0000040000000000L, 0x0000040000000001L, 0x0000040000000080L, 0x0000040000000081L, - 0x0000040000004000L, 0x0000040000004001L, 0x0000040000004080L, 0x0000040000004081L, - 0x0000040000200000L, 0x0000040000200001L, 0x0000040000200080L, 0x0000040000200081L, - 0x0000040000204000L, 0x0000040000204001L, 0x0000040000204080L, 0x0000040000204081L, - 0x0000040010000000L, 0x0000040010000001L, 0x0000040010000080L, 0x0000040010000081L, - 0x0000040010004000L, 0x0000040010004001L, 0x0000040010004080L, 0x0000040010004081L, - 0x0000040010200000L, 0x0000040010200001L, 0x0000040010200080L, 0x0000040010200081L, - 0x0000040010204000L, 0x0000040010204001L, 0x0000040010204080L, 0x0000040010204081L, - 0x0000040800000000L, 0x0000040800000001L, 0x0000040800000080L, 0x0000040800000081L, - 0x0000040800004000L, 0x0000040800004001L, 0x0000040800004080L, 0x0000040800004081L, - 0x0000040800200000L, 0x0000040800200001L, 0x0000040800200080L, 0x0000040800200081L, - 0x0000040800204000L, 0x0000040800204001L, 0x0000040800204080L, 0x0000040800204081L, - 0x0000040810000000L, 0x0000040810000001L, 0x0000040810000080L, 0x0000040810000081L, - 0x0000040810004000L, 0x0000040810004001L, 0x0000040810004080L, 0x0000040810004081L, - 0x0000040810200000L, 0x0000040810200001L, 0x0000040810200080L, 0x0000040810200081L, - 0x0000040810204000L, 0x0000040810204001L, 0x0000040810204080L, 0x0000040810204081L, - 0x0002000000000000L, 0x0002000000000001L, 0x0002000000000080L, 0x0002000000000081L, - 0x0002000000004000L, 0x0002000000004001L, 0x0002000000004080L, 0x0002000000004081L, - 0x0002000000200000L, 0x0002000000200001L, 0x0002000000200080L, 0x0002000000200081L, - 0x0002000000204000L, 0x0002000000204001L, 0x0002000000204080L, 0x0002000000204081L, - 0x0002000010000000L, 0x0002000010000001L, 0x0002000010000080L, 0x0002000010000081L, - 0x0002000010004000L, 0x0002000010004001L, 0x0002000010004080L, 0x0002000010004081L, - 0x0002000010200000L, 0x0002000010200001L, 0x0002000010200080L, 0x0002000010200081L, - 0x0002000010204000L, 0x0002000010204001L, 0x0002000010204080L, 0x0002000010204081L, - 0x0002000800000000L, 0x0002000800000001L, 0x0002000800000080L, 0x0002000800000081L, - 0x0002000800004000L, 0x0002000800004001L, 0x0002000800004080L, 0x0002000800004081L, - 0x0002000800200000L, 0x0002000800200001L, 0x0002000800200080L, 0x0002000800200081L, - 0x0002000800204000L, 0x0002000800204001L, 0x0002000800204080L, 0x0002000800204081L, - 0x0002000810000000L, 0x0002000810000001L, 0x0002000810000080L, 0x0002000810000081L, - 0x0002000810004000L, 0x0002000810004001L, 0x0002000810004080L, 0x0002000810004081L, - 0x0002000810200000L, 0x0002000810200001L, 0x0002000810200080L, 0x0002000810200081L, - 0x0002000810204000L, 0x0002000810204001L, 0x0002000810204080L, 0x0002000810204081L, - 0x0002040000000000L, 0x0002040000000001L, 0x0002040000000080L, 0x0002040000000081L, - 0x0002040000004000L, 0x0002040000004001L, 0x0002040000004080L, 0x0002040000004081L, - 0x0002040000200000L, 0x0002040000200001L, 0x0002040000200080L, 0x0002040000200081L, - 0x0002040000204000L, 0x0002040000204001L, 0x0002040000204080L, 0x0002040000204081L, - 0x0002040010000000L, 0x0002040010000001L, 0x0002040010000080L, 0x0002040010000081L, - 0x0002040010004000L, 0x0002040010004001L, 0x0002040010004080L, 0x0002040010004081L, - 0x0002040010200000L, 0x0002040010200001L, 0x0002040010200080L, 0x0002040010200081L, - 0x0002040010204000L, 0x0002040010204001L, 0x0002040010204080L, 0x0002040010204081L, - 0x0002040800000000L, 0x0002040800000001L, 0x0002040800000080L, 0x0002040800000081L, - 0x0002040800004000L, 0x0002040800004001L, 0x0002040800004080L, 0x0002040800004081L, - 0x0002040800200000L, 0x0002040800200001L, 0x0002040800200080L, 0x0002040800200081L, - 0x0002040800204000L, 0x0002040800204001L, 0x0002040800204080L, 0x0002040800204081L, - 0x0002040810000000L, 0x0002040810000001L, 0x0002040810000080L, 0x0002040810000081L, - 0x0002040810004000L, 0x0002040810004001L, 0x0002040810004080L, 0x0002040810004081L, - 0x0002040810200000L, 0x0002040810200001L, 0x0002040810200080L, 0x0002040810200081L, - 0x0002040810204000L, 0x0002040810204001L, 0x0002040810204080L, 0x0002040810204081L, - 0x0100000000000000L, 0x0100000000000001L, 0x0100000000000080L, 0x0100000000000081L, - 0x0100000000004000L, 0x0100000000004001L, 0x0100000000004080L, 0x0100000000004081L, - 0x0100000000200000L, 0x0100000000200001L, 0x0100000000200080L, 0x0100000000200081L, - 0x0100000000204000L, 0x0100000000204001L, 0x0100000000204080L, 0x0100000000204081L, - 0x0100000010000000L, 0x0100000010000001L, 0x0100000010000080L, 0x0100000010000081L, - 0x0100000010004000L, 0x0100000010004001L, 0x0100000010004080L, 0x0100000010004081L, - 0x0100000010200000L, 0x0100000010200001L, 0x0100000010200080L, 0x0100000010200081L, - 0x0100000010204000L, 0x0100000010204001L, 0x0100000010204080L, 0x0100000010204081L, - 0x0100000800000000L, 0x0100000800000001L, 0x0100000800000080L, 0x0100000800000081L, - 0x0100000800004000L, 0x0100000800004001L, 0x0100000800004080L, 0x0100000800004081L, - 0x0100000800200000L, 0x0100000800200001L, 0x0100000800200080L, 0x0100000800200081L, - 0x0100000800204000L, 0x0100000800204001L, 0x0100000800204080L, 0x0100000800204081L, - 0x0100000810000000L, 0x0100000810000001L, 0x0100000810000080L, 0x0100000810000081L, - 0x0100000810004000L, 0x0100000810004001L, 0x0100000810004080L, 0x0100000810004081L, - 0x0100000810200000L, 0x0100000810200001L, 0x0100000810200080L, 0x0100000810200081L, - 0x0100000810204000L, 0x0100000810204001L, 0x0100000810204080L, 0x0100000810204081L, - 0x0100040000000000L, 0x0100040000000001L, 0x0100040000000080L, 0x0100040000000081L, - 0x0100040000004000L, 0x0100040000004001L, 0x0100040000004080L, 0x0100040000004081L, - 0x0100040000200000L, 0x0100040000200001L, 0x0100040000200080L, 0x0100040000200081L, - 0x0100040000204000L, 0x0100040000204001L, 0x0100040000204080L, 0x0100040000204081L, - 0x0100040010000000L, 0x0100040010000001L, 0x0100040010000080L, 0x0100040010000081L, - 0x0100040010004000L, 0x0100040010004001L, 0x0100040010004080L, 0x0100040010004081L, - 0x0100040010200000L, 0x0100040010200001L, 0x0100040010200080L, 0x0100040010200081L, - 0x0100040010204000L, 0x0100040010204001L, 0x0100040010204080L, 0x0100040010204081L, - 0x0100040800000000L, 0x0100040800000001L, 0x0100040800000080L, 0x0100040800000081L, - 0x0100040800004000L, 0x0100040800004001L, 0x0100040800004080L, 0x0100040800004081L, - 0x0100040800200000L, 0x0100040800200001L, 0x0100040800200080L, 0x0100040800200081L, - 0x0100040800204000L, 0x0100040800204001L, 0x0100040800204080L, 0x0100040800204081L, - 0x0100040810000000L, 0x0100040810000001L, 0x0100040810000080L, 0x0100040810000081L, - 0x0100040810004000L, 0x0100040810004001L, 0x0100040810004080L, 0x0100040810004081L, - 0x0100040810200000L, 0x0100040810200001L, 0x0100040810200080L, 0x0100040810200081L, - 0x0100040810204000L, 0x0100040810204001L, 0x0100040810204080L, 0x0100040810204081L, - 0x0102000000000000L, 0x0102000000000001L, 0x0102000000000080L, 0x0102000000000081L, - 0x0102000000004000L, 0x0102000000004001L, 0x0102000000004080L, 0x0102000000004081L, - 0x0102000000200000L, 0x0102000000200001L, 0x0102000000200080L, 0x0102000000200081L, - 0x0102000000204000L, 0x0102000000204001L, 0x0102000000204080L, 0x0102000000204081L, - 0x0102000010000000L, 0x0102000010000001L, 0x0102000010000080L, 0x0102000010000081L, - 0x0102000010004000L, 0x0102000010004001L, 0x0102000010004080L, 0x0102000010004081L, - 0x0102000010200000L, 0x0102000010200001L, 0x0102000010200080L, 0x0102000010200081L, - 0x0102000010204000L, 0x0102000010204001L, 0x0102000010204080L, 0x0102000010204081L, - 0x0102000800000000L, 0x0102000800000001L, 0x0102000800000080L, 0x0102000800000081L, - 0x0102000800004000L, 0x0102000800004001L, 0x0102000800004080L, 0x0102000800004081L, - 0x0102000800200000L, 0x0102000800200001L, 0x0102000800200080L, 0x0102000800200081L, - 0x0102000800204000L, 0x0102000800204001L, 0x0102000800204080L, 0x0102000800204081L, - 0x0102000810000000L, 0x0102000810000001L, 0x0102000810000080L, 0x0102000810000081L, - 0x0102000810004000L, 0x0102000810004001L, 0x0102000810004080L, 0x0102000810004081L, - 0x0102000810200000L, 0x0102000810200001L, 0x0102000810200080L, 0x0102000810200081L, - 0x0102000810204000L, 0x0102000810204001L, 0x0102000810204080L, 0x0102000810204081L, - 0x0102040000000000L, 0x0102040000000001L, 0x0102040000000080L, 0x0102040000000081L, - 0x0102040000004000L, 0x0102040000004001L, 0x0102040000004080L, 0x0102040000004081L, - 0x0102040000200000L, 0x0102040000200001L, 0x0102040000200080L, 0x0102040000200081L, - 0x0102040000204000L, 0x0102040000204001L, 0x0102040000204080L, 0x0102040000204081L, - 0x0102040010000000L, 0x0102040010000001L, 0x0102040010000080L, 0x0102040010000081L, - 0x0102040010004000L, 0x0102040010004001L, 0x0102040010004080L, 0x0102040010004081L, - 0x0102040010200000L, 0x0102040010200001L, 0x0102040010200080L, 0x0102040010200081L, - 0x0102040010204000L, 0x0102040010204001L, 0x0102040010204080L, 0x0102040010204081L, - 0x0102040800000000L, 0x0102040800000001L, 0x0102040800000080L, 0x0102040800000081L, - 0x0102040800004000L, 0x0102040800004001L, 0x0102040800004080L, 0x0102040800004081L, - 0x0102040800200000L, 0x0102040800200001L, 0x0102040800200080L, 0x0102040800200081L, - 0x0102040800204000L, 0x0102040800204001L, 0x0102040800204080L, 0x0102040800204081L, - 0x0102040810000000L, 0x0102040810000001L, 0x0102040810000080L, 0x0102040810000081L, - 0x0102040810004000L, 0x0102040810004001L, 0x0102040810004080L, 0x0102040810004081L, - 0x0102040810200000L, 0x0102040810200001L, 0x0102040810200080L, 0x0102040810200081L, - 0x0102040810204000L, 0x0102040810204001L, 0x0102040810204080L, 0x0102040810204081L - }; - - // For toString(); must have length 64 - private const string ZEROES = "0000000000000000000000000000000000000000000000000000000000000000"; - - internal static readonly byte[] BitLengths = + internal static bool AreAliased(ref LongArray a, ref LongArray b) { - 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, - 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 - }; + return a.m_data == b.m_data; + } // TODO make m fixed for the LongArray, and hence compute T once and for all - private long[] m_ints; + private ulong[] m_data; - public LongArray(int intLen) + internal LongArray(int intLen) { - m_ints = new long[intLen]; + m_data = new ulong[intLen]; } - public LongArray(long[] ints) + internal LongArray(ulong[] data) { - m_ints = ints; + m_data = data; } - public LongArray(long[] ints, int off, int len) + internal LongArray(ulong[] data, int off, int len) { - if (off == 0 && len == ints.Length) + if (off == 0 && len == data.Length) { - m_ints = ints; + m_data = data; } else { - m_ints = new long[len]; - Array.Copy(ints, off, m_ints, 0, len); + m_data = new ulong[len]; + Array.Copy(data, off, m_data, 0, len); } } - public LongArray(BigInteger bigInt) + internal LongArray(BigInteger bigInt) { if (bigInt == null || bigInt.SignValue < 0) - { - throw new ArgumentException("invalid F2m field value", "bigInt"); - } + throw new ArgumentException("invalid F2m field value", nameof(bigInt)); if (bigInt.SignValue == 0) { - m_ints = new long[] { 0L }; + m_data = new ulong[1]{ 0UL }; return; } @@ -344,11 +63,11 @@ public LongArray(BigInteger bigInt) barrStart = 1; } int intLen = (barrLen + 7) / 8; - m_ints = new long[intLen]; + m_data = new ulong[intLen]; int iarrJ = intLen - 1; int rem = barrLen % 8 + barrStart; - long temp = 0; + ulong temp = 0; int barrI = barrStart; if (barrStart < rem) { @@ -358,7 +77,7 @@ public LongArray(BigInteger bigInt) uint barrBarrI = barr[barrI]; temp |= barrBarrI; } - m_ints[iarrJ--] = temp; + m_data[iarrJ--] = temp; } for (; iarrJ >= 0; iarrJ--) @@ -370,64 +89,58 @@ public LongArray(BigInteger bigInt) uint barrBarrI = barr[barrI++]; temp |= barrBarrI; } - m_ints[iarrJ] = temp; + m_data[iarrJ] = temp; } } - internal void CopyTo(long[] z, int zOff) + internal void CopyTo(ulong[] z, int zOff) { - Array.Copy(m_ints, 0, z, zOff, m_ints.Length); + Array.Copy(m_data, 0, z, zOff, m_data.Length); } - public bool IsOne() + internal bool IsOne() { - long[] a = m_ints; - if (a[0] != 1L) - { + ulong[] a = m_data; + int aLen = a.Length; + if (aLen < 1 || a[0] != 1UL) return false; - } - for (int i = 1; i < a.Length; ++i) + + for (int i = 1; i < aLen; ++i) { - if (a[i] != 0L) - { + if (a[i] != 0UL) return false; - } } return true; } - public bool IsZero() + internal bool IsZero() { - long[] a = m_ints; + ulong[] a = m_data; for (int i = 0; i < a.Length; ++i) { - if (a[i] != 0L) - { + if (a[i] != 0UL) return false; - } } return true; } - public int GetUsedLength() + internal int GetUsedLength() { - return GetUsedLengthFrom(m_ints.Length); + return GetUsedLengthFrom(m_data.Length); } - public int GetUsedLengthFrom(int from) + internal int GetUsedLengthFrom(int from) { - long[] a = m_ints; + ulong[] a = m_data; from = System.Math.Min(from, a.Length); if (from < 1) - { return 0; - } // Check if first element will act as sentinel - if (a[0] != 0) + if (a[0] != 0UL) { - while (a[--from] == 0) + while (a[--from] == 0UL) { } return from + 1; @@ -435,7 +148,7 @@ public int GetUsedLengthFrom(int from) do { - if (a[--from] != 0) + if (a[--from] != 0UL) { return from + 1; } @@ -445,19 +158,18 @@ public int GetUsedLengthFrom(int from) return 0; } - public int Degree() + internal int Degree() { - int i = m_ints.Length; - long w; + int i = m_data.Length; + ulong w; do { if (i == 0) - { return 0; - } - w = m_ints[--i]; + + w = m_data[--i]; } - while (w == 0); + while (w == 0UL); return (i << 6) + BitLength(w); } @@ -465,94 +177,44 @@ public int Degree() private int DegreeFrom(int limit) { int i = (int)(((uint)limit + 62) >> 6); - long w; + ulong w; do { if (i == 0) - { return 0; - } - w = m_ints[--i]; + + w = m_data[--i]; } while (w == 0); return (i << 6) + BitLength(w); } - // private int lowestCoefficient() - // { - // for (int i = 0; i < m_ints.Length; ++i) - // { - // long mi = m_ints[i]; - // if (mi != 0) - // { - // int j = 0; - // while ((mi & 0xFFL) == 0) - // { - // j += 8; - // mi >>>= 8; - // } - // while ((mi & 1L) == 0) - // { - // ++j; - // mi >>>= 1; - // } - // return (i << 6) + j; - // } - // } - // return -1; - // } - - private static int BitLength(long w) + private static int BitLength(ulong w) { - int u = (int)((ulong)w >> 32), b; - if (u == 0) - { - u = (int)w; - b = 0; - } - else - { - b = 32; - } - - int t = (int)((uint)u >> 16), k; - if (t == 0) - { - t = (int)((uint)u >> 8); - k = (t == 0) ? BitLengths[u] : 8 + BitLengths[t]; - } - else - { - int v = (int)((uint)t >> 8); - k = (v == 0) ? 16 + BitLengths[t] : 24 + BitLengths[v]; - } - - return b + k; + return 64 - Longs.NumberOfLeadingZeros((long)w); } - private long[] ResizedInts(int newLen) + private ulong[] ResizedData(int newLen) { - long[] newInts = new long[newLen]; - Array.Copy(m_ints, 0, newInts, 0, System.Math.Min(m_ints.Length, newLen)); + ulong[] newInts = new ulong[newLen]; + Array.Copy(m_data, 0, newInts, 0, System.Math.Min(m_data.Length, newLen)); return newInts; } - public BigInteger ToBigInteger() + internal BigInteger ToBigInteger() { int usedLen = GetUsedLength(); if (usedLen == 0) - { return BigInteger.Zero; - } - long highestInt = m_ints[usedLen - 1]; + ulong highestInt = m_data[usedLen - 1]; byte[] temp = new byte[8]; int barrI = 0; bool trailingZeroBytesDone = false; for (int j = 7; j >= 0; j--) { - byte thisByte = (byte)((ulong)highestInt >> (8 * j)); + byte thisByte = (byte)(highestInt >> (8 * j)); if (trailingZeroBytesDone || (thisByte != 0)) { trailingZeroBytesDone = true; @@ -570,93 +232,52 @@ public BigInteger ToBigInteger() for (int iarrJ = usedLen - 2; iarrJ >= 0; iarrJ--) { - long mi = m_ints[iarrJ]; + ulong mi = m_data[iarrJ]; for (int j = 7; j >= 0; j--) { - barr[barrI++] = (byte)((ulong)mi >> (8 * j)); + barr[barrI++] = (byte)(mi >> (8 * j)); } } return new BigInteger(1, barr); } - // private static long shiftUp(long[] x, int xOff, int count) - // { - // long prev = 0; - // for (int i = 0; i < count; ++i) - // { - // long next = x[xOff + i]; - // x[xOff + i] = (next << 1) | prev; - // prev = next >>> 63; - // } - // return prev; - // } - - private static long ShiftUp(long[] x, int xOff, int count, int shift) + private static ulong ShiftUp(ulong[] x, int xOff, int count, int shift) { int shiftInv = 64 - shift; - long prev = 0; + ulong prev = 0UL; for (int i = 0; i < count; ++i) { - long next = x[xOff + i]; + ulong next = x[xOff + i]; x[xOff + i] = (next << shift) | prev; - prev = (long)((ulong)next >> shiftInv); + prev = next >> shiftInv; } return prev; } - private static long ShiftUp(long[] x, int xOff, long[] z, int zOff, int count, int shift) + private static ulong ShiftUp(ulong[] x, int xOff, ulong[] z, int zOff, int count, int shift) { int shiftInv = 64 - shift; - long prev = 0; + ulong prev = 0UL; for (int i = 0; i < count; ++i) { - long next = x[xOff + i]; + ulong next = x[xOff + i]; z[zOff + i] = (next << shift) | prev; - prev = (long)((ulong)next >> shiftInv); + prev = next >> shiftInv; } return prev; } - public LongArray AddOne() + internal LongArray AddOne() { - if (m_ints.Length == 0) - { - return new LongArray(new long[]{ 1L }); - } + if (m_data.Length == 0) + return new LongArray(new ulong[1]{ 1UL }); int resultLen = System.Math.Max(1, GetUsedLength()); - long[] ints = ResizedInts(resultLen); - ints[0] ^= 1L; - return new LongArray(ints); + ulong[] data = ResizedData(resultLen); + data[0] ^= 1UL; + return new LongArray(data); } - // private void addShiftedByBits(LongArray other, int bits) - // { - // int words = bits >>> 6; - // int shift = bits & 0x3F; - // - // if (shift == 0) - // { - // addShiftedByWords(other, words); - // return; - // } - // - // int otherUsedLen = other.GetUsedLength(); - // if (otherUsedLen == 0) - // { - // return; - // } - // - // int minLen = otherUsedLen + words + 1; - // if (minLen > m_ints.Length) - // { - // m_ints = resizedInts(minLen); - // } - // - // long carry = addShiftedByBits(m_ints, words, other.m_ints, 0, otherUsedLen, shift); - // m_ints[otherUsedLen + words] ^= carry; - // } - private void AddShiftedByBitsSafe(LongArray other, int otherDegree, int bits) { int otherLen = (int)((uint)(otherDegree + 63) >> 6); @@ -666,78 +287,70 @@ private void AddShiftedByBitsSafe(LongArray other, int otherDegree, int bits) if (shift == 0) { - Add(m_ints, words, other.m_ints, 0, otherLen); + Add(m_data, words, other.m_data, 0, otherLen); return; } - long carry = AddShiftedUp(m_ints, words, other.m_ints, 0, otherLen, shift); - if (carry != 0L) + ulong carry = AddShiftedUp(m_data, words, other.m_data, 0, otherLen, shift); + if (carry != 0UL) { - m_ints[otherLen + words] ^= carry; + m_data[otherLen + words] ^= carry; } } - private static long AddShiftedUp(long[] x, int xOff, long[] y, int yOff, int count, int shift) + private static ulong AddShiftedUp(ulong[] x, int xOff, ulong[] y, int yOff, int count, int shift) { int shiftInv = 64 - shift; - long prev = 0; + ulong prev = 0; for (int i = 0; i < count; ++i) { - long next = y[yOff + i]; + ulong next = y[yOff + i]; x[xOff + i] ^= (next << shift) | prev; - prev = (long)((ulong)next >> shiftInv); + prev = next >> shiftInv; } return prev; } - private static long AddShiftedDown(long[] x, int xOff, long[] y, int yOff, int count, int shift) + private static ulong AddShiftedDown(ulong[] x, int xOff, ulong[] y, int yOff, int count, int shift) { int shiftInv = 64 - shift; - long prev = 0; + ulong prev = 0; int i = count; while (--i >= 0) { - long next = y[yOff + i]; - x[xOff + i] ^= (long)((ulong)next >> shift) | prev; + ulong next = y[yOff + i]; + x[xOff + i] ^= (next >> shift) | prev; prev = next << shiftInv; } return prev; } - public void AddShiftedByWords(LongArray other, int words) + internal void AddShiftedByWords(LongArray other, int words) { int otherUsedLen = other.GetUsedLength(); if (otherUsedLen == 0) - { return; - } int minLen = otherUsedLen + words; - if (minLen > m_ints.Length) + if (minLen > m_data.Length) { - m_ints = ResizedInts(minLen); + m_data = ResizedData(minLen); } - Add(m_ints, words, other.m_ints, 0, otherUsedLen); + Add(m_data, words, other.m_data, 0, otherUsedLen); } - private static void Add(long[] x, int xOff, long[] y, int yOff, int count) + private static void Add(ulong[] x, int xOff, ulong[] y, int yOff, int count) { - for (int i = 0; i < count; ++i) - { - x[xOff + i] ^= y[yOff + i]; - } + Nat.XorTo64(count, y, yOff, x, xOff); } - private static void Add(long[] x, int xOff, long[] y, int yOff, long[] z, int zOff, int count) + private static void Add(ulong[] x, int xOff, ulong[] y, int yOff, ulong[] z, int zOff, int count) { - for (int i = 0; i < count; ++i) - { - z[zOff + i] = x[xOff + i] ^ y[yOff + i]; - } + Nat.Xor64(count, x, xOff, y, yOff, z, zOff); } - private static void AddBoth(long[] x, int xOff, long[] y1, int y1Off, long[] y2, int y2Off, int count) + private static void AddBoth(ulong[] x, int xOff, ulong[] y1, int y1Off, ulong[] y2, int y2Off, int count) { for (int i = 0; i < count; ++i) { @@ -745,22 +358,7 @@ private static void AddBoth(long[] x, int xOff, long[] y1, int y1Off, long[] y2, } } - private static void Distribute(long[] x, int src, int dst1, int dst2, int count) - { - for (int i = 0; i < count; ++i) - { - long v = x[src + i]; - x[dst1 + i] ^= v; - x[dst2 + i] ^= v; - } - } - - public int Length - { - get { return m_ints.Length; } - } - - private static void FlipWord(long[] buf, int off, int bit, long word) + private static void FlipWord(ulong[] buf, int off, int bit, ulong word) { int n = off + (int)((uint)bit >> 6); int shift = bit & 0x3F; @@ -771,7 +369,7 @@ private static void FlipWord(long[] buf, int off, int bit, long word) else { buf[n] ^= word << shift; - word = (long)((ulong)word >> (64 - shift)); + word = word >> (64 - shift); if (word != 0) { buf[++n] ^= word; @@ -779,80 +377,44 @@ private static void FlipWord(long[] buf, int off, int bit, long word) } } - // private static long getWord(long[] buf, int off, int len, int bit) - // { - // int n = off + (bit >>> 6); - // int shift = bit & 0x3F; - // if (shift == 0) - // { - // return buf[n]; - // } - // long result = buf[n] >>> shift; - // if (++n < len) - // { - // result |= buf[n] << (64 - shift); - // } - // return result; - // } - - public bool TestBitZero() + internal bool TestBitZero() { - return m_ints.Length > 0 && (m_ints[0] & 1L) != 0; + return m_data.Length > 0 && (m_data[0] & 1UL) != 0; } - private static bool TestBit(long[] buf, int off, int n) + private static bool TestBit(ulong[] buf, int off, int n) { // theInt = n / 64 int theInt = (int)((uint)n >> 6); // theBit = n % 64 int theBit = n & 0x3F; - long tester = 1L << theBit; - return (buf[off + theInt] & tester) != 0; + ulong tester = 1UL << theBit; + return (buf[off + theInt] & tester) != 0UL; } - private static void FlipBit(long[] buf, int off, int n) + private static void FlipBit(ulong[] buf, int off, int n) { // theInt = n / 64 int theInt = (int)((uint)n >> 6); // theBit = n % 64 int theBit = n & 0x3F; - long flipper = 1L << theBit; + ulong flipper = 1UL << theBit; buf[off + theInt] ^= flipper; } - // private static void SetBit(long[] buf, int off, int n) - // { - // // theInt = n / 64 - // int theInt = n >>> 6; - // // theBit = n % 64 - // int theBit = n & 0x3F; - // long setter = 1L << theBit; - // buf[off + theInt] |= setter; - // } - // - // private static void ClearBit(long[] buf, int off, int n) - // { - // // theInt = n / 64 - // int theInt = n >>> 6; - // // theBit = n % 64 - // int theBit = n & 0x3F; - // long setter = 1L << theBit; - // buf[off + theInt] &= ~setter; - // } - - private static void MultiplyWord(long a, long[] b, int bLen, long[] c, int cOff) + private static void MultiplyWord(ulong a, ulong[] b, int bLen, ulong[] c, int cOff) { - if ((a & 1L) != 0L) + if ((a & 1UL) != 0UL) { Add(c, cOff, b, 0, bLen); } int k = 1; - while ((a = (long)((ulong)a >> 1)) != 0L) + while ((a >>= 1) != 0UL) { - if ((a & 1L) != 0L) + if ((a & 1UL) != 0UL) { - long carry = AddShiftedUp(c, cOff, b, 0, bLen, k); - if (carry != 0L) + ulong carry = AddShiftedUp(c, cOff, b, 0, bLen, k); + if (carry != 0UL) { c[cOff + bLen] ^= carry; } @@ -861,21 +423,18 @@ private static void MultiplyWord(long a, long[] b, int bLen, long[] c, int cOff) } } - public LongArray ModMultiplyLD(LongArray other, int m, int[] ks) + internal LongArray ModMultiplyLD(LongArray other, int m, int[] ks) { /* * Find out the degree of each argument and handle the zero cases */ int aDeg = Degree(); if (aDeg == 0) - { return this; - } + int bDeg = other.Degree(); if (bDeg == 0) - { return other; - } /* * Swap if necessary so that A is the smaller argument @@ -896,17 +455,15 @@ public LongArray ModMultiplyLD(LongArray other, int m, int[] ks) if (aLen == 1) { - long a0 = A.m_ints[0]; - if (a0 == 1L) - { + ulong a0 = A.m_data[0]; + if (a0 == 1UL) return B; - } /* * Fast path for small A, with performance dependent only on the number of set bits */ - long[] c0 = new long[cLen]; - MultiplyWord(a0, B.m_ints, bLen, c0, 0); + ulong[] c0 = new ulong[cLen]; + MultiplyWord(a0, B.m_data, bLen, c0, 0); /* * Reduce the raw answer against the reduction coefficients @@ -927,10 +484,10 @@ public LongArray ModMultiplyLD(LongArray other, int m, int[] ks) /* * Precompute table of all 4-bit products of B */ - long[] T0 = new long[bMax << 4]; + ulong[] T0 = new ulong[bMax << 4]; int tOff = bMax; ti[1] = tOff; - Array.Copy(B.m_ints, 0, T0, tOff, bLen); + Array.Copy(B.m_data, 0, T0, tOff, bLen); for (int i = 2; i < 16; ++i) { ti[i] = (tOff += bMax); @@ -947,14 +504,14 @@ public LongArray ModMultiplyLD(LongArray other, int m, int[] ks) /* * Second table with all 4-bit products of B shifted 4 bits */ - long[] T1 = new long[T0.Length]; + ulong[] T1 = new ulong[T0.Length]; ShiftUp(T0, 0, T1, 0, T0.Length, 4); // shiftUp(T0, bMax, T1, bMax, tOff, 4); - long[] a = A.m_ints; - long[] c = new long[cLen]; + ulong[] a = A.m_data; + ulong[] c = new ulong[cLen]; - int MASK = 0xF; + uint MASK = 0xF; /* * Lopez-Dahab algorithm @@ -964,9 +521,9 @@ public LongArray ModMultiplyLD(LongArray other, int m, int[] ks) { for (int j = 1; j < aLen; j += 2) { - int aVal = (int)((ulong)a[j] >> k); - int u = aVal & MASK; - int v = (int)((uint)aVal >> 4) & MASK; + uint aVal = (uint)(a[j] >> k); + uint u = aVal & MASK; + uint v = (aVal >> 4) & MASK; AddBoth(c, j - 1, T0, ti[u], T1, ti[v], bMax); } ShiftUp(c, 0, cLen, 8); @@ -976,9 +533,9 @@ public LongArray ModMultiplyLD(LongArray other, int m, int[] ks) { for (int j = 0; j < aLen; j += 2) { - int aVal = (int)((ulong)a[j] >> k); - int u = aVal & MASK; - int v = (int)((uint)aVal >> 4) & MASK; + uint aVal = (uint)(a[j] >> k); + uint u = aVal & MASK; + uint v = (aVal >> 4) & MASK; AddBoth(c, j, T0, ti[u], T1, ti[v], bMax); } if (k > 0) @@ -993,21 +550,18 @@ public LongArray ModMultiplyLD(LongArray other, int m, int[] ks) return ReduceResult(c, 0, cLen, m, ks); } - public LongArray ModMultiply(LongArray other, int m, int[] ks) + internal LongArray ModMultiply(LongArray other, int m, int[] ks) { /* * Find out the degree of each argument and handle the zero cases */ int aDeg = Degree(); if (aDeg == 0) - { return this; - } + int bDeg = other.Degree(); if (bDeg == 0) - { return other; - } /* * Swap if necessary so that A is the smaller argument @@ -1028,17 +582,15 @@ public LongArray ModMultiply(LongArray other, int m, int[] ks) if (aLen == 1) { - long a0 = A.m_ints[0]; - if (a0 == 1L) - { + ulong a0 = A.m_data[0]; + if (a0 == 1UL) return B; - } /* * Fast path for small A, with performance dependent only on the number of set bits */ - long[] c0 = new long[cLen]; - MultiplyWord(a0, B.m_ints, bLen, c0, 0); + ulong[] c0 = new ulong[cLen]; + MultiplyWord(a0, B.m_data, bLen, c0, 0); /* * Reduce the raw answer against the reduction coefficients @@ -1059,13 +611,14 @@ public LongArray ModMultiply(LongArray other, int m, int[] ks) /* * Precompute table of all 4-bit products of B */ - long[] T0 = new long[bMax << 4]; + ulong[] T0 = new ulong[bMax << 4]; int tOff = bMax; ti[1] = tOff; - Array.Copy(B.m_ints, 0, T0, tOff, bLen); + Array.Copy(B.m_data, 0, T0, tOff, bLen); for (int i = 2; i < 16; ++i) { - ti[i] = (tOff += bMax); + tOff += bMax; + ti[i] = tOff; if ((i & 1) == 0) { ShiftUp(T0, (int)((uint)tOff >> 1), T0, tOff, bMax, 1); @@ -1079,14 +632,14 @@ public LongArray ModMultiply(LongArray other, int m, int[] ks) /* * Second table with all 4-bit products of B shifted 4 bits */ - long[] T1 = new long[T0.Length]; + ulong[] T1 = new ulong[T0.Length]; ShiftUp(T0, 0, T1, 0, T0.Length, 4); // ShiftUp(T0, bMax, T1, bMax, tOff, 4); - long[] a = A.m_ints; - long[] c = new long[cLen << 3]; + ulong[] a = A.m_data; + ulong[] c = new ulong[cLen << 3]; - int MASK = 0xF; + uint MASK = 0xF; /* * Lopez-Dahab (Modified) algorithm @@ -1094,19 +647,16 @@ public LongArray ModMultiply(LongArray other, int m, int[] ks) for (int aPos = 0; aPos < aLen; ++aPos) { - long aVal = a[aPos]; + ulong aVal = a[aPos]; int cOff = aPos; for (;;) { - int u = (int)aVal & MASK; - aVal = (long)((ulong)aVal >> 4); - int v = (int)aVal & MASK; + uint u = (uint)aVal & MASK; aVal >>= 4; + uint v = (uint)aVal & MASK; aVal >>= 4; AddBoth(c, cOff, T0, ti[u], T1, ti[v], bMax); - aVal = (long)((ulong)aVal >> 4); - if (aVal == 0L) - { + if (aVal == 0UL) break; - } + cOff += cLen; } } @@ -1125,245 +675,25 @@ public LongArray ModMultiply(LongArray other, int m, int[] ks) return ReduceResult(c, 0, cLen, m, ks); } - public LongArray ModMultiplyAlt(LongArray other, int m, int[] ks) - { - /* - * Find out the degree of each argument and handle the zero cases - */ - int aDeg = Degree(); - if (aDeg == 0) - { - return this; - } - int bDeg = other.Degree(); - if (bDeg == 0) - { - return other; - } - - /* - * Swap if necessary so that A is the smaller argument - */ - LongArray A = this, B = other; - if (aDeg > bDeg) - { - A = other; B = this; - int tmp = aDeg; aDeg = bDeg; bDeg = tmp; - } - - /* - * Establish the word lengths of the arguments and result - */ - int aLen = (int)((uint)(aDeg + 63) >> 6); - int bLen = (int)((uint)(bDeg + 63) >> 6); - int cLen = (int)((uint)(aDeg + bDeg + 62) >> 6); - - if (aLen == 1) - { - long a0 = A.m_ints[0]; - if (a0 == 1L) - { - return B; - } - - /* - * Fast path for small A, with performance dependent only on the number of set bits - */ - long[] c0 = new long[cLen]; - MultiplyWord(a0, B.m_ints, bLen, c0, 0); - - /* - * Reduce the raw answer against the reduction coefficients - */ - return ReduceResult(c0, 0, cLen, m, ks); - } - - // NOTE: This works, but is slower than width 4 processing - // if (aLen == 2) - // { - // /* - // * Use common-multiplicand optimization to save ~1/4 of the adds - // */ - // long a1 = A.m_ints[0], a2 = A.m_ints[1]; - // long aa = a1 & a2; a1 ^= aa; a2 ^= aa; - // - // long[] b = B.m_ints; - // long[] c = new long[cLen]; - // multiplyWord(aa, b, bLen, c, 1); - // add(c, 0, c, 1, cLen - 1); - // multiplyWord(a1, b, bLen, c, 0); - // multiplyWord(a2, b, bLen, c, 1); - // - // /* - // * Reduce the raw answer against the reduction coefficients - // */ - // return ReduceResult(c, 0, cLen, m, ks); - // } - - /* - * Determine the parameters of the Interleaved window algorithm: the 'width' in bits to - * process together, the number of evaluation 'positions' implied by that width, and the - * 'top' position at which the regular window algorithm stops. - */ - int width, positions, top, banks; - - // NOTE: width 4 is the fastest over the entire range of sizes used in current crypto - // width = 1; positions = 64; top = 64; banks = 4; - // width = 2; positions = 32; top = 64; banks = 4; - // width = 3; positions = 21; top = 63; banks = 3; - width = 4; positions = 16; top = 64; banks = 8; - // width = 5; positions = 13; top = 65; banks = 7; - // width = 7; positions = 9; top = 63; banks = 9; - // width = 8; positions = 8; top = 64; banks = 8; - - /* - * Determine if B will get bigger during shifting - */ - int shifts = top < 64 ? positions : positions - 1; - int bMax = (int)((uint)(bDeg + shifts + 63) >> 6); - - int bTotal = bMax * banks, stride = width * banks; - - /* - * Create a single temporary buffer, with an offset table to find the positions of things in it - */ - int[] ci = new int[1 << width]; - int cTotal = aLen; - { - ci[0] = cTotal; - cTotal += bTotal; - ci[1] = cTotal; - for (int i = 2; i < ci.Length; ++i) - { - cTotal += cLen; - ci[i] = cTotal; - } - cTotal += cLen; - } - // NOTE: Provide a safe dump for "high zeroes" since we are adding 'bMax' and not 'bLen' - ++cTotal; - - long[] c = new long[cTotal]; + //internal LongArray ModReduce(int m, int[] ks) + //{ + // ulong[] buf = Arrays.Clone(m_data); + // int rLen = ReduceInPlace(buf, 0, buf.Length, m, ks); + // return new LongArray(buf, 0, rLen); + //} - // Prepare A in Interleaved form, according to the chosen width - Interleave(A.m_ints, 0, c, 0, aLen, width); - - // Make a working copy of B, since we will be shifting it - { - int bOff = aLen; - Array.Copy(B.m_ints, 0, c, bOff, bLen); - for (int bank = 1; bank < banks; ++bank) - { - ShiftUp(c, aLen, c, bOff += bMax, bMax, bank); - } - } - - /* - * The main loop analyzes the Interleaved windows in A, and for each non-zero window - * a single word-array XOR is performed to a carefully selected slice of 'c'. The loop is - * breadth-first, checking the lowest window in each word, then looping again for the - * next higher window position. - */ - int MASK = (1 << width) - 1; - - int k = 0; - for (;;) - { - int aPos = 0; - do - { - long aVal = (long)((ulong)c[aPos] >> k); - int bank = 0, bOff = aLen; - for (;;) - { - int index = (int)(aVal) & MASK; - if (index != 0) - { - /* - * Add to a 'c' buffer based on the bit-pattern of 'index'. Since A is in - * Interleaved form, the bits represent the current B shifted by 0, 'positions', - * 'positions' * 2, ..., 'positions' * ('width' - 1) - */ - Add(c, aPos + ci[index], c, bOff, bMax); - } - if (++bank == banks) - { - break; - } - bOff += bMax; - aVal = (long)((ulong)aVal >> width); - } - } - while (++aPos < aLen); - - if ((k += stride) >= top) - { - if (k >= 64) - { - break; - } - - /* - * Adjustment for window setups with top == 63, the final bit (if any) is processed - * as the top-bit of a window - */ - k = 64 - width; - MASK &= MASK << (top - k); - } - - /* - * After each position has been checked for all words of A, B is shifted up 1 place - */ - ShiftUp(c, aLen, bTotal, banks); - } - - int ciPos = ci.Length; - while (--ciPos > 1) - { - if ((ciPos & 1L) == 0L) - { - /* - * For even numbers, shift contents and add to the half-position - */ - AddShiftedUp(c, ci[(uint)ciPos >> 1], c, ci[ciPos], cLen, positions); - } - else - { - /* - * For odd numbers, 'distribute' contents to the result and the next-lowest position - */ - Distribute(c, ci[ciPos], ci[ciPos - 1], ci[1], cLen); - } - } - - /* - * Finally the raw answer is collected, reduce it against the reduction coefficients - */ - return ReduceResult(c, ci[1], cLen, m, ks); - } - - public LongArray ModReduce(int m, int[] ks) - { - long[] buf = Arrays.Clone(m_ints); - int rLen = ReduceInPlace(buf, 0, buf.Length, m, ks); - return new LongArray(buf, 0, rLen); - } - - public LongArray Multiply(LongArray other, int m, int[] ks) + internal LongArray Multiply(LongArray other, int m, int[] ks) { /* * Find out the degree of each argument and handle the zero cases */ int aDeg = Degree(); if (aDeg == 0) - { return this; - } + int bDeg = other.Degree(); if (bDeg == 0) - { return other; - } /* * Swap if necessary so that A is the smaller argument @@ -1384,17 +714,15 @@ public LongArray Multiply(LongArray other, int m, int[] ks) if (aLen == 1) { - long a0 = A.m_ints[0]; - if (a0 == 1L) - { + ulong a0 = A.m_data[0]; + if (a0 == 1UL) return B; - } /* * Fast path for small A, with performance dependent only on the number of set bits */ - long[] c0 = new long[cLen]; - MultiplyWord(a0, B.m_ints, bLen, c0, 0); + ulong[] c0 = new ulong[cLen]; + MultiplyWord(a0, B.m_data, bLen, c0, 0); /* * Reduce the raw answer against the reduction coefficients @@ -1416,13 +744,14 @@ public LongArray Multiply(LongArray other, int m, int[] ks) /* * Precompute table of all 4-bit products of B */ - long[] T0 = new long[bMax << 4]; + ulong[] T0 = new ulong[bMax << 4]; int tOff = bMax; ti[1] = tOff; - Array.Copy(B.m_ints, 0, T0, tOff, bLen); + Array.Copy(B.m_data, 0, T0, tOff, bLen); for (int i = 2; i < 16; ++i) { - ti[i] = (tOff += bMax); + tOff += bMax; + ti[i] = tOff; if ((i & 1) == 0) { ShiftUp(T0, (int)((uint)tOff >> 1), T0, tOff, bMax, 1); @@ -1436,14 +765,14 @@ public LongArray Multiply(LongArray other, int m, int[] ks) /* * Second table with all 4-bit products of B shifted 4 bits */ - long[] T1 = new long[T0.Length]; + ulong[] T1 = new ulong[T0.Length]; ShiftUp(T0, 0, T1, 0, T0.Length, 4); - // ShiftUp(T0, bMax, T1, bMax, tOff, 4); + //ShiftUp(T0, bMax, T1, bMax, tOff, 4); - long[] a = A.m_ints; - long[] c = new long[cLen << 3]; + ulong[] a = A.m_data; + ulong[] c = new ulong[cLen << 3]; - int MASK = 0xF; + uint MASK = 0xF; /* * Lopez-Dahab (Modified) algorithm @@ -1451,19 +780,16 @@ public LongArray Multiply(LongArray other, int m, int[] ks) for (int aPos = 0; aPos < aLen; ++aPos) { - long aVal = a[aPos]; + ulong aVal = a[aPos]; int cOff = aPos; for (; ; ) { - int u = (int)aVal & MASK; - aVal = (long)((ulong)aVal >> 4); - int v = (int)aVal & MASK; + uint u = (uint)aVal & MASK; aVal >>= 4; + uint v = (uint)aVal & MASK; aVal >>= 4; AddBoth(c, cOff, T0, ti[u], T1, ti[v], bMax); - aVal = (long)((ulong)aVal >> 4); - if (aVal == 0L) - { + if (aVal == 0UL) break; - } + cOff += cLen; } } @@ -1483,57 +809,28 @@ public LongArray Multiply(LongArray other, int m, int[] ks) return new LongArray(c, 0, cLen); } - public void Reduce(int m, int[] ks) + internal void Reduce(int m, int[] ks) { - long[] buf = m_ints; + ulong[] buf = m_data; int rLen = ReduceInPlace(buf, 0, buf.Length, m, ks); if (rLen < buf.Length) { - m_ints = new long[rLen]; - Array.Copy(buf, 0, m_ints, 0, rLen); + m_data = new ulong[rLen]; + Array.Copy(buf, 0, m_data, 0, rLen); } } - private static LongArray ReduceResult(long[] buf, int off, int len, int m, int[] ks) + private static LongArray ReduceResult(ulong[] buf, int off, int len, int m, int[] ks) { int rLen = ReduceInPlace(buf, off, len, m, ks); return new LongArray(buf, off, rLen); } - // private static void deInterleave(long[] x, int xOff, long[] z, int zOff, int count, int rounds) - // { - // for (int i = 0; i < count; ++i) - // { - // z[zOff + i] = deInterleave(x[zOff + i], rounds); - // } - // } - // - // private static long deInterleave(long x, int rounds) - // { - // while (--rounds >= 0) - // { - // x = deInterleave32(x & DEInterleave_MASK) | (deInterleave32((x >>> 1) & DEInterleave_MASK) << 32); - // } - // return x; - // } - // - // private static long deInterleave32(long x) - // { - // x = (x | (x >>> 1)) & 0x3333333333333333L; - // x = (x | (x >>> 2)) & 0x0F0F0F0F0F0F0F0FL; - // x = (x | (x >>> 4)) & 0x00FF00FF00FF00FFL; - // x = (x | (x >>> 8)) & 0x0000FFFF0000FFFFL; - // x = (x | (x >>> 16)) & 0x00000000FFFFFFFFL; - // return x; - // } - - private static int ReduceInPlace(long[] buf, int off, int len, int m, int[] ks) + private static int ReduceInPlace(ulong[] buf, int off, int len, int m, int[] ks) { int mLen = (m + 63) >> 6; if (len < mLen) - { return len; - } int numBits = System.Math.Min(len << 6, (m << 1) - 1); // TODO use actual degree? int excessBits = (len << 6) - numBits; @@ -1571,7 +868,7 @@ private static int ReduceInPlace(long[] buf, int off, int len, int m, int[] ks) return mLen; } - private static void ReduceBitWise(long[] buf, int off, int BitLength, int m, int[] ks) + private static void ReduceBitWise(ulong[] buf, int off, int BitLength, int m, int[] ks) { while (--BitLength >= m) { @@ -1582,7 +879,7 @@ private static void ReduceBitWise(long[] buf, int off, int BitLength, int m, int } } - private static void ReduceBit(long[] buf, int off, int bit, int m, int[] ks) + private static void ReduceBit(ulong[] buf, int off, int bit, int m, int[] ks) { FlipBit(buf, off, bit); int n = bit - m; @@ -1594,23 +891,23 @@ private static void ReduceBit(long[] buf, int off, int bit, int m, int[] ks) FlipBit(buf, off, n); } - private static void ReduceWordWise(long[] buf, int off, int len, int toBit, int m, int[] ks) + private static void ReduceWordWise(ulong[] buf, int off, int len, int toBit, int m, int[] ks) { int toPos = (int)((uint)toBit >> 6); while (--len > toPos) { - long word = buf[off + len]; + ulong word = buf[off + len]; if (word != 0) { - buf[off + len] = 0; + buf[off + len] = 0UL; ReduceWord(buf, off, (len << 6), word, m, ks); } } { int partial = toBit & 0x3F; - long word = (long)((ulong)buf[off + toPos] >> partial); + ulong word = buf[off + toPos] >> partial; if (word != 0) { buf[off + toPos] ^= word << partial; @@ -1619,7 +916,7 @@ private static void ReduceWordWise(long[] buf, int off, int len, int toBit, int } } - private static void ReduceWord(long[] buf, int off, int bit, long word, int m, int[] ks) + private static void ReduceWord(ulong[] buf, int off, int bit, ulong word, int m, int[] ks) { int offset = bit - m; int j = ks.Length; @@ -1630,7 +927,7 @@ private static void ReduceWord(long[] buf, int off, int bit, long word, int m, i FlipWord(buf, off, offset, word); } - private static void ReduceVectorWise(long[] buf, int off, int len, int words, int m, int[] ks) + private static void ReduceVectorWise(ulong[] buf, int off, int len, int words, int m, int[] ks) { /* * NOTE: It's important we go from highest coefficient to lowest, because for the highest @@ -1646,7 +943,7 @@ private static void ReduceVectorWise(long[] buf, int off, int len, int words, in FlipVector(buf, off, buf, off + words, len - words, baseBit); } - private static void FlipVector(long[] x, int xOff, long[] y, int yOff, int yLen, int bits) + private static void FlipVector(ulong[] x, int xOff, ulong[] y, int yOff, int yLen, int bits) { xOff += (int)((uint)bits >> 6); bits &= 0x3F; @@ -1657,259 +954,54 @@ private static void FlipVector(long[] x, int xOff, long[] y, int yOff, int yLen, } else { - long carry = AddShiftedDown(x, xOff + 1, y, yOff, yLen, 64 - bits); + ulong carry = AddShiftedDown(x, xOff + 1, y, yOff, yLen, 64 - bits); x[xOff] ^= carry; } } - public LongArray ModSquare(int m, int[] ks) + internal LongArray ModSquare(int m, int[] ks) { int len = GetUsedLength(); if (len == 0) - { return this; - } - int _2len = len << 1; - long[] r = new long[_2len]; - - int pos = 0; - while (pos < _2len) - { - long mi = m_ints[(uint)pos >> 1]; - r[pos++] = Interleave2_32to64((int)mi); - r[pos++] = Interleave2_32to64((int)((ulong)mi >> 32)); - } + ulong[] r = new ulong[len << 1]; + Interleave.Expand64To128(m_data, 0, len, r, 0); return new LongArray(r, 0, ReduceInPlace(r, 0, r.Length, m, ks)); } - public LongArray ModSquareN(int n, int m, int[] ks) + internal LongArray ModSquareN(int n, int m, int[] ks) { int len = GetUsedLength(); if (len == 0) - { return this; - } - + int mLen = (m + 63) >> 6; - long[] r = new long[mLen << 1]; - Array.Copy(m_ints, 0, r, 0, len); - + ulong[] r = new ulong[mLen << 1]; + Array.Copy(m_data, 0, r, 0, len); + while (--n >= 0) { - SquareInPlace(r, len, m, ks); + Interleave.Expand64To128(r, 0, len, r, 0); len = ReduceInPlace(r, 0, r.Length, m, ks); } - + return new LongArray(r, 0, len); } - public LongArray Square(int m, int[] ks) + internal LongArray Square(int m, int[] ks) { int len = GetUsedLength(); if (len == 0) - { return this; - } - - int _2len = len << 1; - long[] r = new long[_2len]; - int pos = 0; - while (pos < _2len) - { - long mi = m_ints[(uint)pos >> 1]; - r[pos++] = Interleave2_32to64((int)mi); - r[pos++] = Interleave2_32to64((int)((ulong)mi >> 32)); - } + ulong[] r = new ulong[len << 1]; + Interleave.Expand64To128(m_data, 0, len, r, 0); return new LongArray(r, 0, r.Length); } - private static void SquareInPlace(long[] x, int xLen, int m, int[] ks) - { - int pos = xLen << 1; - while (--xLen >= 0) - { - long xVal = x[xLen]; - x[--pos] = Interleave2_32to64((int)((ulong)xVal >> 32)); - x[--pos] = Interleave2_32to64((int)xVal); - } - } - - private static void Interleave(long[] x, int xOff, long[] z, int zOff, int count, int width) - { - switch (width) - { - case 3: - Interleave3(x, xOff, z, zOff, count); - break; - case 5: - Interleave5(x, xOff, z, zOff, count); - break; - case 7: - Interleave7(x, xOff, z, zOff, count); - break; - default: - Interleave2_n(x, xOff, z, zOff, count, BitLengths[width] - 1); - break; - } - } - - private static void Interleave3(long[] x, int xOff, long[] z, int zOff, int count) - { - for (int i = 0; i < count; ++i) - { - z[zOff + i] = Interleave3(x[xOff + i]); - } - } - - private static long Interleave3(long x) - { - long z = x & (1L << 63); - return z - | Interleave3_21to63((int)x & 0x1FFFFF) - | Interleave3_21to63((int)((ulong)x >> 21) & 0x1FFFFF) << 1 - | Interleave3_21to63((int)((ulong)x >> 42) & 0x1FFFFF) << 2; - - // int zPos = 0, wPos = 0, xPos = 0; - // for (;;) - // { - // z |= ((x >>> xPos) & 1L) << zPos; - // if (++zPos == 63) - // { - // String sz2 = Long.toBinaryString(z); - // return z; - // } - // if ((xPos += 21) >= 63) - // { - // xPos = ++wPos; - // } - // } - } - - private static long Interleave3_21to63(int x) - { - int r00 = INTERLEAVE3_TABLE[x & 0x7F]; - int r21 = INTERLEAVE3_TABLE[((uint)x >> 7) & 0x7F]; - int r42 = INTERLEAVE3_TABLE[(uint)x >> 14]; - return (r42 & 0xFFFFFFFFL) << 42 | (r21 & 0xFFFFFFFFL) << 21 | (r00 & 0xFFFFFFFFL); - } - - private static void Interleave5(long[] x, int xOff, long[] z, int zOff, int count) - { - for (int i = 0; i < count; ++i) - { - z[zOff + i] = Interleave5(x[xOff + i]); - } - } - - private static long Interleave5(long x) - { - return Interleave3_13to65((int)x & 0x1FFF) - | Interleave3_13to65((int)((ulong)x >> 13) & 0x1FFF) << 1 - | Interleave3_13to65((int)((ulong)x >> 26) & 0x1FFF) << 2 - | Interleave3_13to65((int)((ulong)x >> 39) & 0x1FFF) << 3 - | Interleave3_13to65((int)((ulong)x >> 52) & 0x1FFF) << 4; - - // long z = 0; - // int zPos = 0, wPos = 0, xPos = 0; - // for (;;) - // { - // z |= ((x >>> xPos) & 1L) << zPos; - // if (++zPos == 64) - // { - // return z; - // } - // if ((xPos += 13) >= 64) - // { - // xPos = ++wPos; - // } - // } - } - - private static long Interleave3_13to65(int x) - { - int r00 = INTERLEAVE5_TABLE[x & 0x7F]; - int r35 = INTERLEAVE5_TABLE[(uint)x >> 7]; - return (r35 & 0xFFFFFFFFL) << 35 | (r00 & 0xFFFFFFFFL); - } - - private static void Interleave7(long[] x, int xOff, long[] z, int zOff, int count) - { - for (int i = 0; i < count; ++i) - { - z[zOff + i] = Interleave7(x[xOff + i]); - } - } - - private static long Interleave7(long x) - { - long z = x & (1L << 63); - return z - | INTERLEAVE7_TABLE[(int)x & 0x1FF] - | INTERLEAVE7_TABLE[(int)((ulong)x >> 9) & 0x1FF] << 1 - | INTERLEAVE7_TABLE[(int)((ulong)x >> 18) & 0x1FF] << 2 - | INTERLEAVE7_TABLE[(int)((ulong)x >> 27) & 0x1FF] << 3 - | INTERLEAVE7_TABLE[(int)((ulong)x >> 36) & 0x1FF] << 4 - | INTERLEAVE7_TABLE[(int)((ulong)x >> 45) & 0x1FF] << 5 - | INTERLEAVE7_TABLE[(int)((ulong)x >> 54) & 0x1FF] << 6; - - // int zPos = 0, wPos = 0, xPos = 0; - // for (;;) - // { - // z |= ((x >>> xPos) & 1L) << zPos; - // if (++zPos == 63) - // { - // return z; - // } - // if ((xPos += 9) >= 63) - // { - // xPos = ++wPos; - // } - // } - } - - private static void Interleave2_n(long[] x, int xOff, long[] z, int zOff, int count, int rounds) - { - for (int i = 0; i < count; ++i) - { - z[zOff + i] = Interleave2_n(x[xOff + i], rounds); - } - } - - private static long Interleave2_n(long x, int rounds) - { - while (rounds > 1) - { - rounds -= 2; - x = Interleave4_16to64((int)x & 0xFFFF) - | Interleave4_16to64((int)((ulong)x >> 16) & 0xFFFF) << 1 - | Interleave4_16to64((int)((ulong)x >> 32) & 0xFFFF) << 2 - | Interleave4_16to64((int)((ulong)x >> 48) & 0xFFFF) << 3; - } - if (rounds > 0) - { - x = Interleave2_32to64((int)x) | Interleave2_32to64((int)((ulong)x >> 32)) << 1; - } - return x; - } - - private static long Interleave4_16to64(int x) - { - int r00 = INTERLEAVE4_TABLE[x & 0xFF]; - int r32 = INTERLEAVE4_TABLE[(uint)x >> 8]; - return (r32 & 0xFFFFFFFFL) << 32 | (r00 & 0xFFFFFFFFL); - } - - private static long Interleave2_32to64(int x) - { - int r00 = INTERLEAVE2_TABLE[x & 0xFF] | INTERLEAVE2_TABLE[((uint)x >> 8) & 0xFF] << 16; - int r32 = INTERLEAVE2_TABLE[((uint)x >> 16) & 0xFF] | INTERLEAVE2_TABLE[(uint)x >> 24] << 16; - return (r32 & 0xFFFFFFFFL) << 32 | (r00 & 0xFFFFFFFFL); - } - // private static LongArray ExpItohTsujii2(LongArray B, int n, int m, int[] ks) // { // LongArray t1 = B, t3 = new LongArray(new long[]{ 1L }); @@ -2020,7 +1112,7 @@ private static long Interleave2_32to64(int x) // return t4.ModMultiply(t1, m, ks); // } - public LongArray ModInverse(int m, int[] ks) + internal LongArray ModInverse(int m, int[] ks) { /* * Fermat's Little Theorem @@ -2061,26 +1153,23 @@ public LongArray ModInverse(int m, int[] ks) */ int uzDegree = Degree(); if (uzDegree == 0) - { throw new InvalidOperationException(); - } + if (uzDegree == 1) - { return this; - } // u(z) := a(z) - LongArray uz = (LongArray)Copy(); + LongArray uz = Copy(); int t = (m + 63) >> 6; // v(z) := f(z) LongArray vz = new LongArray(t); - ReduceBit(vz.m_ints, 0, m, m, ks); + ReduceBit(vz.m_data, 0, m, m, ks); // g1(z) := 1, g2(z) := 0 LongArray g1z = new LongArray(t); - g1z.m_ints[0] = 1L; + g1z.m_data[0] = 1UL; LongArray g2z = new LongArray(t); int[] uvDeg = new int[]{ uzDegree, m + 1 }; @@ -2110,9 +1199,7 @@ public LongArray ModInverse(int m, int[] ks) int duv2 = uv[b].DegreeFrom(duv1); if (duv2 == 0) - { return gg[1 - b]; - } { int dgg2 = ggDeg[1 - b]; @@ -2136,26 +1223,25 @@ public LongArray ModInverse(int m, int[] ks) public override bool Equals(object obj) { - return Equals(obj as LongArray); + if (obj is LongArray longArray) + return Equals(ref longArray); + + return false; } - public virtual bool Equals(LongArray other) + internal bool Equals(ref LongArray other) { - if (this == other) + if (AreAliased(ref this, ref other)) return true; - if (null == other) - return false; + int usedLen = GetUsedLength(); if (other.GetUsedLength() != usedLen) - { return false; - } + for (int i = 0; i < usedLen; i++) { - if (m_ints[i] != other.m_ints[i]) - { + if (m_data[i] != other.m_data[i]) return false; - } } return true; } @@ -2166,38 +1252,37 @@ public override int GetHashCode() int hash = 1; for (int i = 0; i < usedLen; i++) { - long mi = m_ints[i]; + ulong mi = m_data[i]; hash *= 31; hash ^= (int)mi; hash *= 31; - hash ^= (int)((ulong)mi >> 32); + hash ^= (int)(mi >> 32); } return hash; } public LongArray Copy() { - return new LongArray(Arrays.Clone(m_ints)); + return new LongArray(Arrays.Clone(m_data)); } public override string ToString() { int i = GetUsedLength(); if (i == 0) - { return "0"; - } - StringBuilder sb = new StringBuilder(Convert.ToString(m_ints[--i], 2)); + StringBuilder sb = new StringBuilder(i * 64); + sb.Append(Convert.ToString((long)m_data[--i], 2)); while (--i >= 0) { - string s = Convert.ToString(m_ints[i], 2); + string s = Convert.ToString((long)m_data[i], 2); // Add leading zeroes, except for highest significant word int len = s.Length; if (len < 64) { - sb.Append(ZEROES.Substring(len)); + sb.Append('0', 64 - len); } sb.Append(s); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/djb/Curve25519.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/djb/Curve25519.cs index b152c3f..0454b34 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/djb/Curve25519.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/djb/Curve25519.cs @@ -1,175 +1,3 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) -#pragma warning disable -using System; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders; - -namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Djb -{ - internal class Curve25519 - : AbstractFpCurve - { - public static readonly BigInteger q = Curve25519FieldElement.Q; - - private static readonly BigInteger C_a = new BigInteger(1, Hex.DecodeStrict("2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA984914A144")); - private static readonly BigInteger C_b = new BigInteger(1, Hex.DecodeStrict("7B425ED097B425ED097B425ED097B425ED097B425ED097B4260B5E9C7710C864")); - - private const int CURVE25519_DEFAULT_COORDS = COORD_JACOBIAN_MODIFIED; - private const int CURVE25519_FE_INTS = 8; - private static readonly ECFieldElement[] CURVE25519_AFFINE_ZS = new ECFieldElement[] { - new Curve25519FieldElement(BigInteger.One), new Curve25519FieldElement(C_a) }; - protected readonly Curve25519Point m_infinity; - - public Curve25519() - : base(q) - { - this.m_infinity = new Curve25519Point(this, null, null); - - this.m_a = FromBigInteger(C_a); - this.m_b = FromBigInteger(C_b); - this.m_order = new BigInteger(1, Hex.DecodeStrict("1000000000000000000000000000000014DEF9DEA2F79CD65812631A5CF5D3ED")); - this.m_cofactor = BigInteger.ValueOf(8); - this.m_coord = CURVE25519_DEFAULT_COORDS; - } - - protected override ECCurve CloneCurve() - { - return new Curve25519(); - } - - public override bool SupportsCoordinateSystem(int coord) - { - switch (coord) - { - case COORD_JACOBIAN_MODIFIED: - return true; - default: - return false; - } - } - - public virtual BigInteger Q - { - get { return q; } - } - - public override ECPoint Infinity - { - get { return m_infinity; } - } - - public override int FieldSize - { - get { return q.BitLength; } - } - - public override ECFieldElement FromBigInteger(BigInteger x) - { - return new Curve25519FieldElement(x); - } - - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) - { - return new Curve25519Point(this, x, y, withCompression); - } - - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - { - return new Curve25519Point(this, x, y, zs, withCompression); - } - - public override ECLookupTable CreateCacheSafeLookupTable(ECPoint[] points, int off, int len) - { - uint[] table = new uint[len * CURVE25519_FE_INTS * 2]; - { - int pos = 0; - for (int i = 0; i < len; ++i) - { - ECPoint p = points[off + i]; - Nat256.Copy(((Curve25519FieldElement)p.RawXCoord).x, 0, table, pos); pos += CURVE25519_FE_INTS; - Nat256.Copy(((Curve25519FieldElement)p.RawYCoord).x, 0, table, pos); pos += CURVE25519_FE_INTS; - } - } - - return new Curve25519LookupTable(this, table, len); - } - - public override ECFieldElement RandomFieldElement(SecureRandom r) - { - uint[] x = Nat256.Create(); - Curve25519Field.Random(r, x); - return new Curve25519FieldElement(x); - } - - public override ECFieldElement RandomFieldElementMult(SecureRandom r) - { - uint[] x = Nat256.Create(); - Curve25519Field.RandomMult(r, x); - return new Curve25519FieldElement(x); - } - - private class Curve25519LookupTable - : AbstractECLookupTable - { - private readonly Curve25519 m_outer; - private readonly uint[] m_table; - private readonly int m_size; - - internal Curve25519LookupTable(Curve25519 outer, uint[] table, int size) - { - this.m_outer = outer; - this.m_table = table; - this.m_size = size; - } - - public override int Size - { - get { return m_size; } - } - - public override ECPoint Lookup(int index) - { - uint[] x = Nat256.Create(), y = Nat256.Create(); - int pos = 0; - - for (int i = 0; i < m_size; ++i) - { - uint MASK = (uint)(((i ^ index) - 1) >> 31); - - for (int j = 0; j < CURVE25519_FE_INTS; ++j) - { - x[j] ^= m_table[pos + j] & MASK; - y[j] ^= m_table[pos + CURVE25519_FE_INTS + j] & MASK; - } - - pos += (CURVE25519_FE_INTS * 2); - } - - return CreatePoint(x, y); - } - - public override ECPoint LookupVar(int index) - { - uint[] x = Nat256.Create(), y = Nat256.Create(); - int pos = index * CURVE25519_FE_INTS * 2; - - for (int j = 0; j < CURVE25519_FE_INTS; ++j) - { - x[j] = m_table[pos + j]; - y[j] = m_table[pos + CURVE25519_FE_INTS + j]; - } - - return CreatePoint(x, y); - } - - private ECPoint CreatePoint(uint[] x, uint[] y) - { - return m_outer.CreateRawPoint(new Curve25519FieldElement(x), new Curve25519FieldElement(y), CURVE25519_AFFINE_ZS, false); - } - } - } -} -#pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/djb/Curve25519.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/djb/Curve25519.cs.meta index 8ba9b19..d979f50 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/djb/Curve25519.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/djb/Curve25519.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 62c48392045829f409ce2c44bab3f21f +guid: fd030ecdc7871c74ca192e7bf4c31075 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/djb/Curve25519Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/djb/Curve25519Point.cs index e23b917..0454b34 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/djb/Curve25519Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/djb/Curve25519Point.cs @@ -1,317 +1,3 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) -#pragma warning disable -using System; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; - -namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Djb -{ - internal class Curve25519Point - : AbstractFpPoint - { - /** - * Create a point which encodes with point compression. - * - * @param curve the curve to use - * @param x affine x co-ordinate - * @param y affine y co-ordinate - * - * @deprecated Use ECCurve.CreatePoint to construct points - */ - public Curve25519Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) - { - } - - /** - * Create a point that encodes with or without point compresion. - * - * @param curve the curve to use - * @param x affine x co-ordinate - * @param y affine y co-ordinate - * @param withCompression if true encode with point compression - * - * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} - */ - public Curve25519Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal Curve25519Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) - { - } - - protected override ECPoint Detach() - { - return new Curve25519Point(null, AffineXCoord, AffineYCoord); - } - - public override ECFieldElement GetZCoord(int index) - { - if (index == 1) - { - return GetJacobianModifiedW(); - } - - return base.GetZCoord(index); - } - - public override ECPoint Add(ECPoint b) - { - if (this.IsInfinity) - return b; - if (b.IsInfinity) - return this; - if (this == b) - return Twice(); - - ECCurve curve = this.Curve; - - Curve25519FieldElement X1 = (Curve25519FieldElement)this.RawXCoord, Y1 = (Curve25519FieldElement)this.RawYCoord, - Z1 = (Curve25519FieldElement)this.RawZCoords[0]; - Curve25519FieldElement X2 = (Curve25519FieldElement)b.RawXCoord, Y2 = (Curve25519FieldElement)b.RawYCoord, - Z2 = (Curve25519FieldElement)b.RawZCoords[0]; - - uint c; - uint[] tt1 = Nat256.CreateExt(); - uint[] t2 = Nat256.Create(); - uint[] t3 = Nat256.Create(); - uint[] t4 = Nat256.Create(); - - bool Z1IsOne = Z1.IsOne; - uint[] U2, S2; - if (Z1IsOne) - { - U2 = X2.x; - S2 = Y2.x; - } - else - { - S2 = t3; - Curve25519Field.Square(Z1.x, S2); - - U2 = t2; - Curve25519Field.Multiply(S2, X2.x, U2); - - Curve25519Field.Multiply(S2, Z1.x, S2); - Curve25519Field.Multiply(S2, Y2.x, S2); - } - - bool Z2IsOne = Z2.IsOne; - uint[] U1, S1; - if (Z2IsOne) - { - U1 = X1.x; - S1 = Y1.x; - } - else - { - S1 = t4; - Curve25519Field.Square(Z2.x, S1); - - U1 = tt1; - Curve25519Field.Multiply(S1, X1.x, U1); - - Curve25519Field.Multiply(S1, Z2.x, S1); - Curve25519Field.Multiply(S1, Y1.x, S1); - } - - uint[] H = Nat256.Create(); - Curve25519Field.Subtract(U1, U2, H); - - uint[] R = t2; - Curve25519Field.Subtract(S1, S2, R); - - // Check if b == this or b == -this - if (Nat256.IsZero(H)) - { - if (Nat256.IsZero(R)) - { - // this == b, i.e. this must be doubled - return this.Twice(); - } - - // this == -b, i.e. the result is the point at infinity - return curve.Infinity; - } - - uint[] HSquared = Nat256.Create(); - Curve25519Field.Square(H, HSquared); - - uint[] G = Nat256.Create(); - Curve25519Field.Multiply(HSquared, H, G); - - uint[] V = t3; - Curve25519Field.Multiply(HSquared, U1, V); - - Curve25519Field.Negate(G, G); - Nat256.Mul(S1, G, tt1); - - c = Nat256.AddBothTo(V, V, G); - Curve25519Field.Reduce27(c, G); - - Curve25519FieldElement X3 = new Curve25519FieldElement(t4); - Curve25519Field.Square(R, X3.x); - Curve25519Field.Subtract(X3.x, G, X3.x); - - Curve25519FieldElement Y3 = new Curve25519FieldElement(G); - Curve25519Field.Subtract(V, X3.x, Y3.x); - Curve25519Field.MultiplyAddToExt(Y3.x, R, tt1); - Curve25519Field.Reduce(tt1, Y3.x); - - Curve25519FieldElement Z3 = new Curve25519FieldElement(H); - if (!Z1IsOne) - { - Curve25519Field.Multiply(Z3.x, Z1.x, Z3.x); - } - if (!Z2IsOne) - { - Curve25519Field.Multiply(Z3.x, Z2.x, Z3.x); - } - - uint[] Z3Squared = (Z1IsOne && Z2IsOne) ? HSquared : null; - - // TODO If the result will only be used in a subsequent addition, we don't need W3 - Curve25519FieldElement W3 = CalculateJacobianModifiedW((Curve25519FieldElement)Z3, Z3Squared); - - ECFieldElement[] zs = new ECFieldElement[] { Z3, W3 }; - - return new Curve25519Point(curve, X3, Y3, zs, IsCompressed); - } - - public override ECPoint Twice() - { - if (this.IsInfinity) - return this; - - ECCurve curve = this.Curve; - - ECFieldElement Y1 = this.RawYCoord; - if (Y1.IsZero) - return curve.Infinity; - - return TwiceJacobianModified(true); - } - - public override ECPoint TwicePlus(ECPoint b) - { - if (this == b) - return ThreeTimes(); - if (this.IsInfinity) - return b; - if (b.IsInfinity) - return Twice(); - - ECFieldElement Y1 = this.RawYCoord; - if (Y1.IsZero) - return b; - - return TwiceJacobianModified(false).Add(b); - } - - public override ECPoint ThreeTimes() - { - if (this.IsInfinity || this.RawYCoord.IsZero) - return this; - - return TwiceJacobianModified(false).Add(this); - } - - public override ECPoint Negate() - { - if (IsInfinity) - return this; - - return new Curve25519Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed); - } - - protected virtual Curve25519FieldElement CalculateJacobianModifiedW(Curve25519FieldElement Z, uint[] ZSquared) - { - Curve25519FieldElement a4 = (Curve25519FieldElement)this.Curve.A; - if (Z.IsOne) - return a4; - - Curve25519FieldElement W = new Curve25519FieldElement(); - if (ZSquared == null) - { - ZSquared = W.x; - Curve25519Field.Square(Z.x, ZSquared); - } - Curve25519Field.Square(ZSquared, W.x); - Curve25519Field.Multiply(W.x, a4.x, W.x); - return W; - } - - protected virtual Curve25519FieldElement GetJacobianModifiedW() - { - ECFieldElement[] ZZ = this.RawZCoords; - Curve25519FieldElement W = (Curve25519FieldElement)ZZ[1]; - if (W == null) - { - // NOTE: Rarely, TwicePlus will result in the need for a lazy W1 calculation here - ZZ[1] = W = CalculateJacobianModifiedW((Curve25519FieldElement)ZZ[0], null); - } - return W; - } - - protected virtual Curve25519Point TwiceJacobianModified(bool calculateW) - { - Curve25519FieldElement X1 = (Curve25519FieldElement)this.RawXCoord, Y1 = (Curve25519FieldElement)this.RawYCoord, - Z1 = (Curve25519FieldElement)this.RawZCoords[0], W1 = GetJacobianModifiedW(); - - uint c; - - uint[] M = Nat256.Create(); - Curve25519Field.Square(X1.x, M); - c = Nat256.AddBothTo(M, M, M); - c += Nat256.AddTo(W1.x, M); - Curve25519Field.Reduce27(c, M); - - uint[] _2Y1 = Nat256.Create(); - Curve25519Field.Twice(Y1.x, _2Y1); - - uint[] _2Y1Squared = Nat256.Create(); - Curve25519Field.Multiply(_2Y1, Y1.x, _2Y1Squared); - - uint[] S = Nat256.Create(); - Curve25519Field.Multiply(_2Y1Squared, X1.x, S); - Curve25519Field.Twice(S, S); - - uint[] _8T = Nat256.Create(); - Curve25519Field.Square(_2Y1Squared, _8T); - Curve25519Field.Twice(_8T, _8T); - - Curve25519FieldElement X3 = new Curve25519FieldElement(_2Y1Squared); - Curve25519Field.Square(M, X3.x); - Curve25519Field.Subtract(X3.x, S, X3.x); - Curve25519Field.Subtract(X3.x, S, X3.x); - - Curve25519FieldElement Y3 = new Curve25519FieldElement(S); - Curve25519Field.Subtract(S, X3.x, Y3.x); - Curve25519Field.Multiply(Y3.x, M, Y3.x); - Curve25519Field.Subtract(Y3.x, _8T, Y3.x); - - Curve25519FieldElement Z3 = new Curve25519FieldElement(_2Y1); - if (!Nat256.IsOne(Z1.x)) - { - Curve25519Field.Multiply(Z3.x, Z1.x, Z3.x); - } - - Curve25519FieldElement W3 = null; - if (calculateW) - { - W3 = new Curve25519FieldElement(_8T); - Curve25519Field.Multiply(W3.x, W1.x, W3.x); - Curve25519Field.Twice(W3.x, W3.x); - } - - return new Curve25519Point(this.Curve, X3, Y3, new ECFieldElement[] { Z3, W3 }, IsCompressed); - } - } -} -#pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/djb/Curve25519Point.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/djb/Curve25519Point.cs.meta index 4afbbe4..96c3608 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/djb/Curve25519Point.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/djb/Curve25519Point.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 5876f88aced697149a82ac6ff3f8e27f +guid: 2bc45dc149a92fe4d934ea8137fa7174 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/gm/SM2P256V1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/gm/SM2P256V1Curve.cs index c4f7e45..df68ed2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/gm/SM2P256V1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/gm/SM2P256V1Curve.cs @@ -69,14 +69,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SM2P256V1FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SM2P256V1Point(this, x, y, withCompression); + return new SM2P256V1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SM2P256V1Point(this, x, y, zs, withCompression); + return new SM2P256V1Point(this, x, y, zs); } public override ECLookupTable CreateCacheSafeLookupTable(ECPoint[] points, int off, int len) @@ -165,7 +165,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(uint[] x, uint[] y) { - return m_outer.CreateRawPoint(new SM2P256V1FieldElement(x), new SM2P256V1FieldElement(y), SM2P256V1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SM2P256V1FieldElement(x), new SM2P256V1FieldElement(y), SM2P256V1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/gm/SM2P256V1FieldElement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/gm/SM2P256V1FieldElement.cs index d4ce6ba..2ddffff 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/gm/SM2P256V1FieldElement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/gm/SM2P256V1FieldElement.cs @@ -117,7 +117,6 @@ public override ECFieldElement Square() public override ECFieldElement Invert() { - //return new SM2P256V1FieldElement(ToBigInteger().ModInverse(Q)); uint[] z = Nat256.Create(); SM2P256V1Field.Inv(x, z); return new SM2P256V1FieldElement(z); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/gm/SM2P256V1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/gm/SM2P256V1Point.cs index c210481..a92e7b3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/gm/SM2P256V1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/gm/SM2P256V1Point.cs @@ -9,47 +9,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.GM internal class SM2P256V1Point : AbstractFpPoint { - /** - * Create a point which encodes with point compression. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * - * @deprecated Use ECCurve.createPoint to construct points - */ - public SM2P256V1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SM2P256V1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * Create a point that encodes with or without point compresion. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * @param withCompression - * if true encode with point compression - * - * @deprecated per-point compression property will be removed, refer - * {@link #getEncoded(bool)} - */ - public SM2P256V1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SM2P256V1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SM2P256V1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -174,7 +140,7 @@ public override ECPoint Add(ECPoint b) ECFieldElement[] zs = new ECFieldElement[]{ Z3 }; - return new SM2P256V1Point(curve, X3, Y3, zs, IsCompressed); + return new SM2P256V1Point(curve, X3, Y3, zs); } public override ECPoint Twice() @@ -242,7 +208,7 @@ public override ECPoint Twice() SM2P256V1Field.Multiply(Z3.x, Z1.x, Z3.x); } - return new SM2P256V1Point(curve, X3, Y3, new ECFieldElement[]{ Z3 }, IsCompressed); + return new SM2P256V1Point(curve, X3, Y3, new ECFieldElement[]{ Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -275,7 +241,7 @@ public override ECPoint Negate() if (IsInfinity) return this; - return new SM2P256V1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed); + return new SM2P256V1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP128R1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP128R1Curve.cs index 98f3a12..3da9217 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP128R1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP128R1Curve.cs @@ -70,14 +70,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecP128R1FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecP128R1Point(this, x, y, withCompression); + return new SecP128R1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecP128R1Point(this, x, y, zs, withCompression); + return new SecP128R1Point(this, x, y, zs); } public override ECLookupTable CreateCacheSafeLookupTable(ECPoint[] points, int off, int len) @@ -166,7 +166,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(uint[] x, uint[] y) { - return m_outer.CreateRawPoint(new SecP128R1FieldElement(x), new SecP128R1FieldElement(y), SECP128R1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecP128R1FieldElement(x), new SecP128R1FieldElement(y), SECP128R1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP128R1FieldElement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP128R1FieldElement.cs index 6aee189..dfb0e15 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP128R1FieldElement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP128R1FieldElement.cs @@ -117,7 +117,6 @@ public override ECFieldElement Square() public override ECFieldElement Invert() { - // return new SecP128R1FieldElement(toBigInteger().modInverse(Q)); uint[] z = Nat128.Create(); SecP128R1Field.Inv(x, z); return new SecP128R1FieldElement(z); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP128R1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP128R1Point.cs index 932c1e7..7efdae4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP128R1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP128R1Point.cs @@ -9,47 +9,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecP128R1Point : AbstractFpPoint { - /** - * Create a point which encodes with point compression. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecP128R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecP128R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * Create a point that encodes with or without point compresion. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * @param withCompression - * if true encode with point compression - * - * @deprecated per-point compression property will be removed, refer - * {@link #getEncoded(boolean)} - */ - public SecP128R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecP128R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecP128R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -174,7 +140,7 @@ public override ECPoint Add(ECPoint b) ECFieldElement[] zs = new ECFieldElement[]{ Z3 }; - return new SecP128R1Point(curve, X3, Y3, zs, IsCompressed); + return new SecP128R1Point(curve, X3, Y3, zs); } public override ECPoint Twice() @@ -242,7 +208,7 @@ public override ECPoint Twice() SecP128R1Field.Multiply(Z3.x, Z1.x, Z3.x); } - return new SecP128R1Point(curve, X3, Y3, new ECFieldElement[]{ Z3 }, IsCompressed); + return new SecP128R1Point(curve, X3, Y3, new ECFieldElement[]{ Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -275,7 +241,7 @@ public override ECPoint Negate() if (IsInfinity) return this; - return new SecP128R1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed); + return new SecP128R1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160K1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160K1Curve.cs index bba6296..81d947c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160K1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160K1Curve.cs @@ -67,14 +67,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecP160R2FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecP160K1Point(this, x, y, withCompression); + return new SecP160K1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecP160K1Point(this, x, y, zs, withCompression); + return new SecP160K1Point(this, x, y, zs); } public override ECLookupTable CreateCacheSafeLookupTable(ECPoint[] points, int off, int len) @@ -163,7 +163,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(uint[] x, uint[] y) { - return m_outer.CreateRawPoint(new SecP160R2FieldElement(x), new SecP160R2FieldElement(y), SECP160K1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecP160R2FieldElement(x), new SecP160R2FieldElement(y), SECP160K1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160K1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160K1Point.cs index 7fe95c7..a3162fa 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160K1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160K1Point.cs @@ -9,48 +9,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecP160K1Point : AbstractFpPoint { - /** - * Create a point which encodes with point compression. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * - * @deprecated Use ECCurve.CreatePoint to construct points - */ - public SecP160K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecP160K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * Create a point that encodes with or without point compresion. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * @param withCompression - * if true encode with point compression - * - * @deprecated per-point compression property will be removed, refer - * {@link #getEncoded(bool)} - */ - public SecP160K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecP160K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, - bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecP160K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -176,7 +141,7 @@ public override ECPoint Add(ECPoint b) ECFieldElement[] zs = new ECFieldElement[] { Z3 }; - return new SecP160K1Point(curve, X3, Y3, zs, IsCompressed); + return new SecP160K1Point(curve, X3, Y3, zs); } // B.3 pg 62 @@ -232,7 +197,7 @@ public override ECPoint Twice() SecP160R2Field.Multiply(Z3.x, Z1.x, Z3.x); } - return new SecP160K1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecP160K1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -265,7 +230,7 @@ public override ECPoint Negate() if (IsInfinity) return this; - return new SecP160K1Point(Curve, this.RawXCoord, this.RawYCoord.Negate(), this.RawZCoords, IsCompressed); + return new SecP160K1Point(Curve, this.RawXCoord, this.RawYCoord.Negate(), this.RawZCoords); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R1Curve.cs index 35b4623..811e105 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R1Curve.cs @@ -70,14 +70,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecP160R1FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecP160R1Point(this, x, y, withCompression); + return new SecP160R1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecP160R1Point(this, x, y, zs, withCompression); + return new SecP160R1Point(this, x, y, zs); } public override ECLookupTable CreateCacheSafeLookupTable(ECPoint[] points, int off, int len) @@ -166,7 +166,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(uint[] x, uint[] y) { - return m_outer.CreateRawPoint(new SecP160R1FieldElement(x), new SecP160R1FieldElement(y), SECP160R1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecP160R1FieldElement(x), new SecP160R1FieldElement(y), SECP160R1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R1FieldElement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R1FieldElement.cs index 25da76f..c70dfe9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R1FieldElement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R1FieldElement.cs @@ -117,7 +117,6 @@ public override ECFieldElement Square() public override ECFieldElement Invert() { - // return new SecP160R1FieldElement(ToBigInteger().modInverse(Q)); uint[] z = Nat160.Create(); SecP160R1Field.Inv(x, z); return new SecP160R1FieldElement(z); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R1Point.cs index bfd7a59..0835878 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R1Point.cs @@ -9,47 +9,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecP160R1Point : AbstractFpPoint { - /** - * Create a point which encodes with point compression. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * - * @deprecated Use ECCurve.CreatePoint to construct points - */ - public SecP160R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecP160R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * Create a point that encodes with or without point compresion. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * @param withCompression - * if true encode with point compression - * - * @deprecated per-point compression property will be removed, refer - * {@link #getEncoded(bool)} - */ - public SecP160R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecP160R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecP160R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -174,7 +140,7 @@ public override ECPoint Add(ECPoint b) ECFieldElement[] zs = new ECFieldElement[]{ Z3 }; - return new SecP160R1Point(curve, X3, Y3, zs, IsCompressed); + return new SecP160R1Point(curve, X3, Y3, zs); } public override ECPoint Twice() @@ -242,7 +208,7 @@ public override ECPoint Twice() SecP160R1Field.Multiply(Z3.x, Z1.x, Z3.x); } - return new SecP160R1Point(curve, X3, Y3, new ECFieldElement[]{ Z3 }, IsCompressed); + return new SecP160R1Point(curve, X3, Y3, new ECFieldElement[]{ Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -275,7 +241,7 @@ public override ECPoint Negate() if (IsInfinity) return this; - return new SecP160R1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed); + return new SecP160R1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R2Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R2Curve.cs index 6ccb17f..25f74e7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R2Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R2Curve.cs @@ -70,14 +70,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecP160R2FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecP160R2Point(this, x, y, withCompression); + return new SecP160R2Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecP160R2Point(this, x, y, zs, withCompression); + return new SecP160R2Point(this, x, y, zs); } public override ECLookupTable CreateCacheSafeLookupTable(ECPoint[] points, int off, int len) @@ -166,7 +166,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(uint[] x, uint[] y) { - return m_outer.CreateRawPoint(new SecP160R2FieldElement(x), new SecP160R2FieldElement(y), SECP160R2_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecP160R2FieldElement(x), new SecP160R2FieldElement(y), SECP160R2_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R2FieldElement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R2FieldElement.cs index ae2e6f1..2f3df17 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R2FieldElement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R2FieldElement.cs @@ -117,7 +117,6 @@ public override ECFieldElement Square() public override ECFieldElement Invert() { - // return new SecP160R2FieldElement(ToBigInteger().modInverse(Q)); uint[] z = Nat160.Create(); SecP160R2Field.Inv(x, z); return new SecP160R2FieldElement(z); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R2Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R2Point.cs index 41f129c..4a24328 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R2Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP160R2Point.cs @@ -9,47 +9,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecP160R2Point : AbstractFpPoint { - /** - * Create a point which encodes with point compression. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * - * @deprecated Use ECCurve.CreatePoint to construct points - */ - public SecP160R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecP160R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * Create a point that encodes with or without point compresion. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * @param withCompression - * if true encode with point compression - * - * @deprecated per-point compression property will be removed, refer - * {@link #getEncoded(bool)} - */ - public SecP160R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecP160R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecP160R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -174,7 +140,7 @@ public override ECPoint Add(ECPoint b) ECFieldElement[] zs = new ECFieldElement[]{ Z3 }; - return new SecP160R2Point(curve, X3, Y3, zs, IsCompressed); + return new SecP160R2Point(curve, X3, Y3, zs); } public override ECPoint Twice() @@ -242,7 +208,7 @@ public override ECPoint Twice() SecP160R2Field.Multiply(Z3.x, Z1.x, Z3.x); } - return new SecP160R2Point(curve, X3, Y3, new ECFieldElement[]{ Z3 }, IsCompressed); + return new SecP160R2Point(curve, X3, Y3, new ECFieldElement[]{ Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -275,7 +241,7 @@ public override ECPoint Negate() if (IsInfinity) return this; - return new SecP160R2Point(Curve, this.RawXCoord, this.RawYCoord.Negate(), this.RawZCoords, IsCompressed); + return new SecP160R2Point(Curve, this.RawXCoord, this.RawYCoord.Negate(), this.RawZCoords); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192K1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192K1Curve.cs index 835d29b..56afb38 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192K1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192K1Curve.cs @@ -67,14 +67,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecP192K1FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecP192K1Point(this, x, y, withCompression); + return new SecP192K1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecP192K1Point(this, x, y, zs, withCompression); + return new SecP192K1Point(this, x, y, zs); } public override ECLookupTable CreateCacheSafeLookupTable(ECPoint[] points, int off, int len) @@ -163,7 +163,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(uint[] x, uint[] y) { - return m_outer.CreateRawPoint(new SecP192K1FieldElement(x), new SecP192K1FieldElement(y), SECP192K1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecP192K1FieldElement(x), new SecP192K1FieldElement(y), SECP192K1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192K1FieldElement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192K1FieldElement.cs index c9b126c..a7c7662 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192K1FieldElement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192K1FieldElement.cs @@ -118,7 +118,6 @@ public override ECFieldElement Square() public override ECFieldElement Invert() { - //return new SecP192K1FieldElement(ToBigInteger().ModInverse(Q)); uint[] z = Nat192.Create(); SecP192K1Field.Inv(x, z); return new SecP192K1FieldElement(z); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192K1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192K1Point.cs index 39a7f7d..cf16701 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192K1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192K1Point.cs @@ -9,48 +9,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecP192K1Point : AbstractFpPoint { - /** - * Create a point which encodes with point compression. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecP192K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecP192K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * Create a point that encodes with or without point compresion. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * @param withCompression - * if true encode with point compression - * - * @deprecated per-point compression property will be removed, refer - * {@link #getEncoded(bool)} - */ - public SecP192K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecP192K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, - bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecP192K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -175,7 +140,7 @@ public override ECPoint Add(ECPoint b) ECFieldElement[] zs = new ECFieldElement[] { Z3 }; - return new SecP192K1Point(curve, X3, Y3, zs, IsCompressed); + return new SecP192K1Point(curve, X3, Y3, zs); } public override ECPoint Twice() @@ -230,7 +195,7 @@ public override ECPoint Twice() SecP192K1Field.Multiply(Z3.x, Z1.x, Z3.x); } - return new SecP192K1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecP192K1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -263,7 +228,7 @@ public override ECPoint Negate() if (IsInfinity) return this; - return new SecP192K1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed); + return new SecP192K1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192R1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192R1Curve.cs index bf61776..bca595f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192R1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192R1Curve.cs @@ -70,14 +70,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecP192R1FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecP192R1Point(this, x, y, withCompression); + return new SecP192R1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecP192R1Point(this, x, y, zs, withCompression); + return new SecP192R1Point(this, x, y, zs); } public override ECLookupTable CreateCacheSafeLookupTable(ECPoint[] points, int off, int len) @@ -166,7 +166,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(uint[] x, uint[] y) { - return m_outer.CreateRawPoint(new SecP192R1FieldElement(x), new SecP192R1FieldElement(y), SECP192R1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecP192R1FieldElement(x), new SecP192R1FieldElement(y), SECP192R1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192R1FieldElement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192R1FieldElement.cs index 6a2ff10..6083ae6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192R1FieldElement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192R1FieldElement.cs @@ -117,7 +117,6 @@ public override ECFieldElement Square() public override ECFieldElement Invert() { - //return new SecP192R1FieldElement(ToBigInteger().ModInverse(Q)); uint[] z = Nat192.Create(); SecP192R1Field.Inv(x, z); return new SecP192R1FieldElement(z); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192R1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192R1Point.cs index de2ebaf..3ccbc23 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192R1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP192R1Point.cs @@ -9,47 +9,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecP192R1Point : AbstractFpPoint { - /** - * Create a point which encodes with point compression. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecP192R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecP192R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * Create a point that encodes with or without point compresion. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * @param withCompression - * if true encode with point compression - * - * @deprecated per-point compression property will be removed, refer - * {@link #getEncoded(bool)} - */ - public SecP192R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecP192R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecP192R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -174,7 +140,7 @@ public override ECPoint Add(ECPoint b) ECFieldElement[] zs = new ECFieldElement[] { Z3 }; - return new SecP192R1Point(curve, X3, Y3, zs, IsCompressed); + return new SecP192R1Point(curve, X3, Y3, zs); } public override ECPoint Twice() @@ -242,7 +208,7 @@ public override ECPoint Twice() SecP192R1Field.Multiply(Z3.x, Z1.x, Z3.x); } - return new SecP192R1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecP192R1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -275,7 +241,7 @@ public override ECPoint Negate() if (IsInfinity) return this; - return new SecP192R1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed); + return new SecP192R1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224K1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224K1Curve.cs index 31de2a7..988ee97 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224K1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224K1Curve.cs @@ -67,14 +67,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecP224K1FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecP224K1Point(this, x, y, withCompression); + return new SecP224K1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecP224K1Point(this, x, y, zs, withCompression); + return new SecP224K1Point(this, x, y, zs); } public override ECLookupTable CreateCacheSafeLookupTable(ECPoint[] points, int off, int len) @@ -163,7 +163,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(uint[] x, uint[] y) { - return m_outer.CreateRawPoint(new SecP224K1FieldElement(x), new SecP224K1FieldElement(y), SECP224K1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecP224K1FieldElement(x), new SecP224K1FieldElement(y), SECP224K1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224K1FieldElement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224K1FieldElement.cs index dcefe02..377e5b3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224K1FieldElement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224K1FieldElement.cs @@ -122,7 +122,6 @@ public override ECFieldElement Square() public override ECFieldElement Invert() { - //return new SecP224K1FieldElement(ToBigInteger().ModInverse(Q)); uint[] z = Nat224.Create(); SecP224K1Field.Inv(x, z); return new SecP224K1FieldElement(z); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224K1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224K1Point.cs index c4d6448..cc189cf 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224K1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224K1Point.cs @@ -9,48 +9,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecP224K1Point : AbstractFpPoint { - /** - * Create a point which encodes with point compression. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecP224K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecP224K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * Create a point that encodes with or without point compresion. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * @param withCompression - * if true encode with point compression - * - * @deprecated per-point compression property will be removed, refer - * {@link #getEncoded(bool)} - */ - public SecP224K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecP224K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, - bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecP224K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -175,7 +140,7 @@ public override ECPoint Add(ECPoint b) ECFieldElement[] zs = new ECFieldElement[] { Z3 }; - return new SecP224K1Point(curve, X3, Y3, zs, IsCompressed); + return new SecP224K1Point(curve, X3, Y3, zs); } public override ECPoint Twice() @@ -230,7 +195,7 @@ public override ECPoint Twice() SecP224K1Field.Multiply(Z3.x, Z1.x, Z3.x); } - return new SecP224K1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecP224K1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -263,7 +228,7 @@ public override ECPoint Negate() if (IsInfinity) return this; - return new SecP224K1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed); + return new SecP224K1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224R1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224R1Curve.cs index 71e6337..2b00bcf 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224R1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224R1Curve.cs @@ -70,14 +70,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecP224R1FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecP224R1Point(this, x, y, withCompression); + return new SecP224R1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecP224R1Point(this, x, y, zs, withCompression); + return new SecP224R1Point(this, x, y, zs); } public override ECLookupTable CreateCacheSafeLookupTable(ECPoint[] points, int off, int len) @@ -166,7 +166,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(uint[] x, uint[] y) { - return m_outer.CreateRawPoint(new SecP224R1FieldElement(x), new SecP224R1FieldElement(y), SECP224R1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecP224R1FieldElement(x), new SecP224R1FieldElement(y), SECP224R1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224R1FieldElement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224R1FieldElement.cs index 0c0d0cd..2c5bf43 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224R1FieldElement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224R1FieldElement.cs @@ -3,6 +3,7 @@ using System; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders; @@ -117,7 +118,6 @@ public override ECFieldElement Square() public override ECFieldElement Invert() { - //return new SecP224R1FieldElement(ToBigInteger().ModInverse(Q)); uint[] z = Nat224.Create(); SecP224R1Field.Inv(x, z); return new SecP224R1FieldElement(z); @@ -136,7 +136,7 @@ public override ECFieldElement Sqrt() uint[] nc = Nat224.Create(); SecP224R1Field.Negate(c, nc); - uint[] r = Mod.Random(SecP224R1Field.P); + uint[] r = Mod.Random(SecureRandom.ArbitraryRandom, SecP224R1Field.P); uint[] t = Nat224.Create(); if (!IsSquare(c)) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224R1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224R1Point.cs index c3f5250..caff5cd 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224R1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP224R1Point.cs @@ -9,47 +9,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecP224R1Point : AbstractFpPoint { - /** - * Create a point which encodes with point compression. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecP224R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecP224R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * Create a point that encodes with or without point compresion. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * @param withCompression - * if true encode with point compression - * - * @deprecated per-point compression property will be removed, refer - * {@link #getEncoded(bool)} - */ - public SecP224R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecP224R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecP224R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -174,7 +140,7 @@ public override ECPoint Add(ECPoint b) ECFieldElement[] zs = new ECFieldElement[] { Z3 }; - return new SecP224R1Point(curve, X3, Y3, zs, IsCompressed); + return new SecP224R1Point(curve, X3, Y3, zs); } public override ECPoint Twice() @@ -242,7 +208,7 @@ public override ECPoint Twice() SecP224R1Field.Multiply(Z3.x, Z1.x, Z3.x); } - return new SecP224R1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecP224R1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -275,7 +241,7 @@ public override ECPoint Negate() if (IsInfinity) return this; - return new SecP224R1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed); + return new SecP224R1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256K1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256K1Curve.cs index c6fd3e6..7d5d7e4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256K1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256K1Curve.cs @@ -67,14 +67,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecP256K1FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecP256K1Point(this, x, y, withCompression); + return new SecP256K1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecP256K1Point(this, x, y, zs, withCompression); + return new SecP256K1Point(this, x, y, zs); } public override ECLookupTable CreateCacheSafeLookupTable(ECPoint[] points, int off, int len) @@ -163,7 +163,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(uint[] x, uint[] y) { - return m_outer.CreateRawPoint(new SecP256K1FieldElement(x), new SecP256K1FieldElement(y), SECP256K1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecP256K1FieldElement(x), new SecP256K1FieldElement(y), SECP256K1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256K1Field.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256K1Field.cs index 2363402..8202db8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256K1Field.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256K1Field.cs @@ -99,6 +99,12 @@ public static void Multiply(uint[] x, uint[] y, uint[] z) Reduce(tt, z); } + public static void Multiply(uint[] x, uint[] y, uint[] z, uint[] tt) + { + Nat256.Mul(x, y, tt); + Reduce(tt, z); + } + public static void MultiplyAddToExt(uint[] x, uint[] y, uint[] zz) { uint c = Nat256.MulAddTo(x, y, zz); @@ -172,6 +178,12 @@ public static void Square(uint[] x, uint[] z) Reduce(tt, z); } + public static void Square(uint[] x, uint[] z, uint[] tt) + { + Nat256.Square(x, tt); + Reduce(tt, z); + } + public static void SquareN(uint[] x, int n, uint[] z) { Debug.Assert(n > 0); @@ -187,6 +199,20 @@ public static void SquareN(uint[] x, int n, uint[] z) } } + public static void SquareN(uint[] x, int n, uint[] z, uint[] tt) + { + Debug.Assert(n > 0); + + Nat256.Square(x, tt); + Reduce(tt, z); + + while (--n > 0) + { + Nat256.Square(z, tt); + Reduce(tt, z); + } + } + public static void Subtract(uint[] x, uint[] y, uint[] z) { int c = Nat256.Sub(x, y, z); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256K1FieldElement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256K1FieldElement.cs index e0eded1..89cac69 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256K1FieldElement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256K1FieldElement.cs @@ -117,7 +117,6 @@ public override ECFieldElement Square() public override ECFieldElement Invert() { - //return new SecP256K1FieldElement(ToBigInteger().ModInverse(Q)); uint[] z = Nat256.Create(); SecP256K1Field.Inv(x, z); return new SecP256K1FieldElement(z); @@ -143,49 +142,51 @@ public override ECFieldElement Sqrt() if (Nat256.IsZero(x1) || Nat256.IsOne(x1)) return this; + uint[] tt0 = Nat256.CreateExt(); + uint[] x2 = Nat256.Create(); - SecP256K1Field.Square(x1, x2); - SecP256K1Field.Multiply(x2, x1, x2); + SecP256K1Field.Square(x1, x2, tt0); + SecP256K1Field.Multiply(x2, x1, x2, tt0); uint[] x3 = Nat256.Create(); - SecP256K1Field.Square(x2, x3); - SecP256K1Field.Multiply(x3, x1, x3); + SecP256K1Field.Square(x2, x3, tt0); + SecP256K1Field.Multiply(x3, x1, x3, tt0); uint[] x6 = Nat256.Create(); - SecP256K1Field.SquareN(x3, 3, x6); - SecP256K1Field.Multiply(x6, x3, x6); + SecP256K1Field.SquareN(x3, 3, x6, tt0); + SecP256K1Field.Multiply(x6, x3, x6, tt0); uint[] x9 = x6; - SecP256K1Field.SquareN(x6, 3, x9); - SecP256K1Field.Multiply(x9, x3, x9); + SecP256K1Field.SquareN(x6, 3, x9, tt0); + SecP256K1Field.Multiply(x9, x3, x9, tt0); uint[] x11 = x9; - SecP256K1Field.SquareN(x9, 2, x11); - SecP256K1Field.Multiply(x11, x2, x11); + SecP256K1Field.SquareN(x9, 2, x11, tt0); + SecP256K1Field.Multiply(x11, x2, x11, tt0); uint[] x22 = Nat256.Create(); - SecP256K1Field.SquareN(x11, 11, x22); - SecP256K1Field.Multiply(x22, x11, x22); + SecP256K1Field.SquareN(x11, 11, x22, tt0); + SecP256K1Field.Multiply(x22, x11, x22, tt0); uint[] x44 = x11; - SecP256K1Field.SquareN(x22, 22, x44); - SecP256K1Field.Multiply(x44, x22, x44); + SecP256K1Field.SquareN(x22, 22, x44, tt0); + SecP256K1Field.Multiply(x44, x22, x44, tt0); uint[] x88 = Nat256.Create(); - SecP256K1Field.SquareN(x44, 44, x88); - SecP256K1Field.Multiply(x88, x44, x88); + SecP256K1Field.SquareN(x44, 44, x88, tt0); + SecP256K1Field.Multiply(x88, x44, x88, tt0); uint[] x176 = Nat256.Create(); - SecP256K1Field.SquareN(x88, 88, x176); - SecP256K1Field.Multiply(x176, x88, x176); + SecP256K1Field.SquareN(x88, 88, x176, tt0); + SecP256K1Field.Multiply(x176, x88, x176, tt0); uint[] x220 = x88; - SecP256K1Field.SquareN(x176, 44, x220); - SecP256K1Field.Multiply(x220, x44, x220); + SecP256K1Field.SquareN(x176, 44, x220, tt0); + SecP256K1Field.Multiply(x220, x44, x220, tt0); uint[] x223 = x44; - SecP256K1Field.SquareN(x220, 3, x223); - SecP256K1Field.Multiply(x223, x3, x223); + SecP256K1Field.SquareN(x220, 3, x223, tt0); + SecP256K1Field.Multiply(x223, x3, x223, tt0); uint[] t1 = x223; - SecP256K1Field.SquareN(t1, 23, t1); - SecP256K1Field.Multiply(t1, x22, t1); - SecP256K1Field.SquareN(t1, 6, t1); - SecP256K1Field.Multiply(t1, x2, t1); - SecP256K1Field.SquareN(t1, 2, t1); + SecP256K1Field.SquareN(t1, 23, t1, tt0); + SecP256K1Field.Multiply(t1, x22, t1, tt0); + SecP256K1Field.SquareN(t1, 6, t1, tt0); + SecP256K1Field.Multiply(t1, x2, t1, tt0); + SecP256K1Field.SquareN(t1, 2, t1, tt0); uint[] t2 = x2; - SecP256K1Field.Square(t1, t2); + SecP256K1Field.Square(t1, t2, tt0); return Nat256.Eq(x1, t2) ? new SecP256K1FieldElement(t1) : null; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256K1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256K1Point.cs index 1244399..f2aa6d2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256K1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256K1Point.cs @@ -9,48 +9,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecP256K1Point : AbstractFpPoint { - /** - * Create a point which encodes with point compression. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecP256K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecP256K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * Create a point that encodes with or without point compresion. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * @param withCompression - * if true encode with point compression - * - * @deprecated per-point compression property will be removed, refer - * {@link #getEncoded(bool)} - */ - public SecP256K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecP256K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, - bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecP256K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -77,6 +42,7 @@ public override ECPoint Add(ECPoint b) SecP256K1FieldElement Z2 = (SecP256K1FieldElement)b.RawZCoords[0]; uint c; + uint[] tt0 = Nat256.CreateExt(); uint[] tt1 = Nat256.CreateExt(); uint[] t2 = Nat256.Create(); uint[] t3 = Nat256.Create(); @@ -92,13 +58,13 @@ public override ECPoint Add(ECPoint b) else { S2 = t3; - SecP256K1Field.Square(Z1.x, S2); + SecP256K1Field.Square(Z1.x, S2, tt0); U2 = t2; - SecP256K1Field.Multiply(S2, X2.x, U2); + SecP256K1Field.Multiply(S2, X2.x, U2, tt0); - SecP256K1Field.Multiply(S2, Z1.x, S2); - SecP256K1Field.Multiply(S2, Y2.x, S2); + SecP256K1Field.Multiply(S2, Z1.x, S2, tt0); + SecP256K1Field.Multiply(S2, Y2.x, S2, tt0); } bool Z2IsOne = Z2.IsOne; @@ -111,13 +77,13 @@ public override ECPoint Add(ECPoint b) else { S1 = t4; - SecP256K1Field.Square(Z2.x, S1); + SecP256K1Field.Square(Z2.x, S1, tt0); U1 = tt1; - SecP256K1Field.Multiply(S1, X1.x, U1); + SecP256K1Field.Multiply(S1, X1.x, U1, tt0); - SecP256K1Field.Multiply(S1, Z2.x, S1); - SecP256K1Field.Multiply(S1, Y1.x, S1); + SecP256K1Field.Multiply(S1, Z2.x, S1, tt0); + SecP256K1Field.Multiply(S1, Y1.x, S1, tt0); } uint[] H = Nat256.Create(); @@ -140,13 +106,13 @@ public override ECPoint Add(ECPoint b) } uint[] HSquared = t3; - SecP256K1Field.Square(H, HSquared); + SecP256K1Field.Square(H, HSquared, tt0); uint[] G = Nat256.Create(); - SecP256K1Field.Multiply(HSquared, H, G); + SecP256K1Field.Multiply(HSquared, H, G, tt0); uint[] V = t3; - SecP256K1Field.Multiply(HSquared, U1, V); + SecP256K1Field.Multiply(HSquared, U1, V, tt0); SecP256K1Field.Negate(G, G); Nat256.Mul(S1, G, tt1); @@ -155,7 +121,7 @@ public override ECPoint Add(ECPoint b) SecP256K1Field.Reduce32(c, G); SecP256K1FieldElement X3 = new SecP256K1FieldElement(t4); - SecP256K1Field.Square(R, X3.x); + SecP256K1Field.Square(R, X3.x, tt0); SecP256K1Field.Subtract(X3.x, G, X3.x); SecP256K1FieldElement Y3 = new SecP256K1FieldElement(G); @@ -166,16 +132,16 @@ public override ECPoint Add(ECPoint b) SecP256K1FieldElement Z3 = new SecP256K1FieldElement(H); if (!Z1IsOne) { - SecP256K1Field.Multiply(Z3.x, Z1.x, Z3.x); + SecP256K1Field.Multiply(Z3.x, Z1.x, Z3.x, tt0); } if (!Z2IsOne) { - SecP256K1Field.Multiply(Z3.x, Z2.x, Z3.x); + SecP256K1Field.Multiply(Z3.x, Z2.x, Z3.x, tt0); } ECFieldElement[] zs = new ECFieldElement[] { Z3 }; - return new SecP256K1Point(curve, X3, Y3, zs, IsCompressed); + return new SecP256K1Point(curve, X3, Y3, zs); } public override ECPoint Twice() @@ -192,20 +158,21 @@ public override ECPoint Twice() SecP256K1FieldElement X1 = (SecP256K1FieldElement)this.RawXCoord, Z1 = (SecP256K1FieldElement)this.RawZCoords[0]; uint c; + uint[] tt0 = Nat256.CreateExt(); uint[] Y1Squared = Nat256.Create(); - SecP256K1Field.Square(Y1.x, Y1Squared); + SecP256K1Field.Square(Y1.x, Y1Squared, tt0); uint[] T = Nat256.Create(); - SecP256K1Field.Square(Y1Squared, T); + SecP256K1Field.Square(Y1Squared, T, tt0); uint[] M = Nat256.Create(); - SecP256K1Field.Square(X1.x, M); + SecP256K1Field.Square(X1.x, M, tt0); c = Nat256.AddBothTo(M, M, M); SecP256K1Field.Reduce32(c, M); uint[] S = Y1Squared; - SecP256K1Field.Multiply(Y1Squared, X1.x, S); + SecP256K1Field.Multiply(Y1Squared, X1.x, S, tt0); c = Nat.ShiftUpBits(8, S, 2, 0); SecP256K1Field.Reduce32(c, S); @@ -214,23 +181,23 @@ public override ECPoint Twice() SecP256K1Field.Reduce32(c, t1); SecP256K1FieldElement X3 = new SecP256K1FieldElement(T); - SecP256K1Field.Square(M, X3.x); + SecP256K1Field.Square(M, X3.x, tt0); SecP256K1Field.Subtract(X3.x, S, X3.x); SecP256K1Field.Subtract(X3.x, S, X3.x); SecP256K1FieldElement Y3 = new SecP256K1FieldElement(S); SecP256K1Field.Subtract(S, X3.x, Y3.x); - SecP256K1Field.Multiply(Y3.x, M, Y3.x); + SecP256K1Field.Multiply(Y3.x, M, Y3.x, tt0); SecP256K1Field.Subtract(Y3.x, t1, Y3.x); SecP256K1FieldElement Z3 = new SecP256K1FieldElement(M); SecP256K1Field.Twice(Y1.x, Z3.x); if (!Z1.IsOne) { - SecP256K1Field.Multiply(Z3.x, Z1.x, Z3.x); + SecP256K1Field.Multiply(Z3.x, Z1.x, Z3.x, tt0); } - return new SecP256K1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecP256K1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -263,7 +230,7 @@ public override ECPoint Negate() if (IsInfinity) return this; - return new SecP256K1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed); + return new SecP256K1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256R1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256R1Curve.cs index 5d26a30..cea7048 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256R1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256R1Curve.cs @@ -69,14 +69,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecP256R1FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecP256R1Point(this, x, y, withCompression); + return new SecP256R1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecP256R1Point(this, x, y, zs, withCompression); + return new SecP256R1Point(this, x, y, zs); } public override ECLookupTable CreateCacheSafeLookupTable(ECPoint[] points, int off, int len) @@ -165,7 +165,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(uint[] x, uint[] y) { - return m_outer.CreateRawPoint(new SecP256R1FieldElement(x), new SecP256R1FieldElement(y), SECP256R1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecP256R1FieldElement(x), new SecP256R1FieldElement(y), SECP256R1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256R1Field.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256R1Field.cs index a754ee3..9ddbe5f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256R1Field.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256R1Field.cs @@ -93,6 +93,12 @@ public static void Multiply(uint[] x, uint[] y, uint[] z) Reduce(tt, z); } + public static void Multiply(uint[] x, uint[] y, uint[] z, uint[] tt) + { + Nat256.Mul(x, y, tt); + Reduce(tt, z); + } + public static void MultiplyAddToExt(uint[] x, uint[] y, uint[] zz) { uint c = Nat256.MulAddTo(x, y, zz); @@ -239,6 +245,12 @@ public static void Square(uint[] x, uint[] z) Reduce(tt, z); } + public static void Square(uint[] x, uint[] z, uint[] tt) + { + Nat256.Square(x, tt); + Reduce(tt, z); + } + public static void SquareN(uint[] x, int n, uint[] z) { Debug.Assert(n > 0); @@ -254,6 +266,20 @@ public static void SquareN(uint[] x, int n, uint[] z) } } + public static void SquareN(uint[] x, int n, uint[] z, uint[] tt) + { + Debug.Assert(n > 0); + + Nat256.Square(x, tt); + Reduce(tt, z); + + while (--n > 0) + { + Nat256.Square(z, tt); + Reduce(tt, z); + } + } + public static void Subtract(uint[] x, uint[] y, uint[] z) { int c = Nat256.Sub(x, y, z); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256R1FieldElement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256R1FieldElement.cs index 45a1e92..a3f3f5e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256R1FieldElement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256R1FieldElement.cs @@ -117,7 +117,6 @@ public override ECFieldElement Square() public override ECFieldElement Invert() { - //return new SecP256R1FieldElement(ToBigInteger().ModInverse(Q)); uint[] z = Nat256.Create(); SecP256R1Field.Inv(x, z); return new SecP256R1FieldElement(z); @@ -135,32 +134,33 @@ public override ECFieldElement Sqrt() if (Nat256.IsZero(x1) || Nat256.IsOne(x1)) return this; + uint[] tt0 = Nat256.CreateExt(); uint[] t1 = Nat256.Create(); uint[] t2 = Nat256.Create(); - SecP256R1Field.Square(x1, t1); - SecP256R1Field.Multiply(t1, x1, t1); + SecP256R1Field.Square(x1, t1, tt0); + SecP256R1Field.Multiply(t1, x1, t1, tt0); - SecP256R1Field.SquareN(t1, 2, t2); - SecP256R1Field.Multiply(t2, t1, t2); + SecP256R1Field.SquareN(t1, 2, t2, tt0); + SecP256R1Field.Multiply(t2, t1, t2, tt0); - SecP256R1Field.SquareN(t2, 4, t1); - SecP256R1Field.Multiply(t1, t2, t1); + SecP256R1Field.SquareN(t2, 4, t1, tt0); + SecP256R1Field.Multiply(t1, t2, t1, tt0); - SecP256R1Field.SquareN(t1, 8, t2); - SecP256R1Field.Multiply(t2, t1, t2); + SecP256R1Field.SquareN(t1, 8, t2, tt0); + SecP256R1Field.Multiply(t2, t1, t2, tt0); - SecP256R1Field.SquareN(t2, 16, t1); - SecP256R1Field.Multiply(t1, t2, t1); + SecP256R1Field.SquareN(t2, 16, t1, tt0); + SecP256R1Field.Multiply(t1, t2, t1, tt0); - SecP256R1Field.SquareN(t1, 32, t1); - SecP256R1Field.Multiply(t1, x1, t1); + SecP256R1Field.SquareN(t1, 32, t1, tt0); + SecP256R1Field.Multiply(t1, x1, t1, tt0); - SecP256R1Field.SquareN(t1, 96, t1); - SecP256R1Field.Multiply(t1, x1, t1); + SecP256R1Field.SquareN(t1, 96, t1, tt0); + SecP256R1Field.Multiply(t1, x1, t1, tt0); - SecP256R1Field.SquareN(t1, 94, t1); - SecP256R1Field.Multiply(t1, t1, t2); + SecP256R1Field.SquareN(t1, 94, t1, tt0); + SecP256R1Field.Multiply(t1, t1, t2, tt0); return Nat256.Eq(x1, t2) ? new SecP256R1FieldElement(t1) : null; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256R1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256R1Point.cs index 7e80291..ac2e4db 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256R1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP256R1Point.cs @@ -9,47 +9,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecP256R1Point : AbstractFpPoint { - /** - * Create a point which encodes with point compression. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecP256R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecP256R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * Create a point that encodes with or without point compresion. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * @param withCompression - * if true encode with point compression - * - * @deprecated per-point compression property will be removed, refer - * {@link #getEncoded(bool)} - */ - public SecP256R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecP256R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecP256R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -76,6 +42,7 @@ public override ECPoint Add(ECPoint b) SecP256R1FieldElement Z2 = (SecP256R1FieldElement)b.RawZCoords[0]; uint c; + uint[] tt0 = Nat256.CreateExt(); uint[] tt1 = Nat256.CreateExt(); uint[] t2 = Nat256.Create(); uint[] t3 = Nat256.Create(); @@ -91,13 +58,13 @@ public override ECPoint Add(ECPoint b) else { S2 = t3; - SecP256R1Field.Square(Z1.x, S2); + SecP256R1Field.Square(Z1.x, S2, tt0); U2 = t2; - SecP256R1Field.Multiply(S2, X2.x, U2); + SecP256R1Field.Multiply(S2, X2.x, U2, tt0); - SecP256R1Field.Multiply(S2, Z1.x, S2); - SecP256R1Field.Multiply(S2, Y2.x, S2); + SecP256R1Field.Multiply(S2, Z1.x, S2, tt0); + SecP256R1Field.Multiply(S2, Y2.x, S2, tt0); } bool Z2IsOne = Z2.IsOne; @@ -110,13 +77,13 @@ public override ECPoint Add(ECPoint b) else { S1 = t4; - SecP256R1Field.Square(Z2.x, S1); + SecP256R1Field.Square(Z2.x, S1, tt0); U1 = tt1; - SecP256R1Field.Multiply(S1, X1.x, U1); + SecP256R1Field.Multiply(S1, X1.x, U1, tt0); - SecP256R1Field.Multiply(S1, Z2.x, S1); - SecP256R1Field.Multiply(S1, Y1.x, S1); + SecP256R1Field.Multiply(S1, Z2.x, S1, tt0); + SecP256R1Field.Multiply(S1, Y1.x, S1, tt0); } uint[] H = Nat256.Create(); @@ -139,13 +106,13 @@ public override ECPoint Add(ECPoint b) } uint[] HSquared = t3; - SecP256R1Field.Square(H, HSquared); + SecP256R1Field.Square(H, HSquared, tt0); uint[] G = Nat256.Create(); - SecP256R1Field.Multiply(HSquared, H, G); + SecP256R1Field.Multiply(HSquared, H, G, tt0); uint[] V = t3; - SecP256R1Field.Multiply(HSquared, U1, V); + SecP256R1Field.Multiply(HSquared, U1, V, tt0); SecP256R1Field.Negate(G, G); Nat256.Mul(S1, G, tt1); @@ -154,7 +121,7 @@ public override ECPoint Add(ECPoint b) SecP256R1Field.Reduce32(c, G); SecP256R1FieldElement X3 = new SecP256R1FieldElement(t4); - SecP256R1Field.Square(R, X3.x); + SecP256R1Field.Square(R, X3.x, tt0); SecP256R1Field.Subtract(X3.x, G, X3.x); SecP256R1FieldElement Y3 = new SecP256R1FieldElement(G); @@ -165,16 +132,16 @@ public override ECPoint Add(ECPoint b) SecP256R1FieldElement Z3 = new SecP256R1FieldElement(H); if (!Z1IsOne) { - SecP256R1Field.Multiply(Z3.x, Z1.x, Z3.x); + SecP256R1Field.Multiply(Z3.x, Z1.x, Z3.x, tt0); } if (!Z2IsOne) { - SecP256R1Field.Multiply(Z3.x, Z2.x, Z3.x); + SecP256R1Field.Multiply(Z3.x, Z2.x, Z3.x, tt0); } ECFieldElement[] zs = new ECFieldElement[]{ Z3 }; - return new SecP256R1Point(curve, X3, Y3, zs, IsCompressed); + return new SecP256R1Point(curve, X3, Y3, zs); } public override ECPoint Twice() @@ -191,14 +158,15 @@ public override ECPoint Twice() SecP256R1FieldElement X1 = (SecP256R1FieldElement)this.RawXCoord, Z1 = (SecP256R1FieldElement)this.RawZCoords[0]; uint c; + uint[] tt0 = Nat256.CreateExt(); uint[] t1 = Nat256.Create(); uint[] t2 = Nat256.Create(); uint[] Y1Squared = Nat256.Create(); - SecP256R1Field.Square(Y1.x, Y1Squared); + SecP256R1Field.Square(Y1.x, Y1Squared, tt0); uint[] T = Nat256.Create(); - SecP256R1Field.Square(Y1Squared, T); + SecP256R1Field.Square(Y1Squared, T, tt0); bool Z1IsOne = Z1.IsOne; @@ -206,19 +174,19 @@ public override ECPoint Twice() if (!Z1IsOne) { Z1Squared = t2; - SecP256R1Field.Square(Z1.x, Z1Squared); + SecP256R1Field.Square(Z1.x, Z1Squared, tt0); } SecP256R1Field.Subtract(X1.x, Z1Squared, t1); uint[] M = t2; SecP256R1Field.Add(X1.x, Z1Squared, M); - SecP256R1Field.Multiply(M, t1, M); + SecP256R1Field.Multiply(M, t1, M, tt0); c = Nat256.AddBothTo(M, M, M); SecP256R1Field.Reduce32(c, M); uint[] S = Y1Squared; - SecP256R1Field.Multiply(Y1Squared, X1.x, S); + SecP256R1Field.Multiply(Y1Squared, X1.x, S, tt0); c = Nat.ShiftUpBits(8, S, 2, 0); SecP256R1Field.Reduce32(c, S); @@ -226,23 +194,23 @@ public override ECPoint Twice() SecP256R1Field.Reduce32(c, t1); SecP256R1FieldElement X3 = new SecP256R1FieldElement(T); - SecP256R1Field.Square(M, X3.x); + SecP256R1Field.Square(M, X3.x, tt0); SecP256R1Field.Subtract(X3.x, S, X3.x); SecP256R1Field.Subtract(X3.x, S, X3.x); SecP256R1FieldElement Y3 = new SecP256R1FieldElement(S); SecP256R1Field.Subtract(S, X3.x, Y3.x); - SecP256R1Field.Multiply(Y3.x, M, Y3.x); + SecP256R1Field.Multiply(Y3.x, M, Y3.x, tt0); SecP256R1Field.Subtract(Y3.x, t1, Y3.x); SecP256R1FieldElement Z3 = new SecP256R1FieldElement(M); SecP256R1Field.Twice(Y1.x, Z3.x); if (!Z1IsOne) { - SecP256R1Field.Multiply(Z3.x, Z1.x, Z3.x); + SecP256R1Field.Multiply(Z3.x, Z1.x, Z3.x, tt0); } - return new SecP256R1Point(curve, X3, Y3, new ECFieldElement[]{ Z3 }, IsCompressed); + return new SecP256R1Point(curve, X3, Y3, new ECFieldElement[]{ Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -275,7 +243,7 @@ public override ECPoint Negate() if (IsInfinity) return this; - return new SecP256R1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed); + return new SecP256R1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP384R1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP384R1Curve.cs index 0043f22..47af02e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP384R1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP384R1Curve.cs @@ -69,14 +69,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecP384R1FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecP384R1Point(this, x, y, withCompression); + return new SecP384R1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecP384R1Point(this, x, y, zs, withCompression); + return new SecP384R1Point(this, x, y, zs); } public override ECLookupTable CreateCacheSafeLookupTable(ECPoint[] points, int off, int len) @@ -165,7 +165,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(uint[] x, uint[] y) { - return m_outer.CreateRawPoint(new SecP384R1FieldElement(x), new SecP384R1FieldElement(y), SECP384R1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecP384R1FieldElement(x), new SecP384R1FieldElement(y), SECP384R1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP384R1Field.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP384R1Field.cs index e695c4d..f5033a9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP384R1Field.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP384R1Field.cs @@ -100,6 +100,12 @@ public static void Multiply(uint[] x, uint[] y, uint[] z) Reduce(tt, z); } + public static void Multiply(uint[] x, uint[] y, uint[] z, uint[] tt) + { + Nat384.Mul(x, y, tt); + Reduce(tt, z); + } + public static void Negate(uint[] x, uint[] z) { if (0 != IsZero(x)) @@ -236,6 +242,12 @@ public static void Square(uint[] x, uint[] z) Reduce(tt, z); } + public static void Square(uint[] x, uint[] z, uint[] tt) + { + Nat384.Square(x, tt); + Reduce(tt, z); + } + public static void SquareN(uint[] x, int n, uint[] z) { Debug.Assert(n > 0); @@ -251,6 +263,20 @@ public static void SquareN(uint[] x, int n, uint[] z) } } + public static void SquareN(uint[] x, int n, uint[] z, uint[] tt) + { + Debug.Assert(n > 0); + + Nat384.Square(x, tt); + Reduce(tt, z); + + while (--n > 0) + { + Nat384.Square(z, tt); + Reduce(tt, z); + } + } + public static void Subtract(uint[] x, uint[] y, uint[] z) { int c = Nat.Sub(12, x, y, z); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP384R1FieldElement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP384R1FieldElement.cs index 07b6fff..85ad5b5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP384R1FieldElement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP384R1FieldElement.cs @@ -117,7 +117,6 @@ public override ECFieldElement Square() public override ECFieldElement Invert() { - //return new SecP384R1FieldElement(ToBigInteger().ModInverse(Q)); uint[] z = Nat.Create(12); SecP384R1Field.Inv(x, z); return new SecP384R1FieldElement(z); @@ -135,54 +134,55 @@ public override ECFieldElement Sqrt() if (Nat.IsZero(12, x1) || Nat.IsOne(12, x1)) return this; + uint[] tt0 = Nat.Create(24); uint[] t1 = Nat.Create(12); uint[] t2 = Nat.Create(12); uint[] t3 = Nat.Create(12); uint[] t4 = Nat.Create(12); - SecP384R1Field.Square(x1, t1); - SecP384R1Field.Multiply(t1, x1, t1); + SecP384R1Field.Square(x1, t1, tt0); + SecP384R1Field.Multiply(t1, x1, t1, tt0); - SecP384R1Field.SquareN(t1, 2, t2); - SecP384R1Field.Multiply(t2, t1, t2); + SecP384R1Field.SquareN(t1, 2, t2, tt0); + SecP384R1Field.Multiply(t2, t1, t2, tt0); - SecP384R1Field.Square(t2, t2); - SecP384R1Field.Multiply(t2, x1, t2); + SecP384R1Field.Square(t2, t2, tt0); + SecP384R1Field.Multiply(t2, x1, t2, tt0); - SecP384R1Field.SquareN(t2, 5, t3); - SecP384R1Field.Multiply(t3, t2, t3); + SecP384R1Field.SquareN(t2, 5, t3, tt0); + SecP384R1Field.Multiply(t3, t2, t3, tt0); - SecP384R1Field.SquareN(t3, 5, t4); - SecP384R1Field.Multiply(t4, t2, t4); + SecP384R1Field.SquareN(t3, 5, t4, tt0); + SecP384R1Field.Multiply(t4, t2, t4, tt0); - SecP384R1Field.SquareN(t4, 15, t2); - SecP384R1Field.Multiply(t2, t4, t2); + SecP384R1Field.SquareN(t4, 15, t2, tt0); + SecP384R1Field.Multiply(t2, t4, t2, tt0); - SecP384R1Field.SquareN(t2, 2, t3); - SecP384R1Field.Multiply(t1, t3, t1); + SecP384R1Field.SquareN(t2, 2, t3, tt0); + SecP384R1Field.Multiply(t1, t3, t1, tt0); - SecP384R1Field.SquareN(t3, 28, t3); - SecP384R1Field.Multiply(t2, t3, t2); + SecP384R1Field.SquareN(t3, 28, t3, tt0); + SecP384R1Field.Multiply(t2, t3, t2, tt0); - SecP384R1Field.SquareN(t2, 60, t3); - SecP384R1Field.Multiply(t3, t2, t3); + SecP384R1Field.SquareN(t2, 60, t3, tt0); + SecP384R1Field.Multiply(t3, t2, t3, tt0); uint[] r = t2; - SecP384R1Field.SquareN(t3, 120, r); - SecP384R1Field.Multiply(r, t3, r); + SecP384R1Field.SquareN(t3, 120, r, tt0); + SecP384R1Field.Multiply(r, t3, r, tt0); - SecP384R1Field.SquareN(r, 15, r); - SecP384R1Field.Multiply(r, t4, r); + SecP384R1Field.SquareN(r, 15, r, tt0); + SecP384R1Field.Multiply(r, t4, r, tt0); - SecP384R1Field.SquareN(r, 33, r); - SecP384R1Field.Multiply(r, t1, r); + SecP384R1Field.SquareN(r, 33, r, tt0); + SecP384R1Field.Multiply(r, t1, r, tt0); - SecP384R1Field.SquareN(r, 64, r); - SecP384R1Field.Multiply(r, x1, r); + SecP384R1Field.SquareN(r, 64, r, tt0); + SecP384R1Field.Multiply(r, x1, r, tt0); - SecP384R1Field.SquareN(r, 30, t1); - SecP384R1Field.Square(t1, t2); + SecP384R1Field.SquareN(r, 30, t1, tt0); + SecP384R1Field.Square(t1, t2, tt0); return Nat.Eq(12, x1, t2) ? new SecP384R1FieldElement(t1) : null; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP384R1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP384R1Point.cs index ce008da..3464415 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP384R1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP384R1Point.cs @@ -9,47 +9,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecP384R1Point : AbstractFpPoint { - /** - * Create a point which encodes with point compression. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecP384R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecP384R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * Create a point that encodes with or without point compresion. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * @param withCompression - * if true encode with point compression - * - * @deprecated per-point compression property will be removed, refer - * {@link #getEncoded(bool)} - */ - public SecP384R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecP384R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecP384R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -76,6 +42,7 @@ public override ECPoint Add(ECPoint b) SecP384R1FieldElement Z2 = (SecP384R1FieldElement)b.RawZCoords[0]; uint c; + uint[] tt0 = Nat.Create(24); uint[] tt1 = Nat.Create(24); uint[] tt2 = Nat.Create(24); uint[] t3 = Nat.Create(12); @@ -91,13 +58,13 @@ public override ECPoint Add(ECPoint b) else { S2 = t3; - SecP384R1Field.Square(Z1.x, S2); + SecP384R1Field.Square(Z1.x, S2, tt0); U2 = tt2; - SecP384R1Field.Multiply(S2, X2.x, U2); + SecP384R1Field.Multiply(S2, X2.x, U2, tt0); - SecP384R1Field.Multiply(S2, Z1.x, S2); - SecP384R1Field.Multiply(S2, Y2.x, S2); + SecP384R1Field.Multiply(S2, Z1.x, S2, tt0); + SecP384R1Field.Multiply(S2, Y2.x, S2, tt0); } bool Z2IsOne = Z2.IsOne; @@ -110,13 +77,13 @@ public override ECPoint Add(ECPoint b) else { S1 = t4; - SecP384R1Field.Square(Z2.x, S1); + SecP384R1Field.Square(Z2.x, S1, tt0); U1 = tt1; - SecP384R1Field.Multiply(S1, X1.x, U1); + SecP384R1Field.Multiply(S1, X1.x, U1, tt0); - SecP384R1Field.Multiply(S1, Z2.x, S1); - SecP384R1Field.Multiply(S1, Y1.x, S1); + SecP384R1Field.Multiply(S1, Z2.x, S1, tt0); + SecP384R1Field.Multiply(S1, Y1.x, S1, tt0); } uint[] H = Nat.Create(12); @@ -139,13 +106,13 @@ public override ECPoint Add(ECPoint b) } uint[] HSquared = t3; - SecP384R1Field.Square(H, HSquared); + SecP384R1Field.Square(H, HSquared, tt0); uint[] G = Nat.Create(12); - SecP384R1Field.Multiply(HSquared, H, G); + SecP384R1Field.Multiply(HSquared, H, G, tt0); uint[] V = t3; - SecP384R1Field.Multiply(HSquared, U1, V); + SecP384R1Field.Multiply(HSquared, U1, V, tt0); SecP384R1Field.Negate(G, G); Nat384.Mul(S1, G, tt1); @@ -154,7 +121,7 @@ public override ECPoint Add(ECPoint b) SecP384R1Field.Reduce32(c, G); SecP384R1FieldElement X3 = new SecP384R1FieldElement(t4); - SecP384R1Field.Square(R, X3.x); + SecP384R1Field.Square(R, X3.x, tt0); SecP384R1Field.Subtract(X3.x, G, X3.x); SecP384R1FieldElement Y3 = new SecP384R1FieldElement(G); @@ -166,16 +133,16 @@ public override ECPoint Add(ECPoint b) SecP384R1FieldElement Z3 = new SecP384R1FieldElement(H); if (!Z1IsOne) { - SecP384R1Field.Multiply(Z3.x, Z1.x, Z3.x); + SecP384R1Field.Multiply(Z3.x, Z1.x, Z3.x, tt0); } if (!Z2IsOne) { - SecP384R1Field.Multiply(Z3.x, Z2.x, Z3.x); + SecP384R1Field.Multiply(Z3.x, Z2.x, Z3.x, tt0); } ECFieldElement[] zs = new ECFieldElement[] { Z3 }; - return new SecP384R1Point(curve, X3, Y3, zs, IsCompressed); + return new SecP384R1Point(curve, X3, Y3, zs); } public override ECPoint Twice() @@ -192,14 +159,15 @@ public override ECPoint Twice() SecP384R1FieldElement X1 = (SecP384R1FieldElement)this.RawXCoord, Z1 = (SecP384R1FieldElement)this.RawZCoords[0]; uint c; + uint[] tt0 = Nat.Create(24); uint[] t1 = Nat.Create(12); uint[] t2 = Nat.Create(12); uint[] Y1Squared = Nat.Create(12); - SecP384R1Field.Square(Y1.x, Y1Squared); + SecP384R1Field.Square(Y1.x, Y1Squared, tt0); uint[] T = Nat.Create(12); - SecP384R1Field.Square(Y1Squared, T); + SecP384R1Field.Square(Y1Squared, T, tt0); bool Z1IsOne = Z1.IsOne; @@ -207,19 +175,19 @@ public override ECPoint Twice() if (!Z1IsOne) { Z1Squared = t2; - SecP384R1Field.Square(Z1.x, Z1Squared); + SecP384R1Field.Square(Z1.x, Z1Squared, tt0); } SecP384R1Field.Subtract(X1.x, Z1Squared, t1); uint[] M = t2; SecP384R1Field.Add(X1.x, Z1Squared, M); - SecP384R1Field.Multiply(M, t1, M); + SecP384R1Field.Multiply(M, t1, M, tt0); c = Nat.AddBothTo(12, M, M, M); SecP384R1Field.Reduce32(c, M); uint[] S = Y1Squared; - SecP384R1Field.Multiply(Y1Squared, X1.x, S); + SecP384R1Field.Multiply(Y1Squared, X1.x, S, tt0); c = Nat.ShiftUpBits(12, S, 2, 0); SecP384R1Field.Reduce32(c, S); @@ -227,23 +195,23 @@ public override ECPoint Twice() SecP384R1Field.Reduce32(c, t1); SecP384R1FieldElement X3 = new SecP384R1FieldElement(T); - SecP384R1Field.Square(M, X3.x); + SecP384R1Field.Square(M, X3.x, tt0); SecP384R1Field.Subtract(X3.x, S, X3.x); SecP384R1Field.Subtract(X3.x, S, X3.x); SecP384R1FieldElement Y3 = new SecP384R1FieldElement(S); SecP384R1Field.Subtract(S, X3.x, Y3.x); - SecP384R1Field.Multiply(Y3.x, M, Y3.x); + SecP384R1Field.Multiply(Y3.x, M, Y3.x, tt0); SecP384R1Field.Subtract(Y3.x, t1, Y3.x); SecP384R1FieldElement Z3 = new SecP384R1FieldElement(M); SecP384R1Field.Twice(Y1.x, Z3.x); if (!Z1IsOne) { - SecP384R1Field.Multiply(Z3.x, Z1.x, Z3.x); + SecP384R1Field.Multiply(Z3.x, Z1.x, Z3.x, tt0); } - return new SecP384R1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecP384R1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -276,7 +244,7 @@ public override ECPoint Negate() if (IsInfinity) return this; - return new SecP384R1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed); + return new SecP384R1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP521R1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP521R1Curve.cs index 641cbb7..158b4d8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP521R1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP521R1Curve.cs @@ -69,14 +69,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecP521R1FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecP521R1Point(this, x, y, withCompression); + return new SecP521R1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecP521R1Point(this, x, y, zs, withCompression); + return new SecP521R1Point(this, x, y, zs); } public override ECLookupTable CreateCacheSafeLookupTable(ECPoint[] points, int off, int len) @@ -165,7 +165,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(uint[] x, uint[] y) { - return m_outer.CreateRawPoint(new SecP521R1FieldElement(x), new SecP521R1FieldElement(y), SECP521R1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecP521R1FieldElement(x), new SecP521R1FieldElement(y), SECP521R1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP521R1Field.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP521R1Field.cs index e9dd7ee..399fdd7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP521R1Field.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP521R1Field.cs @@ -79,6 +79,12 @@ public static void Multiply(uint[] x, uint[] y, uint[] z) Reduce(tt, z); } + public static void Multiply(uint[] x, uint[] y, uint[] z, uint[] tt) + { + ImplMultiply(x, y, tt); + Reduce(tt, z); + } + public static void Negate(uint[] x, uint[] z) { if (0 != IsZero(x)) @@ -146,9 +152,16 @@ public static void Square(uint[] x, uint[] z) Reduce(tt, z); } + public static void Square(uint[] x, uint[] z, uint[] tt) + { + ImplSquare(x, tt); + Reduce(tt, z); + } + public static void SquareN(uint[] x, int n, uint[] z) { Debug.Assert(n > 0); + uint[] tt = Nat.Create(33); ImplSquare(x, tt); Reduce(tt, z); @@ -160,6 +173,20 @@ public static void SquareN(uint[] x, int n, uint[] z) } } + public static void SquareN(uint[] x, int n, uint[] z, uint[] tt) + { + Debug.Assert(n > 0); + + ImplSquare(x, tt); + Reduce(tt, z); + + while (--n > 0) + { + ImplSquare(z, tt); + Reduce(tt, z); + } + } + public static void Subtract(uint[] x, uint[] y, uint[] z) { int c = Nat.Sub(16, x, y, z) + (int)(x[16] - y[16]); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP521R1FieldElement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP521R1FieldElement.cs index d1597f6..caf6a7b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP521R1FieldElement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP521R1FieldElement.cs @@ -117,7 +117,6 @@ public override ECFieldElement Square() public override ECFieldElement Invert() { - //return new SecP521R1FieldElement(ToBigInteger().ModInverse(Q)); uint[] z = Nat.Create(17); SecP521R1Field.Inv(x, z); return new SecP521R1FieldElement(z); @@ -135,11 +134,12 @@ public override ECFieldElement Sqrt() if (Nat.IsZero(17, x1) || Nat.IsOne(17, x1)) return this; + uint[] tt0 = Nat.Create(33); uint[] t1 = Nat.Create(17); uint[] t2 = Nat.Create(17); - SecP521R1Field.SquareN(x1, 519, t1); - SecP521R1Field.Square(t1, t2); + SecP521R1Field.SquareN(x1, 519, t1, tt0); + SecP521R1Field.Square(t1, t2, tt0); return Nat.Eq(17, x1, t2) ? new SecP521R1FieldElement(t1) : null; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP521R1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP521R1Point.cs index 67968e4..9bf07c8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP521R1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecP521R1Point.cs @@ -9,47 +9,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecP521R1Point : AbstractFpPoint { - /** - * Create a point which encodes with point compression. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecP521R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecP521R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * Create a point that encodes with or without point compresion. - * - * @param curve - * the curve to use - * @param x - * affine x co-ordinate - * @param y - * affine y co-ordinate - * @param withCompression - * if true encode with point compression - * - * @deprecated per-point compression property will be removed, refer - * {@link #getEncoded(bool)} - */ - public SecP521R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecP521R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecP521R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -75,6 +41,7 @@ public override ECPoint Add(ECPoint b) SecP521R1FieldElement Z1 = (SecP521R1FieldElement)this.RawZCoords[0]; SecP521R1FieldElement Z2 = (SecP521R1FieldElement)b.RawZCoords[0]; + uint[] tt0 = Nat.Create(33); uint[] t1 = Nat.Create(17); uint[] t2 = Nat.Create(17); uint[] t3 = Nat.Create(17); @@ -90,13 +57,13 @@ public override ECPoint Add(ECPoint b) else { S2 = t3; - SecP521R1Field.Square(Z1.x, S2); + SecP521R1Field.Square(Z1.x, S2, tt0); U2 = t2; - SecP521R1Field.Multiply(S2, X2.x, U2); + SecP521R1Field.Multiply(S2, X2.x, U2, tt0); - SecP521R1Field.Multiply(S2, Z1.x, S2); - SecP521R1Field.Multiply(S2, Y2.x, S2); + SecP521R1Field.Multiply(S2, Z1.x, S2, tt0); + SecP521R1Field.Multiply(S2, Y2.x, S2, tt0); } bool Z2IsOne = Z2.IsOne; @@ -109,13 +76,13 @@ public override ECPoint Add(ECPoint b) else { S1 = t4; - SecP521R1Field.Square(Z2.x, S1); + SecP521R1Field.Square(Z2.x, S1, tt0); U1 = t1; - SecP521R1Field.Multiply(S1, X1.x, U1); + SecP521R1Field.Multiply(S1, X1.x, U1, tt0); - SecP521R1Field.Multiply(S1, Z2.x, S1); - SecP521R1Field.Multiply(S1, Y1.x, S1); + SecP521R1Field.Multiply(S1, Z2.x, S1, tt0); + SecP521R1Field.Multiply(S1, Y1.x, S1, tt0); } uint[] H = Nat.Create(17); @@ -138,40 +105,40 @@ public override ECPoint Add(ECPoint b) } uint[] HSquared = t3; - SecP521R1Field.Square(H, HSquared); + SecP521R1Field.Square(H, HSquared, tt0); uint[] G = Nat.Create(17); - SecP521R1Field.Multiply(HSquared, H, G); + SecP521R1Field.Multiply(HSquared, H, G, tt0); uint[] V = t3; - SecP521R1Field.Multiply(HSquared, U1, V); + SecP521R1Field.Multiply(HSquared, U1, V, tt0); - SecP521R1Field.Multiply(S1, G, t1); + SecP521R1Field.Multiply(S1, G, t1, tt0); SecP521R1FieldElement X3 = new SecP521R1FieldElement(t4); - SecP521R1Field.Square(R, X3.x); + SecP521R1Field.Square(R, X3.x, tt0); SecP521R1Field.Add(X3.x, G, X3.x); SecP521R1Field.Subtract(X3.x, V, X3.x); SecP521R1Field.Subtract(X3.x, V, X3.x); SecP521R1FieldElement Y3 = new SecP521R1FieldElement(G); SecP521R1Field.Subtract(V, X3.x, Y3.x); - SecP521R1Field.Multiply(Y3.x, R, t2); + SecP521R1Field.Multiply(Y3.x, R, t2, tt0); SecP521R1Field.Subtract(t2, t1, Y3.x); SecP521R1FieldElement Z3 = new SecP521R1FieldElement(H); if (!Z1IsOne) { - SecP521R1Field.Multiply(Z3.x, Z1.x, Z3.x); + SecP521R1Field.Multiply(Z3.x, Z1.x, Z3.x, tt0); } if (!Z2IsOne) { - SecP521R1Field.Multiply(Z3.x, Z2.x, Z3.x); + SecP521R1Field.Multiply(Z3.x, Z2.x, Z3.x, tt0); } ECFieldElement[] zs = new ECFieldElement[] { Z3 }; - return new SecP521R1Point(curve, X3, Y3, zs, IsCompressed); + return new SecP521R1Point(curve, X3, Y3, zs); } public override ECPoint Twice() @@ -187,14 +154,15 @@ public override ECPoint Twice() SecP521R1FieldElement X1 = (SecP521R1FieldElement)this.RawXCoord, Z1 = (SecP521R1FieldElement)this.RawZCoords[0]; + uint[] tt0 = Nat.Create(33); uint[] t1 = Nat.Create(17); uint[] t2 = Nat.Create(17); uint[] Y1Squared = Nat.Create(17); - SecP521R1Field.Square(Y1.x, Y1Squared); + SecP521R1Field.Square(Y1.x, Y1Squared, tt0); uint[] T = Nat.Create(17); - SecP521R1Field.Square(Y1Squared, T); + SecP521R1Field.Square(Y1Squared, T, tt0); bool Z1IsOne = Z1.IsOne; @@ -202,19 +170,19 @@ public override ECPoint Twice() if (!Z1IsOne) { Z1Squared = t2; - SecP521R1Field.Square(Z1.x, Z1Squared); + SecP521R1Field.Square(Z1.x, Z1Squared, tt0); } SecP521R1Field.Subtract(X1.x, Z1Squared, t1); uint[] M = t2; SecP521R1Field.Add(X1.x, Z1Squared, M); - SecP521R1Field.Multiply(M, t1, M); + SecP521R1Field.Multiply(M, t1, M, tt0); Nat.AddBothTo(17, M, M, M); SecP521R1Field.Reduce23(M); uint[] S = Y1Squared; - SecP521R1Field.Multiply(Y1Squared, X1.x, S); + SecP521R1Field.Multiply(Y1Squared, X1.x, S, tt0); Nat.ShiftUpBits(17, S, 2, 0); SecP521R1Field.Reduce23(S); @@ -222,23 +190,23 @@ public override ECPoint Twice() SecP521R1Field.Reduce23(t1); SecP521R1FieldElement X3 = new SecP521R1FieldElement(T); - SecP521R1Field.Square(M, X3.x); + SecP521R1Field.Square(M, X3.x, tt0); SecP521R1Field.Subtract(X3.x, S, X3.x); SecP521R1Field.Subtract(X3.x, S, X3.x); SecP521R1FieldElement Y3 = new SecP521R1FieldElement(S); SecP521R1Field.Subtract(S, X3.x, Y3.x); - SecP521R1Field.Multiply(Y3.x, M, Y3.x); + SecP521R1Field.Multiply(Y3.x, M, Y3.x, tt0); SecP521R1Field.Subtract(Y3.x, t1, Y3.x); SecP521R1FieldElement Z3 = new SecP521R1FieldElement(M); SecP521R1Field.Twice(Y1.x, Z3.x); if (!Z1IsOne) { - SecP521R1Field.Multiply(Z3.x, Z1.x, Z3.x); + SecP521R1Field.Multiply(Z3.x, Z1.x, Z3.x, tt0); } - return new SecP521R1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecP521R1Point(curve, X3, Y3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -271,7 +239,7 @@ public override ECPoint Negate() if (IsInfinity) return this; - return new SecP521R1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed); + return new SecP521R1Point(Curve, RawXCoord, RawYCoord.Negate(), RawZCoords); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113Field.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113Field.cs index 698d95c..1ca09ad 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113Field.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113Field.cs @@ -2,6 +2,10 @@ #pragma warning disable using System; using System.Diagnostics; +#if NETCOREAPP3_0_OR_GREATER +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; @@ -125,9 +129,7 @@ public static void Reduce15(ulong[] z, int zOff) public static void Sqrt(ulong[] x, ulong[] z) { - ulong u0 = Interleave.Unshuffle(x[0]), u1 = Interleave.Unshuffle(x[1]); - ulong e0 = (u0 & 0x00000000FFFFFFFFUL) | (u1 << 32); - ulong c0 = (u0 >> 32) | (u1 & 0xFFFFFFFF00000000UL); + ulong c0 = Interleave.Unshuffle(x[0], x[1], out ulong e0); z[0] = e0 ^ (c0 << 57) ^ (c0 << 5); z[1] = (c0 >> 7) ^ (c0 >> 59); @@ -170,6 +172,25 @@ public static uint Trace(ulong[] x) protected static void ImplMultiply(ulong[] x, ulong[] y, ulong[] zz) { +#if NETCOREAPP3_0_OR_GREATER + if (Pclmulqdq.IsSupported) + { + var X01 = Vector128.Create(x[0], x[1]); + var Y01 = Vector128.Create(y[0], y[1]); + + var Z01 = Pclmulqdq.CarrylessMultiply(X01, Y01, 0x00); + var Z12 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y01, 0x01), + Pclmulqdq.CarrylessMultiply(X01, Y01, 0x10)); + var Z23 = Pclmulqdq.CarrylessMultiply(X01, Y01, 0x11); + + zz[0] = Z01.GetElement(0); + zz[1] = Z01.GetElement(1) ^ Z12.GetElement(0); + zz[2] = Z23.GetElement(0) ^ Z12.GetElement(1); + zz[3] = Z23.GetElement(1); + return; + } +#endif + /* * "Three-way recursion" as described in "Batch binary Edwards", Daniel J. Bernstein. */ diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113R1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113R1Curve.cs index 5611e26..cf20a3b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113R1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113R1Curve.cs @@ -60,14 +60,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecT113FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecT113R1Point(this, x, y, withCompression); + return new SecT113R1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecT113R1Point(this, x, y, zs, withCompression); + return new SecT113R1Point(this, x, y, zs); } public override bool IsKoblitz @@ -172,7 +172,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(ulong[] x, ulong[] y) { - return m_outer.CreateRawPoint(new SecT113FieldElement(x), new SecT113FieldElement(y), SECT113R1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecT113FieldElement(x), new SecT113FieldElement(y), SECT113R1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113R1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113R1Point.cs index ea698e6..652bc0a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113R1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113R1Point.cs @@ -7,26 +7,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecT113R1Point : AbstractF2mPoint { - /** - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecT113R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecT113R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} - */ - public SecT113R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecT113R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecT113R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -136,7 +123,7 @@ public override ECPoint Add(ECPoint b) X3 = L.Square().Add(L).Add(X1).Add(curve.A); if (X3.IsZero) { - return new SecT113R1Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT113R1Point(curve, X3, curve.B.Sqrt()); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); @@ -153,7 +140,7 @@ public override ECPoint Add(ECPoint b) X3 = AU1.Multiply(AU2); if (X3.IsZero) { - return new SecT113R1Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT113R1Point(curve, X3, curve.B.Sqrt()); } ECFieldElement ABZ2 = A.Multiply(B); @@ -171,7 +158,7 @@ public override ECPoint Add(ECPoint b) } } - return new SecT113R1Point(curve, X3, L3, new ECFieldElement[]{ Z3 }, IsCompressed); + return new SecT113R1Point(curve, X3, L3, new ECFieldElement[]{ Z3 }); } public override ECPoint Twice() @@ -198,7 +185,7 @@ public override ECPoint Twice() ECFieldElement T = L1.Square().Add(L1Z1).Add(aZ1Sq); if (T.IsZero) { - return new SecT113R1Point(curve, T, curve.B.Sqrt(), IsCompressed); + return new SecT113R1Point(curve, T, curve.B.Sqrt()); } ECFieldElement X3 = T.Square(); @@ -207,7 +194,7 @@ public override ECPoint Twice() ECFieldElement X1Z1 = Z1IsOne ? X1 : X1.Multiply(Z1); ECFieldElement L3 = X1Z1.SquarePlusProduct(T, L1Z1).Add(X3).Add(Z3); - return new SecT113R1Point(curve, X3, L3, new ECFieldElement[]{ Z3 }, IsCompressed); + return new SecT113R1Point(curve, X3, L3, new ECFieldElement[]{ Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -256,14 +243,14 @@ public override ECPoint TwicePlus(ECPoint b) if (A.IsZero) { - return new SecT113R1Point(curve, A, curve.B.Sqrt(), IsCompressed); + return new SecT113R1Point(curve, A, curve.B.Sqrt()); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2plus1, Z3); - return new SecT113R1Point(curve, X3, L3, new ECFieldElement[]{ Z3 }, IsCompressed); + return new SecT113R1Point(curve, X3, L3, new ECFieldElement[]{ Z3 }); } public override ECPoint Negate() @@ -277,7 +264,7 @@ public override ECPoint Negate() // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; - return new SecT113R1Point(Curve, X, L.Add(Z), new ECFieldElement[]{ Z }, IsCompressed); + return new SecT113R1Point(Curve, X, L.Add(Z), new ECFieldElement[]{ Z }); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113R2Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113R2Curve.cs index 1be9ef6..02dce23 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113R2Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113R2Curve.cs @@ -60,14 +60,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecT113FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecT113R2Point(this, x, y, withCompression); + return new SecT113R2Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecT113R2Point(this, x, y, zs, withCompression); + return new SecT113R2Point(this, x, y, zs); } public override bool IsKoblitz @@ -172,7 +172,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(ulong[] x, ulong[] y) { - return m_outer.CreateRawPoint(new SecT113FieldElement(x), new SecT113FieldElement(y), SECT113R2_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecT113FieldElement(x), new SecT113FieldElement(y), SECT113R2_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113R2Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113R2Point.cs index 5927161..b5d11ee 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113R2Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT113R2Point.cs @@ -7,26 +7,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecT113R2Point : AbstractF2mPoint { - /** - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecT113R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecT113R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} - */ - public SecT113R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecT113R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecT113R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -140,7 +127,7 @@ public override ECPoint Add(ECPoint b) X3 = L.Square().Add(L).Add(X1).Add(curve.A); if (X3.IsZero) { - return new SecT113R2Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT113R2Point(curve, X3, curve.B.Sqrt()); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); @@ -157,7 +144,7 @@ public override ECPoint Add(ECPoint b) X3 = AU1.Multiply(AU2); if (X3.IsZero) { - return new SecT113R2Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT113R2Point(curve, X3, curve.B.Sqrt()); } ECFieldElement ABZ2 = A.Multiply(B); @@ -175,7 +162,7 @@ public override ECPoint Add(ECPoint b) } } - return new SecT113R2Point(curve, X3, L3, new ECFieldElement[]{ Z3 }, IsCompressed); + return new SecT113R2Point(curve, X3, L3, new ECFieldElement[]{ Z3 }); } public override ECPoint Twice() @@ -204,7 +191,7 @@ public override ECPoint Twice() ECFieldElement T = L1.Square().Add(L1Z1).Add(aZ1Sq); if (T.IsZero) { - return new SecT113R2Point(curve, T, curve.B.Sqrt(), IsCompressed); + return new SecT113R2Point(curve, T, curve.B.Sqrt()); } ECFieldElement X3 = T.Square(); @@ -213,7 +200,7 @@ public override ECPoint Twice() ECFieldElement X1Z1 = Z1IsOne ? X1 : X1.Multiply(Z1); ECFieldElement L3 = X1Z1.SquarePlusProduct(T, L1Z1).Add(X3).Add(Z3); - return new SecT113R2Point(curve, X3, L3, new ECFieldElement[]{ Z3 }, IsCompressed); + return new SecT113R2Point(curve, X3, L3, new ECFieldElement[]{ Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -266,14 +253,14 @@ public override ECPoint TwicePlus(ECPoint b) if (A.IsZero) { - return new SecT113R2Point(curve, A, curve.B.Sqrt(), IsCompressed); + return new SecT113R2Point(curve, A, curve.B.Sqrt()); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2plus1, Z3); - return new SecT113R2Point(curve, X3, L3, new ECFieldElement[]{ Z3 }, IsCompressed); + return new SecT113R2Point(curve, X3, L3, new ECFieldElement[]{ Z3 }); } public override ECPoint Negate() @@ -287,7 +274,7 @@ public override ECPoint Negate() // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; - return new SecT113R2Point(Curve, X, L.Add(Z), new ECFieldElement[]{ Z }, IsCompressed); + return new SecT113R2Point(Curve, X, L.Add(Z), new ECFieldElement[]{ Z }); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131Field.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131Field.cs index 423458d..2292d52 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131Field.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131Field.cs @@ -2,6 +2,10 @@ #pragma warning disable using System; using System.Diagnostics; +#if NETCOREAPP3_0_OR_GREATER +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; @@ -137,14 +141,8 @@ public static void Sqrt(ulong[] x, ulong[] z) { ulong[] odd = Nat192.Create64(); - ulong u0, u1; - u0 = Interleave.Unshuffle(x[0]); u1 = Interleave.Unshuffle(x[1]); - ulong e0 = (u0 & 0x00000000FFFFFFFFUL) | (u1 << 32); - odd[0] = (u0 >> 32) | (u1 & 0xFFFFFFFF00000000UL); - - u0 = Interleave.Unshuffle(x[2]); - ulong e1 = (u0 & 0x00000000FFFFFFFFUL); - odd[1] = (u0 >> 32); + odd[0] = Interleave.Unshuffle(x[0], x[1], out ulong e0); + odd[1] = Interleave.Unshuffle(x[2] , out ulong e1); Multiply(odd, ROOT_Z, z); @@ -202,6 +200,33 @@ protected static void ImplCompactExt(ulong[] zz) protected static void ImplMultiply(ulong[] x, ulong[] y, ulong[] zz) { +#if NETCOREAPP3_0_OR_GREATER + if (Pclmulqdq.IsSupported) + { + var X01 = Vector128.Create(x[0], x[1]); + var X2_ = Vector128.CreateScalar(x[2]); + var Y01 = Vector128.Create(y[0], y[1]); + var Y2_ = Vector128.CreateScalar(y[2]); + + var Z01 = Pclmulqdq.CarrylessMultiply(X01, Y01, 0x00); + var Z12 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y01, 0x01), + Pclmulqdq.CarrylessMultiply(X01, Y01, 0x10)); + var Z23 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y2_, 0x00), + Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y01, 0x11), + Pclmulqdq.CarrylessMultiply(X2_, Y01, 0x00))); + var Z34 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y2_, 0x01), + Pclmulqdq.CarrylessMultiply(X2_, Y01, 0x10)); + var Z4_ = Pclmulqdq.CarrylessMultiply(X2_, Y2_, 0x00); + + zz[0] = Z01.GetElement(0); + zz[1] = Z01.GetElement(1) ^ Z12.GetElement(0); + zz[2] = Z23.GetElement(0) ^ Z12.GetElement(1); + zz[3] = Z23.GetElement(1) ^ Z34.GetElement(0); + zz[4] = Z4_.GetElement(0) ^ Z34.GetElement(1); + return; + } +#endif + /* * "Five-way recursion" as described in "Batch binary Edwards", Daniel J. Bernstein. */ diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131R1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131R1Curve.cs index f0682b3..0775179 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131R1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131R1Curve.cs @@ -60,14 +60,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecT131FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecT131R1Point(this, x, y, withCompression); + return new SecT131R1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecT131R1Point(this, x, y, zs, withCompression); + return new SecT131R1Point(this, x, y, zs); } public override bool IsKoblitz @@ -172,7 +172,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(ulong[] x, ulong[] y) { - return m_outer.CreateRawPoint(new SecT131FieldElement(x), new SecT131FieldElement(y), SECT131R1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecT131FieldElement(x), new SecT131FieldElement(y), SECT131R1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131R1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131R1Point.cs index 162f101..f434d30 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131R1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131R1Point.cs @@ -7,26 +7,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecT131R1Point : AbstractF2mPoint { - /** - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecT131R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecT131R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} - */ - public SecT131R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecT131R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecT131R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -136,7 +123,7 @@ public override ECPoint Add(ECPoint b) X3 = L.Square().Add(L).Add(X1).Add(curve.A); if (X3.IsZero) { - return new SecT131R1Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT131R1Point(curve, X3, curve.B.Sqrt()); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); @@ -153,7 +140,7 @@ public override ECPoint Add(ECPoint b) X3 = AU1.Multiply(AU2); if (X3.IsZero) { - return new SecT131R1Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT131R1Point(curve, X3, curve.B.Sqrt()); } ECFieldElement ABZ2 = A.Multiply(B); @@ -171,7 +158,7 @@ public override ECPoint Add(ECPoint b) } } - return new SecT131R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT131R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Twice() @@ -200,7 +187,7 @@ public override ECPoint Twice() ECFieldElement T = L1.Square().Add(L1Z1).Add(aZ1Sq); if (T.IsZero) { - return new SecT131R1Point(curve, T, curve.B.Sqrt(), IsCompressed); + return new SecT131R1Point(curve, T, curve.B.Sqrt()); } ECFieldElement X3 = T.Square(); @@ -209,7 +196,7 @@ public override ECPoint Twice() ECFieldElement X1Z1 = Z1IsOne ? X1 : X1.Multiply(Z1); ECFieldElement L3 = X1Z1.SquarePlusProduct(T, L1Z1).Add(X3).Add(Z3); - return new SecT131R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT131R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -262,14 +249,14 @@ public override ECPoint TwicePlus(ECPoint b) if (A.IsZero) { - return new SecT131R1Point(curve, A, curve.B.Sqrt(), IsCompressed); + return new SecT131R1Point(curve, A, curve.B.Sqrt()); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2plus1, Z3); - return new SecT131R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT131R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Negate() @@ -283,7 +270,7 @@ public override ECPoint Negate() // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; - return new SecT131R1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }, IsCompressed); + return new SecT131R1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131R2Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131R2Curve.cs index 9d5a7a8..a41c07c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131R2Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131R2Curve.cs @@ -55,14 +55,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecT131FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecT131R2Point(this, x, y, withCompression); + return new SecT131R2Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecT131R2Point(this, x, y, zs, withCompression); + return new SecT131R2Point(this, x, y, zs); } public override ECPoint Infinity @@ -172,7 +172,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(ulong[] x, ulong[] y) { - return m_outer.CreateRawPoint(new SecT131FieldElement(x), new SecT131FieldElement(y), SECT131R2_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecT131FieldElement(x), new SecT131FieldElement(y), SECT131R2_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131R2Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131R2Point.cs index 2f325c5..cd644db 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131R2Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT131R2Point.cs @@ -7,26 +7,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecT131R2Point : AbstractF2mPoint { - /** - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecT131R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecT131R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} - */ - public SecT131R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecT131R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecT131R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -136,7 +123,7 @@ public override ECPoint Add(ECPoint b) X3 = L.Square().Add(L).Add(X1).Add(curve.A); if (X3.IsZero) { - return new SecT131R2Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT131R2Point(curve, X3, curve.B.Sqrt()); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); @@ -153,7 +140,7 @@ public override ECPoint Add(ECPoint b) X3 = AU1.Multiply(AU2); if (X3.IsZero) { - return new SecT131R2Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT131R2Point(curve, X3, curve.B.Sqrt()); } ECFieldElement ABZ2 = A.Multiply(B); @@ -171,7 +158,7 @@ public override ECPoint Add(ECPoint b) } } - return new SecT131R2Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT131R2Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Twice() @@ -200,7 +187,7 @@ public override ECPoint Twice() ECFieldElement T = L1.Square().Add(L1Z1).Add(aZ1Sq); if (T.IsZero) { - return new SecT131R2Point(curve, T, curve.B.Sqrt(), IsCompressed); + return new SecT131R2Point(curve, T, curve.B.Sqrt()); } ECFieldElement X3 = T.Square(); @@ -209,7 +196,7 @@ public override ECPoint Twice() ECFieldElement X1Z1 = Z1IsOne ? X1 : X1.Multiply(Z1); ECFieldElement L3 = X1Z1.SquarePlusProduct(T, L1Z1).Add(X3).Add(Z3); - return new SecT131R2Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT131R2Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -258,14 +245,14 @@ public override ECPoint TwicePlus(ECPoint b) if (A.IsZero) { - return new SecT131R2Point(curve, A, curve.B.Sqrt(), IsCompressed); + return new SecT131R2Point(curve, A, curve.B.Sqrt()); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2plus1, Z3); - return new SecT131R2Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT131R2Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Negate() @@ -279,7 +266,7 @@ public override ECPoint Negate() // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; - return new SecT131R2Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }, IsCompressed); + return new SecT131R2Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163Field.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163Field.cs index cd19faf..fa683ae 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163Field.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163Field.cs @@ -2,6 +2,10 @@ #pragma warning disable using System; using System.Diagnostics; +#if NETCOREAPP3_0_OR_GREATER +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; @@ -150,14 +154,8 @@ public static void Sqrt(ulong[] x, ulong[] z) { ulong[] odd = Nat192.Create64(); - ulong u0, u1; - u0 = Interleave.Unshuffle(x[0]); u1 = Interleave.Unshuffle(x[1]); - ulong e0 = (u0 & 0x00000000FFFFFFFFUL) | (u1 << 32); - odd[0] = (u0 >> 32) | (u1 & 0xFFFFFFFF00000000UL); - - u0 = Interleave.Unshuffle(x[2]); - ulong e1 = (u0 & 0x00000000FFFFFFFFUL); - odd[1] = (u0 >> 32); + odd[0] = Interleave.Unshuffle(x[0], x[1], out ulong e0); + odd[1] = Interleave.Unshuffle(x[2] , out ulong e1); Multiply(odd, ROOT_Z, z); @@ -213,6 +211,34 @@ protected static void ImplCompactExt(ulong[] zz) protected static void ImplMultiply(ulong[] x, ulong[] y, ulong[] zz) { +#if NETCOREAPP3_0_OR_GREATER + if (Pclmulqdq.IsSupported) + { + var X01 = Vector128.Create(x[0], x[1]); + var X2_ = Vector128.CreateScalar(x[2]); + var Y01 = Vector128.Create(y[0], y[1]); + var Y2_ = Vector128.CreateScalar(y[2]); + + var Z01 = Pclmulqdq.CarrylessMultiply(X01, Y01, 0x00); + var Z12 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y01, 0x01), + Pclmulqdq.CarrylessMultiply(X01, Y01, 0x10)); + var Z23 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y2_, 0x00), + Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y01, 0x11), + Pclmulqdq.CarrylessMultiply(X2_, Y01, 0x00))); + var Z34 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y2_, 0x01), + Pclmulqdq.CarrylessMultiply(X2_, Y01, 0x10)); + var Z45 = Pclmulqdq.CarrylessMultiply(X2_, Y2_, 0x00); + + zz[0] = Z01.GetElement(0); + zz[1] = Z01.GetElement(1) ^ Z12.GetElement(0); + zz[2] = Z23.GetElement(0) ^ Z12.GetElement(1); + zz[3] = Z23.GetElement(1) ^ Z34.GetElement(0); + zz[4] = Z45.GetElement(0) ^ Z34.GetElement(1); + zz[5] = Z45.GetElement(1); + return; + } +#endif + /* * "Five-way recursion" as described in "Batch binary Edwards", Daniel J. Bernstein. */ diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163K1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163K1Curve.cs index d96c6cc..0bc01e8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163K1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163K1Curve.cs @@ -66,14 +66,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecT163FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecT163K1Point(this, x, y, withCompression); + return new SecT163K1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecT163K1Point(this, x, y, zs, withCompression); + return new SecT163K1Point(this, x, y, zs); } public override bool IsKoblitz @@ -178,7 +178,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(ulong[] x, ulong[] y) { - return m_outer.CreateRawPoint(new SecT163FieldElement(x), new SecT163FieldElement(y), SECT163K1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecT163FieldElement(x), new SecT163FieldElement(y), SECT163K1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163K1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163K1Point.cs index a64fb45..c0d8373 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163K1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163K1Point.cs @@ -7,26 +7,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecT163K1Point : AbstractF2mPoint { - /** - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecT163K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecT163K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} - */ - public SecT163K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecT163K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecT163K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -136,7 +123,7 @@ public override ECPoint Add(ECPoint b) X3 = L.Square().Add(L).Add(X1).AddOne(); if (X3.IsZero) { - return new SecT163K1Point(curve, X3, curve.B, IsCompressed); + return new SecT163K1Point(curve, X3, curve.B); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); @@ -153,7 +140,7 @@ public override ECPoint Add(ECPoint b) X3 = AU1.Multiply(AU2); if (X3.IsZero) { - return new SecT163K1Point(curve, X3, curve.B, IsCompressed); + return new SecT163K1Point(curve, X3, curve.B); } ECFieldElement ABZ2 = A.Multiply(B); @@ -171,7 +158,7 @@ public override ECPoint Add(ECPoint b) } } - return new SecT163K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT163K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Twice() @@ -198,7 +185,7 @@ public override ECPoint Twice() ECFieldElement T = L1.Square().Add(L1Z1).Add(Z1Sq); if (T.IsZero) { - return new SecT163K1Point(curve, T, curve.B, IsCompressed); + return new SecT163K1Point(curve, T, curve.B); } ECFieldElement X3 = T.Square(); @@ -207,7 +194,7 @@ public override ECPoint Twice() ECFieldElement t1 = L1.Add(X1).Square(); ECFieldElement L3 = t1.Add(T).Add(Z1Sq).Multiply(t1).Add(X3); - return new SecT163K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT163K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -256,14 +243,14 @@ public override ECPoint TwicePlus(ECPoint b) if (A.IsZero) { - return new SecT163K1Point(curve, A, curve.B, IsCompressed); + return new SecT163K1Point(curve, A, curve.B); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2.AddOne(), Z3); - return new SecT163K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT163K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Negate() @@ -277,7 +264,7 @@ public override ECPoint Negate() // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; - return new SecT163K1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }, IsCompressed); + return new SecT163K1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163R1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163R1Curve.cs index d8b9905..5dff820 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163R1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163R1Curve.cs @@ -60,14 +60,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecT163FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecT163R1Point(this, x, y, withCompression); + return new SecT163R1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecT163R1Point(this, x, y, zs, withCompression); + return new SecT163R1Point(this, x, y, zs); } public override bool IsKoblitz @@ -172,7 +172,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(ulong[] x, ulong[] y) { - return m_outer.CreateRawPoint(new SecT163FieldElement(x), new SecT163FieldElement(y), SECT163R1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecT163FieldElement(x), new SecT163FieldElement(y), SECT163R1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163R1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163R1Point.cs index 46e1871..ec59f1f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163R1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163R1Point.cs @@ -7,26 +7,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecT163R1Point : AbstractF2mPoint { - /** - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecT163R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecT163R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} - */ - public SecT163R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecT163R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecT163R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -136,7 +123,7 @@ public override ECPoint Add(ECPoint b) X3 = L.Square().Add(L).Add(X1).Add(curve.A); if (X3.IsZero) { - return new SecT163R1Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT163R1Point(curve, X3, curve.B.Sqrt()); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); @@ -153,7 +140,7 @@ public override ECPoint Add(ECPoint b) X3 = AU1.Multiply(AU2); if (X3.IsZero) { - return new SecT163R1Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT163R1Point(curve, X3, curve.B.Sqrt()); } ECFieldElement ABZ2 = A.Multiply(B); @@ -171,7 +158,7 @@ public override ECPoint Add(ECPoint b) } } - return new SecT163R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT163R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Twice() @@ -200,7 +187,7 @@ public override ECPoint Twice() ECFieldElement T = L1.Square().Add(L1Z1).Add(aZ1Sq); if (T.IsZero) { - return new SecT163R1Point(curve, T, curve.B.Sqrt(), IsCompressed); + return new SecT163R1Point(curve, T, curve.B.Sqrt()); } ECFieldElement X3 = T.Square(); @@ -209,7 +196,7 @@ public override ECPoint Twice() ECFieldElement X1Z1 = Z1IsOne ? X1 : X1.Multiply(Z1); ECFieldElement L3 = X1Z1.SquarePlusProduct(T, L1Z1).Add(X3).Add(Z3); - return new SecT163R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT163R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -258,14 +245,14 @@ public override ECPoint TwicePlus(ECPoint b) if (A.IsZero) { - return new SecT163R1Point(curve, A, curve.B.Sqrt(), IsCompressed); + return new SecT163R1Point(curve, A, curve.B.Sqrt()); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2plus1, Z3); - return new SecT163R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT163R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Negate() @@ -279,7 +266,7 @@ public override ECPoint Negate() // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; - return new SecT163R1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }, IsCompressed); + return new SecT163R1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163R2Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163R2Curve.cs index 044c1d7..504bb31 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163R2Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163R2Curve.cs @@ -60,14 +60,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecT163FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecT163R2Point(this, x, y, withCompression); + return new SecT163R2Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecT163R2Point(this, x, y, zs, withCompression); + return new SecT163R2Point(this, x, y, zs); } public override bool IsKoblitz @@ -172,7 +172,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(ulong[] x, ulong[] y) { - return m_outer.CreateRawPoint(new SecT163FieldElement(x), new SecT163FieldElement(y), SECT163R2_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecT163FieldElement(x), new SecT163FieldElement(y), SECT163R2_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163R2Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163R2Point.cs index 5f8d6ad..4a01500 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163R2Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT163R2Point.cs @@ -7,26 +7,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecT163R2Point : AbstractF2mPoint { - /** - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecT163R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecT163R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} - */ - public SecT163R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecT163R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecT163R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -138,7 +125,7 @@ public override ECPoint Add(ECPoint b) X3 = L.Square().Add(L).Add(X1).AddOne(); if (X3.IsZero) { - return new SecT163R2Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT163R2Point(curve, X3, curve.B.Sqrt()); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); @@ -155,7 +142,7 @@ public override ECPoint Add(ECPoint b) X3 = AU1.Multiply(AU2); if (X3.IsZero) { - return new SecT163R2Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT163R2Point(curve, X3, curve.B.Sqrt()); } ECFieldElement ABZ2 = A.Multiply(B); @@ -173,7 +160,7 @@ public override ECPoint Add(ECPoint b) } } - return new SecT163R2Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT163R2Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Twice() @@ -200,7 +187,7 @@ public override ECPoint Twice() ECFieldElement T = L1.Square().Add(L1Z1).Add(Z1Sq); if (T.IsZero) { - return new SecT163R2Point(curve, T, curve.B.Sqrt(), IsCompressed); + return new SecT163R2Point(curve, T, curve.B.Sqrt()); } ECFieldElement X3 = T.Square(); @@ -209,7 +196,7 @@ public override ECPoint Twice() ECFieldElement X1Z1 = Z1IsOne ? X1 : X1.Multiply(Z1); ECFieldElement L3 = X1Z1.SquarePlusProduct(T, L1Z1).Add(X3).Add(Z3); - return new SecT163R2Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT163R2Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -261,14 +248,14 @@ public override ECPoint TwicePlus(ECPoint b) if (A.IsZero) { - return new SecT163R2Point(curve, A, curve.B.Sqrt(), IsCompressed); + return new SecT163R2Point(curve, A, curve.B.Sqrt()); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2.AddOne(), Z3); - return new SecT163R2Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT163R2Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Negate() @@ -282,7 +269,7 @@ public override ECPoint Negate() // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; - return new SecT163R2Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }, IsCompressed); + return new SecT163R2Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193Field.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193Field.cs index 8e7dea1..a76731b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193Field.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193Field.cs @@ -2,6 +2,10 @@ #pragma warning disable using System; using System.Diagnostics; +#if NETCOREAPP3_0_OR_GREATER +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; @@ -157,14 +161,9 @@ public static void Reduce63(ulong[] z, int zOff) public static void Sqrt(ulong[] x, ulong[] z) { - ulong u0, u1; - u0 = Interleave.Unshuffle(x[0]); u1 = Interleave.Unshuffle(x[1]); - ulong e0 = (u0 & 0x00000000FFFFFFFFUL) | (u1 << 32); - ulong c0 = (u0 >> 32) | (u1 & 0xFFFFFFFF00000000UL); - - u0 = Interleave.Unshuffle(x[2]); - ulong e1 = (u0 & 0x00000000FFFFFFFFUL) ^ (x[3] << 32); - ulong c1 = (u0 >> 32); + ulong c0 = Interleave.Unshuffle(x[0], x[1], out ulong e0); + ulong c1 = Interleave.Unshuffle(x[2] , out ulong e1); + e1 ^= x[3] << 32; z[0] = e0 ^ (c0 << 8); z[1] = e1 ^ (c1 << 8) ^ (c0 >> 56) ^ (c0 << 33); @@ -233,6 +232,38 @@ protected static void ImplExpand(ulong[] x, ulong[] z) protected static void ImplMultiply(ulong[] x, ulong[] y, ulong[] zz) { +#if NETCOREAPP3_0_OR_GREATER + if (Pclmulqdq.IsSupported) + { + var X01 = Vector128.Create(x[0], x[1]); + var X2_ = Vector128.CreateScalar(x[2]); + var Y01 = Vector128.Create(y[0], y[1]); + var Y2_ = Vector128.CreateScalar(y[2]); + + var Z01 = Pclmulqdq.CarrylessMultiply(X01, Y01, 0x00); + var Z12 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y01, 0x01), + Pclmulqdq.CarrylessMultiply(X01, Y01, 0x10)); + var Z23 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y2_, 0x00), + Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y01, 0x11), + Pclmulqdq.CarrylessMultiply(X2_, Y01, 0x00))); + var Z34 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y2_, 0x01), + Pclmulqdq.CarrylessMultiply(X2_, Y01, 0x10)); + var Z45 = Pclmulqdq.CarrylessMultiply(X2_, Y2_, 0x00); + + ulong X3M = 0UL - x[3]; + ulong Y3M = 0UL - y[3]; + + zz[0] = Z01.GetElement(0); + zz[1] = Z01.GetElement(1) ^ Z12.GetElement(0); + zz[2] = Z23.GetElement(0) ^ Z12.GetElement(1); + zz[3] = Z23.GetElement(1) ^ Z34.GetElement(0) ^ (X3M & y[0]) ^ (x[0] & Y3M); + zz[4] = Z45.GetElement(0) ^ Z34.GetElement(1) ^ (X3M & y[1]) ^ (x[1] & Y3M); + zz[5] = Z45.GetElement(1) ^ (X3M & y[2]) ^ (x[2] & Y3M); + zz[6] = X3M & y[3]; + return; + } +#endif + /* * "Two-level seven-way recursion" as described in "Batch binary Edwards", Daniel J. Bernstein. */ diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193R1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193R1Curve.cs index 05e5cfa..db7c136 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193R1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193R1Curve.cs @@ -60,14 +60,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecT193FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecT193R1Point(this, x, y, withCompression); + return new SecT193R1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecT193R1Point(this, x, y, zs, withCompression); + return new SecT193R1Point(this, x, y, zs); } public override bool IsKoblitz @@ -172,7 +172,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(ulong[] x, ulong[] y) { - return m_outer.CreateRawPoint(new SecT193FieldElement(x), new SecT193FieldElement(y), SECT193R1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecT193FieldElement(x), new SecT193FieldElement(y), SECT193R1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193R1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193R1Point.cs index dfbe58b..30d414e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193R1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193R1Point.cs @@ -7,26 +7,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecT193R1Point : AbstractF2mPoint { - /** - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecT193R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecT193R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} - */ - public SecT193R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecT193R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecT193R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -136,7 +123,7 @@ public override ECPoint Add(ECPoint b) X3 = L.Square().Add(L).Add(X1).Add(curve.A); if (X3.IsZero) { - return new SecT193R1Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT193R1Point(curve, X3, curve.B.Sqrt()); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); @@ -153,7 +140,7 @@ public override ECPoint Add(ECPoint b) X3 = AU1.Multiply(AU2); if (X3.IsZero) { - return new SecT193R1Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT193R1Point(curve, X3, curve.B.Sqrt()); } ECFieldElement ABZ2 = A.Multiply(B); @@ -171,7 +158,7 @@ public override ECPoint Add(ECPoint b) } } - return new SecT193R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT193R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Twice() @@ -200,7 +187,7 @@ public override ECPoint Twice() ECFieldElement T = L1.Square().Add(L1Z1).Add(aZ1Sq); if (T.IsZero) { - return new SecT193R1Point(curve, T, curve.B.Sqrt(), IsCompressed); + return new SecT193R1Point(curve, T, curve.B.Sqrt()); } ECFieldElement X3 = T.Square(); @@ -209,7 +196,7 @@ public override ECPoint Twice() ECFieldElement X1Z1 = Z1IsOne ? X1 : X1.Multiply(Z1); ECFieldElement L3 = X1Z1.SquarePlusProduct(T, L1Z1).Add(X3).Add(Z3); - return new SecT193R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT193R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -258,14 +245,14 @@ public override ECPoint TwicePlus(ECPoint b) if (A.IsZero) { - return new SecT193R1Point(curve, A, curve.B.Sqrt(), IsCompressed); + return new SecT193R1Point(curve, A, curve.B.Sqrt()); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2plus1, Z3); - return new SecT193R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT193R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Negate() @@ -279,7 +266,7 @@ public override ECPoint Negate() // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; - return new SecT193R1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }, IsCompressed); + return new SecT193R1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193R2Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193R2Curve.cs index 79670bd..10b970d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193R2Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193R2Curve.cs @@ -60,14 +60,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecT193FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecT193R2Point(this, x, y, withCompression); + return new SecT193R2Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecT193R2Point(this, x, y, zs, withCompression); + return new SecT193R2Point(this, x, y, zs); } public override bool IsKoblitz @@ -172,7 +172,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(ulong[] x, ulong[] y) { - return m_outer.CreateRawPoint(new SecT193FieldElement(x), new SecT193FieldElement(y), SECT193R2_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecT193FieldElement(x), new SecT193FieldElement(y), SECT193R2_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193R2Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193R2Point.cs index c6b4449..e5b8132 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193R2Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT193R2Point.cs @@ -7,26 +7,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecT193R2Point : AbstractF2mPoint { - /** - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecT193R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecT193R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} - */ - public SecT193R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecT193R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecT193R2Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -136,7 +123,7 @@ public override ECPoint Add(ECPoint b) X3 = L.Square().Add(L).Add(X1).Add(curve.A); if (X3.IsZero) { - return new SecT193R2Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT193R2Point(curve, X3, curve.B.Sqrt()); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); @@ -153,7 +140,7 @@ public override ECPoint Add(ECPoint b) X3 = AU1.Multiply(AU2); if (X3.IsZero) { - return new SecT193R2Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT193R2Point(curve, X3, curve.B.Sqrt()); } ECFieldElement ABZ2 = A.Multiply(B); @@ -171,7 +158,7 @@ public override ECPoint Add(ECPoint b) } } - return new SecT193R2Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT193R2Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Twice() @@ -200,7 +187,7 @@ public override ECPoint Twice() ECFieldElement T = L1.Square().Add(L1Z1).Add(aZ1Sq); if (T.IsZero) { - return new SecT193R2Point(curve, T, curve.B.Sqrt(), IsCompressed); + return new SecT193R2Point(curve, T, curve.B.Sqrt()); } ECFieldElement X3 = T.Square(); @@ -209,7 +196,7 @@ public override ECPoint Twice() ECFieldElement X1Z1 = Z1IsOne ? X1 : X1.Multiply(Z1); ECFieldElement L3 = X1Z1.SquarePlusProduct(T, L1Z1).Add(X3).Add(Z3); - return new SecT193R2Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT193R2Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -258,14 +245,14 @@ public override ECPoint TwicePlus(ECPoint b) if (A.IsZero) { - return new SecT193R2Point(curve, A, curve.B.Sqrt(), IsCompressed); + return new SecT193R2Point(curve, A, curve.B.Sqrt()); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2plus1, Z3); - return new SecT193R2Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT193R2Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Negate() @@ -279,7 +266,7 @@ public override ECPoint Negate() // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; - return new SecT193R2Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }, IsCompressed); + return new SecT193R2Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233Field.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233Field.cs index f3d3cec..12913f2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233Field.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233Field.cs @@ -2,6 +2,10 @@ #pragma warning disable using System; using System.Diagnostics; +#if NETCOREAPP3_0_OR_GREATER +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; @@ -153,14 +157,8 @@ public static void Reduce23(ulong[] z, int zOff) public static void Sqrt(ulong[] x, ulong[] z) { - ulong u0, u1; - u0 = Interleave.Unshuffle(x[0]); u1 = Interleave.Unshuffle(x[1]); - ulong e0 = (u0 & 0x00000000FFFFFFFFUL) | (u1 << 32); - ulong c0 = (u0 >> 32) | (u1 & 0xFFFFFFFF00000000UL); - - u0 = Interleave.Unshuffle(x[2]); u1 = Interleave.Unshuffle(x[3]); - ulong e1 = (u0 & 0x00000000FFFFFFFFUL) | (u1 << 32); - ulong c1 = (u0 >> 32) | (u1 & 0xFFFFFFFF00000000UL); + ulong c0 = Interleave.Unshuffle(x[0], x[1], out ulong e0); + ulong c1 = Interleave.Unshuffle(x[2], x[3], out ulong e1); ulong c2; c2 = (c1 >> 27); @@ -245,6 +243,54 @@ protected static void ImplExpand(ulong[] x, ulong[] z) protected static void ImplMultiply(ulong[] x, ulong[] y, ulong[] zz) { +#if NETCOREAPP3_0_OR_GREATER + if (Pclmulqdq.IsSupported) + { + var X01 = Vector128.Create(x[0], x[1]); + var X23 = Vector128.Create(x[2], x[3]); + var Y01 = Vector128.Create(y[0], y[1]); + var Y23 = Vector128.Create(y[2], y[3]); + var X03 = Sse2.Xor(X01, X23); + var Y03 = Sse2.Xor(Y01, Y23); + + var Z01 = Pclmulqdq.CarrylessMultiply(X01, Y01, 0x00); + var Z12 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y01, 0x01), + Pclmulqdq.CarrylessMultiply(X01, Y01, 0x10)); + var Z23 = Pclmulqdq.CarrylessMultiply(X01, Y01, 0x11); + + var Z45 = Pclmulqdq.CarrylessMultiply(X23, Y23, 0x00); + var Z56 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X23, Y23, 0x01), + Pclmulqdq.CarrylessMultiply(X23, Y23, 0x10)); + var Z67 = Pclmulqdq.CarrylessMultiply(X23, Y23, 0x11); + + var K01 = Pclmulqdq.CarrylessMultiply(X03, Y03, 0x00); + var K12 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X03, Y03, 0x01), + Pclmulqdq.CarrylessMultiply(X03, Y03, 0x10)); + var K23 = Pclmulqdq.CarrylessMultiply(X03, Y03, 0x11); + + K01 = Sse2.Xor(K01, Z01); + K12 = Sse2.Xor(K12, Z12); + K23 = Sse2.Xor(K23, Z23); + + K01 = Sse2.Xor(K01, Z45); + K12 = Sse2.Xor(K12, Z56); + K23 = Sse2.Xor(K23, Z67); + + Z23 = Sse2.Xor(Z23, K01); + Z45 = Sse2.Xor(Z45, K23); + + zz[0] = Z01.GetElement(0); + zz[1] = Z01.GetElement(1) ^ Z12.GetElement(0); + zz[2] = Z23.GetElement(0) ^ Z12.GetElement(1); + zz[3] = Z23.GetElement(1) ^ K12.GetElement(0); + zz[4] = Z45.GetElement(0) ^ K12.GetElement(1); + zz[5] = Z45.GetElement(1) ^ Z56.GetElement(0); + zz[6] = Z67.GetElement(0) ^ Z56.GetElement(1); + zz[7] = Z67.GetElement(1); + return; + } +#endif + /* * "Two-level seven-way recursion" as described in "Batch binary Edwards", Daniel J. Bernstein. */ diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233K1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233K1Curve.cs index d750f7c..aa6d452 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233K1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233K1Curve.cs @@ -61,14 +61,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecT233FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecT233K1Point(this, x, y, withCompression); + return new SecT233K1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecT233K1Point(this, x, y, zs, withCompression); + return new SecT233K1Point(this, x, y, zs); } public override ECPoint Infinity @@ -178,7 +178,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(ulong[] x, ulong[] y) { - return m_outer.CreateRawPoint(new SecT233FieldElement(x), new SecT233FieldElement(y), SECT233K1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecT233FieldElement(x), new SecT233FieldElement(y), SECT233K1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233K1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233K1Point.cs index 7f73990..66d270f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233K1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233K1Point.cs @@ -7,32 +7,19 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecT233K1Point : AbstractF2mPoint { - /** - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecT233K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecT233K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} - */ - public SecT233K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecT233K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecT233K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } protected override ECPoint Detach() { - return new SecT233K1Point(null, this.AffineXCoord, this.AffineYCoord); // earlier JDK + return new SecT233K1Point(null, this.AffineXCoord, this.AffineYCoord); } public override ECFieldElement YCoord @@ -138,7 +125,7 @@ public override ECPoint Add(ECPoint b) X3 = L.Square().Add(L).Add(X1); if (X3.IsZero) { - return new SecT233K1Point(curve, X3, curve.B, IsCompressed); + return new SecT233K1Point(curve, X3, curve.B); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); @@ -155,7 +142,7 @@ public override ECPoint Add(ECPoint b) X3 = AU1.Multiply(AU2); if (X3.IsZero) { - return new SecT233K1Point(curve, X3, curve.B, IsCompressed); + return new SecT233K1Point(curve, X3, curve.B); } ECFieldElement ABZ2 = A.Multiply(B); @@ -173,7 +160,7 @@ public override ECPoint Add(ECPoint b) } } - return new SecT233K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT233K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Twice() @@ -208,7 +195,7 @@ public override ECPoint Twice() if (T.IsZero) { - return new SecT233K1Point(curve, T, curve.B, IsCompressed); + return new SecT233K1Point(curve, T, curve.B); } ECFieldElement X3 = T.Square(); @@ -218,7 +205,7 @@ public override ECPoint Twice() ECFieldElement t2 = Z1IsOne ? Z1 : Z1Sq.Square(); ECFieldElement L3 = t1.Add(T).Add(Z1Sq).Multiply(t1).Add(t2).Add(X3).Add(Z3); - return new SecT233K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT233K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -270,14 +257,14 @@ public override ECPoint TwicePlus(ECPoint b) if (A.IsZero) { - return new SecT233K1Point(curve, A, curve.B, IsCompressed); + return new SecT233K1Point(curve, A, curve.B); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2plus1, Z3); - return new SecT233K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT233K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Negate() @@ -291,7 +278,7 @@ public override ECPoint Negate() // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; - return new SecT233K1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }, IsCompressed); + return new SecT233K1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233R1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233R1Curve.cs index 383dded..44ab98b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233R1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233R1Curve.cs @@ -60,14 +60,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecT233FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecT233R1Point(this, x, y, withCompression); + return new SecT233R1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecT233R1Point(this, x, y, zs, withCompression); + return new SecT233R1Point(this, x, y, zs); } public override bool IsKoblitz @@ -172,7 +172,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(ulong[] x, ulong[] y) { - return m_outer.CreateRawPoint(new SecT233FieldElement(x), new SecT233FieldElement(y), SECT233R1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecT233FieldElement(x), new SecT233FieldElement(y), SECT233R1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233R1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233R1Point.cs index 157ca4c..f35013a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233R1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT233R1Point.cs @@ -7,26 +7,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecT233R1Point : AbstractF2mPoint { - /** - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecT233R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecT233R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} - */ - public SecT233R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecT233R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecT233R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -136,7 +123,7 @@ public override ECPoint Add(ECPoint b) X3 = L.Square().Add(L).Add(X1).AddOne(); if (X3.IsZero) { - return new SecT233R1Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT233R1Point(curve, X3, curve.B.Sqrt()); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); @@ -153,7 +140,7 @@ public override ECPoint Add(ECPoint b) X3 = AU1.Multiply(AU2); if (X3.IsZero) { - return new SecT233R1Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT233R1Point(curve, X3, curve.B.Sqrt()); } ECFieldElement ABZ2 = A.Multiply(B); @@ -171,7 +158,7 @@ public override ECPoint Add(ECPoint b) } } - return new SecT233R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT233R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Twice() @@ -196,7 +183,7 @@ public override ECPoint Twice() ECFieldElement T = L1.Square().Add(L1Z1).Add(Z1Sq); if (T.IsZero) { - return new SecT233R1Point(curve, T, curve.B.Sqrt(), IsCompressed); + return new SecT233R1Point(curve, T, curve.B.Sqrt()); } ECFieldElement X3 = T.Square(); @@ -205,7 +192,7 @@ public override ECPoint Twice() ECFieldElement X1Z1 = Z1IsOne ? X1 : X1.Multiply(Z1); ECFieldElement L3 = X1Z1.SquarePlusProduct(T, L1Z1).Add(X3).Add(Z3); - return new SecT233R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT233R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -253,14 +240,14 @@ public override ECPoint TwicePlus(ECPoint b) if (A.IsZero) { - return new SecT233R1Point(curve, A, curve.B.Sqrt(), IsCompressed); + return new SecT233R1Point(curve, A, curve.B.Sqrt()); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2.AddOne(), Z3); - return new SecT233R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT233R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Negate() @@ -274,7 +261,7 @@ public override ECPoint Negate() // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; - return new SecT233R1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }, IsCompressed); + return new SecT233R1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT239Field.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT239Field.cs index 589195f..022768b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT239Field.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT239Field.cs @@ -2,6 +2,10 @@ #pragma warning disable using System; using System.Diagnostics; +#if NETCOREAPP3_0_OR_GREATER +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; @@ -161,14 +165,8 @@ public static void Reduce17(ulong[] z, int zOff) public static void Sqrt(ulong[] x, ulong[] z) { - ulong u0, u1; - u0 = Interleave.Unshuffle(x[0]); u1 = Interleave.Unshuffle(x[1]); - ulong e0 = (u0 & 0x00000000FFFFFFFFUL) | (u1 << 32); - ulong c0 = (u0 >> 32) | (u1 & 0xFFFFFFFF00000000UL); - - u0 = Interleave.Unshuffle(x[2]); u1 = Interleave.Unshuffle(x[3]); - ulong e1 = (u0 & 0x00000000FFFFFFFFUL) | (u1 << 32); - ulong c1 = (u0 >> 32) | (u1 & 0xFFFFFFFF00000000UL); + ulong c0 = Interleave.Unshuffle(x[0], x[1], out ulong e0); + ulong c1 = Interleave.Unshuffle(x[2], x[3], out ulong e1); ulong c2, c3; c3 = (c1 >> 49); @@ -254,6 +252,54 @@ protected static void ImplExpand(ulong[] x, ulong[] z) protected static void ImplMultiply(ulong[] x, ulong[] y, ulong[] zz) { +#if NETCOREAPP3_0_OR_GREATER + if (Pclmulqdq.IsSupported) + { + var X01 = Vector128.Create(x[0], x[1]); + var X23 = Vector128.Create(x[2], x[3]); + var Y01 = Vector128.Create(y[0], y[1]); + var Y23 = Vector128.Create(y[2], y[3]); + var X03 = Sse2.Xor(X01, X23); + var Y03 = Sse2.Xor(Y01, Y23); + + var Z01 = Pclmulqdq.CarrylessMultiply(X01, Y01, 0x00); + var Z12 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y01, 0x01), + Pclmulqdq.CarrylessMultiply(X01, Y01, 0x10)); + var Z23 = Pclmulqdq.CarrylessMultiply(X01, Y01, 0x11); + + var Z45 = Pclmulqdq.CarrylessMultiply(X23, Y23, 0x00); + var Z56 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X23, Y23, 0x01), + Pclmulqdq.CarrylessMultiply(X23, Y23, 0x10)); + var Z67 = Pclmulqdq.CarrylessMultiply(X23, Y23, 0x11); + + var K01 = Pclmulqdq.CarrylessMultiply(X03, Y03, 0x00); + var K12 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X03, Y03, 0x01), + Pclmulqdq.CarrylessMultiply(X03, Y03, 0x10)); + var K23 = Pclmulqdq.CarrylessMultiply(X03, Y03, 0x11); + + K01 = Sse2.Xor(K01, Z01); + K12 = Sse2.Xor(K12, Z12); + K23 = Sse2.Xor(K23, Z23); + + K01 = Sse2.Xor(K01, Z45); + K12 = Sse2.Xor(K12, Z56); + K23 = Sse2.Xor(K23, Z67); + + Z23 = Sse2.Xor(Z23, K01); + Z45 = Sse2.Xor(Z45, K23); + + zz[0] = Z01.GetElement(0); + zz[1] = Z01.GetElement(1) ^ Z12.GetElement(0); + zz[2] = Z23.GetElement(0) ^ Z12.GetElement(1); + zz[3] = Z23.GetElement(1) ^ K12.GetElement(0); + zz[4] = Z45.GetElement(0) ^ K12.GetElement(1); + zz[5] = Z45.GetElement(1) ^ Z56.GetElement(0); + zz[6] = Z67.GetElement(0) ^ Z56.GetElement(1); + zz[7] = Z67.GetElement(1); + return; + } +#endif + /* * "Two-level seven-way recursion" as described in "Batch binary Edwards", Daniel J. Bernstein. */ diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT239K1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT239K1Curve.cs index 2883eef..39f7687 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT239K1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT239K1Curve.cs @@ -66,14 +66,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecT239FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecT239K1Point(this, x, y, withCompression); + return new SecT239K1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecT239K1Point(this, x, y, zs, withCompression); + return new SecT239K1Point(this, x, y, zs); } public override bool IsKoblitz @@ -178,7 +178,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(ulong[] x, ulong[] y) { - return m_outer.CreateRawPoint(new SecT239FieldElement(x), new SecT239FieldElement(y), SECT239K1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecT239FieldElement(x), new SecT239FieldElement(y), SECT239K1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT239K1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT239K1Point.cs index fb781f1..81ead2f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT239K1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT239K1Point.cs @@ -7,32 +7,19 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecT239K1Point : AbstractF2mPoint { - /** - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecT239K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecT239K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} - */ - public SecT239K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecT239K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecT239K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } protected override ECPoint Detach() { - return new SecT239K1Point(null, this.AffineXCoord, this.AffineYCoord); // earlier JDK + return new SecT239K1Point(null, this.AffineXCoord, this.AffineYCoord); } public override ECFieldElement YCoord @@ -136,7 +123,7 @@ public override ECPoint Add(ECPoint b) X3 = L.Square().Add(L).Add(X1); if (X3.IsZero) { - return new SecT239K1Point(curve, X3, curve.B, IsCompressed); + return new SecT239K1Point(curve, X3, curve.B); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); @@ -153,7 +140,7 @@ public override ECPoint Add(ECPoint b) X3 = AU1.Multiply(AU2); if (X3.IsZero) { - return new SecT239K1Point(curve, X3, curve.B, IsCompressed); + return new SecT239K1Point(curve, X3, curve.B); } ECFieldElement ABZ2 = A.Multiply(B); @@ -171,7 +158,7 @@ public override ECPoint Add(ECPoint b) } } - return new SecT239K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT239K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Twice() @@ -205,7 +192,7 @@ public override ECPoint Twice() if (T.IsZero) { - return new SecT239K1Point(curve, T, curve.B, IsCompressed); + return new SecT239K1Point(curve, T, curve.B); } ECFieldElement X3 = T.Square(); @@ -215,7 +202,7 @@ public override ECPoint Twice() ECFieldElement t2 = Z1IsOne ? Z1 : Z1Sq.Square(); ECFieldElement L3 = t1.Add(T).Add(Z1Sq).Multiply(t1).Add(t2).Add(X3).Add(Z3); - return new SecT239K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT239K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -265,14 +252,14 @@ public override ECPoint TwicePlus(ECPoint b) if (A.IsZero) { - return new SecT239K1Point(curve, A, curve.B, IsCompressed); + return new SecT239K1Point(curve, A, curve.B); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2plus1, Z3); - return new SecT239K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT239K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Negate() @@ -286,7 +273,7 @@ public override ECPoint Negate() // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; - return new SecT239K1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }, IsCompressed); + return new SecT239K1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283Field.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283Field.cs index afc5dbb..944dde8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283Field.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283Field.cs @@ -2,6 +2,10 @@ #pragma warning disable using System; using System.Diagnostics; +#if NETCOREAPP3_0_OR_GREATER +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; @@ -160,18 +164,9 @@ public static void Sqrt(ulong[] x, ulong[] z) { ulong[] odd = Nat320.Create64(); - ulong u0, u1; - u0 = Interleave.Unshuffle(x[0]); u1 = Interleave.Unshuffle(x[1]); - ulong e0 = (u0 & 0x00000000FFFFFFFFUL) | (u1 << 32); - odd[0] = (u0 >> 32) | (u1 & 0xFFFFFFFF00000000UL); - - u0 = Interleave.Unshuffle(x[2]); u1 = Interleave.Unshuffle(x[3]); - ulong e1 = (u0 & 0x00000000FFFFFFFFUL) | (u1 << 32); - odd[1] = (u0 >> 32) | (u1 & 0xFFFFFFFF00000000UL); - - u0 = Interleave.Unshuffle(x[4]); - ulong e2 = (u0 & 0x00000000FFFFFFFFUL); - odd[2] = (u0 >> 32); + odd[0] = Interleave.Unshuffle(x[0], x[1], out ulong e0); + odd[1] = Interleave.Unshuffle(x[2], x[3], out ulong e1); + odd[2] = Interleave.Unshuffle(x[4] , out ulong e2); Multiply(odd, ROOT_Z, z); @@ -256,6 +251,56 @@ protected static void ImplExpand(ulong[] x, ulong[] z) protected static void ImplMultiply(ulong[] x, ulong[] y, ulong[] zz) { +#if NETCOREAPP3_0_OR_GREATER + if (Pclmulqdq.IsSupported) + { + var X01 = Vector128.Create(x[0], x[1]); + var X23 = Vector128.Create(x[2], x[3]); + var X4_ = Vector128.CreateScalar(x[4]); + var Y01 = Vector128.Create(y[0], y[1]); + var Y23 = Vector128.Create(y[2], y[3]); + var Y4_ = Vector128.CreateScalar(y[4]); + + var Z01 = Pclmulqdq.CarrylessMultiply(X01, Y01, 0x00); + var Z12 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y01, 0x01), + Pclmulqdq.CarrylessMultiply(X01, Y01, 0x10)); + var Z23 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y23, 0x00), + Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y01, 0x11), + Pclmulqdq.CarrylessMultiply(X23, Y01, 0x00))); + var Z34 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y23, 0x01), + Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y23, 0x10), + Sse2.Xor(Pclmulqdq.CarrylessMultiply(X23, Y01, 0x01), + Pclmulqdq.CarrylessMultiply(X23, Y01, 0x10)))); + var Z45 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y4_, 0x00), + Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y23, 0x11), + Sse2.Xor(Pclmulqdq.CarrylessMultiply(X23, Y23, 0x00), + Sse2.Xor(Pclmulqdq.CarrylessMultiply(X23, Y01, 0x11), + Pclmulqdq.CarrylessMultiply(X4_, Y01, 0x00))))); + var Z56 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X01, Y4_, 0x01), + Sse2.Xor(Pclmulqdq.CarrylessMultiply(X23, Y23, 0x01), + Sse2.Xor(Pclmulqdq.CarrylessMultiply(X23, Y23, 0x10), + Pclmulqdq.CarrylessMultiply(X4_, Y01, 0x10)))); + var Z67 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X23, Y4_, 0x00), + Sse2.Xor(Pclmulqdq.CarrylessMultiply(X23, Y23, 0x11), + Pclmulqdq.CarrylessMultiply(X4_, Y23, 0x00))); + var Z78 = Sse2.Xor(Pclmulqdq.CarrylessMultiply(X23, Y4_, 0x01), + Pclmulqdq.CarrylessMultiply(X4_, Y23, 0x10)); + var Z89 = Pclmulqdq.CarrylessMultiply(X4_, Y4_, 0x00); + + zz[0] = Z01.GetElement(0); + zz[1] = Z01.GetElement(1) ^ Z12.GetElement(0); + zz[2] = Z23.GetElement(0) ^ Z12.GetElement(1); + zz[3] = Z23.GetElement(1) ^ Z34.GetElement(0); + zz[4] = Z45.GetElement(0) ^ Z34.GetElement(1); + zz[5] = Z45.GetElement(1) ^ Z56.GetElement(0); + zz[6] = Z67.GetElement(0) ^ Z56.GetElement(1); + zz[7] = Z67.GetElement(1) ^ Z78.GetElement(0); + zz[8] = Z89.GetElement(0) ^ Z78.GetElement(1); + zz[9] = Z89.GetElement(1); + return; + } +#endif + /* * Formula (17) from "Some New Results on Binary Polynomial Multiplication", * Murat Cenk and M. Anwar Hasan. diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283K1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283K1Curve.cs index 9032803..54dbabd 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283K1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283K1Curve.cs @@ -66,14 +66,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecT283FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecT283K1Point(this, x, y, withCompression); + return new SecT283K1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecT283K1Point(this, x, y, zs, withCompression); + return new SecT283K1Point(this, x, y, zs); } public override bool IsKoblitz @@ -178,7 +178,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(ulong[] x, ulong[] y) { - return m_outer.CreateRawPoint(new SecT283FieldElement(x), new SecT283FieldElement(y), SECT283K1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecT283FieldElement(x), new SecT283FieldElement(y), SECT283K1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283K1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283K1Point.cs index 4519182..25de027 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283K1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283K1Point.cs @@ -7,32 +7,19 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecT283K1Point : AbstractF2mPoint { - /** - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecT283K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecT283K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} - */ - public SecT283K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecT283K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecT283K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } protected override ECPoint Detach() { - return new SecT283K1Point(null, this.AffineXCoord, this.AffineYCoord); // earlier JDK + return new SecT283K1Point(null, this.AffineXCoord, this.AffineYCoord); } public override ECFieldElement YCoord @@ -136,7 +123,7 @@ public override ECPoint Add(ECPoint b) X3 = L.Square().Add(L).Add(X1); if (X3.IsZero) { - return new SecT283K1Point(curve, X3, curve.B, IsCompressed); + return new SecT283K1Point(curve, X3, curve.B); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); @@ -153,7 +140,7 @@ public override ECPoint Add(ECPoint b) X3 = AU1.Multiply(AU2); if (X3.IsZero) { - return new SecT283K1Point(curve, X3, curve.B, IsCompressed); + return new SecT283K1Point(curve, X3, curve.B); } ECFieldElement ABZ2 = A.Multiply(B); @@ -171,7 +158,7 @@ public override ECPoint Add(ECPoint b) } } - return new SecT283K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT283K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Twice() @@ -204,7 +191,7 @@ public override ECPoint Twice() if (T.IsZero) { - return new SecT283K1Point(curve, T, curve.B, IsCompressed); + return new SecT283K1Point(curve, T, curve.B); } ECFieldElement X3 = T.Square(); @@ -214,7 +201,7 @@ public override ECPoint Twice() ECFieldElement t2 = Z1IsOne ? Z1 : Z1Sq.Square(); ECFieldElement L3 = t1.Add(T).Add(Z1Sq).Multiply(t1).Add(t2).Add(X3).Add(Z3); - return new SecT283K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT283K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -264,14 +251,14 @@ public override ECPoint TwicePlus(ECPoint b) if (A.IsZero) { - return new SecT283K1Point(curve, A, curve.B, IsCompressed); + return new SecT283K1Point(curve, A, curve.B); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2plus1, Z3); - return new SecT283K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT283K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Negate() @@ -285,7 +272,7 @@ public override ECPoint Negate() // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; - return new SecT283K1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }, IsCompressed); + return new SecT283K1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283R1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283R1Curve.cs index dce0db7..6743ef5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283R1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283R1Curve.cs @@ -60,14 +60,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecT283FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecT283R1Point(this, x, y, withCompression); + return new SecT283R1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecT283R1Point(this, x, y, zs, withCompression); + return new SecT283R1Point(this, x, y, zs); } public override bool IsKoblitz @@ -172,7 +172,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(ulong[] x, ulong[] y) { - return m_outer.CreateRawPoint(new SecT283FieldElement(x), new SecT283FieldElement(y), SECT283R1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecT283FieldElement(x), new SecT283FieldElement(y), SECT283R1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283R1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283R1Point.cs index 53fee39..87e2cb2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283R1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT283R1Point.cs @@ -7,26 +7,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecT283R1Point : AbstractF2mPoint { - /** - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecT283R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecT283R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} - */ - public SecT283R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecT283R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecT283R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -136,7 +123,7 @@ public override ECPoint Add(ECPoint b) X3 = L.Square().Add(L).Add(X1).AddOne(); if (X3.IsZero) { - return new SecT283R1Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT283R1Point(curve, X3, curve.B.Sqrt()); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); @@ -153,7 +140,7 @@ public override ECPoint Add(ECPoint b) X3 = AU1.Multiply(AU2); if (X3.IsZero) { - return new SecT283R1Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT283R1Point(curve, X3, curve.B.Sqrt()); } ECFieldElement ABZ2 = A.Multiply(B); @@ -171,7 +158,7 @@ public override ECPoint Add(ECPoint b) } } - return new SecT283R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT283R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Twice() @@ -196,7 +183,7 @@ public override ECPoint Twice() ECFieldElement T = L1.Square().Add(L1Z1).Add(Z1Sq); if (T.IsZero) { - return new SecT283R1Point(curve, T, curve.B.Sqrt(), IsCompressed); + return new SecT283R1Point(curve, T, curve.B.Sqrt()); } ECFieldElement X3 = T.Square(); @@ -205,7 +192,7 @@ public override ECPoint Twice() ECFieldElement X1Z1 = Z1IsOne ? X1 : X1.Multiply(Z1); ECFieldElement L3 = X1Z1.SquarePlusProduct(T, L1Z1).Add(X3).Add(Z3); - return new SecT283R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT283R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -253,14 +240,14 @@ public override ECPoint TwicePlus(ECPoint b) if (A.IsZero) { - return new SecT283R1Point(curve, A, curve.B.Sqrt(), IsCompressed); + return new SecT283R1Point(curve, A, curve.B.Sqrt()); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2.AddOne(), Z3); - return new SecT283R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT283R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Negate() @@ -274,7 +261,7 @@ public override ECPoint Negate() // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; - return new SecT283R1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }, IsCompressed); + return new SecT283R1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409Field.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409Field.cs index cb19274..6de0b58 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409Field.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409Field.cs @@ -2,6 +2,10 @@ #pragma warning disable using System; using System.Diagnostics; +#if NETCOREAPP3_0_OR_GREATER +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; @@ -193,22 +197,10 @@ public static void Reduce39(ulong[] z, int zOff) public static void Sqrt(ulong[] x, ulong[] z) { - ulong u0, u1; - u0 = Interleave.Unshuffle(x[0]); u1 = Interleave.Unshuffle(x[1]); - ulong e0 = (u0 & 0x00000000FFFFFFFFUL) | (u1 << 32); - ulong c0 = (u0 >> 32) | (u1 & 0xFFFFFFFF00000000UL); - - u0 = Interleave.Unshuffle(x[2]); u1 = Interleave.Unshuffle(x[3]); - ulong e1 = (u0 & 0x00000000FFFFFFFFUL) | (u1 << 32); - ulong c1 = (u0 >> 32) | (u1 & 0xFFFFFFFF00000000UL); - - u0 = Interleave.Unshuffle(x[4]); u1 = Interleave.Unshuffle(x[5]); - ulong e2 = (u0 & 0x00000000FFFFFFFFUL) | (u1 << 32); - ulong c2 = (u0 >> 32) | (u1 & 0xFFFFFFFF00000000UL); - - u0 = Interleave.Unshuffle(x[6]); - ulong e3 = (u0 & 0x00000000FFFFFFFFUL); - ulong c3 = (u0 >> 32); + ulong c0 = Interleave.Unshuffle(x[0], x[1], out ulong e0); + ulong c1 = Interleave.Unshuffle(x[2], x[3], out ulong e1); + ulong c2 = Interleave.Unshuffle(x[4], x[5], out ulong e2); + ulong c3 = Interleave.Unshuffle(x[6] , out ulong e3); z[0] = e0 ^ (c0 << 44); z[1] = e1 ^ (c1 << 44) ^ (c0 >> 20); @@ -358,6 +350,20 @@ protected static void ImplMulwAcc(ulong[] u, ulong x, ulong y, ulong[] z, int zO Debug.Assert(x >> 59 == 0); Debug.Assert(y >> 59 == 0); +#if NETCOREAPP3_0_OR_GREATER + if (Pclmulqdq.IsSupported) + { + var X = Vector128.CreateScalar(x); + var Y = Vector128.CreateScalar(y); + var Z = Pclmulqdq.CarrylessMultiply(X, Y, 0x00); + ulong z0 = Z.GetElement(0); + ulong z1 = Z.GetElement(1); + z[zOff ] ^= z0 & M59; + z[zOff + 1] ^= (z0 >> 59) ^ (z1 << 5); + return; + } +#endif + //u[0] = 0; u[1] = y; u[2] = u[1] << 1; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409K1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409K1Curve.cs index 8ba1fd5..3d7f3e2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409K1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409K1Curve.cs @@ -66,14 +66,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecT409FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecT409K1Point(this, x, y, withCompression); + return new SecT409K1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecT409K1Point(this, x, y, zs, withCompression); + return new SecT409K1Point(this, x, y, zs); } public override bool IsKoblitz @@ -178,7 +178,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(ulong[] x, ulong[] y) { - return m_outer.CreateRawPoint(new SecT409FieldElement(x), new SecT409FieldElement(y), SECT409K1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecT409FieldElement(x), new SecT409FieldElement(y), SECT409K1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409K1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409K1Point.cs index d3d6af1..c631052 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409K1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409K1Point.cs @@ -7,32 +7,19 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecT409K1Point : AbstractF2mPoint { - /** - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecT409K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecT409K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} - */ - public SecT409K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecT409K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecT409K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } protected override ECPoint Detach() { - return new SecT409K1Point(null, this.AffineXCoord, this.AffineYCoord); // earlier JDK + return new SecT409K1Point(null, this.AffineXCoord, this.AffineYCoord); } public override ECFieldElement YCoord @@ -136,7 +123,7 @@ public override ECPoint Add(ECPoint b) X3 = L.Square().Add(L).Add(X1); if (X3.IsZero) { - return new SecT409K1Point(curve, X3, curve.B, IsCompressed); + return new SecT409K1Point(curve, X3, curve.B); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); @@ -153,7 +140,7 @@ public override ECPoint Add(ECPoint b) X3 = AU1.Multiply(AU2); if (X3.IsZero) { - return new SecT409K1Point(curve, X3, curve.B, IsCompressed); + return new SecT409K1Point(curve, X3, curve.B); } ECFieldElement ABZ2 = A.Multiply(B); @@ -171,7 +158,7 @@ public override ECPoint Add(ECPoint b) } } - return new SecT409K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT409K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Twice() @@ -204,7 +191,7 @@ public override ECPoint Twice() if (T.IsZero) { - return new SecT409K1Point(curve, T, curve.B, IsCompressed); + return new SecT409K1Point(curve, T, curve.B); } ECFieldElement X3 = T.Square(); @@ -214,7 +201,7 @@ public override ECPoint Twice() ECFieldElement t2 = Z1IsOne ? Z1 : Z1Sq.Square(); ECFieldElement L3 = t1.Add(T).Add(Z1Sq).Multiply(t1).Add(t2).Add(X3).Add(Z3); - return new SecT409K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT409K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -264,14 +251,14 @@ public override ECPoint TwicePlus(ECPoint b) if (A.IsZero) { - return new SecT409K1Point(curve, A, curve.B, IsCompressed); + return new SecT409K1Point(curve, A, curve.B); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2plus1, Z3); - return new SecT409K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT409K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Negate() @@ -285,7 +272,7 @@ public override ECPoint Negate() // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; - return new SecT409K1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }, IsCompressed); + return new SecT409K1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409R1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409R1Curve.cs index 3efd40a..570f6fb 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409R1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409R1Curve.cs @@ -60,14 +60,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecT409FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecT409R1Point(this, x, y, withCompression); + return new SecT409R1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecT409R1Point(this, x, y, zs, withCompression); + return new SecT409R1Point(this, x, y, zs); } public override bool IsKoblitz @@ -172,7 +172,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(ulong[] x, ulong[] y) { - return m_outer.CreateRawPoint(new SecT409FieldElement(x), new SecT409FieldElement(y), SECT409R1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecT409FieldElement(x), new SecT409FieldElement(y), SECT409R1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409R1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409R1Point.cs index 4c63cfb..49c17da 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409R1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT409R1Point.cs @@ -7,26 +7,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecT409R1Point : AbstractF2mPoint { - /** - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecT409R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecT409R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} - */ - public SecT409R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecT409R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecT409R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -136,7 +123,7 @@ public override ECPoint Add(ECPoint b) X3 = L.Square().Add(L).Add(X1).AddOne(); if (X3.IsZero) { - return new SecT409R1Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT409R1Point(curve, X3, curve.B.Sqrt()); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); @@ -153,7 +140,7 @@ public override ECPoint Add(ECPoint b) X3 = AU1.Multiply(AU2); if (X3.IsZero) { - return new SecT409R1Point(curve, X3, curve.B.Sqrt(), IsCompressed); + return new SecT409R1Point(curve, X3, curve.B.Sqrt()); } ECFieldElement ABZ2 = A.Multiply(B); @@ -171,7 +158,7 @@ public override ECPoint Add(ECPoint b) } } - return new SecT409R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT409R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Twice() @@ -196,7 +183,7 @@ public override ECPoint Twice() ECFieldElement T = L1.Square().Add(L1Z1).Add(Z1Sq); if (T.IsZero) { - return new SecT409R1Point(curve, T, curve.B.Sqrt(), IsCompressed); + return new SecT409R1Point(curve, T, curve.B.Sqrt()); } ECFieldElement X3 = T.Square(); @@ -205,7 +192,7 @@ public override ECPoint Twice() ECFieldElement X1Z1 = Z1IsOne ? X1 : X1.Multiply(Z1); ECFieldElement L3 = X1Z1.SquarePlusProduct(T, L1Z1).Add(X3).Add(Z3); - return new SecT409R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT409R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -253,14 +240,14 @@ public override ECPoint TwicePlus(ECPoint b) if (A.IsZero) { - return new SecT409R1Point(curve, A, curve.B.Sqrt(), IsCompressed); + return new SecT409R1Point(curve, A, curve.B.Sqrt()); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2.AddOne(), Z3); - return new SecT409R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT409R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Negate() @@ -274,7 +261,7 @@ public override ECPoint Negate() // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; - return new SecT409R1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }, IsCompressed); + return new SecT409R1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571Field.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571Field.cs index 56f7ff6..6c4eaf6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571Field.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571Field.cs @@ -2,6 +2,10 @@ #pragma warning disable using System; using System.Diagnostics; +#if NETCOREAPP3_0_OR_GREATER +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; @@ -17,18 +21,12 @@ internal class SecT571Field public static void Add(ulong[] x, ulong[] y, ulong[] z) { - for (int i = 0; i < 9; ++i) - { - z[i] = x[i] ^ y[i]; - } + Nat.Xor64(9, x, y, z); } private static void Add(ulong[] x, int xOff, ulong[] y, int yOff, ulong[] z, int zOff) { - for (int i = 0; i < 9; ++i) - { - z[zOff + i] = x[xOff + i] ^ y[yOff + i]; - } + Nat.Xor64(9, x, xOff, y, yOff, z, zOff); } public static void AddBothTo(ulong[] x, ulong[] y, ulong[] z) @@ -49,10 +47,7 @@ private static void AddBothTo(ulong[] x, int xOff, ulong[] y, int yOff, ulong[] public static void AddExt(ulong[] xx, ulong[] yy, ulong[] zz) { - for (int i = 0; i < 18; ++i) - { - zz[i] = xx[i] ^ yy[i]; - } + Nat.Xor64(18, xx, yy, zz); } public static void AddOne(ulong[] x, ulong[] z) @@ -66,10 +61,7 @@ public static void AddOne(ulong[] x, ulong[] z) private static void AddTo(ulong[] x, ulong[] z) { - for (int i = 0; i < 9; ++i) - { - z[i] ^= x[i]; - } + Nat.XorTo64(9, x, z); } public static ulong[] FromBigInteger(BigInteger x) @@ -173,6 +165,11 @@ public static void MultiplyPrecompAddToExt(ulong[] x, ulong[] precomp, ulong[] z public static ulong[] PrecompMultiplicand(ulong[] x) { +#if NETCOREAPP3_0_OR_GREATER + ulong[] z = Nat576.Create64(); + Nat576.Copy64(x, z); + return z; +#else /* * Precompute table of all 4-bit products of x (first section) */ @@ -195,6 +192,7 @@ public static ulong[] PrecompMultiplicand(ulong[] x) Nat.ShiftUpBits64(len, t, 0, 4, 0UL, t, len); return t; +#endif } public static void Reduce(ulong[] xx, ulong[] z) @@ -233,19 +231,11 @@ public static void Sqrt(ulong[] x, ulong[] z) { ulong[] evn = Nat576.Create64(), odd = Nat576.Create64(); - int pos = 0; - for (int i = 0; i < 4; ++i) - { - ulong u0 = Interleave.Unshuffle(x[pos++]); - ulong u1 = Interleave.Unshuffle(x[pos++]); - evn[i] = (u0 & 0x00000000FFFFFFFFUL) | (u1 << 32); - odd[i] = (u0 >> 32) | (u1 & 0xFFFFFFFF00000000UL); - } - { - ulong u0 = Interleave.Unshuffle(x[pos]); - evn[4] = (u0 & 0x00000000FFFFFFFFUL); - odd[4] = (u0 >> 32); - } + odd[0] = Interleave.Unshuffle(x[0], x[1], out evn[0]); + odd[1] = Interleave.Unshuffle(x[2], x[3], out evn[1]); + odd[2] = Interleave.Unshuffle(x[4], x[5], out evn[2]); + odd[3] = Interleave.Unshuffle(x[6], x[7], out evn[3]); + odd[4] = Interleave.Unshuffle(x[8] , out evn[4]); Multiply(odd, ROOT_Z, z); Add(z, evn, z); @@ -373,6 +363,9 @@ protected static void ImplMultiply(ulong[] x, ulong[] y, ulong[] zz) protected static void ImplMultiplyPrecomp(ulong[] x, ulong[] precomp, ulong[] zz) { +#if NETCOREAPP3_0_OR_GREATER + ImplMultiply(x, precomp, zz); +#else uint MASK = 0xF; /* @@ -405,10 +398,23 @@ protected static void ImplMultiplyPrecomp(ulong[] x, ulong[] precomp, ulong[] zz Nat.ShiftUpBits64(18, zz, 0, 8, 0UL); } } +#endif } protected static void ImplMulwAcc(ulong[] u, ulong x, ulong y, ulong[] z, int zOff) { +#if NETCOREAPP3_0_OR_GREATER + if (Pclmulqdq.IsSupported) + { + var X = Vector128.CreateScalar(x); + var Y = Vector128.CreateScalar(y); + var Z = Pclmulqdq.CarrylessMultiply(X, Y, 0x00); + z[zOff ] ^= Z.GetElement(0); + z[zOff + 1] ^= Z.GetElement(1); + return; + } +#endif + //u[0] = 0; u[1] = y; for (int i = 2; i < 16; i += 2) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571FieldElement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571FieldElement.cs index c6b2627..b547877 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571FieldElement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571FieldElement.cs @@ -50,7 +50,7 @@ public override BigInteger ToBigInteger() return Nat576.ToBigInteger64(x); } - public override String FieldName + public override string FieldName { get { return "SecT571Field"; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571K1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571K1Curve.cs index 3ff6de2..b3e5041 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571K1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571K1Curve.cs @@ -66,14 +66,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecT571FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecT571K1Point(this, x, y, withCompression); + return new SecT571K1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecT571K1Point(this, x, y, zs, withCompression); + return new SecT571K1Point(this, x, y, zs); } public override bool IsKoblitz @@ -178,7 +178,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(ulong[] x, ulong[] y) { - return m_outer.CreateRawPoint(new SecT571FieldElement(x), new SecT571FieldElement(y), SECT571K1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecT571FieldElement(x), new SecT571FieldElement(y), SECT571K1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571K1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571K1Point.cs index 9c4549f..842ad4a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571K1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571K1Point.cs @@ -9,32 +9,19 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecT571K1Point : AbstractF2mPoint { - /** - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecT571K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecT571K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} - */ - public SecT571K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecT571K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecT571K1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } protected override ECPoint Detach() { - return new SecT571K1Point(null, this.AffineXCoord, this.AffineYCoord); // earlier JDK + return new SecT571K1Point(null, this.AffineXCoord, this.AffineYCoord); } public override ECFieldElement YCoord @@ -156,7 +143,7 @@ public override ECPoint Add(ECPoint b) X3 = (SecT571FieldElement)L.Square().Add(L).Add(X1); if (X3.IsZero) { - return new SecT571K1Point(curve, X3, curve.B, IsCompressed); + return new SecT571K1Point(curve, X3, curve.B); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); @@ -180,7 +167,7 @@ public override ECPoint Add(ECPoint b) if (X3.IsZero) { - return new SecT571K1Point(curve, X3, curve.B, IsCompressed); + return new SecT571K1Point(curve, X3, curve.B); } Z3 = new SecT571FieldElement(t3); @@ -209,7 +196,7 @@ public override ECPoint Add(ECPoint b) } } - return new SecT571K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT571K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Twice() @@ -242,7 +229,7 @@ public override ECPoint Twice() if (T.IsZero) { - return new SecT571K1Point(curve, T, curve.B, IsCompressed); + return new SecT571K1Point(curve, T, curve.B); } ECFieldElement X3 = T.Square(); @@ -252,7 +239,7 @@ public override ECPoint Twice() ECFieldElement t2 = Z1IsOne ? Z1 : Z1Sq.Square(); ECFieldElement L3 = t1.Add(T).Add(Z1Sq).Multiply(t1).Add(t2).Add(X3).Add(Z3); - return new SecT571K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT571K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -302,14 +289,14 @@ public override ECPoint TwicePlus(ECPoint b) if (A.IsZero) { - return new SecT571K1Point(curve, A, curve.B, IsCompressed); + return new SecT571K1Point(curve, A, curve.B); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2plus1, Z3); - return new SecT571K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT571K1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Negate() @@ -323,7 +310,7 @@ public override ECPoint Negate() // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; - return new SecT571K1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }, IsCompressed); + return new SecT571K1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571R1Curve.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571R1Curve.cs index 9b9513e..7600c98 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571R1Curve.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571R1Curve.cs @@ -64,14 +64,14 @@ public override ECFieldElement FromBigInteger(BigInteger x) return new SecT571FieldElement(x); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y) { - return new SecT571R1Point(this, x, y, withCompression); + return new SecT571R1Point(this, x, y); } - protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) + protected internal override ECPoint CreateRawPoint(ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) { - return new SecT571R1Point(this, x, y, zs, withCompression); + return new SecT571R1Point(this, x, y, zs); } public override bool IsKoblitz @@ -176,7 +176,7 @@ public override ECPoint LookupVar(int index) private ECPoint CreatePoint(ulong[] x, ulong[] y) { - return m_outer.CreateRawPoint(new SecT571FieldElement(x), new SecT571FieldElement(y), SECT571R1_AFFINE_ZS, false); + return m_outer.CreateRawPoint(new SecT571FieldElement(x), new SecT571FieldElement(y), SECT571R1_AFFINE_ZS); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571R1Point.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571R1Point.cs index c098a58..95eb0e3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571R1Point.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/custom/sec/SecT571R1Point.cs @@ -9,26 +9,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Custom.Sec internal class SecT571R1Point : AbstractF2mPoint { - /** - * @deprecated Use ECCurve.createPoint to construct points - */ - public SecT571R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) - : this(curve, x, y, false) + internal SecT571R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y) + : base(curve, x, y) { } - /** - * @deprecated per-point compression property will be removed, refer {@link #getEncoded(bool)} - */ - public SecT571R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) - : base(curve, x, y, withCompression) - { - if ((x == null) != (y == null)) - throw new ArgumentException("Exactly one of the field elements is null"); - } - - internal SecT571R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs, bool withCompression) - : base(curve, x, y, zs, withCompression) + internal SecT571R1Point(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs) + : base(curve, x, y, zs) { } @@ -156,7 +143,7 @@ public override ECPoint Add(ECPoint b) X3 = (SecT571FieldElement)L.Square().Add(L).Add(X1).AddOne(); if (X3.IsZero) { - return new SecT571R1Point(curve, X3, SecT571R1Curve.SecT571R1_B_SQRT, IsCompressed); + return new SecT571R1Point(curve, X3, SecT571R1Curve.SecT571R1_B_SQRT); } ECFieldElement Y3 = L.Multiply(X1.Add(X3)).Add(X3).Add(Y1); @@ -180,7 +167,7 @@ public override ECPoint Add(ECPoint b) if (X3.IsZero) { - return new SecT571R1Point(curve, X3, SecT571R1Curve.SecT571R1_B_SQRT, IsCompressed); + return new SecT571R1Point(curve, X3, SecT571R1Curve.SecT571R1_B_SQRT); } Z3 = new SecT571FieldElement(t3); @@ -208,7 +195,7 @@ public override ECPoint Add(ECPoint b) } } - return new SecT571R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT571R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Twice() @@ -249,7 +236,7 @@ public override ECPoint Twice() if (Nat576.IsZero64(T)) { - return new SecT571R1Point(curve, new SecT571FieldElement(T), SecT571R1Curve.SecT571R1_B_SQRT, IsCompressed); + return new SecT571R1Point(curve, new SecT571FieldElement(T), SecT571R1Curve.SecT571R1_B_SQRT); } ulong[] tt = Nat576.CreateExt64(); @@ -279,7 +266,7 @@ public override ECPoint Twice() SecT571Field.AddBothTo(X3.x, Z3.x, t2); SecT571FieldElement L3 = new SecT571FieldElement(t2); - return new SecT571R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT571R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint TwicePlus(ECPoint b) @@ -327,14 +314,14 @@ public override ECPoint TwicePlus(ECPoint b) if (A.IsZero) { - return new SecT571R1Point(curve, A, SecT571R1Curve.SecT571R1_B_SQRT, IsCompressed); + return new SecT571R1Point(curve, A, SecT571R1Curve.SecT571R1_B_SQRT); } ECFieldElement X3 = A.Square().Multiply(X2Z1Sq); ECFieldElement Z3 = A.Multiply(B).Multiply(Z1Sq); ECFieldElement L3 = A.Add(B).Square().MultiplyPlusProduct(T, L2.AddOne(), Z3); - return new SecT571R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }, IsCompressed); + return new SecT571R1Point(curve, X3, L3, new ECFieldElement[] { Z3 }); } public override ECPoint Negate() @@ -348,7 +335,7 @@ public override ECPoint Negate() // L is actually Lambda (X + Y/X) here ECFieldElement L = this.RawYCoord, Z = this.RawZCoords[0]; - return new SecT571R1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }, IsCompressed); + return new SecT571R1Point(Curve, X, L.Add(Z), new ECFieldElement[] { Z }); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/endo/GlvTypeBParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/endo/GlvTypeBParameters.cs index 89f9640..ddcaad9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/endo/GlvTypeBParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/endo/GlvTypeBParameters.cs @@ -9,15 +9,6 @@ public class GlvTypeBParameters protected readonly BigInteger m_beta, m_lambda; protected readonly ScalarSplitParameters m_splitParams; - - public GlvTypeBParameters(BigInteger beta, BigInteger lambda, BigInteger[] v1, BigInteger[] v2, - BigInteger g1, BigInteger g2, int bits) - { - this.m_beta = beta; - this.m_lambda = lambda; - this.m_splitParams = new ScalarSplitParameters(v1, v2, g1, g2, bits); - } - public GlvTypeBParameters(BigInteger beta, BigInteger lambda, ScalarSplitParameters splitParams) { this.m_beta = beta; @@ -39,36 +30,6 @@ public virtual ScalarSplitParameters SplitParams { get { return m_splitParams; } } - - - public virtual BigInteger[] V1 - { - get { return new BigInteger[] { m_splitParams.V1A, m_splitParams.V1B }; } - } - - - public virtual BigInteger[] V2 - { - get { return new BigInteger[] { m_splitParams.V2A, m_splitParams.V2B }; } - } - - - public virtual BigInteger G1 - { - get { return m_splitParams.G1; } - } - - - public virtual BigInteger G2 - { - get { return m_splitParams.G2; } - } - - - public virtual int Bits - { - get { return m_splitParams.Bits; } - } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/multiplier/FixedPointCombMultiplier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/multiplier/FixedPointCombMultiplier.cs index d9046e6..d999eae 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/multiplier/FixedPointCombMultiplier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/multiplier/FixedPointCombMultiplier.cs @@ -30,18 +30,25 @@ protected override ECPoint MultiplyPositive(ECPoint p, BigInteger k) int width = info.Width; int d = (size + width - 1) / width; + int fullComb = d * width; ECPoint R = c.Infinity; - int fullComb = d * width; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int KLen = Nat.GetLengthForBits(fullComb); + Span K = KLen <= 32 + ? stackalloc uint[KLen] + : new uint[KLen]; + Nat.FromBigInteger(fullComb, k, K); +#else uint[] K = Nat.FromBigInteger(fullComb, k); +#endif - int top = fullComb - 1; - for (int i = 0; i < d; ++i) + for (int i = 1; i <= d; ++i) { uint secretIndex = 0; - for (int j = top - i; j >= 0; j -= d) + for (int j = fullComb - i; j >= 0; j -= d) { uint secretBit = K[j >> 5] >> (j & 0x1F); secretIndex ^= secretBit >> 1; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/multiplier/FixedPointUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/multiplier/FixedPointUtilities.cs index 0839a96..7398a50 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/multiplier/FixedPointUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/multiplier/FixedPointUtilities.cs @@ -36,7 +36,7 @@ internal FixedPointCallback(ECPoint p) public PreCompInfo Precompute(PreCompInfo existing) { - FixedPointPreCompInfo existingFP = (existing is FixedPointPreCompInfo) ? (FixedPointPreCompInfo)existing : null; + FixedPointPreCompInfo existingFP = existing as FixedPointPreCompInfo; ECCurve c = m_p.Curve; int bits = FixedPointUtilities.GetCombSize(c); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/multiplier/WNafUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/multiplier/WNafUtilities.cs index 1eeaead..c99a8ed 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/multiplier/WNafUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/multiplier/WNafUtilities.cs @@ -363,18 +363,6 @@ public static int GetWindowSize(int bits, int[] windowSizeCutoffs, int maxWidth) return System.Math.Max(2, System.Math.Min(maxWidth, w + 2)); } - [Obsolete] - public static ECPoint MapPointWithPrecomp(ECPoint p, int minWidth, bool includeNegated, - ECPointMap pointMap) - { - ECCurve c = p.Curve; - WNafPreCompInfo infoP = Precompute(p, minWidth, includeNegated); - - ECPoint q = pointMap.Map(p); - c.Precompute(q, PRECOMP_NAME, new MapPointCallback(infoP, includeNegated, pointMap)); - return q; - } - public static WNafPreCompInfo Precompute(ECPoint p, int minWidth, bool includeNegated) { return (WNafPreCompInfo)p.Curve.Precompute(p, PRECOMP_NAME, diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/multiplier/WTauNafMultiplier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/multiplier/WTauNafMultiplier.cs index 1736cf2..d14130f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/multiplier/WTauNafMultiplier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/multiplier/WTauNafMultiplier.cs @@ -26,10 +26,10 @@ public class WTauNafMultiplier */ protected override ECPoint MultiplyPositive(ECPoint point, BigInteger k) { - if (!(point is AbstractF2mPoint)) + AbstractF2mPoint p = point as AbstractF2mPoint; + if (p == null) throw new ArgumentException("Only AbstractF2mPoint can be used in WTauNafMultiplier"); - AbstractF2mPoint p = (AbstractF2mPoint)point; AbstractF2mCurve curve = (AbstractF2mCurve)p.Curve; int m = curve.FieldSize; sbyte a = (sbyte)curve.A.ToBigInteger().IntValue; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc7748/X25519.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc7748/X25519.cs index 7232bfe..0fe8537 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc7748/X25519.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc7748/X25519.cs @@ -9,13 +9,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc7748 { - public abstract class X25519 + using F = X25519Field; + + public static class X25519 { public const int PointSize = 32; public const int ScalarSize = 32; - private class F : X25519Field {}; - private const int C_A = 486662; private const int C_A24 = (C_A + 2)/4; @@ -28,6 +28,36 @@ public static bool CalculateAgreement(byte[] k, int kOff, byte[] u, int uOff, by return !Arrays.AreAllZeroes(r, rOff, PointSize); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static bool CalculateAgreement(ReadOnlySpan k, ReadOnlySpan u, Span r) + { + ScalarMult(k, u, r); + return !Arrays.AreAllZeroes(r[..PointSize]); + } +#endif + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static uint Decode32(ReadOnlySpan bs) + { + uint n = bs[0]; + n |= (uint)bs[1] << 8; + n |= (uint)bs[2] << 16; + n |= (uint)bs[3] << 24; + return n; + } + + private static void DecodeScalar(ReadOnlySpan k, Span n) + { + for (int i = 0; i < 8; ++i) + { + n[i] = Decode32(k[(i * 4)..]); + } + + n[0] &= 0xFFFFFFF8U; + n[7] &= 0x7FFFFFFFU; + n[7] |= 0x40000000U; + } +#else private static uint Decode32(byte[] bs, int off) { uint n = bs[off]; @@ -48,9 +78,13 @@ private static void DecodeScalar(byte[] k, int kOff, uint[] n) n[7] &= 0x7FFFFFFFU; n[7] |= 0x40000000U; } +#endif public static void GeneratePrivateKey(SecureRandom random, byte[] k) { + if (k.Length != ScalarSize) + throw new ArgumentException(nameof(k)); + random.NextBytes(k); k[0] &= 0xF8; @@ -58,11 +92,32 @@ public static void GeneratePrivateKey(SecureRandom random, byte[] k) k[ScalarSize - 1] |= 0x40; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void GeneratePrivateKey(SecureRandom random, Span k) + { + if (k.Length != ScalarSize) + throw new ArgumentException(nameof(k)); + + random.NextBytes(k); + + k[0] &= 0xF8; + k[ScalarSize - 1] &= 0x7F; + k[ScalarSize - 1] |= 0x40; + } +#endif + public static void GeneratePublicKey(byte[] k, int kOff, byte[] r, int rOff) { ScalarMultBase(k, kOff, r, rOff); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void GeneratePublicKey(ReadOnlySpan k, Span r) + { + ScalarMultBase(k, r); + } +#endif + private static void PointDouble(int[] x, int[] z) { int[] a = F.Create(); @@ -85,6 +140,9 @@ public static void Precompute() public static void ScalarMult(byte[] k, int kOff, byte[] u, int uOff, byte[] r, int rOff) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ScalarMult(k.AsSpan(kOff), u.AsSpan(uOff), r.AsSpan(rOff)); +#else uint[] n = new uint[8]; DecodeScalar(k, kOff, n); int[] x1 = F.Create(); F.Decode(u, uOff, x1); @@ -142,10 +200,77 @@ public static void ScalarMult(byte[] k, int kOff, byte[] u, int uOff, byte[] r, F.Normalize(x2); F.Encode(x2, r, rOff); +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void ScalarMult(ReadOnlySpan k, ReadOnlySpan u, Span r) + { + uint[] n = new uint[8]; DecodeScalar(k, n); + + int[] x1 = F.Create(); F.Decode(u, x1); + int[] x2 = F.Create(); F.Copy(x1, 0, x2, 0); + int[] z2 = F.Create(); z2[0] = 1; + int[] x3 = F.Create(); x3[0] = 1; + int[] z3 = F.Create(); + + int[] t1 = F.Create(); + int[] t2 = F.Create(); + + Debug.Assert(n[7] >> 30 == 1U); + + int bit = 254, swap = 1; + do + { + F.Apm(x3, z3, t1, x3); + F.Apm(x2, z2, z3, x2); + F.Mul(t1, x2, t1); + F.Mul(x3, z3, x3); + F.Sqr(z3, z3); + F.Sqr(x2, x2); + + F.Sub(z3, x2, t2); + F.Mul(t2, C_A24, z2); + F.Add(z2, x2, z2); + F.Mul(z2, t2, z2); + F.Mul(x2, z3, x2); + + F.Apm(t1, x3, x3, z3); + F.Sqr(x3, x3); + F.Sqr(z3, z3); + F.Mul(z3, x1, z3); + + --bit; + + int word = bit >> 5, shift = bit & 0x1F; + int kt = (int)(n[word] >> shift) & 1; + swap ^= kt; + F.CSwap(swap, x2, x3); + F.CSwap(swap, z2, z3); + swap = kt; + } + while (bit >= 3); + + Debug.Assert(swap == 0); + + for (int i = 0; i < 3; ++i) + { + PointDouble(x2, z2); + } + + F.Inv(z2, z2); + F.Mul(x2, z2, x2); + + F.Normalize(x2); + F.Encode(x2, r); + } +#endif + public static void ScalarMultBase(byte[] k, int kOff, byte[] r, int rOff) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ScalarMultBase(k.AsSpan(kOff), r.AsSpan(rOff)); +#else int[] y = F.Create(); int[] z = F.Create(); @@ -158,7 +283,26 @@ public static void ScalarMultBase(byte[] k, int kOff, byte[] r, int rOff) F.Normalize(y); F.Encode(y, r, rOff); +#endif } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void ScalarMultBase(ReadOnlySpan k, Span r) + { + int[] y = F.Create(); + int[] z = F.Create(); + + Ed25519.ScalarMultBaseYZ(k, y, z); + + F.Apm(z, y, y, z); + + F.Inv(z, z); + F.Mul(y, z, y); + + F.Normalize(y); + F.Encode(y, r); + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc7748/X25519Field.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc7748/X25519Field.cs index f7ec5b7..a46fc6d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc7748/X25519Field.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc7748/X25519Field.cs @@ -7,7 +7,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc7748 { - public abstract class X25519Field + public static class X25519Field { public const int Size = 10; @@ -20,8 +20,6 @@ public abstract class X25519Field private static readonly int[] RootNegOne = { 0x020EA0B0, 0x0386C9D2, 0x00478C4E, 0x0035697F, 0x005E8630, 0x01FBD7A7, 0x0340264F, 0x01F0B2B4, 0x00027E0E, 0x00570649 }; - protected X25519Field() {} - public static void Add(int[] x, int[] y, int[] z) { for (int i = 0; i < Size; ++i) @@ -107,6 +105,20 @@ public static void CMov(int cond, int[] x, int xOff, int[] z, int zOff) } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void CMov(int cond, ReadOnlySpan x, Span z) + { + Debug.Assert(0 == cond || -1 == cond); + + for (int i = 0; i < Size; ++i) + { + int z_i = z[i], diff = z_i ^ x[i]; + z_i ^= (diff & cond); + z[i] = z_i; + } + } +#endif + public static void CNegate(int negate, int[] z) { Debug.Assert(negate >> 1 == 0); @@ -126,6 +138,13 @@ public static void Copy(int[] x, int xOff, int[] z, int zOff) } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Copy(ReadOnlySpan x, Span z) + { + x[..Size].CopyTo(z); + } +#endif + public static int[] Create() { return new int[Size]; @@ -151,7 +170,7 @@ public static void CSwap(int swap, int[] a, int[] b) } } - [CLSCompliantAttribute(false)] + [CLSCompliant(false)] public static void Decode(uint[] x, int xOff, int[] z) { Decode128(x, xOff, z, 0); @@ -159,6 +178,16 @@ public static void Decode(uint[] x, int xOff, int[] z) z[9] &= M24; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + [CLSCompliant(false)] + public static void Decode(ReadOnlySpan x, Span z) + { + Decode128(x, z); + Decode128(x[4..], z[5..]); + z[9] &= M24; + } +#endif + public static void Decode(byte[] x, int xOff, int[] z) { Decode128(x, xOff, z, 0); @@ -166,6 +195,15 @@ public static void Decode(byte[] x, int xOff, int[] z) z[9] &= M24; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Decode(ReadOnlySpan x, Span z) + { + Decode128(x, z); + Decode128(x[16..], z[5..]); + z[9] &= M24; + } +#endif + private static void Decode128(uint[] x, int xOff, int[] z, int zOff) { uint t0 = x[xOff + 0], t1 = x[xOff + 1], t2 = x[xOff + 2], t3 = x[xOff + 3]; @@ -177,6 +215,19 @@ private static void Decode128(uint[] x, int xOff, int[] z, int zOff) z[zOff + 4] = (int)(t3 >> 7); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void Decode128(ReadOnlySpan x, Span z) + { + uint t0 = x[0], t1 = x[1], t2 = x[2], t3 = x[3]; + + z[0] = (int)t0 & M26; + z[1] = (int)((t1 << 6) | (t0 >> 26)) & M26; + z[2] = (int)((t2 << 12) | (t1 >> 20)) & M25; + z[3] = (int)((t3 << 19) | (t2 >> 13)) & M26; + z[4] = (int)(t3 >> 7); + } +#endif + private static void Decode128(byte[] bs, int off, int[] z, int zOff) { uint t0 = Decode32(bs, off + 0); @@ -185,12 +236,28 @@ private static void Decode128(byte[] bs, int off, int[] z, int zOff) uint t3 = Decode32(bs, off + 12); z[zOff + 0] = (int)t0 & M26; - z[zOff + 1] = (int)((t1 << 6) | (t0 >> 26)) & M26; + z[zOff + 1] = (int)((t1 << 6) | (t0 >> 26)) & M26; z[zOff + 2] = (int)((t2 << 12) | (t1 >> 20)) & M25; z[zOff + 3] = (int)((t3 << 19) | (t2 >> 13)) & M26; z[zOff + 4] = (int)(t3 >> 7); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void Decode128(ReadOnlySpan bs, Span z) + { + uint t0 = Decode32(bs); + uint t1 = Decode32(bs[4..]); + uint t2 = Decode32(bs[8..]); + uint t3 = Decode32(bs[12..]); + + z[0] = (int)t0 & M26; + z[1] = (int)((t1 << 6) | (t0 >> 26)) & M26; + z[2] = (int)((t2 << 12) | (t1 >> 20)) & M25; + z[3] = (int)((t3 << 19) | (t2 >> 13)) & M26; + z[4] = (int)(t3 >> 7); + } +#endif + private static uint Decode32(byte[] bs, int off) { uint n = bs[off]; @@ -200,19 +267,47 @@ private static uint Decode32(byte[] bs, int off) return n; } - [CLSCompliantAttribute(false)] +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static uint Decode32(ReadOnlySpan bs) + { + uint n = bs[0]; + n |= (uint)bs[1] << 8; + n |= (uint)bs[2] << 16; + n |= (uint)bs[3] << 24; + return n; + } +#endif + + [CLSCompliant(false)] public static void Encode(int[] x, uint[] z, int zOff) { Encode128(x, 0, z, zOff); Encode128(x, 5, z, zOff + 4); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + [CLSCompliant(false)] + public static void Encode(ReadOnlySpan x, Span z) + { + Encode128(x, z); + Encode128(x[5..], z[4..]); + } +#endif + public static void Encode(int[] x, byte[] z, int zOff) { Encode128(x, 0, z, zOff); Encode128(x, 5, z, zOff + 16); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Encode(ReadOnlySpan x, Span z) + { + Encode128(x, z); + Encode128(x[5..], z[16..]); + } +#endif + private static void Encode128(int[] x, int xOff, uint[] z, int zOff) { uint x0 = (uint)x[xOff + 0], x1 = (uint)x[xOff + 1], x2 = (uint)x[xOff + 2], x3 = (uint)x[xOff + 3], @@ -224,6 +319,18 @@ private static void Encode128(int[] x, int xOff, uint[] z, int zOff) z[zOff + 3] = (x3 >> 19) | (x4 << 7); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void Encode128(ReadOnlySpan x, Span z) + { + uint x0 = (uint)x[0], x1 = (uint)x[1], x2 = (uint)x[2], x3 = (uint)x[3], x4 = (uint)x[4]; + + z[0] = x0 | (x1 << 26); + z[1] = (x1 >> 6) | (x2 << 20); + z[2] = (x2 >> 12) | (x3 << 13); + z[3] = (x3 >> 19) | (x4 << 7); + } +#endif + private static void Encode128(int[] x, int xOff, byte[] bs, int off) { uint x0 = (uint)x[xOff + 0], x1 = (uint)x[xOff + 1], x2 = (uint)x[xOff + 2]; @@ -235,6 +342,19 @@ private static void Encode128(int[] x, int xOff, byte[] bs, int off) uint t3 = (x3 >> 19) | (x4 << 7); Encode32(t3, bs, off + 12); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void Encode128(ReadOnlySpan x, Span bs) + { + uint x0 = (uint)x[0], x1 = (uint)x[1], x2 = (uint)x[2]; + uint x3 = (uint)x[3], x4 = (uint)x[4]; + + uint t0 = x0 | (x1 << 26); Encode32(t0, bs); + uint t1 = (x1 >> 6) | (x2 << 20); Encode32(t1, bs[4..]); + uint t2 = (x2 >> 12) | (x3 << 13); Encode32(t2, bs[8..]); + uint t3 = (x3 >> 19) | (x4 << 7); Encode32(t3, bs[12..]); + } +#endif + private static void Encode32(uint n, byte[] bs, int off) { bs[ off] = (byte)(n ); @@ -243,8 +363,21 @@ private static void Encode32(uint n, byte[] bs, int off) bs[++off] = (byte)(n >> 24); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void Encode32(uint n, Span bs) + { + bs[0] = (byte)(n ); + bs[1] = (byte)(n >> 8); + bs[2] = (byte)(n >> 16); + bs[3] = (byte)(n >> 24); + } +#endif + public static void Inv(int[] x, int[] z) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Inv(x.AsSpan(), z.AsSpan()); +#else //int[] x2 = Create(); //int[] t = Create(); //PowPm5d8(x, x2, t); @@ -261,10 +394,30 @@ public static void Inv(int[] x, int[] z) Mod.ModOddInverse(P32, u, u); Decode(u, 0, z); +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Inv(ReadOnlySpan x, Span z) + { + Span t = stackalloc int[Size]; + Span u = stackalloc uint[8]; + + Copy(x, t); + Normalize(t); + Encode(t, u); + + Mod.ModOddInverse(P32, u, u); + + Decode(u, z); + } +#endif + public static void InvVar(int[] x, int[] z) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + InvVar(x.AsSpan(), z.AsSpan()); +#else int[] t = Create(); uint[] u = new uint[8]; @@ -275,7 +428,24 @@ public static void InvVar(int[] x, int[] z) Mod.ModOddInverseVar(P32, u, u); Decode(u, 0, z); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void InvVar(ReadOnlySpan x, Span z) + { + Span t = stackalloc int[Size]; + Span u = stackalloc uint[8]; + + Copy(x, t); + Normalize(t); + Encode(t, u); + + Mod.ModOddInverseVar(P32, u, u); + + Decode(u, z); } +#endif public static int IsOne(int[] x) { @@ -511,6 +681,16 @@ public static void Normalize(int[] z) Debug.Assert(z[9] >> 24 == 0); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Normalize(Span z) + { + int x = (z[9] >> 23) & 1; + Reduce(z, x); + Reduce(z, -x); + Debug.Assert(z[9] >> 24 == 0); + } +#endif + public static void One(int[] z) { z[0] = 1; @@ -560,6 +740,26 @@ private static void Reduce(int[] z, int x) z[9] = z9 + (int)cc; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void Reduce(Span z, int x) + { + int t = z[9], z9 = t & M24; + t = (t >> 24) + x; + + long cc = t * 19; + cc += z[0]; z[0] = (int)cc & M26; cc >>= 26; + cc += z[1]; z[1] = (int)cc & M26; cc >>= 26; + cc += z[2]; z[2] = (int)cc & M25; cc >>= 25; + cc += z[3]; z[3] = (int)cc & M26; cc >>= 26; + cc += z[4]; z[4] = (int)cc & M25; cc >>= 25; + cc += z[5]; z[5] = (int)cc & M26; cc >>= 26; + cc += z[6]; z[6] = (int)cc & M26; cc >>= 26; + cc += z[7]; z[7] = (int)cc & M25; cc >>= 25; + cc += z[8]; z[8] = (int)cc & M26; cc >>= 26; + z[9] = z9 + (int)cc; + } +#endif + public static void Sqr(int[] x, int[] z) { int x0 = x[0]; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc7748/X448.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc7748/X448.cs index a84cb29..ffdf26a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc7748/X448.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc7748/X448.cs @@ -9,13 +9,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc7748 { - public abstract class X448 + using F = X448Field; + + public static class X448 { public const int PointSize = 56; public const int ScalarSize = 56; - private class F : X448Field {}; - private const uint C_A = 156326; private const uint C_A24 = (C_A + 2)/4; @@ -29,6 +29,35 @@ public static bool CalculateAgreement(byte[] k, int kOff, byte[] u, int uOff, by return !Arrays.AreAllZeroes(r, rOff, PointSize); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static bool CalculateAgreement(ReadOnlySpan k, ReadOnlySpan u, Span r) + { + ScalarMult(k, u, r); + return !Arrays.AreAllZeroes(r[..PointSize]); + } +#endif + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static uint Decode32(ReadOnlySpan bs) + { + uint n = bs[0]; + n |= (uint)bs[1] << 8; + n |= (uint)bs[2] << 16; + n |= (uint)bs[3] << 24; + return n; + } + + private static void DecodeScalar(ReadOnlySpan k, uint[] n) + { + for (int i = 0; i < 14; ++i) + { + n[i] = Decode32(k[(i * 4)..]); + } + + n[ 0] &= 0xFFFFFFFCU; + n[13] |= 0x80000000U; + } +#else private static uint Decode32(byte[] bs, int off) { uint n = bs[off]; @@ -48,20 +77,44 @@ private static void DecodeScalar(byte[] k, int kOff, uint[] n) n[ 0] &= 0xFFFFFFFCU; n[13] |= 0x80000000U; } +#endif public static void GeneratePrivateKey(SecureRandom random, byte[] k) { + if (k.Length != ScalarSize) + throw new ArgumentException(nameof(k)); + + random.NextBytes(k); + + k[0] &= 0xFC; + k[ScalarSize - 1] |= 0x80; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void GeneratePrivateKey(SecureRandom random, Span k) + { + if (k.Length != ScalarSize) + throw new ArgumentException(nameof(k)); + random.NextBytes(k); k[0] &= 0xFC; k[ScalarSize - 1] |= 0x80; } +#endif public static void GeneratePublicKey(byte[] k, int kOff, byte[] r, int rOff) { ScalarMultBase(k, kOff, r, rOff); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void GeneratePublicKey(ReadOnlySpan k, Span r) + { + ScalarMultBase(k, r); + } +#endif + private static void PointDouble(uint[] x, uint[] z) { uint[] a = F.Create(); @@ -86,6 +139,9 @@ public static void Precompute() public static void ScalarMult(byte[] k, int kOff, byte[] u, int uOff, byte[] r, int rOff) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ScalarMult(k.AsSpan(kOff), u.AsSpan(uOff), r.AsSpan(rOff)); +#else uint[] n = new uint[14]; DecodeScalar(k, kOff, n); uint[] x1 = F.Create(); F.Decode(u, uOff, x1); @@ -150,10 +206,84 @@ public static void ScalarMult(byte[] k, int kOff, byte[] u, int uOff, byte[] r, F.Normalize(x2); F.Encode(x2, r, rOff); +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void ScalarMult(ReadOnlySpan k, ReadOnlySpan u, Span r) + { + uint[] n = new uint[14]; DecodeScalar(k, n); + + uint[] x1 = F.Create(); F.Decode(u, x1); + uint[] x2 = F.Create(); F.Copy(x1, 0, x2, 0); + uint[] z2 = F.Create(); z2[0] = 1; + uint[] x3 = F.Create(); x3[0] = 1; + uint[] z3 = F.Create(); + + uint[] t1 = F.Create(); + uint[] t2 = F.Create(); + + Debug.Assert(n[13] >> 31 == 1U); + + int bit = 447, swap = 1; + do + { + //F.Apm(x3, z3, t1, x3); + F.Add(x3, z3, t1); + F.Sub(x3, z3, x3); + //F.Apm(x2, z2, z3, x2); + F.Add(x2, z2, z3); + F.Sub(x2, z2, x2); + + F.Mul(t1, x2, t1); + F.Mul(x3, z3, x3); + F.Sqr(z3, z3); + F.Sqr(x2, x2); + + F.Sub(z3, x2, t2); + F.Mul(t2, C_A24, z2); + F.Add(z2, x2, z2); + F.Mul(z2, t2, z2); + F.Mul(x2, z3, x2); + + //F.Apm(t1, x3, x3, z3); + F.Sub(t1, x3, z3); + F.Add(t1, x3, x3); + F.Sqr(x3, x3); + F.Sqr(z3, z3); + F.Mul(z3, x1, z3); + + --bit; + + int word = bit >> 5, shift = bit & 0x1F; + int kt = (int)(n[word] >> shift) & 1; + swap ^= kt; + F.CSwap(swap, x2, x3); + F.CSwap(swap, z2, z3); + swap = kt; + } + while (bit >= 2); + + Debug.Assert(swap == 0); + + for (int i = 0; i < 2; ++i) + { + PointDouble(x2, z2); + } + + F.Inv(z2, z2); + F.Mul(x2, z2, x2); + + F.Normalize(x2); + F.Encode(x2, r); + } +#endif + public static void ScalarMultBase(byte[] k, int kOff, byte[] r, int rOff) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ScalarMultBase(k.AsSpan(kOff), r.AsSpan(rOff)); +#else uint[] x = F.Create(); uint[] y = F.Create(); @@ -165,7 +295,25 @@ public static void ScalarMultBase(byte[] k, int kOff, byte[] r, int rOff) F.Normalize(x); F.Encode(x, r, rOff); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void ScalarMultBase(ReadOnlySpan k, Span r) + { + uint[] x = F.Create(); + uint[] y = F.Create(); + + Ed448.ScalarMultBaseXY(k, x, y); + + F.Inv(x, x); + F.Mul(x, y, x); + F.Sqr(x, x); + + F.Normalize(x); + F.Encode(x, r); } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc7748/X448Field.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc7748/X448Field.cs index 6147cbd..f95982e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc7748/X448Field.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc7748/X448Field.cs @@ -7,8 +7,8 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc7748 { - [CLSCompliantAttribute(false)] - public abstract class X448Field + [CLSCompliant(false)] + public static class X448Field { public const int Size = 16; @@ -18,8 +18,6 @@ public abstract class X448Field 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFEU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU }; - protected X448Field() {} - public static void Add(uint[] x, uint[] y, uint[] z) { for (int i = 0; i < Size; ++i) @@ -116,6 +114,22 @@ public static void CMov(int cond, uint[] x, int xOff, uint[] z, int zOff) } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void CMov(int cond, ReadOnlySpan x, Span z) + { + Debug.Assert(0 == cond || -1 == cond); + + uint MASK = (uint)cond; + + for (int i = 0; i < Size; ++i) + { + uint z_i = z[i], diff = z_i ^ x[i]; + z_i ^= (diff & MASK); + z[i] = z_i; + } + } +#endif + public static void CNegate(int negate, uint[] z) { Debug.Assert(negate >> 1 == 0); @@ -134,6 +148,13 @@ public static void Copy(uint[] x, int xOff, uint[] z, int zOff) } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Copy(ReadOnlySpan x, Span z) + { + x[..Size].CopyTo(z); + } +#endif + public static uint[] Create() { return new uint[Size]; @@ -165,6 +186,14 @@ public static void Decode(uint[] x, int xOff, uint[] z) Decode224(x, xOff + 7, z, 8); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Decode(ReadOnlySpan x, Span z) + { + Decode224(x, z); + Decode224(x[7..], z[8..]); + } +#endif + public static void Decode(byte[] x, int xOff, uint[] z) { Decode56(x, xOff, z, 0); @@ -177,6 +206,20 @@ public static void Decode(byte[] x, int xOff, uint[] z) Decode56(x, xOff + 49, z, 14); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Decode(ReadOnlySpan x, Span z) + { + Decode56(x, z); + Decode56(x[7..], z[2..]); + Decode56(x[14..], z[4..]); + Decode56(x[21..], z[6..]); + Decode56(x[28..], z[8..]); + Decode56(x[35..], z[10..]); + Decode56(x[42..], z[12..]); + Decode56(x[49..], z[14..]); + } +#endif + private static void Decode224(uint[] x, int xOff, uint[] z, int zOff) { uint x0 = x[xOff + 0], x1 = x[xOff + 1], x2 = x[xOff + 2], x3 = x[xOff + 3]; @@ -192,6 +235,23 @@ private static void Decode224(uint[] x, int xOff, uint[] z, int zOff) z[zOff + 7] = x6 >> 4; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void Decode224(ReadOnlySpan x, Span z) + { + uint x0 = x[0], x1 = x[1], x2 = x[2], x3 = x[3]; + uint x4 = x[4], x5 = x[5], x6 = x[6]; + + z[0] = x0 & M28; + z[1] = (x0 >> 28 | x1 << 4) & M28; + z[2] = (x1 >> 24 | x2 << 8) & M28; + z[3] = (x2 >> 20 | x3 << 12) & M28; + z[4] = (x3 >> 16 | x4 << 16) & M28; + z[5] = (x4 >> 12 | x5 << 20) & M28; + z[6] = (x5 >> 8 | x6 << 24) & M28; + z[7] = x6 >> 4; + } +#endif + private static uint Decode24(byte[] bs, int off) { uint n = bs[off]; @@ -200,6 +260,16 @@ private static uint Decode24(byte[] bs, int off) return n; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static uint Decode24(ReadOnlySpan bs) + { + uint n = bs[0]; + n |= (uint)bs[1] << 8; + n |= (uint)bs[2] << 16; + return n; + } +#endif + private static uint Decode32(byte[] bs, int off) { uint n = bs[off]; @@ -209,6 +279,17 @@ private static uint Decode32(byte[] bs, int off) return n; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static uint Decode32(ReadOnlySpan bs) + { + uint n = bs[0]; + n |= (uint)bs[1] << 8; + n |= (uint)bs[2] << 16; + n |= (uint)bs[3] << 24; + return n; + } +#endif + private static void Decode56(byte[] bs, int off, uint[] z, int zOff) { uint lo = Decode32(bs, off); @@ -217,12 +298,30 @@ private static void Decode56(byte[] bs, int off, uint[] z, int zOff) z[zOff + 1] = (lo >> 28) | (hi << 4); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void Decode56(ReadOnlySpan bs, Span z) + { + uint lo = Decode32(bs); + uint hi = Decode24(bs[4..]); + z[0] = lo & M28; + z[1] = (lo >> 28) | (hi << 4); + } +#endif + public static void Encode(uint[] x, uint[] z, int zOff) { Encode224(x, 0, z, zOff); Encode224(x, 8, z, zOff + 7); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Encode(ReadOnlySpan x, Span z) + { + Encode224(x, z); + Encode224(x[8..], z[7..]); + } +#endif + public static void Encode(uint[] x, byte[] z, int zOff) { Encode56(x, 0, z, zOff); @@ -235,6 +334,20 @@ public static void Encode(uint[] x, byte[] z, int zOff) Encode56(x, 14, z, zOff + 49); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Encode(ReadOnlySpan x, Span z) + { + Encode56(x, z); + Encode56(x[2..], z[7..]); + Encode56(x[4..], z[14..]); + Encode56(x[6..], z[21..]); + Encode56(x[8..], z[28..]); + Encode56(x[10..], z[35..]); + Encode56(x[12..], z[42..]); + Encode56(x[14..], z[49..]); + } +#endif + private static void Encode224(uint[] x, int xOff, uint[] z, int zOff) { uint x0 = x[xOff + 0], x1 = x[xOff + 1], x2 = x[xOff + 2], x3 = x[xOff + 3]; @@ -249,6 +362,22 @@ private static void Encode224(uint[] x, int xOff, uint[] z, int zOff) z[zOff + 6] = (x6 >> 24) | (x7 << 4); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void Encode224(ReadOnlySpan x, Span z) + { + uint x0 = x[0], x1 = x[1], x2 = x[2], x3 = x[3]; + uint x4 = x[4], x5 = x[5], x6 = x[6], x7 = x[7]; + + z[0] = x0 | (x1 << 28); + z[1] = (x1 >> 4) | (x2 << 24); + z[2] = (x2 >> 8) | (x3 << 20); + z[3] = (x3 >> 12) | (x4 << 16); + z[4] = (x4 >> 16) | (x5 << 12); + z[5] = (x5 >> 20) | (x6 << 8); + z[6] = (x6 >> 24) | (x7 << 4); + } +#endif + private static void Encode24(uint n, byte[] bs, int off) { bs[ off] = (byte)(n ); @@ -256,6 +385,15 @@ private static void Encode24(uint n, byte[] bs, int off) bs[++off] = (byte)(n >> 16); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void Encode24(uint n, Span bs) + { + bs[0] = (byte)(n ); + bs[1] = (byte)(n >> 8); + bs[2] = (byte)(n >> 16); + } +#endif + private static void Encode32(uint n, byte[] bs, int off) { bs[ off] = (byte)(n ); @@ -264,6 +402,16 @@ private static void Encode32(uint n, byte[] bs, int off) bs[++off] = (byte)(n >> 24); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void Encode32(uint n, Span bs) + { + bs[0] = (byte)(n ); + bs[1] = (byte)(n >> 8); + bs[2] = (byte)(n >> 16); + bs[3] = (byte)(n >> 24); + } +#endif + private static void Encode56(uint[] x, int xOff, byte[] bs, int off) { uint lo = x[xOff], hi = x[xOff + 1]; @@ -271,8 +419,20 @@ private static void Encode56(uint[] x, int xOff, byte[] bs, int off) Encode24(hi >> 4, bs, off + 4); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void Encode56(ReadOnlySpan x, Span bs) + { + uint lo = x[0], hi = x[1]; + Encode32(lo | (hi << 28), bs); + Encode24(hi >> 4, bs[4..]); + } +#endif + public static void Inv(uint[] x, uint[] z) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Inv(x.AsSpan(), z.AsSpan()); +#else //uint[] t = Create(); //PowPm3d4(x, t); //Sqr(t, 2, t); @@ -288,10 +448,30 @@ public static void Inv(uint[] x, uint[] z) Mod.ModOddInverse(P32, u, u); Decode(u, 0, z); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Inv(ReadOnlySpan x, Span z) + { + Span t = stackalloc uint[Size]; + Span u = stackalloc uint[14]; + + Copy(x, t); + Normalize(t); + Encode(t, u); + + Mod.ModOddInverse(P32, u, u); + + Decode(u, z); } +#endif public static void InvVar(uint[] x, uint[] z) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + InvVar(x.AsSpan(), z.AsSpan()); +#else uint[] t = Create(); uint[] u = new uint[14]; @@ -302,7 +482,24 @@ public static void InvVar(uint[] x, uint[] z) Mod.ModOddInverseVar(P32, u, u); Decode(u, 0, z); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void InvVar(ReadOnlySpan x, Span z) + { + Span t = stackalloc uint[Size]; + Span u = stackalloc uint[14]; + + Copy(x, t); + Normalize(t); + Encode(t, u); + + Mod.ModOddInverseVar(P32, u, u); + + Decode(u, z); } +#endif public static int IsOne(uint[] x) { @@ -730,6 +927,16 @@ public static void Normalize(uint[] z) Debug.Assert(z[15] >> 28 == 0U); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Normalize(Span z) + { + //int x = (z[15] >> (28 - 1)) & 1; + Reduce(z, 1); + Reduce(z, -1); + Debug.Assert(z[15] >> 28 == 0U); + } +#endif + public static void One(uint[] z) { z[0] = 1U; @@ -779,6 +986,26 @@ private static void Reduce(uint[] z, int x) z[15] = z15 + (uint)cc; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void Reduce(Span z, int x) + { + uint u = z[15], z15 = u & M28; + int t = (int)(u >> 28) + x; + + long cc = t; + for (int i = 0; i < 8; ++i) + { + cc += z[i]; z[i] = (uint)cc & M28; cc >>= 28; + } + cc += t; + for (int i = 8; i < 15; ++i) + { + cc += z[i]; z[i] = (uint)cc & M28; cc >>= 28; + } + z[15] = z15 + (uint)cc; + } +#endif + public static void Sqr(uint[] x, uint[] z) { uint x0 = x[0]; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc8032/Ed25519.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc8032/Ed25519.cs index 0d526ae..b8565c4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc8032/Ed25519.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc8032/Ed25519.cs @@ -5,14 +5,27 @@ using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc7748; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc8032 { - public abstract class Ed25519 + using F = Rfc7748.X25519Field; + + /// + /// A low-level implementation of the Ed25519, Ed25519ctx, and Ed25519ph instantiations of the Edwards-Curve Digital + /// Signature Algorithm specified in RFC 8032. + /// + /// + /// The implementation strategy is mostly drawn from + /// Mike Hamburg, "Fast and compact elliptic-curve cryptography", notably the "signed multi-comb" algorithm (for + /// scalar multiplication by a fixed point), the "half Niels coordinates" (for precomputed points), and the + /// "extensible coordinates" (for accumulators). Standard + /// extended coordinates are used during + /// precomputations, needing only a single extra point addition formula. + /// + public static class Ed25519 { // -x^2 + y^2 == 1 + 0x52036CEE2B6FFE738CC740797779E89800700A4D4141D8AB75EB4DCA135978A3 * x^2 * y^2 @@ -23,8 +36,6 @@ public enum Algorithm Ed25519ph = 2, } - private class F : X25519Field {}; - private const long M08L = 0x000000FFL; private const long M28L = 0x0FFFFFFFL; private const long M32L = 0xFFFFFFFFL; @@ -49,16 +60,18 @@ private class F : X25519Field {}; private static readonly uint[] L = { 0x5CF5D3EDU, 0x5812631AU, 0xA2F79CD6U, 0x14DEF9DEU, 0x00000000U, 0x00000000U, 0x00000000U, 0x10000000U }; - private const int L0 = unchecked((int)0xFCF5D3ED); // L0:26/-- - private const int L1 = 0x012631A6; // L1:24/22 - private const int L2 = 0x079CD658; // L2:27/-- - private const int L3 = unchecked((int)0xFF9DEA2F); // L3:23/-- - private const int L4 = 0x000014DF; // L4:12/11 + private const int L0 = -0x030A2C13; // L0:26/-- + private const int L1 = 0x012631A6; // L1:24/22 + private const int L2 = 0x079CD658; // L2:27/-- + private const int L3 = -0x006215D1; // L3:23/-- + private const int L4 = 0x000014DF; // L4:12/11 private static readonly int[] B_x = { 0x0325D51A, 0x018B5823, 0x007B2C95, 0x0304A92D, 0x00D2598E, 0x01D6DC5C, 0x01388C7F, 0x013FEC0A, 0x029E6B72, 0x0042D26D }; private static readonly int[] B_y = { 0x02666658, 0x01999999, 0x00666666, 0x03333333, 0x00CCCCCC, 0x02666666, 0x01999999, 0x00666666, 0x03333333, 0x00CCCCCC, }; + + // Note that d == -121665/121666 private static readonly int[] C_d = { 0x035978A3, 0x02D37284, 0x018AB75E, 0x026A0A0E, 0x0000E014, 0x0379E898, 0x01D01E5D, 0x01E738CC, 0x03715B7F, 0x00A406D9 }; private static readonly int[] C_d2 = { 0x02B2F159, 0x01A6E509, 0x01156EBD, 0x00D4141D, 0x0001C029, 0x02F3D130, @@ -66,47 +79,55 @@ private class F : X25519Field {}; private static readonly int[] C_d4 = { 0x0165E2B2, 0x034DCA13, 0x002ADD7A, 0x01A8283B, 0x00038052, 0x01E7A260, 0x03407977, 0x019CE331, 0x01C56DFF, 0x00901B67 }; + private const int WnafWidth = 5; private const int WnafWidthBase = 7; + // ScalarMultBase is hard-coded for these values of blocks, teeth, spacing so they can't be freely changed private const int PrecompBlocks = 8; private const int PrecompTeeth = 4; private const int PrecompSpacing = 8; + //private const int PrecompRange = PrecompBlocks * PrecompTeeth * PrecompSpacing; // range == 256 private const int PrecompPoints = 1 << (PrecompTeeth - 1); private const int PrecompMask = PrecompPoints - 1; - private static readonly object precompLock = new object(); - // TODO[ed25519] Convert to PointPrecomp - private static PointExt[] precompBaseTable = null; - private static int[] precompBase = null; + private static readonly object PrecompLock = new object(); + private static PointPrecomp[] PrecompBaseWnaf = null; + private static int[] PrecompBaseComb = null; + + private struct PointAccum + { + internal int[] x, y, z, u, v; + } + + private struct PointAffine + { + internal int[] x, y; + } - private class PointAccum + private struct PointExtended { - internal int[] x = F.Create(); - internal int[] y = F.Create(); - internal int[] z = F.Create(); - internal int[] u = F.Create(); - internal int[] v = F.Create(); + internal int[] x, y, z, t; } - private class PointAffine + private struct PointPrecomp { - internal int[] x = F.Create(); - internal int[] y = F.Create(); + internal int[] ymx_h; // (y - x)/2 + internal int[] ypx_h; // (y + x)/2 + internal int[] xyd; // x.y.d } - private class PointExt + private struct PointPrecompZ { - internal int[] x = F.Create(); - internal int[] y = F.Create(); - internal int[] z = F.Create(); - internal int[] t = F.Create(); + internal int[] ymx_h; // (y - x)/2 + internal int[] ypx_h; // (y + x)/2 + internal int[] xyd; // x.y.d + internal int[] z; } - private class PointPrecomp + // Temp space to avoid allocations in point formulae. + private struct PointTemp { - internal int[] ypx_h = F.Create(); - internal int[] ymx_h = F.Create(); - internal int[] xyd = F.Create(); + internal int[] r0, r1; } private static byte[] CalculateS(byte[] r, byte[] k, byte[] s) @@ -219,6 +240,17 @@ private static uint Decode32(byte[] bs, int off) return n; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static uint Decode32(ReadOnlySpan bs) + { + uint n = bs[0]; + n |= (uint)bs[1] << 8; + n |= (uint)bs[2] << 16; + n |= (uint)bs[3] << 24; + return n; + } +#endif + private static void Decode32(byte[] bs, int bsOff, uint[] n, int nOff, int nLen) { for (int i = 0; i < nLen; ++i) @@ -227,7 +259,17 @@ private static void Decode32(byte[] bs, int bsOff, uint[] n, int nOff, int nLen) } } - private static bool DecodePointVar(byte[] p, int pOff, bool negate, PointAffine r) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void Decode32(ReadOnlySpan bs, Span n) + { + for (int i = 0; i < n.Length; ++i) + { + n[i] = Decode32(bs[(i * 4)..]); + } + } +#endif + + private static bool DecodePointVar(byte[] p, int pOff, bool negate, ref PointAffine r) { byte[] py = Copy(p, pOff, PointBytes); if (!CheckPointVar(py)) @@ -266,6 +308,13 @@ private static void DecodeScalar(byte[] k, int kOff, uint[] n) Decode32(k, kOff, n, 0, ScalarUints); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void DecodeScalar(ReadOnlySpan k, Span n) + { + Decode32(k, n[..ScalarUints]); + } +#endif + private static void Dom2(IDigest d, byte phflag, byte[] ctx) { if (ctx != null) @@ -302,8 +351,11 @@ private static void Encode56(ulong n, byte[] bs, int off) Encode24((uint)(n >> 32), bs, off + 4); } - private static int EncodePoint(PointAccum p, byte[] r, int rOff) + private static int EncodePoint(ref PointAccum p, byte[] r, int rOff) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return EncodePoint(ref p, r.AsSpan(rOff)); +#else int[] x = F.Create(); int[] y = F.Create(); @@ -319,15 +371,53 @@ private static int EncodePoint(PointAccum p, byte[] r, int rOff) r[rOff + PointBytes - 1] |= (byte)((x[0] & 1) << 7); return result; +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static int EncodePoint(ref PointAccum p, Span r) + { + int[] x = F.Create(); + int[] y = F.Create(); + + F.Inv(p.z, y); + F.Mul(p.x, y, x); + F.Mul(p.y, y, y); + F.Normalize(x); + F.Normalize(y); + + int result = CheckPoint(x, y); + + F.Encode(y, r); + r[PointBytes - 1] |= (byte)((x[0] & 1) << 7); + + return result; + } +#endif + public static void GeneratePrivateKey(SecureRandom random, byte[] k) { + if (k.Length != SecretKeySize) + throw new ArgumentException(nameof(k)); + random.NextBytes(k); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void GeneratePrivateKey(SecureRandom random, Span k) + { + if (k.Length != SecretKeySize) + throw new ArgumentException(nameof(k)); + + random.NextBytes(k); + } +#endif + public static void GeneratePublicKey(byte[] sk, int skOff, byte[] pk, int pkOff) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + GeneratePublicKey(sk.AsSpan(skOff), pk.AsSpan(pkOff)); +#else IDigest d = CreateDigest(); byte[] h = new byte[d.GetDigestSize()]; @@ -338,9 +428,33 @@ public static void GeneratePublicKey(byte[] sk, int skOff, byte[] pk, int pkOff) PruneScalar(h, 0, s); ScalarMultBaseEncoded(s, pk, pkOff); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void GeneratePublicKey(ReadOnlySpan sk, Span pk) + { + IDigest d = CreateDigest(); + int digestSize = d.GetDigestSize(); + Span h = digestSize <= 128 + ? stackalloc byte[digestSize] + : new byte[digestSize]; + + d.BlockUpdate(sk[..SecretKeySize]); + d.DoFinal(h); + + Span s = stackalloc byte[ScalarBytes]; + PruneScalar(h, s); + + ScalarMultBaseEncoded(s, pk); } +#endif +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static uint GetWindow4(ReadOnlySpan x, int n) +#else private static uint GetWindow4(uint[] x, int n) +#endif { int w = (int)((uint)n >> 3), b = (n & 7) << 2; return (x[w] >> b) & 15U; @@ -477,8 +591,8 @@ private static bool ImplVerify(byte[] sig, int sigOff, byte[] pk, int pkOff, byt if (!CheckScalarVar(S, nS)) return false; - PointAffine pA = new PointAffine(); - if (!DecodePointVar(pk, pkOff, true, pA)) + Init(out PointAffine pA); + if (!DecodePointVar(pk, pkOff, true, ref pA)) return false; IDigest d = CreateDigest(); @@ -495,11 +609,89 @@ private static bool ImplVerify(byte[] sig, int sigOff, byte[] pk, int pkOff, byt uint[] nA = new uint[ScalarUints]; DecodeScalar(k, 0, nA); - PointAccum pR = new PointAccum(); - ScalarMultStrausVar(nS, nA, pA, pR); + Init(out PointAccum pR); + ScalarMultStrausVar(nS, nA, ref pA, ref pR); byte[] check = new byte[PointBytes]; - return 0 != EncodePoint(pR, check, 0) && Arrays.AreEqual(check, R); + return 0 != EncodePoint(ref pR, check, 0) && Arrays.AreEqual(check, R); + } + + private static void Init(out PointAccum r) + { + r.x = F.Create(); + r.y = F.Create(); + r.z = F.Create(); + r.u = F.Create(); + r.v = F.Create(); + } + + private static void Init(out PointAffine r) + { + r.x = F.Create(); + r.y = F.Create(); + } + + private static void Init(out PointExtended r) + { + r.x = F.Create(); + r.y = F.Create(); + r.z = F.Create(); + r.t = F.Create(); + } + + private static void Init(out PointPrecomp r) + { + r.ymx_h = F.Create(); + r.ypx_h = F.Create(); + r.xyd = F.Create(); + } + + private static void Init(out PointPrecompZ r) + { + r.ymx_h = F.Create(); + r.ypx_h = F.Create(); + r.xyd = F.Create(); + r.z = F.Create(); + } + + private static void Init(out PointTemp r) + { + r.r0 = F.Create(); + r.r1 = F.Create(); + } + + private static void InvertDoubleZs(PointExtended[] points) + { + int count = points.Length; + int[] cs = F.CreateTable(count); + + int[] u = F.Create(); + F.Copy(points[0].z, 0, u, 0); + F.Copy(u, 0, cs, 0); + + int i = 0; + while (++i < count) + { + F.Mul(u, points[i].z, u); + F.Copy(u, 0, cs, i * F.Size); + } + + F.Add(u, u, u); + F.InvVar(u, u); + --i; + + int[] t = F.Create(); + + while (i > 0) + { + int j = i--; + F.Copy(cs, i * F.Size, t, 0); + F.Mul(t, u, t); + F.Mul(u, points[j].z, u); + F.Copy(t, 0, points[j].z, 0); + } + + F.Copy(u, 0, points[0].z, 0); } private static bool IsNeutralElementVar(int[] x, int[] y) @@ -512,241 +704,200 @@ private static bool IsNeutralElementVar(int[] x, int[] y, int[] z) return F.IsZeroVar(x) && F.AreEqualVar(y, z); } - private static void PointAdd(PointExt p, PointAccum r) + private static void PointAdd(ref PointExtended p, ref PointExtended q, ref PointExtended r, ref PointTemp t) { - int[] a = F.Create(); - int[] b = F.Create(); - int[] c = F.Create(); - int[] d = F.Create(); - int[] e = r.u; - int[] f = F.Create(); - int[] g = F.Create(); - int[] h = r.v; + // p may ref the same point as r (or q), but q may not ref the same point as r. + Debug.Assert(q.x != r.x & q.y != r.y && q.z != r.z && q.t != r.t); - F.Apm(r.y, r.x, b, a); - F.Apm(p.y, p.x, d, c); + int[] a = r.x; + int[] b = r.y; + int[] c = t.r0; + int[] d = t.r1; + int[] e = a; + int[] f = c; + int[] g = d; + int[] h = b; + + F.Apm(p.y, p.x, b, a); + F.Apm(q.y, q.x, d, c); F.Mul(a, c, a); F.Mul(b, d, b); - F.Mul(r.u, r.v, c); - F.Mul(c, p.t, c); + F.Mul(p.t, q.t, c); F.Mul(c, C_d2, c); - F.Mul(r.z, p.z, d); - F.Add(d, d, d); + F.Add(p.z, p.z, d); + F.Mul(d, q.z, d); F.Apm(b, a, h, e); F.Apm(d, c, g, f); - F.Carry(g); - F.Mul(e, f, r.x); - F.Mul(g, h, r.y); + F.Mul(e, h, r.t); F.Mul(f, g, r.z); + F.Mul(e, f, r.x); + F.Mul(h, g, r.y); } - private static void PointAdd(PointExt p, PointExt r) + private static void PointAdd(ref PointPrecomp p, ref PointAccum r, ref PointTemp t) { - int[] a = F.Create(); - int[] b = F.Create(); - int[] c = F.Create(); - int[] d = F.Create(); - int[] e = F.Create(); - int[] f = F.Create(); - int[] g = F.Create(); - int[] h = F.Create(); + int[] a = r.x; + int[] b = r.y; + int[] c = t.r0; + int[] e = r.u; + int[] f = a; + int[] g = b; + int[] h = r.v; - F.Apm(p.y, p.x, b, a); - F.Apm(r.y, r.x, d, c); - F.Mul(a, c, a); - F.Mul(b, d, b); - F.Mul(p.t, r.t, c); - F.Mul(c, C_d2, c); - F.Mul(p.z, r.z, d); - F.Add(d, d, d); + F.Apm(r.y, r.x, b, a); + F.Mul(a, p.ymx_h, a); + F.Mul(b, p.ypx_h, b); + F.Mul(r.u, r.v, c); + F.Mul(c, p.xyd, c); F.Apm(b, a, h, e); - F.Apm(d, c, g, f); - F.Carry(g); - F.Mul(e, f, r.x); - F.Mul(g, h, r.y); + F.Apm(r.z, c, g, f); F.Mul(f, g, r.z); - F.Mul(e, h, r.t); + F.Mul(f, e, r.x); + F.Mul(g, h, r.y); } - private static void PointAddVar(bool negate, PointExt p, PointAccum r) + private static void PointAdd(ref PointPrecompZ p, ref PointAccum r, ref PointTemp t) { - int[] a = F.Create(); - int[] b = F.Create(); - int[] c = F.Create(); - int[] d = F.Create(); + int[] a = r.x; + int[] b = r.y; + int[] c = t.r0; + int[] d = r.z; int[] e = r.u; - int[] f = F.Create(); - int[] g = F.Create(); + int[] f = a; + int[] g = b; int[] h = r.v; - int[] nc, nd, nf, ng; - if (negate) - { - nc = d; nd = c; nf = g; ng = f; - } - else - { - nc = c; nd = d; nf = f; ng = g; - } - F.Apm(r.y, r.x, b, a); - F.Apm(p.y, p.x, nd, nc); - F.Mul(a, c, a); - F.Mul(b, d, b); + F.Mul(a, p.ymx_h, a); + F.Mul(b, p.ypx_h, b); F.Mul(r.u, r.v, c); - F.Mul(c, p.t, c); - F.Mul(c, C_d2, c); + F.Mul(c, p.xyd, c); F.Mul(r.z, p.z, d); - F.Add(d, d, d); F.Apm(b, a, h, e); - F.Apm(d, c, ng, nf); - F.Carry(ng); - F.Mul(e, f, r.x); - F.Mul(g, h, r.y); + F.Apm(d, c, g, f); F.Mul(f, g, r.z); + F.Mul(f, e, r.x); + F.Mul(g, h, r.y); } - private static void PointAddVar(bool negate, PointExt p, PointExt q, PointExt r) + private static void PointAddVar(bool negate, ref PointPrecomp p, ref PointAccum r, ref PointTemp t) { - int[] a = F.Create(); - int[] b = F.Create(); - int[] c = F.Create(); - int[] d = F.Create(); - int[] e = F.Create(); - int[] f = F.Create(); - int[] g = F.Create(); - int[] h = F.Create(); + int[] a = r.x; + int[] b = r.y; + int[] c = t.r0; + int[] e = r.u; + int[] f = a; + int[] g = b; + int[] h = r.v; - int[] nc, nd, nf, ng; + int[] na, nb; if (negate) { - nc = d; nd = c; nf = g; ng = f; + na = b; nb = a; } else { - nc = c; nd = d; nf = f; ng = g; + na = a; nb = b; } + int[] nf = na, ng = nb; - F.Apm(p.y, p.x, b, a); - F.Apm(q.y, q.x, nd, nc); - F.Mul(a, c, a); - F.Mul(b, d, b); - F.Mul(p.t, q.t, c); - F.Mul(c, C_d2, c); - F.Mul(p.z, q.z, d); - F.Add(d, d, d); + F.Apm(r.y, r.x, b, a); + F.Mul(na, p.ymx_h, na); + F.Mul(nb, p.ypx_h, nb); + F.Mul(r.u, r.v, c); + F.Mul(c, p.xyd, c); F.Apm(b, a, h, e); - F.Apm(d, c, ng, nf); - F.Carry(ng); - F.Mul(e, f, r.x); - F.Mul(g, h, r.y); + F.Apm(r.z, c, ng, nf); F.Mul(f, g, r.z); - F.Mul(e, h, r.t); + F.Mul(f, e, r.x); + F.Mul(g, h, r.y); } - private static void PointAddPrecomp(PointPrecomp p, PointAccum r) + private static void PointAddVar(bool negate, ref PointPrecompZ p, ref PointAccum r, ref PointTemp t) { - int[] a = F.Create(); - int[] b = F.Create(); - int[] c = F.Create(); + int[] a = r.x; + int[] b = r.y; + int[] c = t.r0; + int[] d = r.z; int[] e = r.u; - int[] f = F.Create(); - int[] g = F.Create(); + int[] f = a; + int[] g = b; int[] h = r.v; + int[] na, nb; + if (negate) + { + na = b; nb = a; + } + else + { + na = a; nb = b; + } + int[] nf = na, ng = nb; + F.Apm(r.y, r.x, b, a); - F.Mul(a, p.ymx_h, a); - F.Mul(b, p.ypx_h, b); + F.Mul(na, p.ymx_h, na); + F.Mul(nb, p.ypx_h, nb); F.Mul(r.u, r.v, c); F.Mul(c, p.xyd, c); + F.Mul(r.z, p.z, d); F.Apm(b, a, h, e); - F.Apm(r.z, c, g, f); - F.Carry(g); - F.Mul(e, f, r.x); - F.Mul(g, h, r.y); + F.Apm(d, c, ng, nf); F.Mul(f, g, r.z); + F.Mul(f, e, r.x); + F.Mul(g, h, r.y); } - private static PointExt PointCopy(PointAccum p) + private static void PointCopy(ref PointAccum p, ref PointExtended r) { - PointExt r = new PointExt(); F.Copy(p.x, 0, r.x, 0); F.Copy(p.y, 0, r.y, 0); F.Copy(p.z, 0, r.z, 0); F.Mul(p.u, p.v, r.t); - return r; } - private static PointExt PointCopy(PointAffine p) + private static void PointCopy(ref PointAffine p, ref PointExtended r) { - PointExt r = new PointExt(); F.Copy(p.x, 0, r.x, 0); F.Copy(p.y, 0, r.y, 0); - PointExtendXY(r); - return r; - } - - private static PointExt PointCopy(PointExt p) - { - PointExt r = new PointExt(); - PointCopy(p, r); - return r; + F.One(r.z); + F.Mul(p.x, p.y, r.t); } - private static void PointCopy(PointAffine p, PointAccum r) + private static void PointCopy(ref PointExtended p, ref PointPrecompZ r) { - F.Copy(p.x, 0, r.x, 0); - F.Copy(p.y, 0, r.y, 0); - PointExtendXY(r); - } - - private static void PointCopy(PointExt p, PointExt r) - { - F.Copy(p.x, 0, r.x, 0); - F.Copy(p.y, 0, r.y, 0); - F.Copy(p.z, 0, r.z, 0); - F.Copy(p.t, 0, r.t, 0); + // To avoid halving x and y, we double t and z instead. + F.Apm(p.y, p.x, r.ypx_h, r.ymx_h); + F.Mul(p.t, C_d2, r.xyd); + F.Add(p.z, p.z, r.z); } - private static void PointDouble(PointAccum r) + private static void PointDouble(ref PointAccum r) { - int[] a = F.Create(); - int[] b = F.Create(); - int[] c = F.Create(); + int[] a = r.x; + int[] b = r.y; + int[] c = r.z; int[] e = r.u; - int[] f = F.Create(); - int[] g = F.Create(); + int[] f = a; + int[] g = b; int[] h = r.v; + F.Add(r.x, r.y, e); F.Sqr(r.x, a); F.Sqr(r.y, b); F.Sqr(r.z, c); F.Add(c, c, c); F.Apm(a, b, h, g); - F.Add(r.x, r.y, e); F.Sqr(e, e); F.Sub(h, e, e); F.Add(c, g, f); - F.Carry(f); - F.Mul(e, f, r.x); - F.Mul(g, h, r.y); + F.Carry(f); // Probably unnecessary, but keep until better bounds analysis available F.Mul(f, g, r.z); + F.Mul(f, e, r.x); + F.Mul(g, h, r.y); } - private static void PointExtendXY(PointAccum p) - { - F.One(p.z); - F.Copy(p.x, 0, p.u, 0); - F.Copy(p.y, 0, p.v, 0); - } - - private static void PointExtendXY(PointExt p) - { - F.One(p.z); - F.Mul(p.x, p.y, p.t); - } - - private static void PointLookup(int block, int index, PointPrecomp p) + private static void PointLookup(int block, int index, ref PointPrecomp p) { Debug.Assert(0 <= block && block < PrecompBlocks); Debug.Assert(0 <= index && index < PrecompPoints); @@ -756,15 +907,41 @@ private static void PointLookup(int block, int index, PointPrecomp p) for (int i = 0; i < PrecompPoints; ++i) { int cond = ((i ^ index) - 1) >> 31; - F.CMov(cond, precompBase, off, p.ypx_h, 0); off += F.Size; - F.CMov(cond, precompBase, off, p.ymx_h, 0); off += F.Size; - F.CMov(cond, precompBase, off, p.xyd, 0); off += F.Size; + F.CMov(cond, PrecompBaseComb, off, p.ymx_h, 0); off += F.Size; + F.CMov(cond, PrecompBaseComb, off, p.ypx_h, 0); off += F.Size; + F.CMov(cond, PrecompBaseComb, off, p.xyd , 0); off += F.Size; } } - private static void PointLookup(uint[] x, int n, int[] table, PointExt r) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void PointLookupZ(ReadOnlySpan x, int n, ReadOnlySpan table, ref PointPrecompZ r) + { + // TODO This method is currently hard-coded to 4-bit windows and 8 precomputed points + + uint w = GetWindow4(x, n); + + int sign = (int)(w >> (4 - 1)) ^ 1; + int abs = ((int)w ^ -sign) & 7; + + Debug.Assert(sign == 0 || sign == 1); + Debug.Assert(0 <= abs && abs < 8); + + for (int i = 0; i < 8; ++i) + { + int cond = ((i ^ abs) - 1) >> 31; + F.CMov(cond, table, r.ymx_h); table = table[F.Size..]; + F.CMov(cond, table, r.ypx_h); table = table[F.Size..]; + F.CMov(cond, table, r.xyd); table = table[F.Size..]; + F.CMov(cond, table, r.z); table = table[F.Size..]; + } + + F.CSwap(sign, r.ymx_h, r.ypx_h); + F.CNegate(sign, r.xyd); + } +#else + private static void PointLookupZ(uint[] x, int n, int[] table, ref PointPrecompZ r) { - // TODO This method is currently hardcoded to 4-bit windows and 8 precomputed points + // TODO This method is currently hard-coded to 4-bit windows and 8 precomputed points uint w = GetWindow4(x, n); @@ -777,71 +954,92 @@ private static void PointLookup(uint[] x, int n, int[] table, PointExt r) for (int i = 0, off = 0; i < 8; ++i) { int cond = ((i ^ abs) - 1) >> 31; - F.CMov(cond, table, off, r.x, 0); off += F.Size; - F.CMov(cond, table, off, r.y, 0); off += F.Size; - F.CMov(cond, table, off, r.z, 0); off += F.Size; - F.CMov(cond, table, off, r.t, 0); off += F.Size; + F.CMov(cond, table, off, r.ymx_h, 0); off += F.Size; + F.CMov(cond, table, off, r.ypx_h, 0); off += F.Size; + F.CMov(cond, table, off, r.xyd , 0); off += F.Size; + F.CMov(cond, table, off, r.z , 0); off += F.Size; } - F.CNegate(sign, r.x); - F.CNegate(sign, r.t); + F.CSwap(sign, r.ymx_h, r.ypx_h); + F.CNegate(sign, r.xyd); } +#endif - private static void PointLookup(int[] table, int index, PointExt r) + private static void PointPrecompute(ref PointAffine p, PointExtended[] points, int count, ref PointTemp t) { - int off = F.Size * 4 * index; + Debug.Assert(count > 0); - F.Copy(table, off, r.x, 0); off += F.Size; - F.Copy(table, off, r.y, 0); off += F.Size; - F.Copy(table, off, r.z, 0); off += F.Size; - F.Copy(table, off, r.t, 0); + Init(out points[0]); + PointCopy(ref p, ref points[0]); + + Init(out PointExtended d); + PointAdd(ref points[0], ref points[0], ref d, ref t); + + for (int i = 1; i < count; ++i) + { + Init(out points[i]); + PointAdd(ref points[i - 1], ref d, ref points[i], ref t); + } } - private static int[] PointPrecompute(PointAffine p, int count) + private static int[] PointPrecomputeZ(ref PointAffine p, int count, ref PointTemp t) { Debug.Assert(count > 0); - PointExt q = PointCopy(p); - PointExt d = PointCopy(q); - PointAdd(q, d); + Init(out PointExtended q); + PointCopy(ref p, ref q); + + Init(out PointExtended d); + PointAdd(ref q, ref q, ref d, ref t); + Init(out PointPrecompZ r); int[] table = F.CreateTable(count * 4); int off = 0; int i = 0; for (;;) { - F.Copy(q.x, 0, table, off); off += F.Size; - F.Copy(q.y, 0, table, off); off += F.Size; - F.Copy(q.z, 0, table, off); off += F.Size; - F.Copy(q.t, 0, table, off); off += F.Size; + PointCopy(ref q, ref r); + + F.Copy(r.ymx_h, 0, table, off); off += F.Size; + F.Copy(r.ypx_h, 0, table, off); off += F.Size; + F.Copy(r.xyd , 0, table, off); off += F.Size; + F.Copy(r.z , 0, table, off); off += F.Size; if (++i == count) break; - PointAdd(d, q); + PointAdd(ref q, ref d, ref q, ref t); } return table; } - private static PointExt[] PointPrecomputeVar(PointExt p, int count) + private static void PointPrecomputeZ(ref PointAffine p, PointPrecompZ[] points, int count, ref PointTemp t) { Debug.Assert(count > 0); - PointExt d = new PointExt(); - PointAddVar(false, p, p, d); + Init(out PointExtended q); + PointCopy(ref p, ref q); - PointExt[] table = new PointExt[count]; - table[0] = PointCopy(p); - for (int i = 1; i < count; ++i) + Init(out PointExtended d); + PointAdd(ref q, ref q, ref d, ref t); + + int i = 0; + for (;;) { - PointAddVar(false, table[i - 1], d, table[i] = new PointExt()); + ref PointPrecompZ r = ref points[i]; + Init(out r); + PointCopy(ref q, ref r); + + if (++i == count) + break; + + PointAdd(ref q, ref d, ref q, ref t); } - return table; } - private static void PointSetNeutral(PointAccum p) + private static void PointSetNeutral(ref PointAccum p) { F.Zero(p.x); F.One(p.y); @@ -850,141 +1048,138 @@ private static void PointSetNeutral(PointAccum p) F.One(p.v); } - private static void PointSetNeutral(PointExt p) - { - F.Zero(p.x); - F.One(p.y); - F.One(p.z); - F.Zero(p.t); - } - public static void Precompute() { - lock (precompLock) + lock (PrecompLock) { - if (precompBase != null) + if (PrecompBaseWnaf != null && PrecompBaseComb != null) return; - // Precomputed table for the base point in verification ladder - { - PointExt b = new PointExt(); - F.Copy(B_x, 0, b.x, 0); - F.Copy(B_y, 0, b.y, 0); - PointExtendXY(b); + int wnafPoints = 1 << (WnafWidthBase - 2); + int combPoints = PrecompBlocks * PrecompPoints; + int totalPoints = wnafPoints + combPoints; - precompBaseTable = PointPrecomputeVar(b, 1 << (WnafWidthBase - 2)); - } + PointExtended[] points = new PointExtended[totalPoints]; + Init(out PointTemp t); + + Init(out PointAffine b); + F.Copy(B_x, 0, b.x, 0); + F.Copy(B_y, 0, b.y, 0); + + PointPrecompute(ref b, points, wnafPoints, ref t); - PointAccum p = new PointAccum(); + Init(out PointAccum p); F.Copy(B_x, 0, p.x, 0); F.Copy(B_y, 0, p.y, 0); - PointExtendXY(p); + F.One(p.z); + F.Copy(B_x, 0, p.u, 0); + F.Copy(B_y, 0, p.v, 0); - precompBase = F.CreateTable(PrecompBlocks * PrecompPoints * 3); - - int off = 0; - for (int b = 0; b < PrecompBlocks; ++b) + int pointsIndex = wnafPoints; + PointExtended[] toothPowers = new PointExtended[PrecompTeeth]; + for (int tooth = 0; tooth < PrecompTeeth; ++tooth) { - PointExt[] ds = new PointExt[PrecompTeeth]; - - PointExt sum = new PointExt(); - PointSetNeutral(sum); + Init(out toothPowers[tooth]); + } + Init(out PointExtended u); + for (int block = 0; block < PrecompBlocks; ++block) + { + ref PointExtended sum = ref points[pointsIndex++]; + Init(out sum); - for (int t = 0; t < PrecompTeeth; ++t) + for (int tooth = 0; tooth < PrecompTeeth; ++tooth) { - PointExt q = PointCopy(p); - PointAddVar(true, sum, q, sum); - PointDouble(p); + if (tooth == 0) + { + PointCopy(ref p, ref sum); + } + else + { + PointCopy(ref p, ref u); + PointAdd(ref sum, ref u, ref sum, ref t); + } - ds[t] = PointCopy(p); + PointDouble(ref p); + PointCopy(ref p, ref toothPowers[tooth]); - if (b + t != PrecompBlocks + PrecompTeeth - 2) + if (block + tooth != PrecompBlocks + PrecompTeeth - 2) { - for (int s = 1; s < PrecompSpacing; ++s) + for (int spacing = 1; spacing < PrecompSpacing; ++spacing) { - PointDouble(p); + PointDouble(ref p); } } } - PointExt[] points = new PointExt[PrecompPoints]; - int k = 0; - points[k++] = sum; + F.Negate(sum.x, sum.x); + F.Negate(sum.t, sum.t); - for (int t = 0; t < (PrecompTeeth - 1); ++t) + for (int tooth = 0; tooth < (PrecompTeeth - 1); ++tooth) { - int size = 1 << t; - for (int j = 0; j < size; ++j, ++k) + int size = 1 << tooth; + for (int j = 0; j < size; ++j, ++pointsIndex) { - PointAddVar(false, points[k - size], ds[t], points[k] = new PointExt()); + Init(out points[pointsIndex]); + PointAdd(ref points[pointsIndex - size], ref toothPowers[tooth], ref points[pointsIndex], + ref t); } } + } + Debug.Assert(pointsIndex == totalPoints); - Debug.Assert(k == PrecompPoints); - - int[] cs = F.CreateTable(PrecompPoints); - - // TODO[ed25519] A single batch inversion across all blocks? - { - int[] u = F.Create(); - F.Copy(points[0].z, 0, u, 0); - F.Copy(u, 0, cs, 0); - - int i = 0; - while (++i < PrecompPoints) - { - F.Mul(u, points[i].z, u); - F.Copy(u, 0, cs, i * F.Size); - } + // Set each z coordinate to 1/(2.z) to avoid calculating halves of x, y in the following code + InvertDoubleZs(points); - F.Add(u, u, u); - F.InvVar(u, u); - --i; + PrecompBaseWnaf = new PointPrecomp[wnafPoints]; + for (int i = 0; i < wnafPoints; ++i) + { + ref PointExtended q = ref points[i]; + ref PointPrecomp r = ref PrecompBaseWnaf[i]; + Init(out r); - int[] t = F.Create(); + // Calculate x/2 and y/2 (because the z value holds half the inverse; see above). + F.Mul(q.x, q.z, q.x); + F.Mul(q.y, q.z, q.y); - while (i > 0) - { - int j = i--; - F.Copy(cs, i * F.Size, t, 0); - F.Mul(t, u, t); - F.Copy(t, 0, cs, j * F.Size); - F.Mul(u, points[j].z, u); - } + // y/2 +/- x/2 + F.Apm(q.y, q.x, r.ypx_h, r.ymx_h); - F.Copy(u, 0, cs, 0); - } + // x/2 * y/2 * (4.d) == x.y.d + F.Mul(q.x, q.y, r.xyd); + F.Mul(r.xyd, C_d4, r.xyd); - for (int i = 0; i < PrecompPoints; ++i) - { - PointExt q = points[i]; + F.Normalize(r.ymx_h); + F.Normalize(r.ypx_h); + F.Normalize(r.xyd); + } - int[] x = F.Create(); - int[] y = F.Create(); + PrecompBaseComb = F.CreateTable(combPoints * 3); + Init(out PointPrecomp s); + int off = 0; + for (int i = wnafPoints; i < totalPoints; ++i) + { + ref PointExtended q = ref points[i]; - //F.Add(q.z, q.z, x); - //F.InvVar(x, y); - F.Copy(cs, i * F.Size, y, 0); + // Calculate x/2 and y/2 (because the z value holds half the inverse; see above). + F.Mul(q.x, q.z, q.x); + F.Mul(q.y, q.z, q.y); - F.Mul(q.x, y, x); - F.Mul(q.y, y, y); + // y/2 +/- x/2 + F.Apm(q.y, q.x, s.ypx_h, s.ymx_h); - PointPrecomp r = new PointPrecomp(); - F.Apm(y, x, r.ypx_h, r.ymx_h); - F.Mul(x, y, r.xyd); - F.Mul(r.xyd, C_d4, r.xyd); + // x/2 * y/2 * (4.d) == x.y.d + F.Mul(q.x, q.y, s.xyd); + F.Mul(s.xyd, C_d4, s.xyd); - F.Normalize(r.ypx_h); - F.Normalize(r.ymx_h); - //F.Normalize(r.xyd); + F.Normalize(s.ymx_h); + F.Normalize(s.ypx_h); + F.Normalize(s.xyd); - F.Copy(r.ypx_h, 0, precompBase, off); off += F.Size; - F.Copy(r.ymx_h, 0, precompBase, off); off += F.Size; - F.Copy(r.xyd, 0, precompBase, off); off += F.Size; - } + F.Copy(s.ymx_h, 0, PrecompBaseComb, off); off += F.Size; + F.Copy(s.ypx_h, 0, PrecompBaseComb, off); off += F.Size; + F.Copy(s.xyd , 0, PrecompBaseComb, off); off += F.Size; } - - Debug.Assert(off == precompBase.Length); + Debug.Assert(off == PrecompBaseComb.Length); } } @@ -997,6 +1192,17 @@ private static void PruneScalar(byte[] n, int nOff, byte[] r) r[ScalarBytes - 1] |= 0x40; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void PruneScalar(ReadOnlySpan n, Span r) + { + n[..ScalarBytes].CopyTo(r); + + r[0] &= 0xF8; + r[ScalarBytes - 1] &= 0x7F; + r[ScalarBytes - 1] |= 0x40; + } +#endif + private static byte[] ReduceScalar(byte[] n) { long x00 = Decode32(n, 0) & M32L; // x00:32/-- @@ -1133,51 +1339,89 @@ private static byte[] ReduceScalar(byte[] n) return r; } - private static void ScalarMult(byte[] k, PointAffine p, PointAccum r) + private static void ScalarMult(byte[] k, ref PointAffine p, ref PointAccum r) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ScalarMult(k.AsSpan(), ref p, ref r); +#else uint[] n = new uint[ScalarUints]; DecodeScalar(k, 0, n); - Debug.Assert(0U == (n[0] & 7)); - Debug.Assert(1U == n[ScalarUints - 1] >> 30); + // Recode the scalar into signed-digit form + { + uint c1 = Nat.CAdd(ScalarUints, ~(int)n[0] & 1, n, L, n); Debug.Assert(c1 == 0U); + uint c2 = Nat.ShiftDownBit(ScalarUints, n, 1U); Debug.Assert(c2 == (1U << 31)); + } + + Init(out PointPrecompZ q); + Init(out PointTemp t); + int[] table = PointPrecomputeZ(ref p, 8, ref t); + + PointSetNeutral(ref r); - Nat.ShiftDownBits(ScalarUints, n, 3, 1U); + int w = 63; + for (;;) + { + PointLookupZ(n, w, table, ref q); + PointAdd(ref q, ref r, ref t); + + if (--w < 0) + break; + + for (int i = 0; i < 4; ++i) + { + PointDouble(ref r); + } + } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void ScalarMult(ReadOnlySpan k, ref PointAffine p, ref PointAccum r) + { + Span n = stackalloc uint[ScalarUints]; + DecodeScalar(k, n); // Recode the scalar into signed-digit form { uint c1 = Nat.CAdd(ScalarUints, ~(int)n[0] & 1, n, L, n); Debug.Assert(c1 == 0U); - uint c2 = Nat.ShiftDownBit(ScalarUints, n, 0U); Debug.Assert(c2 == (1U << 31)); + uint c2 = Nat.ShiftDownBit(ScalarUints, n, 1U); Debug.Assert(c2 == (1U << 31)); } - Debug.Assert(1U == n[ScalarUints - 1] >> 28); + Init(out PointPrecompZ q); + Init(out PointTemp t); + int[] table = PointPrecomputeZ(ref p, 8, ref t); - int[] table = PointPrecompute(p, 8); - PointExt q = new PointExt(); + PointSetNeutral(ref r); - // Replace first 4 doublings (2^4 * P) with 1 addition (P + 15 * P) - PointCopy(p, r); - PointLookup(table, 7, q); - PointAdd(q, r); - - int w = 62; + int w = 63; for (;;) { - PointLookup(n, w, table, q); - PointAdd(q, r); - - PointDouble(r); - PointDouble(r); - PointDouble(r); + PointLookupZ(n, w, table, ref q); + PointAdd(ref q, ref r, ref t); if (--w < 0) break; - PointDouble(r); + for (int i = 0; i < 4; ++i) + { + PointDouble(ref r); + } } } +#endif - private static void ScalarMultBase(byte[] k, PointAccum r) + private static void ScalarMultBase(byte[] k, ref PointAccum r) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ScalarMultBase(k.AsSpan(), ref r); +#else + // Equivalent (but much slower) + //Init(out PointAffine p); + //F.Copy(B_x, 0, p.x, 0); + //F.Copy(B_y, 0, p.y, 0); + //ScalarMult(k, ref p, ref r); + Precompute(); uint[] n = new uint[ScalarUints]; @@ -1188,15 +1432,88 @@ private static void ScalarMultBase(byte[] k, PointAccum r) uint c1 = Nat.CAdd(ScalarUints, ~(int)n[0] & 1, n, L, n); Debug.Assert(c1 == 0U); uint c2 = Nat.ShiftDownBit(ScalarUints, n, 1U); Debug.Assert(c2 == (1U << 31)); + /* + * Because we are using 4 teeth and 8 spacing, each limb of n corresponds to one of the 8 blocks. + * Therefore we can efficiently group the bits for each comb position using a (double) shuffle. + */ + for (int i = 0; i < ScalarUints; ++i) + { + n[i] = Interleave.Shuffle2(n[i]); + } + } + + Init(out PointPrecomp p); + Init(out PointTemp t); + + PointSetNeutral(ref r); + int resultSign = 0; + + int cOff = (PrecompSpacing - 1) * PrecompTeeth; + for (;;) + { + for (int b = 0; b < PrecompBlocks; ++b) + { + uint w = n[b] >> cOff; + int sign = (int)(w >> (PrecompTeeth - 1)) & 1; + int abs = ((int)w ^ -sign) & PrecompMask; + + Debug.Assert(sign == 0 || sign == 1); + Debug.Assert(0 <= abs && abs < PrecompPoints); + + PointLookup(b, abs, ref p); + + F.CNegate(resultSign ^ sign, r.x); + F.CNegate(resultSign ^ sign, r.u); + resultSign = sign; + + PointAdd(ref p, ref r, ref t); + } + + if ((cOff -= PrecompTeeth) < 0) + break; + + PointDouble(ref r); + } + + F.CNegate(resultSign, r.x); + F.CNegate(resultSign, r.u); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void ScalarMultBase(ReadOnlySpan k, ref PointAccum r) + { + // Equivalent (but much slower) + //Init(out PointAffine p); + //F.Copy(B_x, 0, p.x, 0); + //F.Copy(B_y, 0, p.y, 0); + //ScalarMult(k, ref p, ref r); + + Precompute(); + + Span n = stackalloc uint[ScalarUints]; + DecodeScalar(k, n); + + // Recode the scalar into signed-digit form, then group comb bits in each block + { + uint c1 = Nat.CAdd(ScalarUints, ~(int)n[0] & 1, n, L, n); Debug.Assert(c1 == 0U); + uint c2 = Nat.ShiftDownBit(ScalarUints, n, 1U); Debug.Assert(c2 == (1U << 31)); + + /* + * Because we are using 4 teeth and 8 spacing, each limb of n corresponds to one of the 8 blocks. + * Therefore we can efficiently group the bits for each comb position using a (double) shuffle. + */ for (int i = 0; i < ScalarUints; ++i) { n[i] = Interleave.Shuffle2(n[i]); } } - PointPrecomp p = new PointPrecomp(); + Init(out PointPrecomp p); + Init(out PointTemp t); - PointSetNeutral(r); + PointSetNeutral(ref r); + int resultSign = 0; int cOff = (PrecompSpacing - 1) * PrecompTeeth; for (;;) @@ -1210,55 +1527,96 @@ private static void ScalarMultBase(byte[] k, PointAccum r) Debug.Assert(sign == 0 || sign == 1); Debug.Assert(0 <= abs && abs < PrecompPoints); - PointLookup(b, abs, p); + PointLookup(b, abs, ref p); - F.CSwap(sign, p.ypx_h, p.ymx_h); - F.CNegate(sign, p.xyd); + F.CNegate(resultSign ^ sign, r.x); + F.CNegate(resultSign ^ sign, r.u); + resultSign = sign; - PointAddPrecomp(p, r); + PointAdd(ref p, ref r, ref t); } if ((cOff -= PrecompTeeth) < 0) break; - PointDouble(r); + PointDouble(ref r); } + + F.CNegate(resultSign, r.x); + F.CNegate(resultSign, r.u); } +#endif private static void ScalarMultBaseEncoded(byte[] k, byte[] r, int rOff) { - PointAccum p = new PointAccum(); - ScalarMultBase(k, p); - if (0 == EncodePoint(p, r, rOff)) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ScalarMultBaseEncoded(k.AsSpan(), r.AsSpan(rOff)); +#else + Init(out PointAccum p); + ScalarMultBase(k, ref p); + if (0 == EncodePoint(ref p, r, rOff)) throw new InvalidOperationException(); +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void ScalarMultBaseEncoded(ReadOnlySpan k, Span r) + { + Init(out PointAccum p); + ScalarMultBase(k, ref p); + if (0 == EncodePoint(ref p, r)) + throw new InvalidOperationException(); + } +#endif + internal static void ScalarMultBaseYZ(byte[] k, int kOff, int[] y, int[] z) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ScalarMultBaseYZ(k.AsSpan(kOff), y.AsSpan(), z.AsSpan()); +#else byte[] n = new byte[ScalarBytes]; PruneScalar(k, kOff, n); - PointAccum p = new PointAccum(); - ScalarMultBase(n, p); + Init(out PointAccum p); + ScalarMultBase(n, ref p); if (0 == CheckPoint(p.x, p.y, p.z)) throw new InvalidOperationException(); F.Copy(p.y, 0, y, 0); F.Copy(p.z, 0, z, 0); +#endif } - private static void ScalarMultOrderVar(PointAffine p, PointAccum r) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal static void ScalarMultBaseYZ(ReadOnlySpan k, Span y, Span z) { - int width = 5; + Span n = stackalloc byte[ScalarBytes]; + PruneScalar(k, n); - sbyte[] ws_p = GetWnafVar(L, width); + Init(out PointAccum p); + ScalarMultBase(n, ref p); - PointExt[] tp = PointPrecomputeVar(PointCopy(p), 1 << (width - 2)); + if (0 == CheckPoint(p.x, p.y, p.z)) + throw new InvalidOperationException(); - PointSetNeutral(r); + F.Copy(p.y, y); + F.Copy(p.z, z); + } +#endif - for (int bit = 252; ;) + private static void ScalarMultOrderVar(ref PointAffine p, ref PointAccum r) + { + sbyte[] ws_p = GetWnafVar(L, WnafWidth); + + int count = 1 << (WnafWidth - 2); + PointPrecompZ[] tp = new PointPrecompZ[count]; + Init(out PointTemp t); + PointPrecomputeZ(ref p, tp, count, ref t); + + PointSetNeutral(ref r); + + for (int bit = 252;;) { int wp = ws_p[bit]; if (wp != 0) @@ -1266,28 +1624,29 @@ private static void ScalarMultOrderVar(PointAffine p, PointAccum r) int sign = wp >> 31; int index = (wp ^ sign) >> 1; - PointAddVar((sign != 0), tp[index], r); + PointAddVar(sign != 0, ref tp[index], ref r, ref t); } if (--bit < 0) break; - PointDouble(r); + PointDouble(ref r); } } - private static void ScalarMultStrausVar(uint[] nb, uint[] np, PointAffine p, PointAccum r) + private static void ScalarMultStrausVar(uint[] nb, uint[] np, ref PointAffine p, ref PointAccum r) { Precompute(); - int width = 5; - sbyte[] ws_b = GetWnafVar(nb, WnafWidthBase); - sbyte[] ws_p = GetWnafVar(np, width); + sbyte[] ws_p = GetWnafVar(np, WnafWidth); - PointExt[] tp = PointPrecomputeVar(PointCopy(p), 1 << (width - 2)); + int count = 1 << (WnafWidth - 2); + PointPrecompZ[] tp = new PointPrecompZ[count]; + Init(out PointTemp t); + PointPrecomputeZ(ref p, tp, count, ref t); - PointSetNeutral(r); + PointSetNeutral(ref r); for (int bit = 252;;) { @@ -1297,7 +1656,7 @@ private static void ScalarMultStrausVar(uint[] nb, uint[] np, PointAffine p, Poi int sign = wb >> 31; int index = (wb ^ sign) >> 1; - PointAddVar((sign != 0), precompBaseTable[index], r); + PointAddVar(sign != 0, ref PrecompBaseWnaf[index], ref r, ref t); } int wp = ws_p[bit]; @@ -1306,13 +1665,13 @@ private static void ScalarMultStrausVar(uint[] nb, uint[] np, PointAffine p, Poi int sign = wp >> 31; int index = (wp ^ sign) >> 1; - PointAddVar((sign != 0), tp[index], r); + PointAddVar(sign != 0, ref tp[index], ref r, ref t); } if (--bit < 0) break; - PointDouble(r); + PointDouble(ref r); } } @@ -1384,8 +1743,8 @@ public static void SignPrehash(byte[] sk, int skOff, byte[] pk, int pkOff, byte[ public static bool ValidatePublicKeyFull(byte[] pk, int pkOff) { - PointAffine p = new PointAffine(); - if (!DecodePointVar(pk, pkOff, false, p)) + Init(out PointAffine p); + if (!DecodePointVar(pk, pkOff, false, ref p)) return false; F.Normalize(p.x); @@ -1394,8 +1753,8 @@ public static bool ValidatePublicKeyFull(byte[] pk, int pkOff) if (IsNeutralElementVar(p.x, p.y)) return false; - PointAccum r = new PointAccum(); - ScalarMultOrderVar(p, r); + Init(out PointAccum r); + ScalarMultOrderVar(ref p, ref r); F.Normalize(r.x); F.Normalize(r.y); @@ -1406,8 +1765,8 @@ public static bool ValidatePublicKeyFull(byte[] pk, int pkOff) public static bool ValidatePublicKeyPartial(byte[] pk, int pkOff) { - PointAffine p = new PointAffine(); - return DecodePointVar(pk, pkOff, false, p); + Init(out PointAffine p); + return DecodePointVar(pk, pkOff, false, ref p); } public static bool Verify(byte[] sig, int sigOff, byte[] pk, int pkOff, byte[] m, int mOff, int mLen) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc8032/Ed448.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc8032/Ed448.cs index f95ce54..9f03489 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc8032/Ed448.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/ec/rfc8032/Ed448.cs @@ -5,14 +5,25 @@ using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc7748; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC.Rfc8032 { - public abstract class Ed448 + using F = Rfc7748.X448Field; + + /// + /// A low-level implementation of the Ed448 and Ed448ph instantiations of the Edwards-Curve Digital Signature + /// Algorithm specified in RFC 8032. + /// + /// + /// The implementation uses the "signed mult-comb" algorithm (for scalar multiplication by a fixed point) from + /// Mike Hamburg, "Fast and compact elliptic-curve cryptography". Standard + /// projective coordinates are used + /// for most point arithmetic. + /// + public static class Ed448 { // x^2 + y^2 == 1 - 39081 * x^2 * y^2 @@ -22,8 +33,6 @@ public enum Algorithm Ed448ph = 1, } - private class F : X448Field {}; - private const ulong M26UL = 0x03FFFFFFUL; private const ulong M28UL = 0x0FFFFFFFUL; @@ -69,30 +78,29 @@ private class F : X448Field {}; 0x005A0C2DU, 0x07789C1EU, 0x0A398408U, 0x0A73736CU, 0x0C7624BEU, 0x003756C9U, 0x02488762U, 0x016EB6BCU, 0x0693F467U }; private const int C_d = -39081; + private const int WnafWidth = 5; private const int WnafWidthBase = 7; + // ScalarMultBase supports varying blocks, teeth, spacing so long as their product is in range [449, 479] private const int PrecompBlocks = 5; private const int PrecompTeeth = 5; private const int PrecompSpacing = 18; + private const int PrecompRange = PrecompBlocks * PrecompTeeth * PrecompSpacing; // 448 < range < 480 private const int PrecompPoints = 1 << (PrecompTeeth - 1); private const int PrecompMask = PrecompPoints - 1; - private static readonly object precompLock = new object(); - // TODO[ed448] Convert to PointPrecomp - private static PointExt[] precompBaseTable = null; - private static uint[] precompBase = null; + private static readonly object PrecompLock = new object(); + private static PointAffine[] PrecompBaseWnaf = null; + private static uint[] PrecompBaseComb = null; - private class PointExt + private struct PointAffine { - internal uint[] x = F.Create(); - internal uint[] y = F.Create(); - internal uint[] z = F.Create(); + internal uint[] x, y; } - private class PointPrecomp + private struct PointProjective { - internal uint[] x = F.Create(); - internal uint[] y = F.Create(); + internal uint[] x, y, z; } private static byte[] CalculateS(byte[] r, byte[] k, byte[] s) @@ -216,6 +224,17 @@ private static uint Decode32(byte[] bs, int off) return n; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static uint Decode32(ReadOnlySpan bs) + { + uint n = bs[0]; + n |= (uint)bs[1] << 8; + n |= (uint)bs[2] << 16; + n |= (uint)bs[3] << 24; + return n; + } +#endif + private static void Decode32(byte[] bs, int bsOff, uint[] n, int nOff, int nLen) { for (int i = 0; i < nLen; ++i) @@ -224,7 +243,17 @@ private static void Decode32(byte[] bs, int bsOff, uint[] n, int nOff, int nLen) } } - private static bool DecodePointVar(byte[] p, int pOff, bool negate, PointExt r) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void Decode32(ReadOnlySpan bs, Span n) + { + for (int i = 0; i < n.Length; ++i) + { + n[i] = Decode32(bs[(i * 4)..]); + } + } +#endif + + private static bool DecodePointVar(byte[] p, int pOff, bool negate, ref PointProjective r) { byte[] py = Copy(p, pOff, PointBytes); if (!CheckPointVar(py)) @@ -256,7 +285,7 @@ private static bool DecodePointVar(byte[] p, int pOff, bool negate, PointExt r) F.Negate(r.x, r.x); } - PointExtendXY(r); + F.One(r.z); return true; } @@ -267,6 +296,15 @@ private static void DecodeScalar(byte[] k, int kOff, uint[] n) Decode32(k, kOff, n, 0, ScalarUints); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void DecodeScalar(ReadOnlySpan k, Span n) + { + Debug.Assert(k[ScalarBytes - 1] == 0x00); + + Decode32(k, n[..ScalarUints]); + } +#endif + private static void Dom4(IXof d, byte phflag, byte[] ctx) { int n = Dom4Prefix.Length; @@ -300,7 +338,7 @@ private static void Encode56(ulong n, byte[] bs, int off) Encode24((uint)(n >> 32), bs, off + 4); } - private static int EncodePoint(PointExt p, byte[] r, int rOff) + private static int EncodePoint(ref PointProjective p, byte[] r, int rOff) { uint[] x = F.Create(); uint[] y = F.Create(); @@ -319,26 +357,84 @@ private static int EncodePoint(PointExt p, byte[] r, int rOff) return result; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static int EncodePoint(ref PointProjective p, Span r) + { + uint[] x = F.Create(); + uint[] y = F.Create(); + + F.Inv(p.z, y); + F.Mul(p.x, y, x); + F.Mul(p.y, y, y); + F.Normalize(x); + F.Normalize(y); + + int result = CheckPoint(x, y); + + F.Encode(y, r); + r[PointBytes - 1] = (byte)((x[0] & 1) << 7); + + return result; + } +#endif + public static void GeneratePrivateKey(SecureRandom random, byte[] k) { + if (k.Length != SecretKeySize) + throw new ArgumentException(nameof(k)); + + random.NextBytes(k); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void GeneratePrivateKey(SecureRandom random, Span k) + { + if (k.Length != SecretKeySize) + throw new ArgumentException(nameof(k)); + random.NextBytes(k); } +#endif public static void GeneratePublicKey(byte[] sk, int skOff, byte[] pk, int pkOff) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + GeneratePublicKey(sk.AsSpan(skOff), pk.AsSpan(pkOff)); +#else IXof d = CreateXof(); byte[] h = new byte[ScalarBytes * 2]; d.BlockUpdate(sk, skOff, SecretKeySize); - d.DoFinal(h, 0, h.Length); + d.OutputFinal(h, 0, h.Length); byte[] s = new byte[ScalarBytes]; PruneScalar(h, 0, s); ScalarMultBaseEncoded(s, pk, pkOff); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void GeneratePublicKey(ReadOnlySpan sk, Span pk) + { + IXof d = CreateXof(); + Span h = stackalloc byte[ScalarBytes * 2]; + + d.BlockUpdate(sk[..SecretKeySize]); + d.OutputFinal(h); + + Span s = stackalloc byte[ScalarBytes]; + PruneScalar(h, s); + + ScalarMultBaseEncoded(s, pk); } +#endif +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static uint GetWindow4(ReadOnlySpan x, int n) +#else private static uint GetWindow4(uint[] x, int n) +#endif { int w = (int)((uint)n >> 3), b = (n & 7) << 2; return (x[w] >> b) & 15U; @@ -401,7 +497,7 @@ private static void ImplSign(IXof d, byte[] h, byte[] s, byte[] pk, int pkOff, b Dom4(d, phflag, ctx); d.BlockUpdate(h, ScalarBytes, ScalarBytes); d.BlockUpdate(m, mOff, mLen); - d.DoFinal(h, 0, h.Length); + d.OutputFinal(h, 0, h.Length); byte[] r = ReduceScalar(h); byte[] R = new byte[PointBytes]; @@ -411,7 +507,7 @@ private static void ImplSign(IXof d, byte[] h, byte[] s, byte[] pk, int pkOff, b d.BlockUpdate(R, 0, PointBytes); d.BlockUpdate(pk, pkOff, PointBytes); d.BlockUpdate(m, mOff, mLen); - d.DoFinal(h, 0, h.Length); + d.OutputFinal(h, 0, h.Length); byte[] k = ReduceScalar(h); byte[] S = CalculateS(r, k, s); @@ -430,7 +526,7 @@ private static void ImplSign(byte[] sk, int skOff, byte[] ctx, byte phflag, byte byte[] h = new byte[ScalarBytes * 2]; d.BlockUpdate(sk, skOff, SecretKeySize); - d.DoFinal(h, 0, h.Length); + d.OutputFinal(h, 0, h.Length); byte[] s = new byte[ScalarBytes]; PruneScalar(h, 0, s); @@ -451,7 +547,7 @@ private static void ImplSign(byte[] sk, int skOff, byte[] pk, int pkOff, byte[] byte[] h = new byte[ScalarBytes * 2]; d.BlockUpdate(sk, skOff, SecretKeySize); - d.DoFinal(h, 0, h.Length); + d.OutputFinal(h, 0, h.Length); byte[] s = new byte[ScalarBytes]; PruneScalar(h, 0, s); @@ -475,8 +571,8 @@ private static bool ImplVerify(byte[] sig, int sigOff, byte[] pk, int pkOff, byt if (!CheckScalarVar(S, nS)) return false; - PointExt pA = new PointExt(); - if (!DecodePointVar(pk, pkOff, true, pA)) + Init(out PointProjective pA); + if (!DecodePointVar(pk, pkOff, true, ref pA)) return false; IXof d = CreateXof(); @@ -486,23 +582,64 @@ private static bool ImplVerify(byte[] sig, int sigOff, byte[] pk, int pkOff, byt d.BlockUpdate(R, 0, PointBytes); d.BlockUpdate(pk, pkOff, PointBytes); d.BlockUpdate(m, mOff, mLen); - d.DoFinal(h, 0, h.Length); + d.OutputFinal(h, 0, h.Length); byte[] k = ReduceScalar(h); uint[] nA = new uint[ScalarUints]; DecodeScalar(k, 0, nA); - PointExt pR = new PointExt(); - ScalarMultStrausVar(nS, nA, pA, pR); + Init(out PointProjective pR); + ScalarMultStrausVar(nS, nA, ref pA, ref pR); byte[] check = new byte[PointBytes]; - return 0 != EncodePoint(pR, check, 0) && Arrays.AreEqual(check, R); + return 0 != EncodePoint(ref pR, check, 0) && Arrays.AreEqual(check, R); + } + + private static void Init(out PointAffine r) + { + r.x = F.Create(); + r.y = F.Create(); } - private static bool IsNeutralElementVar(uint[] x, uint[] y) + private static void Init(out PointProjective r) { - return F.IsZeroVar(x) && F.IsOneVar(y); + r.x = F.Create(); + r.y = F.Create(); + r.z = F.Create(); + } + + private static void InvertZs(PointProjective[] points) + { + int count = points.Length; + uint[] cs = F.CreateTable(count); + + uint[] u = F.Create(); + F.Copy(points[0].z, 0, u, 0); + F.Copy(u, 0, cs, 0); + + int i = 0; + while (++i < count) + { + F.Mul(u, points[i].z, u); + F.Copy(u, 0, cs, i * F.Size); + } + + F.InvVar(u, u); + --i; + + uint[] t = F.Create(); + + while (i > 0) + { + int j = i--; + F.Copy(cs, i * F.Size, t, 0); + F.Mul(t, u, t); + F.Mul(u, points[j].z, u); + F.Copy(t, 0, points[j].z, 0); + } + + F.Copy(u, 0, points[0].z, 0); } private static bool IsNeutralElementVar(uint[] x, uint[] y, uint[] z) @@ -510,7 +647,40 @@ private static bool IsNeutralElementVar(uint[] x, uint[] y, uint[] z) return F.IsZeroVar(x) && F.AreEqualVar(y, z); } - private static void PointAdd(PointExt p, PointExt r) + private static void PointAdd(ref PointAffine p, ref PointProjective r) + { + uint[] b = F.Create(); + uint[] c = F.Create(); + uint[] d = F.Create(); + uint[] e = F.Create(); + uint[] f = F.Create(); + uint[] g = F.Create(); + uint[] h = F.Create(); + + F.Sqr(r.z, b); + F.Mul(p.x, r.x, c); + F.Mul(p.y, r.y, d); + F.Mul(c, d, e); + F.Mul(e, -C_d, e); + //F.Apm(b, e, f, g); + F.Add(b, e, f); + F.Sub(b, e, g); + F.Add(p.y, p.x, h); + F.Add(r.y, r.x, e); + F.Mul(h, e, h); + //F.Apm(d, c, b, e); + F.Add(d, c, b); + F.Sub(d, c, e); + F.Carry(b); + F.Sub(h, b, h); + F.Mul(h, r.z, h); + F.Mul(e, r.z, e); + F.Mul(f, h, r.x); + F.Mul(e, g, r.y); + F.Mul(f, g, r.z); + } + + private static void PointAdd(ref PointProjective p, ref PointProjective r) { uint[] a = F.Create(); uint[] b = F.Create(); @@ -530,9 +700,9 @@ private static void PointAdd(PointExt p, PointExt r) //F.Apm(b, e, f, g); F.Add(b, e, f); F.Sub(b, e, g); - F.Add(p.x, p.y, b); - F.Add(r.x, r.y, e); - F.Mul(b, e, h); + F.Add(p.y, p.x, h); + F.Add(r.y, r.x, e); + F.Mul(h, e, h); //F.Apm(d, c, b, e); F.Add(d, c, b); F.Sub(d, c, e); @@ -545,9 +715,8 @@ private static void PointAdd(PointExt p, PointExt r) F.Mul(f, g, r.z); } - private static void PointAddVar(bool negate, PointExt p, PointExt r) + private static void PointAddVar(bool negate, ref PointAffine p, ref PointProjective r) { - uint[] a = F.Create(); uint[] b = F.Create(); uint[] c = F.Create(); uint[] d = F.Create(); @@ -568,8 +737,7 @@ private static void PointAddVar(bool negate, PointExt p, PointExt r) F.Add(p.y, p.x, h); } - F.Mul(p.z, r.z, a); - F.Sqr(a, b); + F.Sqr(r.z, b); F.Mul(p.x, r.x, c); F.Mul(p.y, r.y, d); F.Mul(c, d, e); @@ -577,22 +745,23 @@ private static void PointAddVar(bool negate, PointExt p, PointExt r) //F.Apm(b, e, nf, ng); F.Add(b, e, nf); F.Sub(b, e, ng); - F.Add(r.x, r.y, e); + F.Add(r.y, r.x, e); F.Mul(h, e, h); //F.Apm(d, c, nb, ne); F.Add(d, c, nb); F.Sub(d, c, ne); F.Carry(nb); F.Sub(h, b, h); - F.Mul(h, a, h); - F.Mul(e, a, e); + F.Mul(h, r.z, h); + F.Mul(e, r.z, e); F.Mul(f, h, r.x); F.Mul(e, g, r.y); F.Mul(f, g, r.z); } - private static void PointAddPrecomp(PointPrecomp p, PointExt r) + private static void PointAddVar(bool negate, ref PointProjective p, ref PointProjective r) { + uint[] a = F.Create(); uint[] b = F.Create(); uint[] c = F.Create(); uint[] d = F.Create(); @@ -601,44 +770,49 @@ private static void PointAddPrecomp(PointPrecomp p, PointExt r) uint[] g = F.Create(); uint[] h = F.Create(); - F.Sqr(r.z, b); + uint[] nb, ne, nf, ng; + if (negate) + { + nb = e; ne = b; nf = g; ng = f; + F.Sub(p.y, p.x, h); + } + else + { + nb = b; ne = e; nf = f; ng = g; + F.Add(p.y, p.x, h); + } + + F.Mul(p.z, r.z, a); + F.Sqr(a, b); F.Mul(p.x, r.x, c); F.Mul(p.y, r.y, d); F.Mul(c, d, e); F.Mul(e, -C_d, e); - //F.Apm(b, e, f, g); - F.Add(b, e, f); - F.Sub(b, e, g); - F.Add(p.x, p.y, b); - F.Add(r.x, r.y, e); - F.Mul(b, e, h); - //F.Apm(d, c, b, e); - F.Add(d, c, b); - F.Sub(d, c, e); - F.Carry(b); + //F.Apm(b, e, nf, ng); + F.Add(b, e, nf); + F.Sub(b, e, ng); + F.Add(r.y, r.x, e); + F.Mul(h, e, h); + //F.Apm(d, c, nb, ne); + F.Add(d, c, nb); + F.Sub(d, c, ne); + F.Carry(nb); F.Sub(h, b, h); - F.Mul(h, r.z, h); - F.Mul(e, r.z, e); + F.Mul(h, a, h); + F.Mul(e, a, e); F.Mul(f, h, r.x); F.Mul(e, g, r.y); F.Mul(f, g, r.z); } - private static PointExt PointCopy(PointExt p) - { - PointExt r = new PointExt(); - PointCopy(p, r); - return r; - } - - private static void PointCopy(PointExt p, PointExt r) + private static void PointCopy(ref PointProjective p, ref PointProjective r) { F.Copy(p.x, 0, r.x, 0); F.Copy(p.y, 0, r.y, 0); F.Copy(p.z, 0, r.z, 0); } - private static void PointDouble(PointExt r) + private static void PointDouble(ref PointProjective r) { uint[] b = F.Create(); uint[] c = F.Create(); @@ -664,12 +838,7 @@ private static void PointDouble(PointExt r) F.Mul(e, j, r.z); } - private static void PointExtendXY(PointExt p) - { - F.One(p.z); - } - - private static void PointLookup(int block, int index, PointPrecomp p) + private static void PointLookup(int block, int index, ref PointAffine p) { Debug.Assert(0 <= block && block < PrecompBlocks); Debug.Assert(0 <= index && index < PrecompPoints); @@ -679,12 +848,36 @@ private static void PointLookup(int block, int index, PointPrecomp p) for (int i = 0; i < PrecompPoints; ++i) { int cond = ((i ^ index) - 1) >> 31; - F.CMov(cond, precompBase, off, p.x, 0); off += F.Size; - F.CMov(cond, precompBase, off, p.y, 0); off += F.Size; + F.CMov(cond, PrecompBaseComb, off, p.x, 0); off += F.Size; + F.CMov(cond, PrecompBaseComb, off, p.y, 0); off += F.Size; } } - private static void PointLookup(uint[] x, int n, uint[] table, PointExt r) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void PointLookup(ReadOnlySpan x, int n, ReadOnlySpan table, ref PointProjective r) + { + // TODO This method is currently hardcoded to 4-bit windows and 8 precomputed points + + uint w = GetWindow4(x, n); + + int sign = (int)(w >> (4 - 1)) ^ 1; + int abs = ((int)w ^ -sign) & 7; + + Debug.Assert(sign == 0 || sign == 1); + Debug.Assert(0 <= abs && abs < 8); + + for (int i = 0; i < 8; ++i) + { + int cond = ((i ^ abs) - 1) >> 31; + F.CMov(cond, table, r.x); table = table[F.Size..]; + F.CMov(cond, table, r.y); table = table[F.Size..]; + F.CMov(cond, table, r.z); table = table[F.Size..]; + } + + F.CNegate(sign, r.x); + } +#else + private static void PointLookup(uint[] x, int n, uint[] table, ref PointProjective r) { // TODO This method is currently hardcoded to 4-bit windows and 8 precomputed points @@ -706,14 +899,27 @@ private static void PointLookup(uint[] x, int n, uint[] table, PointExt r) F.CNegate(sign, r.x); } +#endif + + private static void PointLookup15(uint[] table, ref PointProjective r) + { + int off = F.Size * 3 * 7; + + F.Copy(table, off, r.x, 0); off += F.Size; + F.Copy(table, off, r.y, 0); off += F.Size; + F.Copy(table, off, r.z, 0); + } - private static uint[] PointPrecompute(PointExt p, int count) + private static uint[] PointPrecompute(ref PointProjective p, int count) { Debug.Assert(count > 0); - PointExt q = PointCopy(p); - PointExt d = PointCopy(q); - PointDouble(d); + Init(out PointProjective q); + PointCopy(ref p, ref q); + + Init(out PointProjective d); + PointCopy(ref q, ref d); + PointDouble(ref d); uint[] table = F.CreateTable(count * 3); int off = 0; @@ -728,30 +934,31 @@ private static uint[] PointPrecompute(PointExt p, int count) if (++i == count) break; - PointAdd(d, q); + PointAdd(ref d, ref q); } return table; } - private static PointExt[] PointPrecomputeVar(PointExt p, int count) + private static void PointPrecomputeVar(ref PointProjective p, PointProjective[] points, int count) { Debug.Assert(count > 0); - PointExt d = PointCopy(p); - PointDouble(d); + Init(out PointProjective d); + PointCopy(ref p, ref d); + PointDouble(ref d); - PointExt[] table = new PointExt[count]; - table[0] = PointCopy(p); + Init(out points[0]); + PointCopy(ref p, ref points[0]); for (int i = 1; i < count; ++i) { - table[i] = PointCopy(table[i - 1]); - PointAddVar(false, d, table[i]); + Init(out points[i]); + PointCopy(ref points[i - 1], ref points[i]); + PointAdd(ref d, ref points[i]); } - return table; } - private static void PointSetNeutral(PointExt p) + private static void PointSetNeutral(ref PointProjective p) { F.Zero(p.x); F.One(p.y); @@ -760,111 +967,102 @@ private static void PointSetNeutral(PointExt p) public static void Precompute() { - lock (precompLock) + lock (PrecompLock) { - if (precompBase != null) + if (PrecompBaseWnaf != null && PrecompBaseComb != null) return; - PointExt p = new PointExt(); + Debug.Assert(PrecompRange > 448); + Debug.Assert(PrecompRange < 480); + + int wnafPoints = 1 << (WnafWidthBase - 2); + int combPoints = PrecompBlocks * PrecompPoints; + int totalPoints = wnafPoints + combPoints; + + PointProjective[] points = new PointProjective[totalPoints]; + + Init(out PointProjective p); F.Copy(B_x, 0, p.x, 0); F.Copy(B_y, 0, p.y, 0); - PointExtendXY(p); - - precompBaseTable = PointPrecomputeVar(p, 1 << (WnafWidthBase - 2)); + F.One(p.z); - precompBase = F.CreateTable(PrecompBlocks * PrecompPoints * 2); + PointPrecomputeVar(ref p, points, wnafPoints); - int off = 0; - for (int b = 0; b < PrecompBlocks; ++b) + int pointsIndex = wnafPoints; + PointProjective[] toothPowers = new PointProjective[PrecompTeeth]; + for (int tooth = 0; tooth < PrecompTeeth; ++tooth) { - PointExt[] ds = new PointExt[PrecompTeeth]; - - PointExt sum = new PointExt(); - PointSetNeutral(sum); + Init(out toothPowers[tooth]); + } + for (int block = 0; block < PrecompBlocks; ++block) + { + ref PointProjective sum = ref points[pointsIndex++]; + Init(out sum); - for (int t = 0; t < PrecompTeeth; ++t) + for (int tooth = 0; tooth < PrecompTeeth; ++tooth) { - PointAddVar(true, p, sum); - PointDouble(p); + if (tooth == 0) + { + PointCopy(ref p, ref sum); + } + else + { + PointAdd(ref p, ref sum); + } - ds[t] = PointCopy(p); + PointDouble(ref p); + PointCopy(ref p, ref toothPowers[tooth]); - if (b + t != PrecompBlocks + PrecompTeeth - 2) + if (block + tooth != PrecompBlocks + PrecompTeeth - 2) { - for (int s = 1; s < PrecompSpacing; ++s) + for (int spacing = 1; spacing < PrecompSpacing; ++spacing) { - PointDouble(p); + PointDouble(ref p); } } } - PointExt[] points = new PointExt[PrecompPoints]; - int k = 0; - points[k++] = sum; + F.Negate(sum.x, sum.x); - for (int t = 0; t < (PrecompTeeth - 1); ++t) + for (int tooth = 0; tooth < (PrecompTeeth - 1); ++tooth) { - int size = 1 << t; - for (int j = 0; j < size; ++j, ++k) + int size = 1 << tooth; + for (int j = 0; j < size; ++j, ++pointsIndex) { - points[k] = PointCopy(points[k - size]); - PointAddVar(false, ds[t], points[k]); + Init(out points[pointsIndex]); + PointCopy(ref points[pointsIndex - size], ref points[pointsIndex]); + PointAdd(ref toothPowers[tooth], ref points[pointsIndex]); } } + } + Debug.Assert(pointsIndex == totalPoints); - Debug.Assert(k == PrecompPoints); - - uint[] cs = F.CreateTable(PrecompPoints); - - // TODO[ed448] A single batch inversion across all blocks? - { - uint[] u = F.Create(); - F.Copy(points[0].z, 0, u, 0); - F.Copy(u, 0, cs, 0); - - int i = 0; - while (++i < PrecompPoints) - { - F.Mul(u, points[i].z, u); - F.Copy(u, 0, cs, i * F.Size); - } - - F.InvVar(u, u); - --i; - - uint[] t = F.Create(); - - while (i > 0) - { - int j = i--; - F.Copy(cs, i * F.Size, t, 0); - F.Mul(t, u, t); - F.Copy(t, 0, cs, j * F.Size); - F.Mul(u, points[j].z, u); - } - - F.Copy(u, 0, cs, 0); - } + InvertZs(points); - for (int i = 0; i < PrecompPoints; ++i) - { - PointExt q = points[i]; + PrecompBaseWnaf = new PointAffine[wnafPoints]; + for (int i = 0; i < wnafPoints; ++i) + { + ref PointProjective q = ref points[i]; + ref PointAffine r = ref PrecompBaseWnaf[i]; + Init(out r); - //F.InvVar(q.z, q.z); - F.Copy(cs, i * F.Size, q.z, 0); + F.Mul(q.x, q.z, r.x); F.Normalize(r.x); + F.Mul(q.y, q.z, r.y); F.Normalize(r.y); + } - F.Mul(q.x, q.z, q.x); - F.Mul(q.y, q.z, q.y); + PrecompBaseComb = F.CreateTable(combPoints * 2); + int off = 0; + for (int i = wnafPoints; i < totalPoints; ++i) + { + ref PointProjective q = ref points[i]; - //F.Normalize(q.x); - //F.Normalize(q.y); + F.Mul(q.x, q.z, q.x); F.Normalize(q.x); + F.Mul(q.y, q.z, q.y); F.Normalize(q.y); - F.Copy(q.x, 0, precompBase, off); off += F.Size; - F.Copy(q.y, 0, precompBase, off); off += F.Size; - } + F.Copy(q.x, 0, PrecompBaseComb, off); off += F.Size; + F.Copy(q.y, 0, PrecompBaseComb, off); off += F.Size; } - - Debug.Assert(off == precompBase.Length); + Debug.Assert(off == PrecompBaseComb.Length); } } @@ -877,6 +1075,17 @@ private static void PruneScalar(byte[] n, int nOff, byte[] r) r[ScalarBytes - 1] = 0x00; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void PruneScalar(ReadOnlySpan n, Span r) + { + n[..(ScalarBytes - 1)].CopyTo(r); + + r[0] &= 0xFC; + r[ScalarBytes - 2] |= 0x80; + r[ScalarBytes - 1] = 0x00; + } +#endif + private static byte[] ReduceScalar(byte[] n) { ulong x00 = Decode32(n, 0); // x00:32/-- @@ -1154,46 +1363,96 @@ private static byte[] ReduceScalar(byte[] n) return r; } - private static void ScalarMult(byte[] k, PointExt p, PointExt r) + private static void ScalarMult(byte[] k, ref PointProjective p, ref PointProjective r) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ScalarMult(k.AsSpan(), ref p, ref r); +#else uint[] n = new uint[ScalarUints]; DecodeScalar(k, 0, n); - Debug.Assert(0U == (n[0] & 3)); - Debug.Assert(1U == n[ScalarUints - 1] >> 31); - - Nat.ShiftDownBits(ScalarUints, n, 2, 0U); - // Recode the scalar into signed-digit form { - uint c1 = Nat.CAdd(ScalarUints, ~(int)n[0] & 1, n, L, n); Debug.Assert(c1 == 0U); - uint c2 = Nat.ShiftDownBit(ScalarUints, n, 1U); Debug.Assert(c2 == (1U << 31)); + uint c1 = Nat.CAdd(ScalarUints, ~(int)n[0] & 1, n, L, n); + uint c2 = Nat.ShiftDownBit(ScalarUints, n, c1); Debug.Assert(c2 == (1U << 31)); + + // NOTE: Bit 448 is implicitly set after the signed-digit recoding } - uint[] table = PointPrecompute(p, 8); - PointExt q = new PointExt(); + uint[] table = PointPrecompute(ref p, 8); + Init(out PointProjective q); - PointLookup(n, 111, table, r); + // Replace first 4 doublings (2^4 * P) with 1 addition (P + 15 * P) + PointLookup15(table, ref r); + PointAdd(ref p, ref r); - for (int w = 110; w >= 0; --w) + int w = 111; + for (;;) { + PointLookup(n, w, table, ref q); + PointAdd(ref q, ref r); + + if (--w < 0) + break; + for (int i = 0; i < 4; ++i) { - PointDouble(r); + PointDouble(ref r); } + } +#endif + } - PointLookup(n, w, table, q); - PointAdd(q, r); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void ScalarMult(ReadOnlySpan k, ref PointProjective p, ref PointProjective r) + { + Span n = stackalloc uint[ScalarUints]; + DecodeScalar(k, n); + + // Recode the scalar into signed-digit form + { + uint c1 = Nat.CAdd(ScalarUints, ~(int)n[0] & 1, n, L, n); + uint c2 = Nat.ShiftDownBit(ScalarUints, n, c1); Debug.Assert(c2 == (1U << 31)); + + // NOTE: Bit 448 is implicitly set after the signed-digit recoding } - for (int i = 0; i < 2; ++i) + uint[] table = PointPrecompute(ref p, 8); + Init(out PointProjective q); + + // Replace first 4 doublings (2^4 * P) with 1 addition (P + 15 * P) + PointLookup15(table, ref r); + PointAdd(ref p, ref r); + + int w = 111; + for (;;) { - PointDouble(r); + PointLookup(n, w, table, ref q); + PointAdd(ref q, ref r); + + if (--w < 0) + break; + + for (int i = 0; i < 4; ++i) + { + PointDouble(ref r); + } } } +#endif - private static void ScalarMultBase(byte[] k, PointExt r) + private static void ScalarMultBase(byte[] k, ref PointProjective r) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ScalarMultBase(k.AsSpan(), ref r); +#else + // Equivalent (but much slower) + //Init(out PointProjective p); + //F.Copy(B_x, 0, p.x, 0); + //F.Copy(B_y, 0, p.y, 0); + //F.One(p.z); + //ScalarMult(k, ref p, ref r); + Precompute(); uint[] n = new uint[ScalarUints + 1]; @@ -1201,14 +1460,15 @@ private static void ScalarMultBase(byte[] k, PointExt r) // Recode the scalar into signed-digit form { - n[ScalarUints] = 4U + Nat.CAdd(ScalarUints, ~(int)n[0] & 1, n, L, n); + n[ScalarUints] = (1U << (PrecompRange - 448)) + + Nat.CAdd(ScalarUints, ~(int)n[0] & 1, n, L, n); uint c = Nat.ShiftDownBit(n.Length, n, 0); Debug.Assert(c == (1U << 31)); } - PointPrecomp p = new PointPrecomp(); + Init(out PointAffine p); - PointSetNeutral(r); + PointSetNeutral(ref r); int cOff = PrecompSpacing - 1; for (;;) @@ -1232,54 +1492,154 @@ private static void ScalarMultBase(byte[] k, PointExt r) Debug.Assert(sign == 0 || sign == 1); Debug.Assert(0 <= abs && abs < PrecompPoints); - PointLookup(b, abs, p); + PointLookup(b, abs, ref p); F.CNegate(sign, p.x); - PointAddPrecomp(p, r); + PointAdd(ref p, ref r); } if (--cOff < 0) break; - PointDouble(r); + PointDouble(ref r); } +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void ScalarMultBase(ReadOnlySpan k, ref PointProjective r) + { + // Equivalent (but much slower) + //Init(out PointProjective p); + //F.Copy(B_x, 0, p.x, 0); + //F.Copy(B_y, 0, p.y, 0); + //F.One(p.z); + //ScalarMult(k, ref p, ref r); + + Precompute(); + + Span n = stackalloc uint[ScalarUints + 1]; + DecodeScalar(k, n); + + // Recode the scalar into signed-digit form + { + n[ScalarUints] = (1U << (PrecompRange - 448)) + + Nat.CAdd(ScalarUints, ~(int)n[0] & 1, n, L, n); + uint c = Nat.ShiftDownBit(n.Length, n, 0); + Debug.Assert(c == (1U << 31)); + } + + Init(out PointAffine p); + + PointSetNeutral(ref r); + + int cOff = PrecompSpacing - 1; + for (;;) + { + int tPos = cOff; + + for (int b = 0; b < PrecompBlocks; ++b) + { + uint w = 0; + for (int t = 0; t < PrecompTeeth; ++t) + { + uint tBit = n[tPos >> 5] >> (tPos & 0x1F); + w &= ~(1U << t); + w ^= (tBit << t); + tPos += PrecompSpacing; + } + + int sign = (int)(w >> (PrecompTeeth - 1)) & 1; + int abs = ((int)w ^ -sign) & PrecompMask; + + Debug.Assert(sign == 0 || sign == 1); + Debug.Assert(0 <= abs && abs < PrecompPoints); + + PointLookup(b, abs, ref p); + + F.CNegate(sign, p.x); + + PointAdd(ref p, ref r); + } + + if (--cOff < 0) + break; + + PointDouble(ref r); + } + } +#endif + private static void ScalarMultBaseEncoded(byte[] k, byte[] r, int rOff) { - PointExt p = new PointExt(); - ScalarMultBase(k, p); - if (0 == EncodePoint(p, r, rOff)) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ScalarMultBaseEncoded(k.AsSpan(), r.AsSpan(rOff)); +#else + Init(out PointProjective p); + ScalarMultBase(k, ref p); + if (0 == EncodePoint(ref p, r, rOff)) + throw new InvalidOperationException(); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void ScalarMultBaseEncoded(ReadOnlySpan k, Span r) + { + Init(out PointProjective p); + ScalarMultBase(k, ref p); + if (0 == EncodePoint(ref p, r)) throw new InvalidOperationException(); } +#endif internal static void ScalarMultBaseXY(byte[] k, int kOff, uint[] x, uint[] y) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ScalarMultBaseXY(k.AsSpan(kOff), x.AsSpan(), y.AsSpan()); +#else byte[] n = new byte[ScalarBytes]; PruneScalar(k, kOff, n); - PointExt p = new PointExt(); - ScalarMultBase(n, p); + Init(out PointProjective p); + ScalarMultBase(n, ref p); if (0 == CheckPoint(p.x, p.y, p.z)) throw new InvalidOperationException(); F.Copy(p.x, 0, x, 0); F.Copy(p.y, 0, y, 0); +#endif } - private static void ScalarMultOrderVar(PointExt p, PointExt r) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal static void ScalarMultBaseXY(ReadOnlySpan k, Span x, Span y) { - int width = 5; + Span n = stackalloc byte[ScalarBytes]; + PruneScalar(k, n); - sbyte[] ws_p = GetWnafVar(L, width); + Init(out PointProjective p); + ScalarMultBase(n, ref p); - PointExt[] tp = PointPrecomputeVar(p, 1 << (width - 2)); + if (0 == CheckPoint(p.x, p.y, p.z)) + throw new InvalidOperationException(); - PointSetNeutral(r); + F.Copy(p.x, x); + F.Copy(p.y, y); + } +#endif + + private static void ScalarMultOrderVar(ref PointProjective p, ref PointProjective r) + { + sbyte[] ws_p = GetWnafVar(L, WnafWidth); - for (int bit = 446; ;) + int count = 1 << (WnafWidth - 2); + PointProjective[] tp = new PointProjective[count]; + PointPrecomputeVar(ref p, tp, count); + + PointSetNeutral(ref r); + + for (int bit = 446;;) { int wp = ws_p[bit]; if (wp != 0) @@ -1287,28 +1647,28 @@ private static void ScalarMultOrderVar(PointExt p, PointExt r) int sign = wp >> 31; int index = (wp ^ sign) >> 1; - PointAddVar((sign != 0), tp[index], r); + PointAddVar(sign != 0, ref tp[index], ref r); } if (--bit < 0) break; - PointDouble(r); + PointDouble(ref r); } } - private static void ScalarMultStrausVar(uint[] nb, uint[] np, PointExt p, PointExt r) + private static void ScalarMultStrausVar(uint[] nb, uint[] np, ref PointProjective p, ref PointProjective r) { Precompute(); - int width = 5; - sbyte[] ws_b = GetWnafVar(nb, WnafWidthBase); - sbyte[] ws_p = GetWnafVar(np, width); + sbyte[] ws_p = GetWnafVar(np, WnafWidth); - PointExt[] tp = PointPrecomputeVar(p, 1 << (width - 2)); + int count = 1 << (WnafWidth - 2); + PointProjective[] tp = new PointProjective[count]; + PointPrecomputeVar(ref p, tp, count); - PointSetNeutral(r); + PointSetNeutral(ref r); for (int bit = 446;;) { @@ -1318,7 +1678,7 @@ private static void ScalarMultStrausVar(uint[] nb, uint[] np, PointExt p, PointE int sign = wb >> 31; int index = (wb ^ sign) >> 1; - PointAddVar((sign != 0), precompBaseTable[index], r); + PointAddVar(sign != 0, ref PrecompBaseWnaf[index], ref r); } int wp = ws_p[bit]; @@ -1327,13 +1687,13 @@ private static void ScalarMultStrausVar(uint[] nb, uint[] np, PointExt p, PointE int sign = wp >> 31; int index = (wp ^ sign) >> 1; - PointAddVar((sign != 0), tp[index], r); + PointAddVar(sign != 0, ref tp[index], ref r); } if (--bit < 0) break; - PointDouble(r); + PointDouble(ref r); } } @@ -1368,7 +1728,7 @@ public static void SignPrehash(byte[] sk, int skOff, byte[] pk, int pkOff, byte[ public static void SignPrehash(byte[] sk, int skOff, byte[] ctx, IXof ph, byte[] sig, int sigOff) { byte[] m = new byte[PrehashSize]; - if (PrehashSize != ph.DoFinal(m, 0, PrehashSize)) + if (PrehashSize != ph.OutputFinal(m, 0, PrehashSize)) throw new ArgumentException("ph"); byte phflag = 0x01; @@ -1379,7 +1739,7 @@ public static void SignPrehash(byte[] sk, int skOff, byte[] ctx, IXof ph, byte[] public static void SignPrehash(byte[] sk, int skOff, byte[] pk, int pkOff, byte[] ctx, IXof ph, byte[] sig, int sigOff) { byte[] m = new byte[PrehashSize]; - if (PrehashSize != ph.DoFinal(m, 0, PrehashSize)) + if (PrehashSize != ph.OutputFinal(m, 0, PrehashSize)) throw new ArgumentException("ph"); byte phflag = 0x01; @@ -1389,8 +1749,8 @@ public static void SignPrehash(byte[] sk, int skOff, byte[] pk, int pkOff, byte[ public static bool ValidatePublicKeyFull(byte[] pk, int pkOff) { - PointExt p = new PointExt(); - if (!DecodePointVar(pk, pkOff, false, p)) + Init(out PointProjective p); + if (!DecodePointVar(pk, pkOff, false, ref p)) return false; F.Normalize(p.x); @@ -1400,8 +1760,8 @@ public static bool ValidatePublicKeyFull(byte[] pk, int pkOff) if (IsNeutralElementVar(p.x, p.y, p.z)) return false; - PointExt r = new PointExt(); - ScalarMultOrderVar(p, r); + Init(out PointProjective r); + ScalarMultOrderVar(ref p, ref r); F.Normalize(r.x); F.Normalize(r.y); @@ -1412,8 +1772,8 @@ public static bool ValidatePublicKeyFull(byte[] pk, int pkOff) public static bool ValidatePublicKeyPartial(byte[] pk, int pkOff) { - PointExt p = new PointExt(); - return DecodePointVar(pk, pkOff, false, p); + Init(out PointProjective p); + return DecodePointVar(pk, pkOff, false, ref p); } public static bool Verify(byte[] sig, int sigOff, byte[] pk, int pkOff, byte[] ctx, byte[] m, int mOff, int mLen) @@ -1433,7 +1793,7 @@ public static bool VerifyPrehash(byte[] sig, int sigOff, byte[] pk, int pkOff, b public static bool VerifyPrehash(byte[] sig, int sigOff, byte[] pk, int pkOff, byte[] ctx, IXof ph) { byte[] m = new byte[PrehashSize]; - if (PrehashSize != ph.DoFinal(m, 0, PrehashSize)) + if (PrehashSize != ph.OutputFinal(m, 0, PrehashSize)) throw new ArgumentException("ph"); byte phflag = 0x01; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Bits.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Bits.cs index a006efc..0bc62ca 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Bits.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Bits.cs @@ -1,30 +1,87 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System; +using System.Diagnostics; +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER +using System.Runtime.CompilerServices; +#endif namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw { - internal abstract class Bits + internal static class Bits { +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif internal static uint BitPermuteStep(uint x, uint m, int s) { + Debug.Assert((m & (m << s)) == 0U); + Debug.Assert((m << s) >> s == m); + uint t = (x ^ (x >> s)) & m; - return (t ^ (t << s)) ^ x; + return t ^ (t << s) ^ x; } +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif internal static ulong BitPermuteStep(ulong x, ulong m, int s) { + Debug.Assert((m & (m << s)) == 0UL); + Debug.Assert((m << s) >> s == m); + ulong t = (x ^ (x >> s)) & m; - return (t ^ (t << s)) ^ x; + return t ^ (t << s) ^ x; + } + +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif + internal static void BitPermuteStep2(ref uint hi, ref uint lo, uint m, int s) + { +#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP1_1_OR_GREATER || UNITY_2021_2_OR_NEWER + //Debug.Assert(!Unsafe.AreSame(ref hi, ref lo) || (m & (m << s)) == 0U); +#endif + Debug.Assert((m << s) >> s == m); + + uint t = ((lo >> s) ^ hi) & m; + lo ^= t << s; + hi ^= t; } +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif + internal static void BitPermuteStep2(ref ulong hi, ref ulong lo, ulong m, int s) + { +#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP1_1_OR_GREATER || UNITY_2021_2_OR_NEWER + //Debug.Assert(!Unsafe.AreSame(ref hi, ref lo) || (m & (m << s)) == 0UL); +#endif + Debug.Assert((m << s) >> s == m); + + ulong t = ((lo >> s) ^ hi) & m; + lo ^= t << s; + hi ^= t; + } + +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif internal static uint BitPermuteStepSimple(uint x, uint m, int s) { + Debug.Assert((m & (m << s)) == 0U); + Debug.Assert((m << s) >> s == m); + return ((x & m) << s) | ((x >> s) & m); } +#if NETSTANDARD1_0_OR_GREATER || NETCOREAPP1_0_OR_GREATER || UNITY_2021_2_OR_NEWER + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#endif internal static ulong BitPermuteStepSimple(ulong x, ulong m, int s) { + Debug.Assert((m & (m << s)) == 0UL); + Debug.Assert((m << s) >> s == m); + return ((x & m) << s) | ((x >> s) & m); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Interleave.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Interleave.cs index 9b15d21..8f6006b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Interleave.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Interleave.cs @@ -1,6 +1,10 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Diagnostics; +#if NETCOREAPP3_0_OR_GREATER +using System.Runtime.Intrinsics.X86; +#endif namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw { @@ -10,46 +14,6 @@ internal abstract class Interleave private const ulong M64 = 0x5555555555555555UL; private const ulong M64R = 0xAAAAAAAAAAAAAAAAUL; - /* - * This expands 8 bit indices into 16 bit contents (high bit 14), by inserting 0s between bits. - * In a binary field, this operation is the same as squaring an 8 bit number. - */ - //private static readonly ushort[] INTERLEAVE2_TABLE = new ushort[] - //{ - // 0x0000, 0x0001, 0x0004, 0x0005, 0x0010, 0x0011, 0x0014, 0x0015, - // 0x0040, 0x0041, 0x0044, 0x0045, 0x0050, 0x0051, 0x0054, 0x0055, - // 0x0100, 0x0101, 0x0104, 0x0105, 0x0110, 0x0111, 0x0114, 0x0115, - // 0x0140, 0x0141, 0x0144, 0x0145, 0x0150, 0x0151, 0x0154, 0x0155, - // 0x0400, 0x0401, 0x0404, 0x0405, 0x0410, 0x0411, 0x0414, 0x0415, - // 0x0440, 0x0441, 0x0444, 0x0445, 0x0450, 0x0451, 0x0454, 0x0455, - // 0x0500, 0x0501, 0x0504, 0x0505, 0x0510, 0x0511, 0x0514, 0x0515, - // 0x0540, 0x0541, 0x0544, 0x0545, 0x0550, 0x0551, 0x0554, 0x0555, - // 0x1000, 0x1001, 0x1004, 0x1005, 0x1010, 0x1011, 0x1014, 0x1015, - // 0x1040, 0x1041, 0x1044, 0x1045, 0x1050, 0x1051, 0x1054, 0x1055, - // 0x1100, 0x1101, 0x1104, 0x1105, 0x1110, 0x1111, 0x1114, 0x1115, - // 0x1140, 0x1141, 0x1144, 0x1145, 0x1150, 0x1151, 0x1154, 0x1155, - // 0x1400, 0x1401, 0x1404, 0x1405, 0x1410, 0x1411, 0x1414, 0x1415, - // 0x1440, 0x1441, 0x1444, 0x1445, 0x1450, 0x1451, 0x1454, 0x1455, - // 0x1500, 0x1501, 0x1504, 0x1505, 0x1510, 0x1511, 0x1514, 0x1515, - // 0x1540, 0x1541, 0x1544, 0x1545, 0x1550, 0x1551, 0x1554, 0x1555, - // 0x4000, 0x4001, 0x4004, 0x4005, 0x4010, 0x4011, 0x4014, 0x4015, - // 0x4040, 0x4041, 0x4044, 0x4045, 0x4050, 0x4051, 0x4054, 0x4055, - // 0x4100, 0x4101, 0x4104, 0x4105, 0x4110, 0x4111, 0x4114, 0x4115, - // 0x4140, 0x4141, 0x4144, 0x4145, 0x4150, 0x4151, 0x4154, 0x4155, - // 0x4400, 0x4401, 0x4404, 0x4405, 0x4410, 0x4411, 0x4414, 0x4415, - // 0x4440, 0x4441, 0x4444, 0x4445, 0x4450, 0x4451, 0x4454, 0x4455, - // 0x4500, 0x4501, 0x4504, 0x4505, 0x4510, 0x4511, 0x4514, 0x4515, - // 0x4540, 0x4541, 0x4544, 0x4545, 0x4550, 0x4551, 0x4554, 0x4555, - // 0x5000, 0x5001, 0x5004, 0x5005, 0x5010, 0x5011, 0x5014, 0x5015, - // 0x5040, 0x5041, 0x5044, 0x5045, 0x5050, 0x5051, 0x5054, 0x5055, - // 0x5100, 0x5101, 0x5104, 0x5105, 0x5110, 0x5111, 0x5114, 0x5115, - // 0x5140, 0x5141, 0x5144, 0x5145, 0x5150, 0x5151, 0x5154, 0x5155, - // 0x5400, 0x5401, 0x5404, 0x5405, 0x5410, 0x5411, 0x5414, 0x5415, - // 0x5440, 0x5441, 0x5444, 0x5445, 0x5450, 0x5451, 0x5454, 0x5455, - // 0x5500, 0x5501, 0x5504, 0x5505, 0x5510, 0x5511, 0x5514, 0x5515, - // 0x5540, 0x5541, 0x5544, 0x5545, 0x5550, 0x5551, 0x5554, 0x5555 - //}; - internal static uint Expand8to16(uint x) { x &= 0xFFU; @@ -71,6 +35,14 @@ internal static uint Expand16to32(uint x) internal static ulong Expand32to64(uint x) { +#if NETCOREAPP3_0_OR_GREATER + if (Bmi2.IsSupported) + { + return (ulong)Bmi2.ParallelBitDeposit(x >> 16, 0x55555555U) << 32 + | Bmi2.ParallelBitDeposit(x , 0x55555555U); + } +#endif + // "shuffle" low half to even bits and high half to odd bits x = Bits.BitPermuteStep(x, 0x0000FF00U, 8); x = Bits.BitPermuteStep(x, 0x00F000F0U, 4); @@ -82,6 +54,15 @@ internal static ulong Expand32to64(uint x) internal static void Expand64To128(ulong x, ulong[] z, int zOff) { +#if NETCOREAPP3_0_OR_GREATER + if (Bmi2.X64.IsSupported) + { + z[zOff ] = Bmi2.X64.ParallelBitDeposit(x , 0x5555555555555555UL); + z[zOff + 1] = Bmi2.X64.ParallelBitDeposit(x >> 32, 0x5555555555555555UL); + return; + } +#endif + // "shuffle" low half to even bits and high half to odd bits x = Bits.BitPermuteStep(x, 0x00000000FFFF0000UL, 16); x = Bits.BitPermuteStep(x, 0x0000FF000000FF00UL, 8); @@ -93,17 +74,63 @@ internal static void Expand64To128(ulong x, ulong[] z, int zOff) z[zOff + 1] = (x >> 1) & M64; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal static void Expand64To128(ulong x, Span z) + { +#if NETCOREAPP3_0_OR_GREATER + if (Bmi2.X64.IsSupported) + { + z[0] = Bmi2.X64.ParallelBitDeposit(x , 0x5555555555555555UL); + z[1] = Bmi2.X64.ParallelBitDeposit(x >> 32, 0x5555555555555555UL); + return; + } +#endif + + // "shuffle" low half to even bits and high half to odd bits + x = Bits.BitPermuteStep(x, 0x00000000FFFF0000UL, 16); + x = Bits.BitPermuteStep(x, 0x0000FF000000FF00UL, 8); + x = Bits.BitPermuteStep(x, 0x00F000F000F000F0UL, 4); + x = Bits.BitPermuteStep(x, 0x0C0C0C0C0C0C0C0CUL, 2); + x = Bits.BitPermuteStep(x, 0x2222222222222222UL, 1); + + z[0] = (x ) & M64; + z[1] = (x >> 1) & M64; + } +#endif + internal static void Expand64To128(ulong[] xs, int xsOff, int xsLen, ulong[] zs, int zsOff) { - for (int i = 0; i < xsLen; ++i) + int xsPos = xsLen, zsPos = zsOff + (xsLen << 1); + while (--xsPos >= 0) { - Expand64To128(xs[xsOff + i], zs, zsOff); - zsOff += 2; + zsPos -= 2; + Expand64To128(xs[xsOff + xsPos], zs, zsPos); } } - internal static void Expand64To128Rev(ulong x, ulong[] z, int zOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + internal static void Expand64To128(ReadOnlySpan xs, Span zs) { + int xsPos = xs.Length, zsPos = xs.Length << 1; + Debug.Assert(!zs[xsPos..zsPos].Overlaps(xs)); + while (--xsPos >= 0) + { + zsPos -= 2; + Expand64To128(xs[xsPos], zs[zsPos..]); + } + } +#endif + + internal static ulong Expand64To128Rev(ulong x, out ulong low) + { +#if NETCOREAPP3_0_OR_GREATER + if (Bmi2.X64.IsSupported) + { + low = Bmi2.X64.ParallelBitDeposit(x >> 32, 0xAAAAAAAAAAAAAAAAUL); + return Bmi2.X64.ParallelBitDeposit(x , 0xAAAAAAAAAAAAAAAAUL); + } +#endif + // "shuffle" low half to even bits and high half to odd bits x = Bits.BitPermuteStep(x, 0x00000000FFFF0000UL, 16); x = Bits.BitPermuteStep(x, 0x0000FF000000FF00UL, 8); @@ -111,8 +138,8 @@ internal static void Expand64To128Rev(ulong x, ulong[] z, int zOff) x = Bits.BitPermuteStep(x, 0x0C0C0C0C0C0C0C0CUL, 2); x = Bits.BitPermuteStep(x, 0x2222222222222222UL, 1); - z[zOff] = (x ) & M64R; - z[zOff + 1] = (x << 1) & M64R; + low = (x ) & M64R; + return (x << 1) & M64R; } internal static uint Shuffle(uint x) @@ -158,6 +185,14 @@ internal static uint Unshuffle(uint x) internal static ulong Unshuffle(ulong x) { +#if NETCOREAPP3_0_OR_GREATER + if (Bmi2.X64.IsSupported) + { + return Bmi2.X64.ParallelBitExtract(x, 0xAAAAAAAAAAAAAAAAUL) << 32 + | Bmi2.X64.ParallelBitExtract(x, 0x5555555555555555UL); + } +#endif + // "unshuffle" even bits to low half and odd bits to high half x = Bits.BitPermuteStep(x, 0x2222222222222222UL, 1); x = Bits.BitPermuteStep(x, 0x0C0C0C0C0C0C0C0CUL, 2); @@ -167,6 +202,39 @@ internal static ulong Unshuffle(ulong x) return x; } + internal static ulong Unshuffle(ulong x, out ulong even) + { +#if NETCOREAPP3_0_OR_GREATER + if (Bmi2.X64.IsSupported) + { + even = Bmi2.X64.ParallelBitExtract(x, 0x5555555555555555UL); + return Bmi2.X64.ParallelBitExtract(x, 0xAAAAAAAAAAAAAAAAUL); + } +#endif + + ulong u0 = Unshuffle(x); + even = u0 & 0x00000000FFFFFFFFUL; + return u0 >> 32; + } + + internal static ulong Unshuffle(ulong x0, ulong x1, out ulong even) + { +#if NETCOREAPP3_0_OR_GREATER + if (Bmi2.X64.IsSupported) + { + even = Bmi2.X64.ParallelBitExtract(x0, 0x5555555555555555UL) + | Bmi2.X64.ParallelBitExtract(x1, 0x5555555555555555UL) << 32; + return Bmi2.X64.ParallelBitExtract(x0, 0xAAAAAAAAAAAAAAAAUL) + | Bmi2.X64.ParallelBitExtract(x1, 0xAAAAAAAAAAAAAAAAUL) << 32; + } +#endif + + ulong u0 = Unshuffle(x0); + ulong u1 = Unshuffle(x1); + even = (u1 << 32) | (u0 & 0x00000000FFFFFFFFUL); + return (u0 >> 32) | (u1 & 0xFFFFFFFF00000000UL); + } + internal static uint Unshuffle2(uint x) { // "unshuffle" (twice) even bits to low half and odd bits to high half diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Mod.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Mod.cs index 00bcccf..6fb0842 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Mod.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Mod.cs @@ -14,20 +14,26 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw * computation and modular inversion" by Daniel J. Bernstein and Bo-Yin Yang. */ - internal abstract class Mod + internal static class Mod { - private static readonly SecureRandom RandomSource = new SecureRandom(); - private const int M30 = 0x3FFFFFFF; private const ulong M32UL = 0xFFFFFFFFUL; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void CheckedModOddInverse(ReadOnlySpan m, ReadOnlySpan x, Span z) +#else public static void CheckedModOddInverse(uint[] m, uint[] x, uint[] z) +#endif { if (0 == ModOddInverse(m, x, z)) throw new ArithmeticException("Inverse does not exist."); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void CheckedModOddInverseVar(ReadOnlySpan m, ReadOnlySpan x, Span z) +#else public static void CheckedModOddInverseVar(uint[] m, uint[] x, uint[] z) +#endif { if (!ModOddInverseVar(m, x, z)) throw new ArithmeticException("Inverse does not exist."); @@ -35,7 +41,7 @@ public static void CheckedModOddInverseVar(uint[] m, uint[] x, uint[] z) public static uint Inverse32(uint d) { - Debug.Assert((d & 1) == 1); + Debug.Assert((d & 1U) == 1U); //int x = d + (((d + 1) & 4) << 1); // d.x == 1 mod 2**4 uint x = d; // d.x == 1 mod 2**3 @@ -43,12 +49,30 @@ public static uint Inverse32(uint d) x *= 2 - d * x; // d.x == 1 mod 2**12 x *= 2 - d * x; // d.x == 1 mod 2**24 x *= 2 - d * x; // d.x == 1 mod 2**48 - Debug.Assert(d * x == 1); + Debug.Assert(d * x == 1U); + return x; + } + + public static ulong Inverse64(ulong d) + { + Debug.Assert((d & 1UL) == 1UL); + + //ulong x = d + (((d + 1) & 4) << 1); // d.x == 1 mod 2**4 + ulong x = d; // d.x == 1 mod 2**3 + x *= 2 - d * x; // d.x == 1 mod 2**6 + x *= 2 - d * x; // d.x == 1 mod 2**12 + x *= 2 - d * x; // d.x == 1 mod 2**24 + x *= 2 - d * x; // d.x == 1 mod 2**48 + x *= 2 - d * x; // d.x == 1 mod 2**96 + Debug.Assert(d * x == 1UL); return x; } public static uint ModOddInverse(uint[] m, uint[] x, uint[] z) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ModOddInverse(m.AsSpan(), x.AsSpan(), z.AsSpan()); +#else int len32 = m.Length; Debug.Assert(len32 > 0); Debug.Assert((m[0] & 1) != 0); @@ -69,13 +93,13 @@ public static uint ModOddInverse(uint[] m, uint[] x, uint[] z) Encode30(bits, m, 0, M, 0); Array.Copy(M, 0, F, 0, len30); - int eta = -1; + int delta = 0; int m0Inv32 = (int)Inverse32((uint)M[0]); int maxDivsteps = GetMaximumDivsteps(bits); for (int divSteps = 0; divSteps < maxDivsteps; divSteps += 30) { - eta = Divsteps30(eta, F[0], G[0], t); + delta = Divsteps30(delta, F[0], G[0], t); UpdateDE30(len30, D, E, t, m0Inv32, M); UpdateFG30(len30, F, G, t); } @@ -91,13 +115,72 @@ public static uint ModOddInverse(uint[] m, uint[] x, uint[] z) CNormalize30(len30, signF, D, M); Decode30(bits, D, 0, z, 0); - Debug.Assert(0 != Nat.LessThan(len32, z, m)); + Debug.Assert(0 != Nat.LessThan(m.Length, z, m)); + + return (uint)(EqualTo(len30, F, 1) & EqualToZero(len30, G)); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint ModOddInverse(ReadOnlySpan m, ReadOnlySpan x, Span z) + { + int len32 = m.Length; + Debug.Assert(len32 > 0); + Debug.Assert((m[0] & 1) != 0); + Debug.Assert(m[len32 - 1] != 0); + + int bits = (len32 << 5) - Integers.NumberOfLeadingZeros((int)m[len32 - 1]); + int len30 = (bits + 29) / 30; + + Span alloc = len30 <= 50 + ? stackalloc int[len30 * 5] + : new int[len30 * 5]; + + Span t = stackalloc int[4]; + Span D = alloc[..len30]; alloc = alloc[len30..]; + Span E = alloc[..len30]; alloc = alloc[len30..]; + Span F = alloc[..len30]; alloc = alloc[len30..]; + Span G = alloc[..len30]; alloc = alloc[len30..]; + Span M = alloc[..len30]; + + E[0] = 1; + Encode30(bits, x, G); + Encode30(bits, m, M); + M.CopyTo(F); + + int delta = 0; + int m0Inv32 = (int)Inverse32((uint)M[0]); + int maxDivsteps = GetMaximumDivsteps(bits); + + for (int divSteps = 0; divSteps < maxDivsteps; divSteps += 30) + { + delta = Divsteps30(delta, F[0], G[0], t); + UpdateDE30(len30, D, E, t, m0Inv32, M); + UpdateFG30(len30, F, G, t); + } + + int signF = F[len30 - 1] >> 31; + CNegate30(len30, signF, F); + + /* + * D is in the range (-2.M, M). First, conditionally add M if D is negative, to bring it + * into the range (-M, M). Then normalize by conditionally negating (according to signF) + * and/or then adding M, to bring it into the range [0, M). + */ + CNormalize30(len30, signF, D, M); + + Decode30(bits, D, z); + Debug.Assert(0 != Nat.LessThan(m.Length, z, m)); return (uint)(EqualTo(len30, F, 1) & EqualToZero(len30, G)); } +#endif public static bool ModOddInverseVar(uint[] m, uint[] x, uint[] z) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ModOddInverseVar(m.AsSpan(), x.AsSpan(), z.AsSpan()); +#else int len32 = m.Length; Debug.Assert(len32 > 0); Debug.Assert((m[0] & 1) != 0); @@ -180,12 +263,108 @@ public static bool ModOddInverseVar(uint[] m, uint[] x, uint[] z) Debug.Assert(0 == signD); Decode30(bits, D, 0, z, 0); - Debug.Assert(!Nat.Gte(len32, z, m)); + Debug.Assert(!Nat.Gte(m.Length, z, m)); return true; +#endif } - public static uint[] Random(uint[] p) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static bool ModOddInverseVar(ReadOnlySpan m, ReadOnlySpan x, Span z) + { + int len32 = m.Length; + Debug.Assert(len32 > 0); + Debug.Assert((m[0] & 1) != 0); + Debug.Assert(m[len32 - 1] != 0); + + int bits = (len32 << 5) - Integers.NumberOfLeadingZeros((int)m[len32 - 1]); + int len30 = (bits + 29) / 30; + + Span alloc = len30 <= 50 + ? stackalloc int[len30 * 5] + : new int[len30 * 5]; + + Span t = stackalloc int[4]; + Span D = alloc[..len30]; alloc = alloc[len30..]; + Span E = alloc[..len30]; alloc = alloc[len30..]; + Span F = alloc[..len30]; alloc = alloc[len30..]; + Span G = alloc[..len30]; alloc = alloc[len30..]; + Span M = alloc[..len30]; + + E[0] = 1; + Encode30(bits, x, G); + Encode30(bits, m, M); + M.CopyTo(F); + + int clzG = Integers.NumberOfLeadingZeros(G[len30 - 1] | 1) - (len30 * 30 + 2 - bits); + int eta = -1 - clzG; + int lenDE = len30, lenFG = len30; + int m0Inv32 = (int)Inverse32((uint)M[0]); + int maxDivsteps = GetMaximumDivsteps(bits); + + int divsteps = 0; + while (!IsZero(lenFG, G)) + { + if (divsteps >= maxDivsteps) + return false; + + divsteps += 30; + + eta = Divsteps30Var(eta, F[0], G[0], t); + UpdateDE30(lenDE, D, E, t, m0Inv32, M); + UpdateFG30(lenFG, F, G, t); + + int fn = F[lenFG - 1]; + int gn = G[lenFG - 1]; + + int cond = (lenFG - 2) >> 31; + cond |= fn ^ (fn >> 31); + cond |= gn ^ (gn >> 31); + + if (cond == 0) + { + F[lenFG - 2] |= fn << 30; + G[lenFG - 2] |= gn << 30; + --lenFG; + } + } + + int signF = F[lenFG - 1] >> 31; + + /* + * D is in the range (-2.M, M). First, conditionally add M if D is negative, to bring it + * into the range (-M, M). Then normalize by conditionally negating (according to signF) + * and/or then adding M, to bring it into the range [0, M). + */ + int signD = D[lenDE - 1] >> 31; + if (signD < 0) + { + signD = Add30(lenDE, D, M); + } + if (signF < 0) + { + signD = Negate30(lenDE, D); + signF = Negate30(lenFG, F); + } + Debug.Assert(0 == signF); + + if (!IsOne(lenFG, F)) + return false; + + if (signD < 0) + { + signD = Add30(lenDE, D, M); + } + Debug.Assert(0 == signD); + + Decode30(bits, D, z); + Debug.Assert(!Nat.Gte(m.Length, z, m)); + + return true; + } +#endif + + public static uint[] Random(SecureRandom random, uint[] p) { int len = p.Length; uint[] s = Nat.Create(len); @@ -197,10 +376,10 @@ public static uint[] Random(uint[] p) m |= m >> 8; m |= m >> 16; + byte[] bytes = new byte[len << 2]; do { - byte[] bytes = new byte[len << 2]; - RandomSource.NextBytes(bytes); + random.NextBytes(bytes); Pack.BE_To_UInt32(bytes, 0, s); s[len - 1] &= m; } @@ -209,7 +388,41 @@ public static uint[] Random(uint[] p) return s; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Random(SecureRandom random, ReadOnlySpan p, Span z) + { + int len = p.Length; + if (z.Length < len) + throw new ArgumentException("insufficient space", nameof(z)); + + var s = z[..len]; + + uint m = p[len - 1]; + m |= m >> 1; + m |= m >> 2; + m |= m >> 4; + m |= m >> 8; + m |= m >> 16; + + Span bytes = len <= 256 + ? stackalloc byte[len << 2] + : new byte[len << 2]; + + do + { + random.NextBytes(bytes); + Pack.BE_To_UInt32(bytes, s); + s[len - 1] &= m; + } + while (Nat.Gte(len, s, p)); + } +#endif + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static int Add30(int len30, Span D, ReadOnlySpan M) +#else private static int Add30(int len30, int[] D, int[] M) +#endif { Debug.Assert(len30 > 0); Debug.Assert(D.Length >= len30); @@ -226,7 +439,11 @@ private static int Add30(int len30, int[] D, int[] M) return c; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void CNegate30(int len30, int cond, Span D) +#else private static void CNegate30(int len30, int cond, int[] D) +#endif { Debug.Assert(len30 > 0); Debug.Assert(D.Length >= len30); @@ -241,7 +458,11 @@ private static void CNegate30(int len30, int cond, int[] D) D[last] = c; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void CNormalize30(int len30, int condNegate, Span D, ReadOnlySpan M) +#else private static void CNormalize30(int len30, int condNegate, int[] D, int[] M) +#endif { Debug.Assert(len30 > 0); Debug.Assert(D.Length >= len30); @@ -279,6 +500,29 @@ private static void CNormalize30(int len30, int condNegate, int[] D, int[] M) } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void Decode30(int bits, ReadOnlySpan x, Span z) + { + Debug.Assert(bits > 0); + + int avail = 0; + ulong data = 0L; + + int xOff = 0, zOff = 0; + while (bits > 0) + { + while (avail < System.Math.Min(32, bits)) + { + data |= (ulong)x[xOff++] << avail; + avail += 30; + } + + z[zOff++] = (uint)data; data >>= 32; + avail -= 32; + bits -= 32; + } + } +#else private static void Decode30(int bits, int[] x, int xOff, uint[] z, int zOff) { Debug.Assert(bits > 0); @@ -299,39 +543,44 @@ private static void Decode30(int bits, int[] x, int xOff, uint[] z, int zOff) bits -= 32; } } +#endif - private static int Divsteps30(int eta, int f0, int g0, int[] t) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static int Divsteps30(int delta, int f0, int g0, Span t) +#else + private static int Divsteps30(int delta, int f0, int g0, int[] t) +#endif { - int u = 1, v = 0, q = 0, r = 1; + int u = 1 << 30, v = 0, q = 0, r = 1 << 30; int f = f0, g = g0; for (int i = 0; i < 30; ++i) { Debug.Assert((f & 1) == 1); - Debug.Assert((u * f0 + v * g0) == f << i); - Debug.Assert((q * f0 + r * g0) == g << i); + Debug.Assert(((u >> (30 - i)) * f0 + (v >> (30 - i)) * g0) == f << i); + Debug.Assert(((q >> (30 - i)) * f0 + (r >> (30 - i)) * g0) == g << i); - int c1 = eta >> 31; + int c1 = delta >> 31; int c2 = -(g & 1); - int x = (f ^ c1) - c1; - int y = (u ^ c1) - c1; - int z = (v ^ c1) - c1; + int x = f ^ c1; + int y = u ^ c1; + int z = v ^ c1; - g += x & c2; - q += y & c2; - r += z & c2; + g -= x & c2; + q -= y & c2; + r -= z & c2; - c1 &= c2; - eta = (eta ^ c1) - (c1 + 1); + c2 &= ~c1; + delta = (delta ^ c2) - (c2 - 1); - f += g & c1; - u += q & c1; - v += r & c1; + f += g & c2; + u += q & c2; + v += r & c2; g >>= 1; - u <<= 1; - v <<= 1; + q >>= 1; + r >>= 1; } t[0] = u; @@ -339,10 +588,14 @@ private static int Divsteps30(int eta, int f0, int g0, int[] t) t[2] = q; t[3] = r; - return eta; + return delta; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static int Divsteps30Var(int eta, int f0, int g0, Span t) +#else private static int Divsteps30Var(int eta, int f0, int g0, int[] t) +#endif { int u = 1, v = 0, q = 0, r = 1; int f = f0, g = g0, m, w, x, y, z; @@ -405,6 +658,29 @@ private static int Divsteps30Var(int eta, int f0, int g0, int[] t) return eta; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void Encode30(int bits, ReadOnlySpan x, Span z) + { + Debug.Assert(bits > 0); + + int avail = 0; + ulong data = 0UL; + + int xOff = 0, zOff = 0; + while (bits > 0) + { + if (avail < System.Math.Min(30, bits)) + { + data |= (x[xOff++] & M32UL) << avail; + avail += 32; + } + + z[zOff++] = (int)data & M30; data >>= 30; + avail -= 30; + bits -= 30; + } + } +#else private static void Encode30(int bits, uint[] x, int xOff, int[] z, int zOff) { Debug.Assert(bits > 0); @@ -425,8 +701,13 @@ private static void Encode30(int bits, uint[] x, int xOff, int[] z, int zOff) bits -= 30; } } +#endif +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static int EqualTo(int len, ReadOnlySpan x, int y) +#else private static int EqualTo(int len, int[] x, int y) +#endif { int d = x[0] ^ y; for (int i = 1; i < len; ++i) @@ -437,7 +718,11 @@ private static int EqualTo(int len, int[] x, int y) return (d - 1) >> 31; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static int EqualToZero(int len, ReadOnlySpan x) +#else private static int EqualToZero(int len, int[] x) +#endif { int d = 0; for (int i = 0; i < len; ++i) @@ -453,7 +738,11 @@ private static int GetMaximumDivsteps(int bits) return (49 * bits + (bits < 46 ? 80 : 47)) / 17; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static bool IsOne(int len, ReadOnlySpan x) +#else private static bool IsOne(int len, int[] x) +#endif { if (x[0] != 1) { @@ -469,7 +758,11 @@ private static bool IsOne(int len, int[] x) return true; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static bool IsZero(int len, ReadOnlySpan x) +#else private static bool IsZero(int len, int[] x) +#endif { if (x[0] != 0) { @@ -485,7 +778,11 @@ private static bool IsZero(int len, int[] x) return true; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static int Negate30(int len30, Span D) +#else private static int Negate30(int len30, int[] D) +#endif { Debug.Assert(len30 > 0); Debug.Assert(D.Length >= len30); @@ -501,7 +798,12 @@ private static int Negate30(int len30, int[] D) return c; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void UpdateDE30(int len30, Span D, Span E, ReadOnlySpan t, int m0Inv32, + ReadOnlySpan M) +#else private static void UpdateDE30(int len30, int[] D, int[] E, int[] t, int m0Inv32, int[] M) +#endif { Debug.Assert(len30 > 0); Debug.Assert(D.Length >= len30); @@ -565,7 +867,11 @@ private static void UpdateDE30(int len30, int[] D, int[] E, int[] t, int m0Inv32 E[len30 - 1] = (int)ce; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private static void UpdateFG30(int len30, Span F, Span G, ReadOnlySpan t) +#else private static void UpdateFG30(int len30, int[] F, int[] G, int[] t) +#endif { Debug.Assert(len30 > 0); Debug.Assert(F.Length >= len30); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Nat.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Nat.cs index 80dd930..54d4b5a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Nat.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Nat.cs @@ -23,6 +23,20 @@ public static uint Add(int len, uint[] x, uint[] y, uint[] z) return (uint)c; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint Add(int len, ReadOnlySpan x, ReadOnlySpan y, Span z) + { + ulong c = 0; + for (int i = 0; i < len; ++i) + { + c += (ulong)x[i] + y[i]; + z[i] = (uint)c; + c >>= 32; + } + return (uint)c; + } +#endif + public static uint Add33At(int len, uint x, uint[] z, int zPos) { Debug.Assert(zPos <= (len - 2)); @@ -47,6 +61,20 @@ public static uint Add33At(int len, uint x, uint[] z, int zOff, int zPos) return c == 0 ? 0 : IncAt(len, z, zOff, zPos + 2); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint Add33At(int len, uint x, Span z, int zPos) + { + Debug.Assert(zPos <= (len - 2)); + ulong c = (ulong)z[zPos + 0] + x; + z[zPos + 0] = (uint)c; + c >>= 32; + c += (ulong)z[zPos + 1] + 1; + z[zPos + 1] = (uint)c; + c >>= 32; + return c == 0 ? 0 : IncAt(len, z, zPos + 2); + } +#endif + public static uint Add33To(int len, uint x, uint[] z) { ulong c = (ulong)z[0] + x; @@ -69,6 +97,19 @@ public static uint Add33To(int len, uint x, uint[] z, int zOff) return c == 0 ? 0 : IncAt(len, z, zOff, 2); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint Add33To(int len, uint x, Span z) + { + ulong c = (ulong)z[0] + x; + z[0] = (uint)c; + c >>= 32; + c += (ulong)z[1] + 1; + z[1] = (uint)c; + c >>= 32; + return c == 0 ? 0 : IncAt(len, z, 2); + } +#endif + public static uint AddBothTo(int len, uint[] x, uint[] y, uint[] z) { ulong c = 0; @@ -93,13 +134,27 @@ public static uint AddBothTo(int len, uint[] x, int xOff, uint[] y, int yOff, ui return (uint)c; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint AddBothTo(int len, ReadOnlySpan x, ReadOnlySpan y, Span z) + { + ulong c = 0; + for (int i = 0; i < len; ++i) + { + c += (ulong)x[i] + y[i] + z[i]; + z[i] = (uint)c; + c >>= 32; + } + return (uint)c; + } +#endif + public static uint AddDWordAt(int len, ulong x, uint[] z, int zPos) { Debug.Assert(zPos <= (len - 2)); - ulong c = (ulong)z[zPos + 0] + (x & M); + ulong c = z[zPos + 0] + (x & M); z[zPos + 0] = (uint)c; c >>= 32; - c += (ulong)z[zPos + 1] + (x >> 32); + c += z[zPos + 1] + (x >> 32); z[zPos + 1] = (uint)c; c >>= 32; return c == 0 ? 0 : IncAt(len, z, zPos + 2); @@ -108,15 +163,29 @@ public static uint AddDWordAt(int len, ulong x, uint[] z, int zPos) public static uint AddDWordAt(int len, ulong x, uint[] z, int zOff, int zPos) { Debug.Assert(zPos <= (len - 2)); - ulong c = (ulong)z[zOff + zPos] + (x & M); + ulong c = z[zOff + zPos] + (x & M); z[zOff + zPos] = (uint)c; c >>= 32; - c += (ulong)z[zOff + zPos + 1] + (x >> 32); + c += z[zOff + zPos + 1] + (x >> 32); z[zOff + zPos + 1] = (uint)c; c >>= 32; return c == 0 ? 0 : IncAt(len, z, zOff, zPos + 2); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint AddDWordAt(int len, ulong x, Span z, int zPos) + { + Debug.Assert(zPos <= (len - 2)); + ulong c = z[zPos + 0] + (x & M); + z[zPos + 0] = (uint)c; + c >>= 32; + c += z[zPos + 1] + (x >> 32); + z[zPos + 1] = (uint)c; + c >>= 32; + return c == 0 ? 0 : IncAt(len, z, zPos + 2); + } +#endif + public static uint AddDWordTo(int len, ulong x, uint[] z) { ulong c = (ulong)z[0] + (x & M); @@ -139,6 +208,19 @@ public static uint AddDWordTo(int len, ulong x, uint[] z, int zOff) return c == 0 ? 0 : IncAt(len, z, zOff, 2); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint AddDWordTo(int len, ulong x, Span z) + { + ulong c = z[0] + (x & M); + z[0] = (uint)c; + c >>= 32; + c += z[1] + (x >> 32); + z[1] = (uint)c; + c >>= 32; + return c == 0 ? 0 : IncAt(len, z, 2); + } +#endif + public static uint AddTo(int len, uint[] x, uint[] z) { ulong c = 0; @@ -163,6 +245,20 @@ public static uint AddTo(int len, uint[] x, int xOff, uint[] z, int zOff) return (uint)c; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint AddTo(int len, ReadOnlySpan x, Span z) + { + ulong c = 0; + for (int i = 0; i < len; ++i) + { + c += (ulong)x[i] + z[i]; + z[i] = (uint)c; + c >>= 32; + } + return (uint)c; + } +#endif + public static uint AddTo(int len, uint[] x, int xOff, uint[] z, int zOff, uint cIn) { ulong c = cIn; @@ -175,6 +271,20 @@ public static uint AddTo(int len, uint[] x, int xOff, uint[] z, int zOff, uint c return (uint)c; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint AddTo(int len, ReadOnlySpan x, Span z, uint cIn) + { + ulong c = cIn; + for (int i = 0; i < len; ++i) + { + c += (ulong)x[i] + z[i]; + z[i] = (uint)c; + c >>= 32; + } + return (uint)c; + } +#endif + public static uint AddToEachOther(int len, uint[] u, int uOff, uint[] v, int vOff) { ulong c = 0; @@ -188,6 +298,21 @@ public static uint AddToEachOther(int len, uint[] u, int uOff, uint[] v, int vOf return (uint)c; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint AddToEachOther(int len, Span u, Span v) + { + ulong c = 0; + for (int i = 0; i < len; ++i) + { + c += (ulong)u[i] + v[i]; + u[i] = (uint)c; + v[i] = (uint)c; + c >>= 32; + } + return (uint)c; + } +#endif + public static uint AddWordAt(int len, uint x, uint[] z, int zPos) { Debug.Assert(zPos <= (len - 1)); @@ -206,6 +331,17 @@ public static uint AddWordAt(int len, uint x, uint[] z, int zOff, int zPos) return c == 0 ? 0 : IncAt(len, z, zOff, zPos + 1); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint AddWordAt(int len, uint x, Span z, int zPos) + { + Debug.Assert(zPos <= (len - 1)); + ulong c = (ulong)x + z[zPos]; + z[zPos] = (uint)c; + c >>= 32; + return c == 0 ? 0 : IncAt(len, z, zPos + 1); + } +#endif + public static uint AddWordTo(int len, uint x, uint[] z) { ulong c = (ulong)x + z[0]; @@ -222,6 +358,16 @@ public static uint AddWordTo(int len, uint x, uint[] z, int zOff) return c == 0 ? 0 : IncAt(len, z, zOff, 1); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint AddWordTo(int len, uint x, Span z) + { + ulong c = (ulong)x + z[0]; + z[0] = (uint)c; + c >>= 32; + return c == 0 ? 0 : IncAt(len, z, 1); + } +#endif + public static uint CAdd(int len, int mask, uint[] x, uint[] y, uint[] z) { uint MASK = (uint)-(mask & 1); @@ -236,6 +382,22 @@ public static uint CAdd(int len, int mask, uint[] x, uint[] y, uint[] z) return (uint)c; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint CAdd(int len, int mask, ReadOnlySpan x, ReadOnlySpan y, Span z) + { + uint MASK = (uint)-(mask & 1); + + ulong c = 0; + for (int i = 0; i < len; ++i) + { + c += (ulong)x[i] + (y[i] & MASK); + z[i] = (uint)c; + c >>= 32; + } + return (uint)c; + } +#endif + public static void CMov(int len, int mask, uint[] x, int xOff, uint[] z, int zOff) { uint MASK = (uint)-(mask & 1); @@ -243,7 +405,7 @@ public static void CMov(int len, int mask, uint[] x, int xOff, uint[] z, int zOf for (int i = 0; i < len; ++i) { uint z_i = z[zOff + i], diff = z_i ^ x[xOff + i]; - z_i ^= (diff & MASK); + z_i ^= diff & MASK; z[zOff + i] = z_i; } @@ -258,27 +420,29 @@ public static void CMov(int len, int mask, uint[] x, int xOff, uint[] z, int zOf //} } - public static void CMov(int len, int mask, int[] x, int xOff, int[] z, int zOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void CMov(int len, int mask, ReadOnlySpan x, Span z) { - mask = -(mask & 1); + uint MASK = (uint)-(mask & 1); for (int i = 0; i < len; ++i) { - int z_i = z[zOff + i], diff = z_i ^ x[xOff + i]; - z_i ^= (diff & mask); - z[zOff + i] = z_i; + uint z_i = z[i], diff = z_i ^ x[i]; + z_i ^= diff & MASK; + z[i] = z_i; } - //int half = 0x55555555, rest = half << (-mask); + //uint half = 0x55555555U, rest = half << (-(int)MASK); //for (int i = 0; i < len; ++i) //{ - // int z_i = z[zOff + i], diff = z_i ^ x[xOff + i]; + // uint z_i = z[i], diff = z_i ^ x[i]; // z_i ^= (diff & half); // z_i ^= (diff & rest); - // z[zOff + i] = z_i; + // z[i] = z_i; //} } +#endif public static int Compare(int len, uint[] x, uint[] y) { @@ -308,10 +472,21 @@ public static int Compare(int len, uint[] x, int xOff, uint[] y, int yOff) return 0; } - public static void Copy(int len, uint[] x, uint[] z) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static int Compare(int len, ReadOnlySpan x, ReadOnlySpan y) { - Array.Copy(x, 0, z, 0, len); + for (int i = len - 1; i >= 0; --i) + { + uint x_i = x[i]; + uint y_i = y[i]; + if (x_i < y_i) + return -1; + if (x_i > y_i) + return 1; + } + return 0; } +#endif public static uint[] Copy(int len, uint[] x) { @@ -320,11 +495,23 @@ public static uint[] Copy(int len, uint[] x) return z; } + public static void Copy(int len, uint[] x, uint[] z) + { + Array.Copy(x, 0, z, 0, len); + } + public static void Copy(int len, uint[] x, int xOff, uint[] z, int zOff) { Array.Copy(x, xOff, z, zOff, len); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Copy(int len, ReadOnlySpan x, Span z) + { + x[..len].CopyTo(z); + } +#endif + public static ulong[] Copy64(int len, ulong[] x) { ulong[] z = new ulong[len]; @@ -342,6 +529,13 @@ public static void Copy64(int len, ulong[] x, int xOff, ulong[] z, int zOff) Array.Copy(x, xOff, z, zOff, len); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Copy64(int len, ReadOnlySpan x, Span z) + { + x[..len].CopyTo(z); + } +#endif + public static uint[] Create(int len) { return new uint[len]; @@ -358,7 +552,7 @@ public static int CSub(int len, int mask, uint[] x, uint[] y, uint[] z) long c = 0; for (int i = 0; i < len; ++i) { - c += (long)x[i] - (y[i] & MASK); + c += x[i] - (y[i] & MASK); z[i] = (uint)c; c >>= 32; } @@ -371,26 +565,73 @@ public static int CSub(int len, int mask, uint[] x, int xOff, uint[] y, int yOff long c = 0; for (int i = 0; i < len; ++i) { - c += (long)x[xOff + i] - (y[yOff + i] & MASK); + c += x[xOff + i] - (y[yOff + i] & MASK); z[zOff + i] = (uint)c; c >>= 32; } return (int)c; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static int CSub(int len, int mask, ReadOnlySpan x, ReadOnlySpan y, Span z) + { + long MASK = (uint)-(mask & 1); + long c = 0; + for (int i = 0; i < len; ++i) + { + c += x[i] - (y[i] & MASK); + z[i] = (uint)c; + c >>= 32; + } + return (int)c; + } +#endif + public static int Dec(int len, uint[] z) { for (int i = 0; i < len; ++i) { if (--z[i] != uint.MaxValue) + return 0; + } + return -1; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static int Dec(int len, Span z) + { + for (int i = 0; i < len; ++i) + { + if (--z[i] != uint.MaxValue) + return 0; + } + return -1; + } +#endif + + public static int Dec(int len, uint[] x, uint[] z) + { + int i = 0; + while (i < len) + { + uint c = x[i] - 1; + z[i] = c; + ++i; + if (c != uint.MaxValue) { + while (i < len) + { + z[i] = x[i]; + ++i; + } return 0; } } return -1; } - public static int Dec(int len, uint[] x, uint[] z) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static int Dec(int len, ReadOnlySpan x, Span z) { int i = 0; while (i < len) @@ -410,6 +651,7 @@ public static int Dec(int len, uint[] x, uint[] z) } return -1; } +#endif public static int DecAt(int len, uint[] z, int zPos) { @@ -417,9 +659,7 @@ public static int DecAt(int len, uint[] z, int zPos) for (int i = zPos; i < len; ++i) { if (--z[i] != uint.MaxValue) - { return 0; - } } return -1; } @@ -430,25 +670,46 @@ public static int DecAt(int len, uint[] z, int zOff, int zPos) for (int i = zPos; i < len; ++i) { if (--z[zOff + i] != uint.MaxValue) - { return 0; - } } return -1; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static int DecAt(int len, Span z, int zPos) + { + Debug.Assert(zPos <= len); + for (int i = zPos; i < len; ++i) + { + if (--z[i] != uint.MaxValue) + return 0; + } + return -1; + } +#endif + public static bool Eq(int len, uint[] x, uint[] y) { for (int i = len - 1; i >= 0; --i) { if (x[i] != y[i]) - { return false; - } } return true; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static bool Eq(int len, ReadOnlySpan x, ReadOnlySpan y) + { + for (int i = len - 1; i >= 0; --i) + { + if (x[i] != y[i]) + return false; + } + return true; + } +#endif + public static uint EqualTo(int len, uint[] x, uint y) { uint d = x[0] ^ y; @@ -471,6 +732,19 @@ public static uint EqualTo(int len, uint[] x, int xOff, uint y) return (uint)(((int)d - 1) >> 31); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint EqualTo(int len, ReadOnlySpan x, uint y) + { + uint d = x[0] ^ y; + for (int i = 1; i < len; ++i) + { + d |= x[i]; + } + d = (d >> 1) | (d & 1); + return (uint)(((int)d - 1) >> 31); + } +#endif + public static uint EqualTo(int len, uint[] x, uint[] y) { uint d = 0; @@ -493,6 +767,19 @@ public static uint EqualTo(int len, uint[] x, int xOff, uint[] y, int yOff) return (uint)(((int)d - 1) >> 31); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint EqualTo(int len, ReadOnlySpan x, ReadOnlySpan y) + { + uint d = 0; + for (int i = 0; i < len; ++i) + { + d |= x[i] ^ y[i]; + } + d = (d >> 1) | (d & 1); + return (uint)(((int)d - 1) >> 31); + } +#endif + public static uint EqualToZero(int len, uint[] x) { uint d = 0; @@ -515,15 +802,26 @@ public static uint EqualToZero(int len, uint[] x, int xOff) return (uint)(((int)d - 1) >> 31); } - public static uint[] FromBigInteger(int bits, BigInteger x) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint EqualToZero(int len, ReadOnlySpan x) { - if (bits < 1) - throw new ArgumentException(); + uint d = 0; + for (int i = 0; i < len; ++i) + { + d |= x[i]; + } + d = (d >> 1) | (d & 1); + return (uint)(((int)d - 1) >> 31); + } +#endif + + public static uint[] FromBigInteger(int bits, BigInteger x) + { + int len = GetLengthForBits(bits); + if (x.SignValue < 0 || x.BitLength > bits) throw new ArgumentException(); - int len = (bits + 31) >> 5; - Debug.Assert(len > 0); uint[] z = Create(len); // NOTE: Use a fixed number of loop iterations @@ -536,15 +834,33 @@ public static uint[] FromBigInteger(int bits, BigInteger x) return z; } - public static ulong[] FromBigInteger64(int bits, BigInteger x) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void FromBigInteger(int bits, BigInteger x, Span z) { - if (bits < 1) + int len = GetLengthForBits(bits); + + if (x.SignValue < 0 || x.BitLength > bits) throw new ArgumentException(); + if (z.Length < len) + throw new ArgumentException(); + + // NOTE: Use a fixed number of loop iterations + z[0] = (uint)x.IntValue; + for (int i = 1; i < len; ++i) + { + x = x.ShiftRight(32); + z[i] = (uint)x.IntValue; + } + } +#endif + + public static ulong[] FromBigInteger64(int bits, BigInteger x) + { + int len = GetLengthForBits64(bits); + if (x.SignValue < 0 || x.BitLength > bits) throw new ArgumentException(); - int len = (bits + 63) >> 6; - Debug.Assert(len > 0); ulong[] z = Create64(len); // NOTE: Use a fixed number of loop iterations @@ -557,20 +873,69 @@ public static ulong[] FromBigInteger64(int bits, BigInteger x) return z; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void FromBigInteger64(int bits, BigInteger x, Span z) + { + int len = GetLengthForBits64(bits); + + if (x.SignValue < 0 || x.BitLength > bits) + throw new ArgumentException(); + if (z.Length < len) + throw new ArgumentException(); + + // NOTE: Use a fixed number of loop iterations + z[0] = (ulong)x.LongValue; + for (int i = 1; i < len; ++i) + { + x = x.ShiftRight(64); + z[i] = (ulong)x.LongValue; + } + } +#endif + public static uint GetBit(uint[] x, int bit) { if (bit == 0) - { return x[0] & 1; - } + int w = bit >> 5; if (w < 0 || w >= x.Length) - { return 0; - } + + int b = bit & 31; + return (x[w] >> b) & 1; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint GetBit(ReadOnlySpan x, int bit) + { + if (bit == 0) + return x[0] & 1; + + int w = bit >> 5; + if (w < 0 || w >= x.Length) + return 0; + int b = bit & 31; return (x[w] >> b) & 1; } +#endif + + public static int GetLengthForBits(int bits) + { + if (bits < 1) + throw new ArgumentException(); + + return (int)(((uint)bits + 31) >> 5); + } + + public static int GetLengthForBits64(int bits) + { + if (bits < 1) + throw new ArgumentException(); + + return (int)(((uint)bits + 63) >> 6); + } public static bool Gte(int len, uint[] x, uint[] y) { @@ -585,19 +950,66 @@ public static bool Gte(int len, uint[] x, uint[] y) return true; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static bool Gte(int len, ReadOnlySpan x, ReadOnlySpan y) + { + for (int i = len - 1; i >= 0; --i) + { + uint x_i = x[i], y_i = y[i]; + if (x_i < y_i) + return false; + if (x_i > y_i) + return true; + } + return true; + } +#endif + public static uint Inc(int len, uint[] z) { for (int i = 0; i < len; ++i) { if (++z[i] != uint.MinValue) + return 0; + } + return 1; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint Inc(int len, Span z) + { + for (int i = 0; i < len; ++i) + { + if (++z[i] != uint.MinValue) + return 0; + } + return 1; + } +#endif + + public static uint Inc(int len, uint[] x, uint[] z) + { + int i = 0; + while (i < len) + { + uint c = x[i] + 1; + z[i] = c; + ++i; + if (c != 0) { + while (i < len) + { + z[i] = x[i]; + ++i; + } return 0; } } return 1; } - public static uint Inc(int len, uint[] x, uint[] z) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint Inc(int len, ReadOnlySpan x, Span z) { int i = 0; while (i < len) @@ -617,6 +1029,7 @@ public static uint Inc(int len, uint[] x, uint[] z) } return 1; } +#endif public static uint IncAt(int len, uint[] z, int zPos) { @@ -624,9 +1037,7 @@ public static uint IncAt(int len, uint[] z, int zPos) for (int i = zPos; i < len; ++i) { if (++z[i] != uint.MinValue) - { return 0; - } } return 1; } @@ -637,44 +1048,79 @@ public static uint IncAt(int len, uint[] z, int zOff, int zPos) for (int i = zPos; i < len; ++i) { if (++z[zOff + i] != uint.MinValue) - { return 0; - } } return 1; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint IncAt(int len, Span z, int zPos) + { + Debug.Assert(zPos <= len); + for (int i = zPos; i < len; ++i) + { + if (++z[i] != uint.MinValue) + return 0; + } + return 1; + } +#endif + public static bool IsOne(int len, uint[] x) { if (x[0] != 1) - { return false; + + for (int i = 1; i < len; ++i) + { + if (x[i] != 0) + return false; } + return true; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static bool IsOne(int len, ReadOnlySpan x) + { + if (x[0] != 1) + return false; + for (int i = 1; i < len; ++i) { if (x[i] != 0) - { return false; - } } return true; } +#endif public static bool IsZero(int len, uint[] x) { if (x[0] != 0) - { return false; + + for (int i = 1; i < len; ++i) + { + if (x[i] != 0) + return false; } + return true; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static bool IsZero(int len, ReadOnlySpan x) + { + if (x[0] != 0) + return false; + for (int i = 1; i < len; ++i) { if (x[i] != 0) - { return false; - } } return true; } +#endif public static int LessThan(int len, uint[] x, uint[] y) { @@ -700,6 +1146,20 @@ public static int LessThan(int len, uint[] x, int xOff, uint[] y, int yOff) return (int)c; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static int LessThan(int len, ReadOnlySpan x, ReadOnlySpan y) + { + long c = 0; + for (int i = 0; i < len; ++i) + { + c += (long)x[i] - y[i]; + c >>= 32; + } + Debug.Assert(c == 0L || c == -1L); + return (int)c; + } +#endif + public static void Mul(int len, uint[] x, uint[] y, uint[] zz) { zz[len] = MulWord(len, x[0], y, zz); @@ -720,6 +1180,18 @@ public static void Mul(int len, uint[] x, int xOff, uint[] y, int yOff, uint[] z } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Mul(int len, ReadOnlySpan x, ReadOnlySpan y, Span zz) + { + zz[len] = MulWord(len, x[0], y, zz); + + for (int i = 1; i < len; ++i) + { + zz[i + len] = MulWordAddTo(len, x[i], y, zz[i..]); + } + } +#endif + public static void Mul(uint[] x, int xOff, int xLen, uint[] y, int yOff, int yLen, uint[] zz, int zzOff) { zz[zzOff + yLen] = MulWord(yLen, x[xOff], y, yOff, zz, zzOff); @@ -730,6 +1202,19 @@ public static void Mul(uint[] x, int xOff, int xLen, uint[] y, int yOff, int yLe } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Mul(ReadOnlySpan x, ReadOnlySpan y, Span zz) + { + int xLen = x.Length, yLen = y.Length; + zz[yLen] = MulWord(yLen, x[0], y, zz); + + for (int i = 1; i < xLen; ++i) + { + zz[i + yLen] = MulWordAddTo(yLen, x[i], y, zz[i..]); + } + } +#endif + public static uint MulAddTo(int len, uint[] x, uint[] y, uint[] zz) { ulong zc = 0; @@ -757,9 +1242,24 @@ public static uint MulAddTo(int len, uint[] x, int xOff, uint[] y, int yOff, uin return (uint)zc; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint MulAddTo(int len, ReadOnlySpan x, ReadOnlySpan y, Span zz) + { + ulong zc = 0; + for (int i = 0; i < len; ++i) + { + zc += MulWordAddTo(len, x[i], y, zz[i..]) & M; + zc += zz[i + len] & M; + zz[i + len] = (uint)zc; + zc >>= 32; + } + return (uint)zc; + } +#endif + public static uint Mul31BothAdd(int len, uint a, uint[] x, uint b, uint[] y, uint[] z, int zOff) { - ulong c = 0, aVal = (ulong)a, bVal = (ulong)b; + ulong c = 0, aVal = a, bVal = b; int i = 0; do { @@ -771,9 +1271,26 @@ public static uint Mul31BothAdd(int len, uint a, uint[] x, uint b, uint[] y, uin return (uint)c; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint Mul31BothAdd(int len, uint a, ReadOnlySpan x, uint b, ReadOnlySpan y, + Span z) + { + ulong c = 0, aVal = a, bVal = b; + int i = 0; + do + { + c += aVal * x[i] + bVal * y[i] + z[i]; + z[i] = (uint)c; + c >>= 32; + } + while (++i < len); + return (uint)c; + } +#endif + public static uint MulWord(int len, uint x, uint[] y, uint[] z) { - ulong c = 0, xVal = (ulong)x; + ulong c = 0, xVal = x; int i = 0; do { @@ -787,7 +1304,7 @@ public static uint MulWord(int len, uint x, uint[] y, uint[] z) public static uint MulWord(int len, uint x, uint[] y, int yOff, uint[] z, int zOff) { - ulong c = 0, xVal = (ulong)x; + ulong c = 0, xVal = x; int i = 0; do { @@ -799,9 +1316,25 @@ public static uint MulWord(int len, uint x, uint[] y, int yOff, uint[] z, int zO return (uint)c; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint MulWord(int len, uint x, ReadOnlySpan y, Span z) + { + ulong c = 0, xVal = x; + int i = 0; + do + { + c += xVal * y[i]; + z[i] = (uint)c; + c >>= 32; + } + while (++i < len); + return (uint)c; + } +#endif + public static uint MulWordAddTo(int len, uint x, uint[] y, int yOff, uint[] z, int zOff) { - ulong c = 0, xVal = (ulong)x; + ulong c = 0, xVal = x; int i = 0; do { @@ -813,30 +1346,64 @@ public static uint MulWordAddTo(int len, uint x, uint[] y, int yOff, uint[] z, i return (uint)c; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint MulWordAddTo(int len, uint x, ReadOnlySpan y, Span z) + { + ulong c = 0, xVal = x; + int i = 0; + do + { + c += xVal * y[i] + z[i]; + z[i] = (uint)c; + c >>= 32; + } + while (++i < len); + return (uint)c; + } +#endif + public static uint MulWordDwordAddAt(int len, uint x, ulong y, uint[] z, int zPos) { Debug.Assert(zPos <= (len - 3)); - ulong c = 0, xVal = (ulong)x; + ulong c = 0, xVal = x; c += xVal * (uint)y + z[zPos + 0]; z[zPos + 0] = (uint)c; c >>= 32; c += xVal * (y >> 32) + z[zPos + 1]; z[zPos + 1] = (uint)c; c >>= 32; - c += (ulong)z[zPos + 2]; + c += z[zPos + 2]; z[zPos + 2] = (uint)c; c >>= 32; return c == 0 ? 0 : IncAt(len, z, zPos + 3); } - public static uint ShiftDownBit(int len, uint[] z, uint c) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint MulWordDwordAddAt(int len, uint x, ulong y, Span z, int zPos) { - int i = len; - while (--i >= 0) - { - uint next = z[i]; - z[i] = (next >> 1) | (c << 31); - c = next; + Debug.Assert(zPos <= (len - 3)); + ulong c = 0, xVal = x; + c += xVal * (uint)y + z[zPos + 0]; + z[zPos + 0] = (uint)c; + c >>= 32; + c += xVal * (y >> 32) + z[zPos + 1]; + z[zPos + 1] = (uint)c; + c >>= 32; + c += z[zPos + 2]; + z[zPos + 2] = (uint)c; + c >>= 32; + return c == 0 ? 0 : IncAt(len, z, zPos + 3); + } +#endif + + public static uint ShiftDownBit(int len, uint[] z, uint c) + { + int i = len; + while (--i >= 0) + { + uint next = z[i]; + z[i] = (next >> 1) | (c << 31); + c = next; } return c << 31; } @@ -853,6 +1420,20 @@ public static uint ShiftDownBit(int len, uint[] z, int zOff, uint c) return c << 31; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint ShiftDownBit(int len, Span z, uint c) + { + int i = len; + while (--i >= 0) + { + uint next = z[i]; + z[i] = (next >> 1) | (c << 31); + c = next; + } + return c << 31; + } +#endif + public static uint ShiftDownBit(int len, uint[] x, uint c, uint[] z) { int i = len; @@ -877,6 +1458,20 @@ public static uint ShiftDownBit(int len, uint[] x, int xOff, uint c, uint[] z, i return c << 31; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint ShiftDownBit(int len, ReadOnlySpan x, uint c, Span z) + { + int i = len; + while (--i >= 0) + { + uint next = x[i]; + z[i] = (next >> 1) | (c << 31); + c = next; + } + return c << 31; + } +#endif + public static uint ShiftDownBits(int len, uint[] z, int bits, uint c) { Debug.Assert(bits > 0 && bits < 32); @@ -903,6 +1498,21 @@ public static uint ShiftDownBits(int len, uint[] z, int zOff, int bits, uint c) return c << -bits; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint ShiftDownBits(int len, Span z, int bits, uint c) + { + Debug.Assert(bits > 0 && bits < 32); + int i = len; + while (--i >= 0) + { + uint next = z[i]; + z[i] = (next >> bits) | (c << -bits); + c = next; + } + return c << -bits; + } +#endif + public static uint ShiftDownBits(int len, uint[] x, int bits, uint c, uint[] z) { Debug.Assert(bits > 0 && bits < 32); @@ -929,6 +1539,21 @@ public static uint ShiftDownBits(int len, uint[] x, int xOff, int bits, uint c, return c << -bits; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint ShiftDownBits(int len, ReadOnlySpan x, int bits, uint c, Span z) + { + Debug.Assert(bits > 0 && bits < 32); + int i = len; + while (--i >= 0) + { + uint next = x[i]; + z[i] = (next >> bits) | (c << -bits); + c = next; + } + return c << -bits; + } +#endif + public static uint ShiftDownWord(int len, uint[] z, uint c) { int i = len; @@ -941,132 +1566,647 @@ public static uint ShiftDownWord(int len, uint[] z, uint c) return c; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint ShiftDownWord(int len, Span z, uint c) + { + int i = len; + while (--i >= 0) + { + uint next = z[i]; + z[i] = c; + c = next; + } + return c; + } +#endif + public static uint ShiftUpBit(int len, uint[] z, uint c) { - for (int i = 0; i < len; ++i) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ShiftUpBit(len, z.AsSpan(0, len), c); +#else + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + uint next0 = z[i + 0]; + uint next1 = z[i + 1]; + uint next2 = z[i + 2]; + uint next3 = z[i + 3]; + z[i + 0] = (next0 << 1) | (c >> 31); + z[i + 1] = (next1 << 1) | (next0 >> 31); + z[i + 2] = (next2 << 1) | (next1 >> 31); + z[i + 3] = (next3 << 1) | (next2 >> 31); + c = next3; + i += 4; + } + while (i < len) { uint next = z[i]; z[i] = (next << 1) | (c >> 31); c = next; + ++i; } return c >> 31; +#endif } public static uint ShiftUpBit(int len, uint[] z, int zOff, uint c) { - for (int i = 0; i < len; ++i) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ShiftUpBit(len, z.AsSpan(zOff, len), c); +#else + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + uint next0 = z[zOff + i + 0]; + uint next1 = z[zOff + i + 1]; + uint next2 = z[zOff + i + 2]; + uint next3 = z[zOff + i + 3]; + z[zOff + i + 0] = (next0 << 1) | (c >> 31); + z[zOff + i + 1] = (next1 << 1) | (next0 >> 31); + z[zOff + i + 2] = (next2 << 1) | (next1 >> 31); + z[zOff + i + 3] = (next3 << 1) | (next2 >> 31); + c = next3; + i += 4; + } + while (i < len) { uint next = z[zOff + i]; z[zOff + i] = (next << 1) | (c >> 31); c = next; + ++i; } return c >> 31; +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint ShiftUpBit(int len, Span z, uint c) + { + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + uint next0 = z[i + 0]; + uint next1 = z[i + 1]; + uint next2 = z[i + 2]; + uint next3 = z[i + 3]; + z[i + 0] = (next0 << 1) | (c >> 31); + z[i + 1] = (next1 << 1) | (next0 >> 31); + z[i + 2] = (next2 << 1) | (next1 >> 31); + z[i + 3] = (next3 << 1) | (next2 >> 31); + c = next3; + i += 4; + } + while (i < len) + { + uint next = z[i]; + z[i] = (next << 1) | (c >> 31); + c = next; + ++i; + } + return c >> 31; + } +#endif + public static uint ShiftUpBit(int len, uint[] x, uint c, uint[] z) { - for (int i = 0; i < len; ++i) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ShiftUpBit(len, x.AsSpan(0, len), c, z.AsSpan(0, len)); +#else + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + uint next0 = x[i + 0]; + uint next1 = x[i + 1]; + uint next2 = x[i + 2]; + uint next3 = x[i + 3]; + z[i + 0] = (next0 << 1) | (c >> 31); + z[i + 1] = (next1 << 1) | (next0 >> 31); + z[i + 2] = (next2 << 1) | (next1 >> 31); + z[i + 3] = (next3 << 1) | (next2 >> 31); + c = next3; + i += 4; + } + while (i < len) { uint next = x[i]; z[i] = (next << 1) | (c >> 31); c = next; + ++i; } return c >> 31; +#endif } public static uint ShiftUpBit(int len, uint[] x, int xOff, uint c, uint[] z, int zOff) { - for (int i = 0; i < len; ++i) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ShiftUpBit(len, x.AsSpan(xOff, len), c, z.AsSpan(zOff, len)); +#else + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + uint next0 = x[xOff + i + 0]; + uint next1 = x[xOff + i + 1]; + uint next2 = x[xOff + i + 2]; + uint next3 = x[xOff + i + 3]; + z[zOff + i + 0] = (next0 << 1) | (c >> 31); + z[zOff + i + 1] = (next1 << 1) | (next0 >> 31); + z[zOff + i + 2] = (next2 << 1) | (next1 >> 31); + z[zOff + i + 3] = (next3 << 1) | (next2 >> 31); + c = next3; + i += 4; + } + while (i < len) { uint next = x[xOff + i]; z[zOff + i] = (next << 1) | (c >> 31); c = next; + ++i; } return c >> 31; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint ShiftUpBit(int len, ReadOnlySpan x, uint c, Span z) + { + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + uint next0 = x[i + 0]; + uint next1 = x[i + 1]; + uint next2 = x[i + 2]; + uint next3 = x[i + 3]; + z[i + 0] = (next0 << 1) | (c >> 31); + z[i + 1] = (next1 << 1) | (next0 >> 31); + z[i + 2] = (next2 << 1) | (next1 >> 31); + z[i + 3] = (next3 << 1) | (next2 >> 31); + c = next3; + i += 4; + } + while (i < len) + { + uint next = x[i]; + z[i] = (next << 1) | (c >> 31); + c = next; + ++i; + } + return c >> 31; + } +#endif + + public static ulong ShiftUpBit64(int len, ulong[] x, ulong c, ulong[] z) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ShiftUpBit64(len, x.AsSpan(0, len), c, z.AsSpan(0, len)); +#else + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + ulong next0 = x[i + 0]; + ulong next1 = x[i + 1]; + ulong next2 = x[i + 2]; + ulong next3 = x[i + 3]; + z[i + 0] = (next0 << 1) | (c >> 63); + z[i + 1] = (next1 << 1) | (next0 >> 63); + z[i + 2] = (next2 << 1) | (next1 >> 63); + z[i + 3] = (next3 << 1) | (next2 >> 63); + c = next3; + i += 4; + } + while (i < len) + { + ulong next = x[i]; + z[i] = (next << 1) | (c >> 63); + c = next; + ++i; + } + return c >> 63; +#endif } public static ulong ShiftUpBit64(int len, ulong[] x, int xOff, ulong c, ulong[] z, int zOff) { - for (int i = 0; i < len; ++i) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ShiftUpBit64(len, x.AsSpan(xOff, len), c, z.AsSpan(zOff, len)); +#else + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + ulong next0 = x[xOff + i + 0]; + ulong next1 = x[xOff + i + 1]; + ulong next2 = x[xOff + i + 2]; + ulong next3 = x[xOff + i + 3]; + z[zOff + i + 0] = (next0 << 1) | (c >> 63); + z[zOff + i + 1] = (next1 << 1) | (next0 >> 63); + z[zOff + i + 2] = (next2 << 1) | (next1 >> 63); + z[zOff + i + 3] = (next3 << 1) | (next2 >> 63); + c = next3; + i += 4; + } + while (i < len) { ulong next = x[xOff + i]; z[zOff + i] = (next << 1) | (c >> 63); c = next; + ++i; } return c >> 63; +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static ulong ShiftUpBit64(int len, ReadOnlySpan x, ulong c, Span z) + { + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + ulong next0 = x[i + 0]; + ulong next1 = x[i + 1]; + ulong next2 = x[i + 2]; + ulong next3 = x[i + 3]; + z[i + 0] = (next0 << 1) | (c >> 63); + z[i + 1] = (next1 << 1) | (next0 >> 63); + z[i + 2] = (next2 << 1) | (next1 >> 63); + z[i + 3] = (next3 << 1) | (next2 >> 63); + c = next3; + i += 4; + } + while (i < len) + { + ulong next = x[i]; + z[i] = (next << 1) | (c >> 63); + c = next; + ++i; + } + return c >> 63; + } +#endif + public static uint ShiftUpBits(int len, uint[] z, int bits, uint c) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ShiftUpBits(len, z.AsSpan(0, len), bits, c); +#else Debug.Assert(bits > 0 && bits < 32); - for (int i = 0; i < len; ++i) + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + uint next0 = z[i + 0]; + uint next1 = z[i + 1]; + uint next2 = z[i + 2]; + uint next3 = z[i + 3]; + z[i + 0] = (next0 << bits) | (c >> -bits); + z[i + 1] = (next1 << bits) | (next0 >> -bits); + z[i + 2] = (next2 << bits) | (next1 >> -bits); + z[i + 3] = (next3 << bits) | (next2 >> -bits); + c = next3; + i += 4; + } + while (i < len) { uint next = z[i]; z[i] = (next << bits) | (c >> -bits); c = next; + ++i; } return c >> -bits; +#endif } public static uint ShiftUpBits(int len, uint[] z, int zOff, int bits, uint c) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ShiftUpBits(len, z.AsSpan(zOff, len), bits, c); +#else Debug.Assert(bits > 0 && bits < 32); - for (int i = 0; i < len; ++i) + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + uint next0 = z[zOff + i + 0]; + uint next1 = z[zOff + i + 1]; + uint next2 = z[zOff + i + 2]; + uint next3 = z[zOff + i + 3]; + z[zOff + i + 0] = (next0 << bits) | (c >> -bits); + z[zOff + i + 1] = (next1 << bits) | (next0 >> -bits); + z[zOff + i + 2] = (next2 << bits) | (next1 >> -bits); + z[zOff + i + 3] = (next3 << bits) | (next2 >> -bits); + c = next3; + i += 4; + } + while (i < len) { uint next = z[zOff + i]; z[zOff + i] = (next << bits) | (c >> -bits); c = next; + ++i; } return c >> -bits; +#endif } - public static ulong ShiftUpBits64(int len, ulong[] z, int zOff, int bits, ulong c) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint ShiftUpBits(int len, Span z, int bits, uint c) { - Debug.Assert(bits > 0 && bits < 64); - for (int i = 0; i < len; ++i) + Debug.Assert(bits > 0 && bits < 32); + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + uint next0 = z[i + 0]; + uint next1 = z[i + 1]; + uint next2 = z[i + 2]; + uint next3 = z[i + 3]; + z[i + 0] = (next0 << bits) | (c >> -bits); + z[i + 1] = (next1 << bits) | (next0 >> -bits); + z[i + 2] = (next2 << bits) | (next1 >> -bits); + z[i + 3] = (next3 << bits) | (next2 >> -bits); + c = next3; + i += 4; + } + while (i < len) { - ulong next = z[zOff + i]; - z[zOff + i] = (next << bits) | (c >> -bits); + uint next = z[i]; + z[i] = (next << bits) | (c >> -bits); c = next; + ++i; } return c >> -bits; } +#endif public static uint ShiftUpBits(int len, uint[] x, int bits, uint c, uint[] z) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ShiftUpBits(len, x.AsSpan(0, len), bits, c, z.AsSpan(0, len)); +#else Debug.Assert(bits > 0 && bits < 32); - for (int i = 0; i < len; ++i) + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + uint next0 = x[i + 0]; + uint next1 = x[i + 1]; + uint next2 = x[i + 2]; + uint next3 = x[i + 3]; + z[i + 0] = (next0 << bits) | (c >> -bits); + z[i + 1] = (next1 << bits) | (next0 >> -bits); + z[i + 2] = (next2 << bits) | (next1 >> -bits); + z[i + 3] = (next3 << bits) | (next2 >> -bits); + c = next3; + i += 4; + } + while (i < len) { uint next = x[i]; z[i] = (next << bits) | (c >> -bits); c = next; + ++i; } return c >> -bits; +#endif } public static uint ShiftUpBits(int len, uint[] x, int xOff, int bits, uint c, uint[] z, int zOff) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ShiftUpBits(len, x.AsSpan(xOff, len), bits, c, z.AsSpan(zOff, len)); +#else Debug.Assert(bits > 0 && bits < 32); - for (int i = 0; i < len; ++i) + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + uint next0 = x[xOff + i + 0]; + uint next1 = x[xOff + i + 1]; + uint next2 = x[xOff + i + 2]; + uint next3 = x[xOff + i + 3]; + z[zOff + i + 0] = (next0 << bits) | (c >> -bits); + z[zOff + i + 1] = (next1 << bits) | (next0 >> -bits); + z[zOff + i + 2] = (next2 << bits) | (next1 >> -bits); + z[zOff + i + 3] = (next3 << bits) | (next2 >> -bits); + c = next3; + i += 4; + } + while (i < len) { uint next = x[xOff + i]; z[zOff + i] = (next << bits) | (c >> -bits); c = next; + ++i; } return c >> -bits; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint ShiftUpBits(int len, ReadOnlySpan x, int bits, uint c, Span z) + { + Debug.Assert(bits > 0 && bits < 32); + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + uint next0 = x[i + 0]; + uint next1 = x[i + 1]; + uint next2 = x[i + 2]; + uint next3 = x[i + 3]; + z[i + 0] = (next0 << bits) | (c >> -bits); + z[i + 1] = (next1 << bits) | (next0 >> -bits); + z[i + 2] = (next2 << bits) | (next1 >> -bits); + z[i + 3] = (next3 << bits) | (next2 >> -bits); + c = next3; + i += 4; + } + while (i < len) + { + uint next = x[i]; + z[i] = (next << bits) | (c >> -bits); + c = next; + ++i; + } + return c >> -bits; + } +#endif + + public static ulong ShiftUpBits64(int len, ulong[] z, int bits, ulong c) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ShiftUpBits64(len, z.AsSpan(0, len), bits, c); +#else + Debug.Assert(bits > 0 && bits < 64); + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + ulong next0 = z[i + 0]; + ulong next1 = z[i + 1]; + ulong next2 = z[i + 2]; + ulong next3 = z[i + 3]; + z[i + 0] = (next0 << bits) | (c >> -bits); + z[i + 1] = (next1 << bits) | (next0 >> -bits); + z[i + 2] = (next2 << bits) | (next1 >> -bits); + z[i + 3] = (next3 << bits) | (next2 >> -bits); + c = next3; + i += 4; + } + while (i < len) + { + ulong next = z[i]; + z[i] = (next << bits) | (c >> -bits); + c = next; + ++i; + } + return c >> -bits; +#endif + } + + public static ulong ShiftUpBits64(int len, ulong[] z, int zOff, int bits, ulong c) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ShiftUpBits64(len, z.AsSpan(zOff, len), bits, c); +#else + Debug.Assert(bits > 0 && bits < 64); + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + ulong next0 = z[zOff + i + 0]; + ulong next1 = z[zOff + i + 1]; + ulong next2 = z[zOff + i + 2]; + ulong next3 = z[zOff + i + 3]; + z[zOff + i + 0] = (next0 << bits) | (c >> -bits); + z[zOff + i + 1] = (next1 << bits) | (next0 >> -bits); + z[zOff + i + 2] = (next2 << bits) | (next1 >> -bits); + z[zOff + i + 3] = (next3 << bits) | (next2 >> -bits); + c = next3; + i += 4; + } + while (i < len) + { + ulong next = z[zOff + i]; + z[zOff + i] = (next << bits) | (c >> -bits); + c = next; + ++i; + } + return c >> -bits; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static ulong ShiftUpBits64(int len, Span z, int bits, ulong c) + { + Debug.Assert(bits > 0 && bits < 64); + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + ulong next0 = z[i + 0]; + ulong next1 = z[i + 1]; + ulong next2 = z[i + 2]; + ulong next3 = z[i + 3]; + z[i + 0] = (next0 << bits) | (c >> -bits); + z[i + 1] = (next1 << bits) | (next0 >> -bits); + z[i + 2] = (next2 << bits) | (next1 >> -bits); + z[i + 3] = (next3 << bits) | (next2 >> -bits); + c = next3; + i += 4; + } + while (i < len) + { + ulong next = z[i]; + z[i] = (next << bits) | (c >> -bits); + c = next; + ++i; + } + return c >> -bits; + } +#endif + + public static ulong ShiftUpBits64(int len, ulong[] x, int bits, ulong c, ulong[] z) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ShiftUpBits64(len, x.AsSpan(0, len), bits, c, z.AsSpan(0, len)); +#else + Debug.Assert(bits > 0 && bits < 64); + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + ulong next0 = x[i + 0]; + ulong next1 = x[i + 1]; + ulong next2 = x[i + 2]; + ulong next3 = x[i + 3]; + z[i + 0] = (next0 << bits) | (c >> -bits); + z[i + 1] = (next1 << bits) | (next0 >> -bits); + z[i + 2] = (next2 << bits) | (next1 >> -bits); + z[i + 3] = (next3 << bits) | (next2 >> -bits); + c = next3; + i += 4; + } + while (i < len) + { + ulong next = x[i]; + z[i] = (next << bits) | (c >> -bits); + c = next; + ++i; + } + return c >> -bits; +#endif } public static ulong ShiftUpBits64(int len, ulong[] x, int xOff, int bits, ulong c, ulong[] z, int zOff) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ShiftUpBits64(len, x.AsSpan(xOff, len), bits, c, z.AsSpan(zOff, len)); +#else Debug.Assert(bits > 0 && bits < 64); - for (int i = 0; i < len; ++i) + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + ulong next0 = x[xOff + i + 0]; + ulong next1 = x[xOff + i + 1]; + ulong next2 = x[xOff + i + 2]; + ulong next3 = x[xOff + i + 3]; + z[zOff + i + 0] = (next0 << bits) | (c >> -bits); + z[zOff + i + 1] = (next1 << bits) | (next0 >> -bits); + z[zOff + i + 2] = (next2 << bits) | (next1 >> -bits); + z[zOff + i + 3] = (next3 << bits) | (next2 >> -bits); + c = next3; + i += 4; + } + while (i < len) { ulong next = x[xOff + i]; z[zOff + i] = (next << bits) | (c >> -bits); c = next; + ++i; + } + return c >> -bits; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static ulong ShiftUpBits64(int len, ReadOnlySpan x, int bits, ulong c, Span z) + { + Debug.Assert(bits > 0 && bits < 64); + int i = 0, limit4 = len - 4; + while (i <= limit4) + { + ulong next0 = x[i + 0]; + ulong next1 = x[i + 1]; + ulong next2 = x[i + 2]; + ulong next3 = x[i + 3]; + z[i + 0] = (next0 << bits) | (c >> -bits); + z[i + 1] = (next1 << bits) | (next0 >> -bits); + z[i + 2] = (next2 << bits) | (next1 >> -bits); + z[i + 3] = (next3 << bits) | (next2 >> -bits); + c = next3; + i += 4; + } + while (i < len) + { + ulong next = x[i]; + z[i] = (next << bits) | (c >> -bits); + c = next; + ++i; } return c >> -bits; } +#endif public static void Square(int len, uint[] x, uint[] zz) { @@ -1088,7 +2228,38 @@ public static void Square(int len, uint[] x, uint[] zz) for (int i = 1; i < len; ++i) { - d += SquareWordAddTo(x, i, zz); + d += SquareWordAddTo(x, i, zz); + d += zz[zzPos]; + zz[zzPos++] = (uint)d; d >>= 32; + d += zz[zzPos]; + zz[zzPos++] = (uint)d; d >>= 32; + } + Debug.Assert(0UL == d); + + ShiftUpBit(extLen, zz, x[0] << 31); + } + + public static void Square(int len, uint[] x, int xOff, uint[] zz, int zzOff) + { + int extLen = len << 1; + uint c = 0; + int j = len, k = extLen; + do + { + ulong xVal = (ulong)x[xOff + --j]; + ulong p = xVal * xVal; + zz[zzOff + --k] = (c << 31) | (uint)(p >> 33); + zz[zzOff + --k] = (uint)(p >> 1); + c = (uint)p; + } + while (j > 0); + + ulong d = 0UL; + int zzPos = zzOff + 2; + + for (int i = 1; i < len; ++i) + { + d += SquareWordAddTo(x, xOff, i, zz, zzOff); d += zz[zzPos]; zz[zzPos++] = (uint)d; d >>= 32; d += zz[zzPos]; @@ -1096,30 +2267,31 @@ public static void Square(int len, uint[] x, uint[] zz) } Debug.Assert(0UL == d); - ShiftUpBit(extLen, zz, x[0] << 31); + ShiftUpBit(extLen, zz, zzOff, x[xOff] << 31); } - public static void Square(int len, uint[] x, int xOff, uint[] zz, int zzOff) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Square(int len, ReadOnlySpan x, Span zz) { int extLen = len << 1; uint c = 0; int j = len, k = extLen; do { - ulong xVal = (ulong)x[xOff + --j]; + ulong xVal = (ulong)x[--j]; ulong p = xVal * xVal; - zz[zzOff + --k] = (c << 31) | (uint)(p >> 33); - zz[zzOff + --k] = (uint)(p >> 1); + zz[--k] = (c << 31) | (uint)(p >> 33); + zz[--k] = (uint)(p >> 1); c = (uint)p; } while (j > 0); ulong d = 0UL; - int zzPos = zzOff + 2; + int zzPos = 2; for (int i = 1; i < len; ++i) { - d += SquareWordAddTo(x, xOff, i, zz, zzOff); + d += SquareWordAddTo(x, i, zz); d += zz[zzPos]; zz[zzPos++] = (uint)d; d >>= 32; d += zz[zzPos]; @@ -1127,11 +2299,11 @@ public static void Square(int len, uint[] x, int xOff, uint[] zz, int zzOff) } Debug.Assert(0UL == d); - ShiftUpBit(extLen, zz, zzOff, x[xOff] << 31); + ShiftUpBit(extLen, zz, x[0] << 31); } +#endif - - public static uint SquareWordAdd(uint[] x, int xPos, uint[] z) + public static uint SquareWordAddTo(uint[] x, int xPos, uint[] z) { ulong c = 0, xVal = (ulong)x[xPos]; int i = 0; @@ -1145,8 +2317,7 @@ public static uint SquareWordAdd(uint[] x, int xPos, uint[] z) return (uint)c; } - - public static uint SquareWordAdd(uint[] x, int xOff, int xPos, uint[] z, int zOff) + public static uint SquareWordAddTo(uint[] x, int xOff, int xPos, uint[] z, int zOff) { ulong c = 0, xVal = (ulong)x[xOff + xPos]; int i = 0; @@ -1161,9 +2332,10 @@ public static uint SquareWordAdd(uint[] x, int xOff, int xPos, uint[] z, int zOf return (uint)c; } - public static uint SquareWordAddTo(uint[] x, int xPos, uint[] z) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static uint SquareWordAddTo(ReadOnlySpan x, int xPos, Span z) { - ulong c = 0, xVal = (ulong)x[xPos]; + ulong c = 0, xVal = x[xPos]; int i = 0; do { @@ -1174,21 +2346,7 @@ public static uint SquareWordAddTo(uint[] x, int xPos, uint[] z) while (++i < xPos); return (uint)c; } - - public static uint SquareWordAddTo(uint[] x, int xOff, int xPos, uint[] z, int zOff) - { - ulong c = 0, xVal = (ulong)x[xOff + xPos]; - int i = 0; - do - { - c += xVal * (x[xOff + i] & M) + (z[xPos + zOff] & M); - z[xPos + zOff] = (uint)c; - c >>= 32; - ++zOff; - } - while (++i < xPos); - return (uint)c; - } +#endif public static int Sub(int len, uint[] x, uint[] y, uint[] z) { @@ -1213,6 +2371,21 @@ public static int Sub(int len, uint[] x, int xOff, uint[] y, int yOff, uint[] z, } return (int)c; } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static int Sub(int len, ReadOnlySpan x, ReadOnlySpan y, Span z) + { + long c = 0; + for (int i = 0; i < len; ++i) + { + c += (long)x[i] - y[i]; + z[i] = (uint)c; + c >>= 32; + } + return (int)c; + } +#endif + public static int Sub33At(int len, uint x, uint[] z, int zPos) { Debug.Assert(zPos <= (len - 2)); @@ -1237,6 +2410,20 @@ public static int Sub33At(int len, uint x, uint[] z, int zOff, int zPos) return c == 0 ? 0 : DecAt(len, z, zOff, zPos + 2); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static int Sub33At(int len, uint x, Span z, int zPos) + { + Debug.Assert(zPos <= (len - 2)); + long c = (long)z[zPos + 0] - x; + z[zPos + 0] = (uint)c; + c >>= 32; + c += (long)z[zPos + 1] - 1; + z[zPos + 1] = (uint)c; + c >>= 32; + return c == 0 ? 0 : DecAt(len, z, zPos + 2); + } +#endif + public static int Sub33From(int len, uint x, uint[] z) { long c = (long)z[0] - x; @@ -1259,6 +2446,19 @@ public static int Sub33From(int len, uint x, uint[] z, int zOff) return c == 0 ? 0 : DecAt(len, z, zOff, 2); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static int Sub33From(int len, uint x, Span z) + { + long c = (long)z[0] - x; + z[0] = (uint)c; + c >>= 32; + c += (long)z[1] - 1; + z[1] = (uint)c; + c >>= 32; + return c == 0 ? 0 : DecAt(len, z, 2); + } +#endif + public static int SubBothFrom(int len, uint[] x, uint[] y, uint[] z) { long c = 0; @@ -1283,13 +2483,27 @@ public static int SubBothFrom(int len, uint[] x, int xOff, uint[] y, int yOff, u return (int)c; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static int SubBothFrom(int len, ReadOnlySpan x, ReadOnlySpan y, Span z) + { + long c = 0; + for (int i = 0; i < len; ++i) + { + c += (long)z[i] - x[i] - y[i]; + z[i] = (uint)c; + c >>= 32; + } + return (int)c; + } +#endif + public static int SubDWordAt(int len, ulong x, uint[] z, int zPos) { Debug.Assert(zPos <= (len - 2)); - long c = (long)z[zPos + 0] - (long)(x & M); + long c = z[zPos + 0] - (long)(x & M); z[zPos + 0] = (uint)c; c >>= 32; - c += (long)z[zPos + 1] - (long)(x >> 32); + c += z[zPos + 1] - (long)(x >> 32); z[zPos + 1] = (uint)c; c >>= 32; return c == 0 ? 0 : DecAt(len, z, zPos + 2); @@ -1298,21 +2512,35 @@ public static int SubDWordAt(int len, ulong x, uint[] z, int zPos) public static int SubDWordAt(int len, ulong x, uint[] z, int zOff, int zPos) { Debug.Assert(zPos <= (len - 2)); - long c = (long)z[zOff + zPos] - (long)(x & M); + long c = z[zOff + zPos] - (long)(x & M); z[zOff + zPos] = (uint)c; c >>= 32; - c += (long)z[zOff + zPos + 1] - (long)(x >> 32); + c += z[zOff + zPos + 1] - (long)(x >> 32); z[zOff + zPos + 1] = (uint)c; c >>= 32; - return c == 0 ? 0 : DecAt(len, z, zOff, zPos + 2); + return c == 0 ? 0 : DecAt(len, z, zOff, zPos + 2); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static int SubDWordAt(int len, ulong x, Span z, int zPos) + { + Debug.Assert(zPos <= (len - 2)); + long c = z[zPos + 0] - (long)(x & M); + z[zPos + 0] = (uint)c; + c >>= 32; + c += z[zPos + 1] - (long)(x >> 32); + z[zPos + 1] = (uint)c; + c >>= 32; + return c == 0 ? 0 : DecAt(len, z, zPos + 2); } +#endif public static int SubDWordFrom(int len, ulong x, uint[] z) { - long c = (long)z[0] - (long)(x & M); + long c = z[0] - (long)(x & M); z[0] = (uint)c; c >>= 32; - c += (long)z[1] - (long)(x >> 32); + c += z[1] - (long)(x >> 32); z[1] = (uint)c; c >>= 32; return c == 0 ? 0 : DecAt(len, z, 2); @@ -1320,15 +2548,28 @@ public static int SubDWordFrom(int len, ulong x, uint[] z) public static int SubDWordFrom(int len, ulong x, uint[] z, int zOff) { - long c = (long)z[zOff + 0] - (long)(x & M); + long c = z[zOff + 0] - (long)(x & M); z[zOff + 0] = (uint)c; c >>= 32; - c += (long)z[zOff + 1] - (long)(x >> 32); + c += z[zOff + 1] - (long)(x >> 32); z[zOff + 1] = (uint)c; c >>= 32; return c == 0 ? 0 : DecAt(len, z, zOff, 2); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static int SubDWordFrom(int len, ulong x, Span z) + { + long c = z[0] - (long)(x & M); + z[0] = (uint)c; + c >>= 32; + c += z[1] - (long)(x >> 32); + z[1] = (uint)c; + c >>= 32; + return c == 0 ? 0 : DecAt(len, z, 2); + } +#endif + public static int SubFrom(int len, uint[] x, uint[] z) { long c = 0; @@ -1353,6 +2594,20 @@ public static int SubFrom(int len, uint[] x, int xOff, uint[] z, int zOff) return (int)c; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static int SubFrom(int len, ReadOnlySpan x, Span z) + { + long c = 0; + for (int i = 0; i < len; ++i) + { + c += (long)z[i] - x[i]; + z[i] = (uint)c; + c >>= 32; + } + return (int)c; + } +#endif + public static int SubWordAt(int len, uint x, uint[] z, int zPos) { Debug.Assert(zPos <= (len - 1)); @@ -1371,6 +2626,17 @@ public static int SubWordAt(int len, uint x, uint[] z, int zOff, int zPos) return c == 0 ? 0 : DecAt(len, z, zOff, zPos + 1); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static int SubWordAt(int len, uint x, Span z, int zPos) + { + Debug.Assert(zPos <= (len - 1)); + long c = (long)z[zPos] - x; + z[zPos] = (uint)c; + c >>= 32; + return c == 0 ? 0 : DecAt(len, z, zPos + 1); + } +#endif + public static int SubWordFrom(int len, uint x, uint[] z) { long c = (long)z[0] - x; @@ -1387,35 +2653,252 @@ public static int SubWordFrom(int len, uint x, uint[] z, int zOff) return c == 0 ? 0 : DecAt(len, z, zOff, 1); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static int SubWordFrom(int len, uint x, Span z) + { + long c = (long)z[0] - x; + z[0] = (uint)c; + c >>= 32; + return c == 0 ? 0 : DecAt(len, z, 1); + } +#endif + public static BigInteger ToBigInteger(int len, uint[] x) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ToBigInteger(len, x.AsSpan()); +#else byte[] bs = new byte[len << 2]; - for (int i = 0; i < len; ++i) + int xPos = len, bsPos = 0; + while (--xPos >= 0) { - uint x_i = x[i]; - if (x_i != 0) - { - Pack.UInt32_To_BE(x_i, bs, (len - 1 - i) << 2); - } + Pack.UInt32_To_BE(x[xPos], bs, bsPos); + bsPos += 4; + } + return new BigInteger(1, bs); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static BigInteger ToBigInteger(int len, ReadOnlySpan x) + { + int bsLen = len << 2; + Span bs = bsLen <= 512 + ? stackalloc byte[bsLen] + : new byte[bsLen]; + + int xPos = len; + Span t = bs; + while (--xPos >= 0) + { + Pack.UInt32_To_BE(x[xPos], t); + t = t[4..]; } return new BigInteger(1, bs); } +#endif + + public static void Xor(int len, uint[] x, uint[] y, uint[] z) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Xor(len, x.AsSpan(0, len), y.AsSpan(0, len), z.AsSpan(0, len)); +#else + for (int i = 0; i < len; ++i) + { + z[i] = x[i] ^ y[i]; + } +#endif + } + + public static void Xor(int len, uint[] x, int xOff, uint[] y, int yOff, uint[] z, int zOff) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Xor(len, x.AsSpan(xOff, len), y.AsSpan(yOff, len), z.AsSpan(zOff, len)); +#else + for (int i = 0; i < len; ++i) + { + z[zOff + i] = x[xOff + i] ^ y[yOff + i]; + } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Xor(int len, ReadOnlySpan x, ReadOnlySpan y, Span z) + { + int i = 0, limit16 = len - 16; + while (i <= limit16) + { + Nat512.Xor(x[i..], y[i..], z[i..]); + i += 16; + } + while (i < len) + { + z[i] = x[i] ^ y[i]; + ++i; + } + } +#endif + + public static void Xor64(int len, ulong[] x, ulong[] y, ulong[] z) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Xor64(len, x.AsSpan(0, len), y.AsSpan(0, len), z.AsSpan(0, len)); +#else + for (int i = 0; i < len; ++i) + { + z[i] = x[i] ^ y[i]; + } +#endif + } + + public static void Xor64(int len, ulong[] x, int xOff, ulong[] y, int yOff, ulong[] z, int zOff) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Xor64(len, x.AsSpan(xOff, len), y.AsSpan(yOff, len), z.AsSpan(zOff, len)); +#else + for (int i = 0; i < len; ++i) + { + z[zOff + i] = x[xOff + i] ^ y[yOff + i]; + } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Xor64(int len, ReadOnlySpan x, ReadOnlySpan y, Span z) + { + int i = 0, limit8 = len - 8; + while (i <= limit8) + { + Nat512.Xor64(x[i..], y[i..], z[i..]); + i += 8; + } + while (i < len) + { + z[i] = x[i] ^ y[i]; + ++i; + } + } +#endif + + public static void XorTo(int len, uint[] x, uint[] z) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + XorTo(len, x.AsSpan(0, len), z.AsSpan(0, len)); +#else + for (int i = 0; i < len; ++i) + { + z[i] ^= x[i]; + } +#endif + } + + public static void XorTo(int len, uint[] x, int xOff, uint[] z, int zOff) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + XorTo(len, x.AsSpan(xOff, len), z.AsSpan(zOff, len)); +#else + for (int i = 0; i < len; ++i) + { + z[zOff + i] ^= x[xOff + i]; + } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void XorTo(int len, ReadOnlySpan x, Span z) + { + int i = 0, limit16 = len - 16; + while (i <= limit16) + { + Nat512.XorTo(x[i..], z[i..]); + i += 16; + } + while (i < len) + { + z[i] ^= x[i]; + ++i; + } + } +#endif + + public static void XorTo64(int len, ulong[] x, ulong[] z) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + XorTo64(len, x.AsSpan(0, len), z.AsSpan(0, len)); +#else + for (int i = 0; i < len; ++i) + { + z[i] ^= x[i]; + } +#endif + } + + public static void XorTo64(int len, ulong[] x, int xOff, ulong[] z, int zOff) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + XorTo64(len, x.AsSpan(xOff, len), z.AsSpan(zOff, len)); +#else + for (int i = 0; i < len; ++i) + { + z[zOff + i] ^= x[xOff + i]; + } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void XorTo64(int len, ReadOnlySpan x, Span z) + { + int i = 0, limit8 = len - 8; + while (i <= limit8) + { + Nat512.XorTo64(x[i..], z[i..]); + i += 8; + } + while (i < len) + { + z[i] ^= x[i]; + ++i; + } + } +#endif public static void Zero(int len, uint[] z) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + z.AsSpan(0, len).Fill(0U); +#else for (int i = 0; i < len; ++i) { - z[i] = 0; + z[i] = 0U; } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Zero(int len, Span z) + { + z[..len].Fill(0U); } +#endif public static void Zero64(int len, ulong[] z) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + z.AsSpan(0, len).Fill(0UL); +#else for (int i = 0; i < len; ++i) { z[i] = 0UL; } +#endif } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Zero64(int len, Span z) + { + z[..len].Fill(0UL); + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Nat256.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Nat256.cs index 1672e72..8576bd9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Nat256.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Nat256.cs @@ -2,6 +2,12 @@ #pragma warning disable using System; using System.Diagnostics; +#if NETCOREAPP3_0_OR_GREATER +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities; @@ -1366,6 +1372,71 @@ public static BigInteger ToBigInteger64(ulong[] x) return new BigInteger(1, bs); } + public static void Xor(uint[] x, int xOff, uint[] y, int yOff, uint[] z, int zOff) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Xor(x.AsSpan(xOff), y.AsSpan(yOff), z.AsSpan(zOff)); +#else + for (int i = 0; i < 8; i += 4) + { + z[zOff + i + 0] = x[xOff + i + 0] ^ y[yOff + i + 0]; + z[zOff + i + 1] = x[xOff + i + 1] ^ y[yOff + i + 1]; + z[zOff + i + 2] = x[xOff + i + 2] ^ y[yOff + i + 2]; + z[zOff + i + 3] = x[xOff + i + 3] ^ y[yOff + i + 3]; + } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Xor(ReadOnlySpan x, ReadOnlySpan y, Span z) + { +#if NETCOREAPP3_0_OR_GREATER + if (Avx2.IsSupported && Unsafe.SizeOf>() == 32) + { + var X = MemoryMarshal.AsBytes(x[..8]); + var Y = MemoryMarshal.AsBytes(y[..8]); + var Z = MemoryMarshal.AsBytes(z[..8]); + + var X0 = MemoryMarshal.Read>(X[0x00..0x20]); + var Y0 = MemoryMarshal.Read>(Y[0x00..0x20]); + + var Z0 = Avx2.Xor(X0, Y0); + + MemoryMarshal.Write(Z[0x00..0x20], ref Z0); + return; + } + + if (Sse2.IsSupported && Unsafe.SizeOf>() == 16) + { + var X = MemoryMarshal.AsBytes(x[..8]); + var Y = MemoryMarshal.AsBytes(y[..8]); + var Z = MemoryMarshal.AsBytes(z[..8]); + + var X0 = MemoryMarshal.Read>(X[0x00..0x10]); + var X1 = MemoryMarshal.Read>(X[0x10..0x20]); + + var Y0 = MemoryMarshal.Read>(Y[0x00..0x10]); + var Y1 = MemoryMarshal.Read>(Y[0x10..0x20]); + + var Z0 = Sse2.Xor(X0, Y0); + var Z1 = Sse2.Xor(X1, Y1); + + MemoryMarshal.Write(Z[0x00..0x10], ref Z0); + MemoryMarshal.Write(Z[0x10..0x20], ref Z1); + return; + } +#endif + + for (int i = 0; i < 8; i += 4) + { + z[i + 0] = x[i + 0] ^ y[i + 0]; + z[i + 1] = x[i + 1] ^ y[i + 1]; + z[i + 2] = x[i + 2] ^ y[i + 2]; + z[i + 3] = x[i + 3] ^ y[i + 3]; + } + } +#endif + public static void Zero(uint[] z) { z[0] = 0; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Nat512.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Nat512.cs index a641020..c825897 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Nat512.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/math/raw/Nat512.cs @@ -1,7 +1,12 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Diagnostics; +#if NETCOREAPP3_0_OR_GREATER +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; +#endif namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw { @@ -44,6 +49,314 @@ public static void Square(uint[] x, uint[] zz) c24 += (uint)Nat.SubFrom(16, m, 0, zz, 8); Nat.AddWordAt(32, c24, zz, 24); } + + public static void Xor(uint[] x, int xOff, uint[] y, int yOff, uint[] z, int zOff) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Xor(x.AsSpan(xOff), y.AsSpan(yOff), z.AsSpan(zOff)); +#else + for (int i = 0; i < 16; i += 4) + { + z[zOff + i + 0] = x[xOff + i + 0] ^ y[yOff + i + 0]; + z[zOff + i + 1] = x[xOff + i + 1] ^ y[yOff + i + 1]; + z[zOff + i + 2] = x[xOff + i + 2] ^ y[yOff + i + 2]; + z[zOff + i + 3] = x[xOff + i + 3] ^ y[yOff + i + 3]; + } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Xor(ReadOnlySpan x, ReadOnlySpan y, Span z) + { +#if NETCOREAPP3_0_OR_GREATER + if (Avx2.IsSupported && Unsafe.SizeOf>() == 32) + { + var X = MemoryMarshal.AsBytes(x[..16]); + var Y = MemoryMarshal.AsBytes(y[..16]); + var Z = MemoryMarshal.AsBytes(z[..16]); + + var X0 = MemoryMarshal.Read>(X[0x00..0x20]); + var X1 = MemoryMarshal.Read>(X[0x20..0x40]); + + var Y0 = MemoryMarshal.Read>(Y[0x00..0x20]); + var Y1 = MemoryMarshal.Read>(Y[0x20..0x40]); + + var Z0 = Avx2.Xor(X0, Y0); + var Z1 = Avx2.Xor(X1, Y1); + + MemoryMarshal.Write(Z[0x00..0x20], ref Z0); + MemoryMarshal.Write(Z[0x20..0x40], ref Z1); + return; + } + + if (Sse2.IsSupported && Unsafe.SizeOf>() == 16) + { + var X = MemoryMarshal.AsBytes(x[..16]); + var Y = MemoryMarshal.AsBytes(y[..16]); + var Z = MemoryMarshal.AsBytes(z[..16]); + + var X0 = MemoryMarshal.Read>(X[0x00..0x10]); + var X1 = MemoryMarshal.Read>(X[0x10..0x20]); + var X2 = MemoryMarshal.Read>(X[0x20..0x30]); + var X3 = MemoryMarshal.Read>(X[0x30..0x40]); + + var Y0 = MemoryMarshal.Read>(Y[0x00..0x10]); + var Y1 = MemoryMarshal.Read>(Y[0x10..0x20]); + var Y2 = MemoryMarshal.Read>(Y[0x20..0x30]); + var Y3 = MemoryMarshal.Read>(Y[0x30..0x40]); + + var Z0 = Sse2.Xor(X0, Y0); + var Z1 = Sse2.Xor(X1, Y1); + var Z2 = Sse2.Xor(X2, Y2); + var Z3 = Sse2.Xor(X3, Y3); + + MemoryMarshal.Write(Z[0x00..0x10], ref Z0); + MemoryMarshal.Write(Z[0x10..0x20], ref Z1); + MemoryMarshal.Write(Z[0x20..0x30], ref Z2); + MemoryMarshal.Write(Z[0x30..0x40], ref Z3); + return; + } +#endif + + for (int i = 0; i < 16; i += 4) + { + z[i + 0] = x[i + 0] ^ y[i + 0]; + z[i + 1] = x[i + 1] ^ y[i + 1]; + z[i + 2] = x[i + 2] ^ y[i + 2]; + z[i + 3] = x[i + 3] ^ y[i + 3]; + } + } +#endif + + public static void XorTo(uint[] x, int xOff, uint[] z, int zOff) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + XorTo(x.AsSpan(xOff), z.AsSpan(zOff)); +#else + for (int i = 0; i < 16; i += 4) + { + z[zOff + i + 0] ^= x[xOff + i + 0]; + z[zOff + i + 1] ^= x[xOff + i + 1]; + z[zOff + i + 2] ^= x[xOff + i + 2]; + z[zOff + i + 3] ^= x[xOff + i + 3]; + } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void XorTo(ReadOnlySpan x, Span z) + { +#if NETCOREAPP3_0_OR_GREATER + if (Avx2.IsSupported && Unsafe.SizeOf>() == 32) + { + var X = MemoryMarshal.AsBytes(x[..16]); + var Z = MemoryMarshal.AsBytes(z[..16]); + + var X0 = MemoryMarshal.Read>(X[0x00..0x20]); + var X1 = MemoryMarshal.Read>(X[0x20..0x40]); + + var Y0 = MemoryMarshal.Read>(Z[0x00..0x20]); + var Y1 = MemoryMarshal.Read>(Z[0x20..0x40]); + + var Z0 = Avx2.Xor(X0, Y0); + var Z1 = Avx2.Xor(X1, Y1); + + MemoryMarshal.Write(Z[0x00..0x20], ref Z0); + MemoryMarshal.Write(Z[0x20..0x40], ref Z1); + return; + } + + if (Sse2.IsSupported && Unsafe.SizeOf>() == 16) + { + var X = MemoryMarshal.AsBytes(x[..16]); + var Z = MemoryMarshal.AsBytes(z[..16]); + + var X0 = MemoryMarshal.Read>(X[0x00..0x10]); + var X1 = MemoryMarshal.Read>(X[0x10..0x20]); + var X2 = MemoryMarshal.Read>(X[0x20..0x30]); + var X3 = MemoryMarshal.Read>(X[0x30..0x40]); + + var Y0 = MemoryMarshal.Read>(Z[0x00..0x10]); + var Y1 = MemoryMarshal.Read>(Z[0x10..0x20]); + var Y2 = MemoryMarshal.Read>(Z[0x20..0x30]); + var Y3 = MemoryMarshal.Read>(Z[0x30..0x40]); + + var Z0 = Sse2.Xor(X0, Y0); + var Z1 = Sse2.Xor(X1, Y1); + var Z2 = Sse2.Xor(X2, Y2); + var Z3 = Sse2.Xor(X3, Y3); + + MemoryMarshal.Write(Z[0x00..0x10], ref Z0); + MemoryMarshal.Write(Z[0x10..0x20], ref Z1); + MemoryMarshal.Write(Z[0x20..0x30], ref Z2); + MemoryMarshal.Write(Z[0x30..0x40], ref Z3); + return; + } +#endif + + for (int i = 0; i < 16; i += 4) + { + z[i + 0] ^= x[i + 0]; + z[i + 1] ^= x[i + 1]; + z[i + 2] ^= x[i + 2]; + z[i + 3] ^= x[i + 3]; + } + } +#endif + + public static void Xor64(ulong[] x, int xOff, ulong[] y, int yOff, ulong[] z, int zOff) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Xor64(x.AsSpan(xOff), y.AsSpan(yOff), z.AsSpan(zOff)); +#else + for (int i = 0; i < 8; i += 4) + { + z[zOff + i + 0] = x[xOff + i + 0] ^ y[yOff + i + 0]; + z[zOff + i + 1] = x[xOff + i + 1] ^ y[yOff + i + 1]; + z[zOff + i + 2] = x[xOff + i + 2] ^ y[yOff + i + 2]; + z[zOff + i + 3] = x[xOff + i + 3] ^ y[yOff + i + 3]; + } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Xor64(ReadOnlySpan x, ReadOnlySpan y, Span z) + { +#if NETCOREAPP3_0_OR_GREATER + if (Avx2.IsSupported && Unsafe.SizeOf>() == 32) + { + var X = MemoryMarshal.AsBytes(x[..8]); + var Y = MemoryMarshal.AsBytes(y[..8]); + var Z = MemoryMarshal.AsBytes(z[..8]); + + var X0 = MemoryMarshal.Read>(X[0x00..0x20]); + var X1 = MemoryMarshal.Read>(X[0x20..0x40]); + + var Y0 = MemoryMarshal.Read>(Y[0x00..0x20]); + var Y1 = MemoryMarshal.Read>(Y[0x20..0x40]); + + var Z0 = Avx2.Xor(X0, Y0); + var Z1 = Avx2.Xor(X1, Y1); + + MemoryMarshal.Write(Z[0x00..0x20], ref Z0); + MemoryMarshal.Write(Z[0x20..0x40], ref Z1); + return; + } + + if (Sse2.IsSupported && Unsafe.SizeOf>() == 16) + { + var X = MemoryMarshal.AsBytes(x[..8]); + var Y = MemoryMarshal.AsBytes(y[..8]); + var Z = MemoryMarshal.AsBytes(z[..8]); + + var X0 = MemoryMarshal.Read>(X[0x00..0x10]); + var X1 = MemoryMarshal.Read>(X[0x10..0x20]); + var X2 = MemoryMarshal.Read>(X[0x20..0x30]); + var X3 = MemoryMarshal.Read>(X[0x30..0x40]); + + var Y0 = MemoryMarshal.Read>(Y[0x00..0x10]); + var Y1 = MemoryMarshal.Read>(Y[0x10..0x20]); + var Y2 = MemoryMarshal.Read>(Y[0x20..0x30]); + var Y3 = MemoryMarshal.Read>(Y[0x30..0x40]); + + var Z0 = Sse2.Xor(X0, Y0); + var Z1 = Sse2.Xor(X1, Y1); + var Z2 = Sse2.Xor(X2, Y2); + var Z3 = Sse2.Xor(X3, Y3); + + MemoryMarshal.Write(Z[0x00..0x10], ref Z0); + MemoryMarshal.Write(Z[0x10..0x20], ref Z1); + MemoryMarshal.Write(Z[0x20..0x30], ref Z2); + MemoryMarshal.Write(Z[0x30..0x40], ref Z3); + return; + } +#endif + + for (int i = 0; i < 8; i += 4) + { + z[i + 0] = x[i + 0] ^ y[i + 0]; + z[i + 1] = x[i + 1] ^ y[i + 1]; + z[i + 2] = x[i + 2] ^ y[i + 2]; + z[i + 3] = x[i + 3] ^ y[i + 3]; + } + } +#endif + + public static void XorTo64(ulong[] x, int xOff, ulong[] z, int zOff) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + XorTo64(x.AsSpan(xOff), z.AsSpan(zOff)); +#else + for (int i = 0; i < 8; i += 4) + { + z[zOff + i + 0] ^= x[xOff + i + 0]; + z[zOff + i + 1] ^= x[xOff + i + 1]; + z[zOff + i + 2] ^= x[xOff + i + 2]; + z[zOff + i + 3] ^= x[xOff + i + 3]; + } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void XorTo64(ReadOnlySpan x, Span z) + { +#if NETCOREAPP3_0_OR_GREATER + if (Avx2.IsSupported && Unsafe.SizeOf>() == 32) + { + var X = MemoryMarshal.AsBytes(x[..8]); + var Z = MemoryMarshal.AsBytes(z[..8]); + + var X0 = MemoryMarshal.Read>(X[0x00..0x20]); + var X1 = MemoryMarshal.Read>(X[0x20..0x40]); + + var Y0 = MemoryMarshal.Read>(Z[0x00..0x20]); + var Y1 = MemoryMarshal.Read>(Z[0x20..0x40]); + + var Z0 = Avx2.Xor(X0, Y0); + var Z1 = Avx2.Xor(X1, Y1); + + MemoryMarshal.Write(Z[0x00..0x20], ref Z0); + MemoryMarshal.Write(Z[0x20..0x40], ref Z1); + return; + } + + if (Sse2.IsSupported && Unsafe.SizeOf>() == 16) + { + var X = MemoryMarshal.AsBytes(x[..8]); + var Z = MemoryMarshal.AsBytes(z[..8]); + + var X0 = MemoryMarshal.Read>(X[0x00..0x10]); + var X1 = MemoryMarshal.Read>(X[0x10..0x20]); + var X2 = MemoryMarshal.Read>(X[0x20..0x30]); + var X3 = MemoryMarshal.Read>(X[0x30..0x40]); + + var Y0 = MemoryMarshal.Read>(Z[0x00..0x10]); + var Y1 = MemoryMarshal.Read>(Z[0x10..0x20]); + var Y2 = MemoryMarshal.Read>(Z[0x20..0x30]); + var Y3 = MemoryMarshal.Read>(Z[0x30..0x40]); + + var Z0 = Sse2.Xor(X0, Y0); + var Z1 = Sse2.Xor(X1, Y1); + var Z2 = Sse2.Xor(X2, Y2); + var Z3 = Sse2.Xor(X3, Y3); + + MemoryMarshal.Write(Z[0x00..0x10], ref Z0); + MemoryMarshal.Write(Z[0x10..0x20], ref Z1); + MemoryMarshal.Write(Z[0x20..0x30], ref Z2); + MemoryMarshal.Write(Z[0x30..0x40], ref Z3); + return; + } +#endif + + for (int i = 0; i < 8; i += 4) + { + z[i + 0] ^= x[i + 0]; + z[i + 1] ^= x[i + 1]; + z[i + 2] ^= x[i + 2]; + z[i + 3] ^= x[i + 3]; + } + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/BasicOCSPResp.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/BasicOCSPResp.cs index 2ac2040..ea92eef 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/BasicOCSPResp.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/BasicOCSPResp.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; @@ -9,10 +9,8 @@ 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; -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.Ocsp { @@ -105,72 +103,42 @@ public string SignatureAlgOid get { return resp.SignatureAlgorithm.Algorithm.Id; } } - - public RespData GetResponseData() - { - return new RespData(data); - } - public byte[] GetSignature() { return resp.GetSignatureOctets(); } - private IList GetCertList() + private List GetCertList() { - // load the certificates and revocation lists if we have any + // load the certificates if we have any - IList certs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); - Asn1Sequence s = resp.Certs; + var result = new List(); - if (s != null) + Asn1Sequence certs = resp.Certs; + if (certs != null) { - foreach (Asn1Encodable ae in s) + foreach (Asn1Encodable ae in certs) { - try - { - certs.Add(new X509CertificateParser().ReadCertificate(ae.GetEncoded())); - } - catch (IOException ex) - { - throw new OcspException("can't re-encode certificate!", ex); - } - catch (CertificateException ex) + if (ae != null && ae.ToAsn1Object() is Asn1Sequence s) { - throw new OcspException("can't re-encode certificate!", ex); + result.Add(new X509Certificate(X509CertificateStructure.GetInstance(s))); } } } - return certs; + return result; } public X509Certificate[] GetCerts() { - IList certs = GetCertList(); - X509Certificate[] result = new X509Certificate[certs.Count]; - for (int i = 0; i < certs.Count; ++i) - { - result[i] = (X509Certificate)certs[i]; - } - return result; + return GetCertList().ToArray(); } /// The certificates, if any, associated with the response. /// In the event of an encoding error. - public IX509Store GetCertificates( - string type) + public IStore GetCertificates() { - try - { - return X509StoreFactory.Create( - "Certificate/" + type, - new X509CollectionStoreParameters(this.GetCertList())); - } - catch (Exception e) - { - throw new OcspException("can't setup the CertStore", e); - } + return CollectionUtilities.CreateStore(this.GetCertList()); } /// diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/BasicOCSPRespGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/BasicOCSPRespGenerator.cs index c3e1510..635fdbc 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/BasicOCSPRespGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/BasicOCSPRespGenerator.cs @@ -1,18 +1,17 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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.Operators; 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.Crypto.Operators; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Ocsp { @@ -21,7 +20,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Ocsp */ public class BasicOcspRespGenerator { - private readonly IList list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + private readonly List list = new List(); private X509Extensions responseExtensions; private RespID responderID; @@ -30,34 +29,15 @@ private class ResponseObject { internal CertificateID certId; internal CertStatus certStatus; - internal DerGeneralizedTime thisUpdate; - internal DerGeneralizedTime nextUpdate; + internal Asn1GeneralizedTime thisUpdate; + internal Asn1GeneralizedTime nextUpdate; internal X509Extensions extensions; - public ResponseObject( - CertificateID certId, - CertificateStatus certStatus, - DateTime thisUpdate, - X509Extensions extensions) - : this(certId, certStatus, new DerGeneralizedTime(thisUpdate), null, extensions) - { - } - - public ResponseObject( + internal ResponseObject( CertificateID certId, CertificateStatus certStatus, DateTime thisUpdate, - DateTime nextUpdate, - X509Extensions extensions) - : this(certId, certStatus, new DerGeneralizedTime(thisUpdate), new DerGeneralizedTime(nextUpdate), extensions) - { - } - - private ResponseObject( - CertificateID certId, - CertificateStatus certStatus, - DerGeneralizedTime thisUpdate, - DerGeneralizedTime nextUpdate, + DateTime? nextUpdate, X509Extensions extensions) { this.certId = certId; @@ -78,11 +58,11 @@ private ResponseObject( : null; this.certStatus = new CertStatus( - new RevokedInfo(new DerGeneralizedTime(rs.RevocationTime), revocationReason)); + new RevokedInfo(new Asn1GeneralizedTime(rs.RevocationTime), revocationReason)); } - this.thisUpdate = thisUpdate; - this.nextUpdate = nextUpdate; + this.thisUpdate = new DerGeneralizedTime(thisUpdate); + this.nextUpdate = nextUpdate.HasValue ? new DerGeneralizedTime(nextUpdate.Value) : null; this.extensions = extensions; } @@ -121,7 +101,7 @@ public void AddResponse( CertificateID certID, CertificateStatus certStatus) { - list.Add(new ResponseObject(certID, certStatus, DateTime.UtcNow, null)); + list.Add(new ResponseObject(certID, certStatus, DateTime.UtcNow, null, null)); } /** @@ -136,7 +116,7 @@ public void AddResponse( CertificateStatus certStatus, X509Extensions singleExtensions) { - list.Add(new ResponseObject(certID, certStatus, DateTime.UtcNow, singleExtensions)); + list.Add(new ResponseObject(certID, certStatus, DateTime.UtcNow, null, singleExtensions)); } /** @@ -150,7 +130,7 @@ public void AddResponse( public void AddResponse( CertificateID certID, CertificateStatus certStatus, - DateTime nextUpdate, + DateTime? nextUpdate, X509Extensions singleExtensions) { list.Add(new ResponseObject(certID, certStatus, DateTime.UtcNow, nextUpdate, singleExtensions)); @@ -169,7 +149,7 @@ public void AddResponse( CertificateID certID, CertificateStatus certStatus, DateTime thisUpdate, - DateTime nextUpdate, + DateTime? nextUpdate, X509Extensions singleExtensions) { list.Add(new ResponseObject(certID, certStatus, thisUpdate, nextUpdate, singleExtensions)); @@ -208,20 +188,19 @@ private BasicOcspResp GenerateResponse( } } - ResponseData tbsResp = new ResponseData(responderID.ToAsn1Object(), new DerGeneralizedTime(producedAt), new DerSequence(responses), responseExtensions); - DerBitString bitSig = null; + ResponseData tbsResp = new ResponseData(responderID.ToAsn1Object(), new Asn1GeneralizedTime(producedAt), + new DerSequence(responses), responseExtensions); + DerBitString bitSig; try { - IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator(); - - byte[] encoded = tbsResp.GetDerEncoded(); - - streamCalculator.Stream.Write(encoded, 0, encoded.Length); - - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(streamCalculator.Stream); + IStreamCalculator streamCalculator = signatureCalculator.CreateCalculator(); + using (Stream sigStream = streamCalculator.Stream) + { + tbsResp.EncodeTo(sigStream, Asn1Encodable.Der); + } - bitSig = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect()); + bitSig = new DerBitString(streamCalculator.GetResult().Collect()); } catch (Exception e) { @@ -233,14 +212,12 @@ private BasicOcspResp GenerateResponse( DerSequence chainSeq = null; if (chain != null && chain.Length > 0) { - Asn1EncodableVector v = new Asn1EncodableVector(); + Asn1EncodableVector v = new Asn1EncodableVector(chain.Length); try { for (int i = 0; i != chain.Length; i++) { - v.Add( - X509CertificateStructure.GetInstance( - Asn1Object.FromByteArray(chain[i].GetEncoded()))); + v.Add(chain[i].CertificateStructure); } } catch (IOException e) @@ -307,7 +284,7 @@ public BasicOcspResp Generate( * * @return an IEnumerable containing recognised names. */ - public IEnumerable SignatureAlgNames + public IEnumerable SignatureAlgNames { get { return OcspUtilities.AlgNames; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/CertificateID.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/CertificateID.cs index 9fbbc97..850ceb9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/CertificateID.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/CertificateID.cs @@ -120,7 +120,7 @@ private static CertID CreateCertID( { try { - String hashAlgorithm = hashAlg.Algorithm.Id; + string hashAlgorithm = hashAlg.Algorithm.Id; X509Name issuerName = PrincipalUtilities.GetSubjectX509Principal(issuerCert); byte[] issuerNameHash = DigestUtilities.CalculateDigest( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPException.cs index 81405af..c77acb3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPException.cs @@ -1,29 +1,31 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Ocsp { -#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE) [Serializable] -#endif public class OcspException : Exception { public OcspException() + : base() { } - public OcspException( - string message) + public OcspException(string message) : base(message) { } - public OcspException( - string message, - Exception e) - : base(message, e) + public OcspException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected OcspException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPReq.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPReq.cs index 6639dab..2b76681 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPReq.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPReq.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; @@ -9,10 +9,8 @@ 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; -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.Ocsp { @@ -158,29 +156,25 @@ public byte[] GetSignature() return req.OptionalSignature.GetSignatureOctets(); } - private IList GetCertList() + private List GetCertList() { // load the certificates if we have any - IList certs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); - Asn1Sequence s = req.OptionalSignature.Certs; + var result = new List(); - if (s != null) + Asn1Sequence certs = req.OptionalSignature.Certs; + if (certs != null) { - foreach (Asn1Encodable ae in s) + foreach (Asn1Encodable ae in certs) { - try - { - certs.Add(new X509CertificateParser().ReadCertificate(ae.GetEncoded())); - } - catch (Exception e) - { - throw new OcspException("can't re-encode certificate!", e); - } - } + if (ae != null && ae.ToAsn1Object() is Asn1Sequence s) + { + result.Add(new X509Certificate(X509CertificateStructure.GetInstance(s))); + } + } } - return certs; + return result; } public X509Certificate[] GetCerts() @@ -188,13 +182,7 @@ 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; + return this.GetCertList().ToArray(); } /** @@ -204,22 +192,12 @@ public X509Certificate[] GetCerts() * @return null if not signed, a CertStore otherwise * @throws OcspException */ - public IX509Store GetCertificates( - string type) + public IStore GetCertificates() { 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 CollectionUtilities.CreateStore(this.GetCertList()); } /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPReqGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPReqGenerator.cs index 26cea1c..5a60924 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPReqGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPReqGenerator.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; @@ -18,7 +18,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Ocsp { public class OcspReqGenerator { - private IList list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + private List list = new List(); private GeneralName requestorName = null; private X509Extensions requestExtensions = null; @@ -167,9 +167,7 @@ private OcspReq GenerateRequest( { for (int i = 0; i != chain.Length; i++) { - v.Add( - X509CertificateStructure.GetInstance( - Asn1Object.FromByteArray(chain[i].GetEncoded()))); + v.Add(chain[i].CertificateStructure); } } catch (IOException e) @@ -237,7 +235,7 @@ public OcspReq Generate( * * @return an IEnumerable containing recognised names. */ - public IEnumerable SignatureAlgNames + public IEnumerable SignatureAlgNames { get { return OcspUtilities.AlgNames; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPRespStatus.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPRespStatus.cs index b10f7ff..3dd0206 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPRespStatus.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPRespStatus.cs @@ -4,11 +4,6 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Ocsp { - - public abstract class OcscpRespStatus : OcspRespStatus - { - } - public abstract class OcspRespStatus { /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPUtil.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPUtil.cs index 45e2c55..4323a13 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPUtil.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/OCSPUtil.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro; @@ -11,149 +11,138 @@ 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 + internal 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(); + private static readonly Dictionary Algorithms = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly Dictionary Oids = + new Dictionary(); + private static readonly HashSet 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("SHA-1WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha1WithRsaEncryption); - algorithms.Add("SHA1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption); - algorithms.Add("SHA-1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption); - algorithms.Add("SHA224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption); - algorithms.Add("SHA-224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption); - algorithms.Add("SHA224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption); - algorithms.Add("SHA-224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption); - algorithms.Add("SHA256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption); - algorithms.Add("SHA-256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption); - algorithms.Add("SHA256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption); - algorithms.Add("SHA-256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption); - algorithms.Add("SHA384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption); - algorithms.Add("SHA-384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption); - algorithms.Add("SHA384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption); - algorithms.Add("SHA-384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption); - algorithms.Add("SHA512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption); - algorithms.Add("SHA-512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption); - algorithms.Add("SHA512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption); - algorithms.Add("SHA-512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption); - algorithms.Add("SHA512(224)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); - algorithms.Add("SHA-512(224)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); - algorithms.Add("SHA512(224)WITHRSA", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); - algorithms.Add("SHA-512(224)WITHRSA", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); - algorithms.Add("SHA512(256)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); - algorithms.Add("SHA-512(256)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); - algorithms.Add("SHA512(256)WITHRSA", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); - algorithms.Add("SHA-512(256)WITHRSA", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); - 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); + 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("SHA-1WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha1WithRsaEncryption); + Algorithms.Add("SHA1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption); + Algorithms.Add("SHA-1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption); + Algorithms.Add("SHA224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption); + Algorithms.Add("SHA-224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption); + Algorithms.Add("SHA224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption); + Algorithms.Add("SHA-224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption); + Algorithms.Add("SHA256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption); + Algorithms.Add("SHA-256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption); + Algorithms.Add("SHA256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption); + Algorithms.Add("SHA-256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption); + Algorithms.Add("SHA384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption); + Algorithms.Add("SHA-384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption); + Algorithms.Add("SHA384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption); + Algorithms.Add("SHA-384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption); + Algorithms.Add("SHA512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption); + Algorithms.Add("SHA-512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption); + Algorithms.Add("SHA512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption); + Algorithms.Add("SHA-512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption); + Algorithms.Add("SHA512(224)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); + Algorithms.Add("SHA-512(224)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); + Algorithms.Add("SHA512(224)WITHRSA", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); + Algorithms.Add("SHA-512(224)WITHRSA", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); + Algorithms.Add("SHA512(256)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); + Algorithms.Add("SHA-512(256)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); + Algorithms.Add("SHA512(256)WITHRSA", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); + Algorithms.Add("SHA-512(256)WITHRSA", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); + 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(PkcsObjectIdentifiers.Sha512_224WithRSAEncryption, "SHA512(224)WITHRSA"); - oids.Add(PkcsObjectIdentifiers.Sha512_256WithRSAEncryption, "SHA512(256)WITHRSA"); - 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"); + 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(PkcsObjectIdentifiers.Sha512_224WithRSAEncryption, "SHA512(224)WITHRSA"); + Oids.Add(PkcsObjectIdentifiers.Sha512_256WithRSAEncryption, "SHA512(256)WITHRSA"); + 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(OiwObjectIdentifiers.DsaWithSha1); - noParams.Add(NistObjectIdentifiers.DsaWithSha224); - noParams.Add(NistObjectIdentifiers.DsaWithSha256); + 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(OiwObjectIdentifiers.DsaWithSha1); + NoParams.Add(NistObjectIdentifiers.DsaWithSha224); + NoParams.Add(NistObjectIdentifiers.DsaWithSha256); } - internal static DerObjectIdentifier GetAlgorithmOid( - string algorithmName) + internal static DerObjectIdentifier GetAlgorithmOid(string algorithmName) { - algorithmName = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithmName); - - if (algorithms.Contains(algorithmName)) - { - return (DerObjectIdentifier)algorithms[algorithmName]; - } + if (Algorithms.TryGetValue(algorithmName, out var oid)) + return oid; return new DerObjectIdentifier(algorithmName); } - - internal static string GetAlgorithmName( - DerObjectIdentifier oid) + internal static string GetAlgorithmName(DerObjectIdentifier oid) { - if (oids.Contains(oid)) - { - return (string)oids[oid]; - } + if (Oids.TryGetValue(oid, out var algorithmName)) + return algorithmName; return oid.Id; } - internal static AlgorithmIdentifier GetSigAlgID( - DerObjectIdentifier sigOid) + internal static AlgorithmIdentifier GetSigAlgID(DerObjectIdentifier sigOid) { - if (noParams.Contains(sigOid)) - { - return new AlgorithmIdentifier(sigOid); - } + if (NoParams.Contains(sigOid)) + return new AlgorithmIdentifier(sigOid); return new AlgorithmIdentifier(sigOid, DerNull.Instance); } - internal static IEnumerable AlgNames + internal static IEnumerable AlgNames { - get { return new EnumerableProxy(algorithms.Keys); } + get { return CollectionUtilities.Proxy(Algorithms.Keys); } } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/Req.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/Req.cs index 0879fc6..b4912b9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/Req.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/Req.cs @@ -1,10 +1,7 @@ #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; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/RespData.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/RespData.cs index ec7a974..f02752a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/RespData.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/RespData.cs @@ -1,7 +1,6 @@ #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; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/RevokedStatus.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/RevokedStatus.cs index acceeb6..a320621 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/RevokedStatus.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/RevokedStatus.cs @@ -8,52 +8,49 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Ocsp { - /** - * wrapper for the RevokedInfo object - */ - public class RevokedStatus + /// Wrapper for the RevokedInfo object + public class RevokedStatus : CertificateStatus { - internal readonly RevokedInfo info; + private readonly RevokedInfo m_revokedInfo; - public RevokedStatus( - RevokedInfo info) + public RevokedStatus(RevokedInfo revokedInfo) { - this.info = info; + m_revokedInfo = revokedInfo; } - public RevokedStatus( - DateTime revocationDate, - int reason) + public RevokedStatus(DateTime revocationDate) { - this.info = new RevokedInfo(new DerGeneralizedTime(revocationDate), new CrlReason(reason)); + m_revokedInfo = new RevokedInfo(new Asn1GeneralizedTime(revocationDate)); + } + + public RevokedStatus(DateTime revocationDate, int reason) + { + m_revokedInfo = new RevokedInfo(new Asn1GeneralizedTime(revocationDate), new CrlReason(reason)); } public DateTime RevocationTime { - get { return info.RevocationTime.ToDateTime(); } + get { return m_revokedInfo.RevocationTime.ToDateTime(); } } public bool HasRevocationReason { - get { return (info.RevocationReason != null); } + get { return m_revokedInfo.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 + /// Return the revocation reason, if there is one. + /// This field is optional; test for it with first. + /// The revocation reason, if available. + /// If no revocation reason is available. + public int RevocationReason { get { - if (info.RevocationReason == null) - { + if (m_revokedInfo.RevocationReason == null) throw new InvalidOperationException("attempt to get a reason where none is available"); - } - return info.RevocationReason.IntValueExact; + return m_revokedInfo.RevocationReason.IntValueExact; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/SingleResp.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/SingleResp.cs index f52f226..c9412f1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/SingleResp.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/ocsp/SingleResp.cs @@ -1,12 +1,9 @@ #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 @@ -60,15 +57,7 @@ public DateTime ThisUpdate * * @return nextUpdate, or null if not present. */ - public DateTimeObject NextUpdate - { - get - { - return resp.NextUpdate == null - ? null - : new DateTimeObject(resp.NextUpdate.ToDateTime()); - } - } + public DateTime? NextUpdate => resp.NextUpdate?.ToDateTime(); public X509Extensions SingleExtensions { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/EncryptionException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/EncryptionException.cs index b156125..acb1038 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/EncryptionException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/EncryptionException.cs @@ -2,25 +2,31 @@ #pragma warning disable using System; using System.IO; +using System.Runtime.Serialization; 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) + public EncryptionException() + : base() + { + } + + public EncryptionException(string message) : base(message) { } - public EncryptionException( - string message, - Exception exception) - : base(message, exception) + public EncryptionException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected EncryptionException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/MiscPemGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/MiscPemGenerator.cs index 8823d57..12f2bdd 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/MiscPemGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/MiscPemGenerator.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; @@ -28,10 +28,10 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.OpenSsl public class MiscPemGenerator : PemObjectGenerator { - private object obj; - private string algorithm; - private char[] password; - private SecureRandom random; + private readonly object obj; + private readonly string algorithm; + private readonly char[] password; + private readonly SecureRandom random; public MiscPemGenerator(object obj) { @@ -55,48 +55,47 @@ private static PemObject CreatePemObject(object obj) if (obj == null) throw new ArgumentNullException("obj"); - if (obj is AsymmetricCipherKeyPair) + if (obj is AsymmetricCipherKeyPair keyPair) { - return CreatePemObject(((AsymmetricCipherKeyPair)obj).Private); + return CreatePemObject(keyPair.Private); } string type; byte[] encoding; - if (obj is PemObject) - return (PemObject)obj; + if (obj is PemObject pemObject) + return pemObject; - if (obj is PemObjectGenerator) - return ((PemObjectGenerator)obj).Generate(); + if (obj is PemObjectGenerator pemObjectGenerator) + return pemObjectGenerator.Generate(); - if (obj is X509Certificate) + if (obj is X509Certificate certificate) { // TODO Should we prefer "X509 CERTIFICATE" here? type = "CERTIFICATE"; try { - encoding = ((X509Certificate)obj).GetEncoded(); + encoding = certificate.GetEncoded(); } catch (CertificateEncodingException e) { throw new IOException("Cannot Encode object: " + e.ToString()); } } - else if (obj is X509Crl) + else if (obj is X509Crl crl) { type = "X509 CRL"; try { - encoding = ((X509Crl)obj).GetEncoded(); + encoding = crl.GetEncoded(); } catch (CrlException e) { throw new IOException("Cannot Encode object: " + e.ToString()); } } - else if (obj is AsymmetricKeyParameter) + else if (obj is AsymmetricKeyParameter akp) { - AsymmetricKeyParameter akp = (AsymmetricKeyParameter) obj; if (akp.IsPrivate) { encoding = EncodePrivateKey(akp, out type); @@ -108,24 +107,24 @@ private static PemObject CreatePemObject(object obj) encoding = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(akp).GetDerEncoded(); } } - else if (obj is IX509AttributeCertificate) + else if (obj is X509V2AttributeCertificate attrCert) { type = "ATTRIBUTE CERTIFICATE"; - encoding = ((X509V2AttributeCertificate)obj).GetEncoded(); + encoding = attrCert.GetEncoded(); } - else if (obj is Pkcs10CertificationRequest) + else if (obj is Pkcs10CertificationRequest certReq) { type = "CERTIFICATE REQUEST"; - encoding = ((Pkcs10CertificationRequest)obj).GetEncoded(); + encoding = certReq.GetEncoded(); } - else if (obj is Asn1.Cms.ContentInfo) + else if (obj is Asn1.Cms.ContentInfo contentInfo) { type = "PKCS7"; - encoding = ((Asn1.Cms.ContentInfo)obj).GetEncoded(); + encoding = contentInfo.GetEncoded(); } else { - throw new PemGenerationException("Object type not supported: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new PemGenerationException("Object type not supported: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } return new PemObject(type, encoding); @@ -160,17 +159,16 @@ private static PemObject CreatePemObject( if (random == null) throw new ArgumentNullException("random"); - if (obj is AsymmetricCipherKeyPair) + if (obj is AsymmetricCipherKeyPair keyPair) { - return CreatePemObject(((AsymmetricCipherKeyPair)obj).Private, algorithm, password, random); + return CreatePemObject(keyPair.Private, algorithm, password, random); } string type = null; byte[] keyData = null; - if (obj is AsymmetricKeyParameter) + if (obj is AsymmetricKeyParameter akp) { - AsymmetricKeyParameter akp = (AsymmetricKeyParameter) obj; if (akp.IsPrivate) { keyData = EncodePrivateKey(akp, out type); @@ -180,11 +178,11 @@ private static PemObject CreatePemObject( if (type == null || keyData == null) { // TODO Support other types? - throw new PemGenerationException("Object type not supported: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); + throw new PemGenerationException("Object type not supported: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(obj)); } - string dekAlgName = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm); + string dekAlgName = algorithm.ToUpperInvariant(); // Note: For backward compatibility if (dekAlgName == "DESEDE") @@ -192,17 +190,16 @@ private static PemObject CreatePemObject( dekAlgName = "DES-EDE3-CBC"; } - int ivLength = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(dekAlgName, "AES-") ? 16 : 8; + int ivLength = 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); - + var headers = new List(2); headers.Add(new PemHeader("Proc-Type", "4,ENCRYPTED")); - headers.Add(new PemHeader("DEK-Info", dekAlgName + "," + Hex.ToHexString(iv))); + headers.Add(new PemHeader("DEK-Info", dekAlgName + "," + Hex.ToHexString(iv).ToUpperInvariant())); return new PemObject(type, headers, encData); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PEMException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PEMException.cs index fec661b..93a9ade 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PEMException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PEMException.cs @@ -2,25 +2,31 @@ #pragma warning disable using System; using System.IO; +using System.Runtime.Serialization; 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) + public PemException() + : base() + { + } + + public PemException(string message) : base(message) { } - public PemException( - string message, - Exception exception) - : base(message, exception) + public PemException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected PemException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PEMReader.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PEMReader.cs index 0debee6..ee8d54c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PEMReader.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PEMReader.cs @@ -1,25 +1,22 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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.Collections; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Pem; using BestHTTP.SecureProtocol.Org.BouncyCastle.X509; @@ -34,27 +31,27 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.OpenSsl * Certificates will be returned using the appropriate java.security type.

*/ public class PemReader - : BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Pem.PemReader + : Utilities.IO.Pem.PemReader { -// private static readonly IDictionary parsers = new Hashtable(); + //private static readonly Dictionary Parsers = new Dictionary(); 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)); +// 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; @@ -95,7 +92,7 @@ public object ReadObject() // if (parsers.Contains(obj.Type)) // return ((PemObjectParser)parsers[obj.Type]).ParseObject(obj); - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(obj.Type, "PRIVATE KEY")) + if (Org.BouncyCastle.Utilities.Platform.EndsWith(obj.Type, "PRIVATE KEY")) return ReadPrivateKey(obj); switch (obj.Type) @@ -201,7 +198,7 @@ private Pkcs10CertificationRequest ReadCertificateRequest(PemObject pemObject) * @return the X509 Attribute Certificate * @throws IOException if an I/O error occured */ - private IX509AttributeCertificate ReadAttributeCertificate(PemObject pemObject) + private X509V2AttributeCertificate ReadAttributeCertificate(PemObject pemObject) { return new X509V2AttributeCertificate(pemObject.Content); } @@ -235,18 +232,18 @@ private object ReadPrivateKey(PemObject pemObject) // // extract the key // - Debug.Assert(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(pemObject.Type, "PRIVATE KEY")); + Debug.Assert(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(); + var fields = new Dictionary(); foreach (PemHeader header in pemObject.Headers) { fields[header.Name] = header.Value; } - string procType = (string) fields["Proc-Type"]; + string procType = CollectionUtilities.GetValueOrNull(fields, "Proc-Type"); if (procType == "4,ENCRYPTED") { @@ -254,11 +251,12 @@ private object ReadPrivateKey(PemObject pemObject) 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"]; + if (!fields.TryGetValue("DEK-Info", out var dekInfo)) + throw new PemException("missing DEK-info"); + string[] tknz = dekInfo.Split(','); string dekAlgName = tknz[0].Trim(); @@ -381,22 +379,12 @@ private object ReadPrivateKey(PemObject pemObject) // return GetCurveParameters(oid.Id); // } - //private static ECDomainParameters GetCurveParameters( - private static X9ECParameters GetCurveParameters( - string name) + private static X9ECParameters GetCurveParameters(string name) { - // TODO ECGost3410NamedCurves support (returns ECDomainParameters though) - - X9ECParameters ecP = CustomNamedCurves.GetByName(name); - if (ecP == null) - { - ecP = ECNamedCurveTable.GetByName(name); - } - + X9ECParameters ecP = ECKeyPairGenerator.FindECCurveByName(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; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PEMUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PEMUtilities.cs index 9e1e4d2..44d82ee 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PEMUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PEMUtilities.cs @@ -18,8 +18,8 @@ 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(); + Enums.GetArbitraryValue().ToString(); + Enums.GetArbitraryValue().ToString(); } private static void ParseDekAlgName( @@ -33,16 +33,16 @@ private static void ParseDekAlgName( if (dekAlgName == "DES-EDE" || dekAlgName == "DES-EDE3") { - baseAlg = (PemBaseAlg)Enums.GetEnumValue(typeof(PemBaseAlg), dekAlgName); + baseAlg = Enums.GetEnumValue(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; + baseAlg = Enums.GetEnumValue(dekAlgName.Substring(0, pos)); + mode = Enums.GetEnumValue(dekAlgName.Substring(pos + 1)); + return; } } catch (ArgumentException) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PEMWriter.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PEMWriter.cs index f0563e5..d82e5cf 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PEMWriter.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PEMWriter.cs @@ -1,42 +1,23 @@ #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 + : Utilities.IO.Pem.PemWriter { /// The TextWriter object to write the output to. - public PemWriter( - TextWriter writer) + public PemWriter(TextWriter writer) : base(writer) { } - public void WriteObject( - object obj) + public void WriteObject(object obj) { try { @@ -44,8 +25,8 @@ public void WriteObject( } catch (PemGenerationException e) { - if (e.InnerException is IOException) - throw (IOException)e.InnerException; + if (e.InnerException is IOException inner) + throw inner; throw e; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PasswordException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PasswordException.cs index b1ee028..ab58281 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PasswordException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/PasswordException.cs @@ -2,25 +2,31 @@ #pragma warning disable using System; using System.IO; +using System.Runtime.Serialization; 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) + public PasswordException() + : base() + { + } + + public PasswordException(string message) : base(message) { } - public PasswordException( - string message, - Exception exception) - : base(message, exception) + public PasswordException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected PasswordException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/Pkcs8Generator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/Pkcs8Generator.cs index 0d67b85..bff46ae 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/Pkcs8Generator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/openssl/Pkcs8Generator.cs @@ -1,15 +1,9 @@ #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; @@ -91,10 +85,7 @@ public PemObject Generate() // TODO Theoretically, the amount of salt needed depends on the algorithm byte[] salt = new byte[20]; - if (random == null) - { - random = new SecureRandom(); - } + random = CryptoServicesRegistrar.GetSecureRandom(random); random.NextBytes(salt); try diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/AsymmetricKeyEntry.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/AsymmetricKeyEntry.cs index 7dba455..c156d0d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/AsymmetricKeyEntry.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/AsymmetricKeyEntry.cs @@ -1,10 +1,9 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System; -using System.Collections; +using System.Collections.Generic; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs { @@ -13,27 +12,14 @@ public class AsymmetricKeyEntry { private readonly AsymmetricKeyParameter key; - public AsymmetricKeyEntry( - AsymmetricKeyParameter key) - : base(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable()) + public AsymmetricKeyEntry(AsymmetricKeyParameter key) + : base(new Dictionary()) { 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) + public AsymmetricKeyEntry(AsymmetricKeyParameter key, + IDictionary attributes) : base(attributes) { this.key = key; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/PKCS12StoreBuilder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/PKCS12StoreBuilder.cs index cb24ce0..eafbc66 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/PKCS12StoreBuilder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/PKCS12StoreBuilder.cs @@ -12,7 +12,6 @@ public class Pkcs12StoreBuilder private DerObjectIdentifier keyAlgorithm = PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc; private DerObjectIdentifier certAlgorithm = PkcsObjectIdentifiers.PbewithShaAnd40BitRC2Cbc; private DerObjectIdentifier keyPrfAlgorithm = null; - private DerObjectIdentifier certPrfAlgorithm = null; private bool useDerEncoding = false; public Pkcs12StoreBuilder() @@ -21,7 +20,7 @@ public Pkcs12StoreBuilder() public Pkcs12Store Build() { - return new Pkcs12Store(keyAlgorithm, keyPrfAlgorithm, certAlgorithm, certPrfAlgorithm, useDerEncoding); + return new Pkcs12Store(keyAlgorithm, keyPrfAlgorithm, certAlgorithm, useDerEncoding); } public Pkcs12StoreBuilder SetCertAlgorithm(DerObjectIdentifier certAlgorithm) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs10CertificationRequest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs10CertificationRequest.cs index 79b2d9b..5f28426 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs10CertificationRequest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs10CertificationRequest.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; @@ -15,10 +15,8 @@ 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; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs { @@ -50,147 +48,151 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs 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(); + internal static readonly Dictionary m_algorithms = + new Dictionary(StringComparer.OrdinalIgnoreCase); + internal static readonly Dictionary m_exParams = + new Dictionary(StringComparer.OrdinalIgnoreCase); + internal static readonly Dictionary m_keyAlgorithms = + new Dictionary(); + internal static readonly Dictionary m_oids = + new Dictionary(); + internal static readonly HashSet m_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("SHA-1WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha1WithRsaEncryption); - algorithms.Add("SHA1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption); - algorithms.Add("SHA-1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption); - algorithms.Add("SHA224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption); - algorithms.Add("SHA-224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption); - algorithms.Add("SHA224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption); - algorithms.Add("SHA-224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption); - algorithms.Add("SHA256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption); - algorithms.Add("SHA-256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption); - algorithms.Add("SHA256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption); - algorithms.Add("SHA-256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption); - algorithms.Add("SHA384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption); - algorithms.Add("SHA-384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption); - algorithms.Add("SHA384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption); - algorithms.Add("SHA-384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption); - algorithms.Add("SHA512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption); - algorithms.Add("SHA-512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption); - algorithms.Add("SHA512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption); - algorithms.Add("SHA-512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption); - algorithms.Add("SHA512(224)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); - algorithms.Add("SHA-512(224)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); - algorithms.Add("SHA512(224)WITHRSA", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); - algorithms.Add("SHA-512(224)WITHRSA", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); - algorithms.Add("SHA512(256)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); - algorithms.Add("SHA-512(256)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); - algorithms.Add("SHA512(256)WITHRSA", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); - algorithms.Add("SHA-512(256)WITHRSA", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); - 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); + m_algorithms.Add("MD2WITHRSAENCRYPTION", PkcsObjectIdentifiers.MD2WithRsaEncryption); + m_algorithms.Add("MD2WITHRSA", PkcsObjectIdentifiers.MD2WithRsaEncryption); + m_algorithms.Add("MD5WITHRSAENCRYPTION", PkcsObjectIdentifiers.MD5WithRsaEncryption); + m_algorithms.Add("MD5WITHRSA", PkcsObjectIdentifiers.MD5WithRsaEncryption); + m_algorithms.Add("RSAWITHMD5", PkcsObjectIdentifiers.MD5WithRsaEncryption); + m_algorithms.Add("SHA1WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha1WithRsaEncryption); + m_algorithms.Add("SHA-1WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha1WithRsaEncryption); + m_algorithms.Add("SHA1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption); + m_algorithms.Add("SHA-1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption); + m_algorithms.Add("SHA224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption); + m_algorithms.Add("SHA-224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption); + m_algorithms.Add("SHA224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption); + m_algorithms.Add("SHA-224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption); + m_algorithms.Add("SHA256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption); + m_algorithms.Add("SHA-256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption); + m_algorithms.Add("SHA256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption); + m_algorithms.Add("SHA-256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption); + m_algorithms.Add("SHA384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption); + m_algorithms.Add("SHA-384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption); + m_algorithms.Add("SHA384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption); + m_algorithms.Add("SHA-384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption); + m_algorithms.Add("SHA512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption); + m_algorithms.Add("SHA-512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption); + m_algorithms.Add("SHA512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption); + m_algorithms.Add("SHA-512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption); + m_algorithms.Add("SHA512(224)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); + m_algorithms.Add("SHA-512(224)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); + m_algorithms.Add("SHA512(224)WITHRSA", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); + m_algorithms.Add("SHA-512(224)WITHRSA", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); + m_algorithms.Add("SHA512(256)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); + m_algorithms.Add("SHA-512(256)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); + m_algorithms.Add("SHA512(256)WITHRSA", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); + m_algorithms.Add("SHA-512(256)WITHRSA", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); + m_algorithms.Add("SHA1WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss); + m_algorithms.Add("SHA224WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss); + m_algorithms.Add("SHA256WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss); + m_algorithms.Add("SHA384WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss); + m_algorithms.Add("SHA512WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss); + m_algorithms.Add("RSAWITHSHA1", PkcsObjectIdentifiers.Sha1WithRsaEncryption); + m_algorithms.Add("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128); + m_algorithms.Add("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128); + m_algorithms.Add("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160); + m_algorithms.Add("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160); + m_algorithms.Add("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256); + m_algorithms.Add("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256); + m_algorithms.Add("SHA1WITHDSA", X9ObjectIdentifiers.IdDsaWithSha1); + m_algorithms.Add("DSAWITHSHA1", X9ObjectIdentifiers.IdDsaWithSha1); + m_algorithms.Add("SHA224WITHDSA", NistObjectIdentifiers.DsaWithSha224); + m_algorithms.Add("SHA256WITHDSA", NistObjectIdentifiers.DsaWithSha256); + m_algorithms.Add("SHA384WITHDSA", NistObjectIdentifiers.DsaWithSha384); + m_algorithms.Add("SHA512WITHDSA", NistObjectIdentifiers.DsaWithSha512); + m_algorithms.Add("SHA1WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha1); + m_algorithms.Add("SHA224WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha224); + m_algorithms.Add("SHA256WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha256); + m_algorithms.Add("SHA384WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha384); + m_algorithms.Add("SHA512WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha512); + m_algorithms.Add("ECDSAWITHSHA1", X9ObjectIdentifiers.ECDsaWithSha1); + m_algorithms.Add("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94); + m_algorithms.Add("GOST3410WITHGOST3411", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94); + m_algorithms.Add("GOST3411WITHECGOST3410", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001); + m_algorithms.Add("GOST3411WITHECGOST3410-2001", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001); + m_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(PkcsObjectIdentifiers.Sha512_224WithRSAEncryption, "SHA512(224)WITHRSA"); - oids.Add(PkcsObjectIdentifiers.Sha512_256WithRSAEncryption, "SHA512(256)WITHRSA"); - 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"); + m_oids.Add(PkcsObjectIdentifiers.Sha1WithRsaEncryption, "SHA1WITHRSA"); + m_oids.Add(PkcsObjectIdentifiers.Sha224WithRsaEncryption, "SHA224WITHRSA"); + m_oids.Add(PkcsObjectIdentifiers.Sha256WithRsaEncryption, "SHA256WITHRSA"); + m_oids.Add(PkcsObjectIdentifiers.Sha384WithRsaEncryption, "SHA384WITHRSA"); + m_oids.Add(PkcsObjectIdentifiers.Sha512WithRsaEncryption, "SHA512WITHRSA"); + m_oids.Add(PkcsObjectIdentifiers.Sha512_224WithRSAEncryption, "SHA512(224)WITHRSA"); + m_oids.Add(PkcsObjectIdentifiers.Sha512_256WithRSAEncryption, "SHA512(256)WITHRSA"); + m_oids.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94, "GOST3411WITHGOST3410"); + m_oids.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001, "GOST3411WITHECGOST3410"); + + m_oids.Add(PkcsObjectIdentifiers.MD5WithRsaEncryption, "MD5WITHRSA"); + m_oids.Add(PkcsObjectIdentifiers.MD2WithRsaEncryption, "MD2WITHRSA"); + m_oids.Add(X9ObjectIdentifiers.IdDsaWithSha1, "SHA1WITHDSA"); + m_oids.Add(X9ObjectIdentifiers.ECDsaWithSha1, "SHA1WITHECDSA"); + m_oids.Add(X9ObjectIdentifiers.ECDsaWithSha224, "SHA224WITHECDSA"); + m_oids.Add(X9ObjectIdentifiers.ECDsaWithSha256, "SHA256WITHECDSA"); + m_oids.Add(X9ObjectIdentifiers.ECDsaWithSha384, "SHA384WITHECDSA"); + m_oids.Add(X9ObjectIdentifiers.ECDsaWithSha512, "SHA512WITHECDSA"); + m_oids.Add(OiwObjectIdentifiers.MD5WithRsa, "MD5WITHRSA"); + m_oids.Add(OiwObjectIdentifiers.Sha1WithRsa, "SHA1WITHRSA"); + m_oids.Add(OiwObjectIdentifiers.DsaWithSha1, "SHA1WITHDSA"); + m_oids.Add(NistObjectIdentifiers.DsaWithSha224, "SHA224WITHDSA"); + m_oids.Add(NistObjectIdentifiers.DsaWithSha256, "SHA256WITHDSA"); // // key types // - keyAlgorithms.Add(PkcsObjectIdentifiers.RsaEncryption, "RSA"); - keyAlgorithms.Add(X9ObjectIdentifiers.IdDsa, "DSA"); + m_keyAlgorithms.Add(PkcsObjectIdentifiers.RsaEncryption, "RSA"); + m_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(OiwObjectIdentifiers.DsaWithSha1); - noParams.Add(NistObjectIdentifiers.DsaWithSha224); - noParams.Add(NistObjectIdentifiers.DsaWithSha256); + m_noParams.Add(X9ObjectIdentifiers.ECDsaWithSha1); + m_noParams.Add(X9ObjectIdentifiers.ECDsaWithSha224); + m_noParams.Add(X9ObjectIdentifiers.ECDsaWithSha256); + m_noParams.Add(X9ObjectIdentifiers.ECDsaWithSha384); + m_noParams.Add(X9ObjectIdentifiers.ECDsaWithSha512); + m_noParams.Add(X9ObjectIdentifiers.IdDsaWithSha1); + m_noParams.Add(OiwObjectIdentifiers.DsaWithSha1); + m_noParams.Add(NistObjectIdentifiers.DsaWithSha224); + m_noParams.Add(NistObjectIdentifiers.DsaWithSha256); // // RFC 4491 // - noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94); - noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001); + m_noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94); + m_noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001); // // explicit params // AlgorithmIdentifier sha1AlgId = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance); - exParams.Add("SHA1WITHRSAANDMGF1", CreatePssParams(sha1AlgId, 20)); + m_exParams.Add("SHA1WITHRSAANDMGF1", CreatePssParams(sha1AlgId, 20)); AlgorithmIdentifier sha224AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha224, DerNull.Instance); - exParams.Add("SHA224WITHRSAANDMGF1", CreatePssParams(sha224AlgId, 28)); + m_exParams.Add("SHA224WITHRSAANDMGF1", CreatePssParams(sha224AlgId, 28)); AlgorithmIdentifier sha256AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256, DerNull.Instance); - exParams.Add("SHA256WITHRSAANDMGF1", CreatePssParams(sha256AlgId, 32)); + m_exParams.Add("SHA256WITHRSAANDMGF1", CreatePssParams(sha256AlgId, 32)); AlgorithmIdentifier sha384AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha384, DerNull.Instance); - exParams.Add("SHA384WITHRSAANDMGF1", CreatePssParams(sha384AlgId, 48)); + m_exParams.Add("SHA384WITHRSAANDMGF1", CreatePssParams(sha384AlgId, 48)); AlgorithmIdentifier sha512AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha512, DerNull.Instance); - exParams.Add("SHA512WITHRSAANDMGF1", CreatePssParams(sha512AlgId, 64)); + m_exParams.Add("SHA512WITHRSAANDMGF1", CreatePssParams(sha512AlgId, 64)); } private static RsassaPssParameters CreatePssParams( @@ -244,25 +246,6 @@ public Pkcs10CertificationRequest( { } - /// - /// 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. - - 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. /// @@ -300,16 +283,14 @@ private void Init( 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); + IStreamCalculator streamCalculator = signatureFactory.CreateCalculator(); + using (Stream sigStream = streamCalculator.Stream) + { + reqInfo.EncodeTo(sigStream, Der); + } // Generate Signature. - sigBits = new DerBitString(((IBlockResult)streamCalculator.GetResult()).Collect()); + sigBits = new DerBitString(streamCalculator.GetResult().Collect()); } // internal Pkcs10CertificationRequest( @@ -365,13 +346,13 @@ public bool Verify( { byte[] b = reqInfo.GetDerEncoded(); - IStreamCalculator streamCalculator = verifier.CreateCalculator(); - - streamCalculator.Stream.Write(b, 0, b.Length); - - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(streamCalculator.Stream); + IStreamCalculator streamCalculator = verifier.CreateCalculator(); + using (var stream = streamCalculator.Stream) + { + stream.Write(b, 0, b.Length); + } - return ((IVerifier)streamCalculator.GetResult()).IsVerified(sigBits.GetOctets()); + return streamCalculator.GetResult().IsVerified(sigBits.GetOctets()); } catch (Exception e) { @@ -406,9 +387,9 @@ private void SetSignatureParameters( // throw new SignatureException("IOException decoding parameters: " + e.Message); // } - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(signature.AlgorithmName, "MGF1")) + if (Org.BouncyCastle.Utilities.Platform.EndsWith(signature.AlgorithmName, "MGF1")) { - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("signature algorithm with MGF1"); + throw new NotImplementedException("signature algorithm with MGF1"); // try // { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs10CertificationRequestDelaySigned.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs10CertificationRequestDelaySigned.cs index b4ec7c6..af6e8e6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs10CertificationRequestDelaySigned.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs10CertificationRequestDelaySigned.cs @@ -1,21 +1,12 @@ #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; @@ -105,27 +96,26 @@ public Pkcs10CertificationRequestDelaySigned( 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]; + + DerObjectIdentifier sigOid = CollectionUtilities.GetValueOrNull(m_algorithms, signatureAlgorithm); if (sigOid == null) { try { - sigOid = new DerObjectIdentifier(algorithmName); + sigOid = new DerObjectIdentifier(signatureAlgorithm); } catch (Exception e) { throw new ArgumentException("Unknown signature type requested", e); } } - if (noParams.Contains(sigOid)) + if (m_noParams.Contains(sigOid)) { this.sigAlgId = new AlgorithmIdentifier(sigOid); } - else if (exParams.Contains(algorithmName)) + else if (m_exParams.TryGetValue(signatureAlgorithm, out var explicitParameters)) { - this.sigAlgId = new AlgorithmIdentifier(sigOid, (Asn1Encodable) exParams[algorithmName]); + this.sigAlgId = new AlgorithmIdentifier(sigOid, explicitParameters); } else { @@ -134,6 +124,7 @@ public Pkcs10CertificationRequestDelaySigned( SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey); this.reqInfo = new CertificationRequestInfo(subject, pubInfo, attributes); } + public byte[] GetDataToSign() { return reqInfo.GetDerEncoded(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs12Entry.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs12Entry.cs index c07ad6e..50b3e55 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs12Entry.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs12Entry.cs @@ -1,7 +1,6 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; @@ -10,57 +9,21 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs { public abstract class Pkcs12Entry { - private readonly IDictionary attributes; + private readonly IDictionary m_attributes; - protected internal Pkcs12Entry( - 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"); - } - } - - - public Asn1Encodable GetBagAttribute( - DerObjectIdentifier oid) - { - return (Asn1Encodable)this.attributes[oid.Id]; - } - - - public Asn1Encodable GetBagAttribute( - string oid) - { - return (Asn1Encodable)this.attributes[oid]; - } - - - public IEnumerator GetBagAttributeKeys() - { - return this.attributes.Keys.GetEnumerator(); + m_attributes = attributes; } - public Asn1Encodable this[ - DerObjectIdentifier oid] - { - get { return (Asn1Encodable) this.attributes[oid.Id]; } - } - - public Asn1Encodable this[ - string oid] + public Asn1Encodable this[DerObjectIdentifier oid] { - get { return (Asn1Encodable) this.attributes[oid]; } + get { return CollectionUtilities.GetValueOrNull(m_attributes, oid); } } - public IEnumerable BagAttributeKeys + public IEnumerable BagAttributeKeys { - get { return new EnumerableProxy(this.attributes.Keys); } + get { return CollectionUtilities.Proxy(m_attributes.Keys); } } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs12Store.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs12Store.cs index 0909e8b..979e176 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs12Store.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs12Store.cs @@ -1,15 +1,14 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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.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; @@ -23,24 +22,26 @@ public class Pkcs12Store { public const string IgnoreUselessPasswordProperty = "BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs12.IgnoreUselessPassword"; - 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 keyPrfAlgorithm; - private readonly DerObjectIdentifier certAlgorithm; - private readonly DerObjectIdentifier certPrfAlgorithm; - private readonly bool useDerEncoding; + private readonly Dictionary m_keys = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary m_localIds = new Dictionary(); + private readonly Dictionary m_certs = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary m_chainCerts = + new Dictionary(); + private readonly Dictionary m_keyCerts = + new Dictionary(); + private readonly DerObjectIdentifier keyAlgorithm; + private readonly DerObjectIdentifier keyPrfAlgorithm; + 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) + private static SubjectKeyIdentifier CreateSubjectKeyID(AsymmetricKeyParameter pubKey) { return new SubjectKeyIdentifier( SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKey)); @@ -87,55 +88,20 @@ public override bool Equals( } } - internal Pkcs12Store( - DerObjectIdentifier keyAlgorithm, - DerObjectIdentifier certAlgorithm, - bool useDerEncoding) - { - this.keyAlgorithm = keyAlgorithm; - this.keyPrfAlgorithm = null; - this.certAlgorithm = certAlgorithm; - this.certPrfAlgorithm = null; - this.useDerEncoding = useDerEncoding; - } - - internal Pkcs12Store( - DerObjectIdentifier keyAlgorithm, - DerObjectIdentifier keyPrfAlgorithm, - DerObjectIdentifier certAlgorithm, - DerObjectIdentifier certPrfAlgorithm, - bool useDerEncoding) + internal Pkcs12Store(DerObjectIdentifier keyAlgorithm, DerObjectIdentifier keyPrfAlgorithm, + DerObjectIdentifier certAlgorithm, bool useDerEncoding) { this.keyAlgorithm = keyAlgorithm; this.keyPrfAlgorithm = keyPrfAlgorithm; this.certAlgorithm = certAlgorithm; - this.certPrfAlgorithm = certPrfAlgorithm; this.useDerEncoding = useDerEncoding; } - // TODO Consider making obsolete - - public Pkcs12Store() - : this(PkcsObjectIdentifiers.PbeWithShaAnd3KeyTripleDesCbc, - PkcsObjectIdentifiers.PbewithShaAnd40BitRC2Cbc, false) - { - } - - // TODO Consider making obsolete - - 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(); + var attributes = new Dictionary(); AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(privKey, attributes); string alias = null; @@ -156,22 +122,22 @@ protected virtual void LoadKeyBag(PrivateKeyInfo privKeyInfo, Asn1Set bagAttribu // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error - if (attributes.Contains(aOid.Id)) + if (attributes.TryGetValue(aOid, out var attributeValue)) { // OK, but the value has to be the same - if (!attributes[aOid.Id].Equals(attr)) + if (!attributeValue.Equals(attr)) throw new IOException("attempt to add existing attribute with different value"); } else { - attributes.Add(aOid.Id, attr); + attributes[aOid] = attr; } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) { alias = ((DerBmpString)attr).GetString(); // TODO Do these in a separate loop, just collect aliases here - keys[alias] = keyEntry; + m_keys[alias] = keyEntry; } else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) { @@ -187,12 +153,12 @@ protected virtual void LoadKeyBag(PrivateKeyInfo privKeyInfo, Asn1Set bagAttribu if (alias == null) { - keys[name] = keyEntry; + m_keys[name] = keyEntry; } else { // TODO There may have been more than one alias - localIds[alias] = name; + m_localIds[alias] = name; } } else @@ -213,9 +179,7 @@ protected virtual void LoadPkcs8ShroudedKeyBag(EncryptedPrivateKeyInfo encPrivKe } } - public void Load( - Stream input, - char[] password) + public void Load(Stream input, char[] password) { if (input == null) throw new ArgumentNullException("input"); @@ -256,8 +220,8 @@ public void Load( } else if (password != null) { - string ignoreProperty = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetEnvironmentVariable(IgnoreUselessPasswordProperty); - bool ignore = ignoreProperty != null && BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase("true", ignoreProperty); + string ignoreProperty = Org.BouncyCastle.Utilities.Platform.GetEnvironmentVariable(IgnoreUselessPasswordProperty); + bool ignore = ignoreProperty != null && Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase("true", ignoreProperty); if (!ignore) { @@ -265,11 +229,11 @@ public void Load( } } - keys.Clear(); - localIds.Clear(); + m_keys.Clear(); + m_localIds.Clear(); unmarkedKeyEntry = null; - IList certBags = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var certBags = new List(); if (info.ContentType.Equals(PkcsObjectIdentifiers.Data)) { @@ -330,9 +294,9 @@ public void Load( } } - certs.Clear(); - chainCerts.Clear(); - keyCerts.Clear(); + m_certs.Clear(); + m_chainCerts.Clear(); + m_keyCerts.Clear(); foreach (SafeBag b in certBags) { @@ -343,7 +307,7 @@ public void Load( // // set the attributes // - IDictionary attributes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + var attributes = new Dictionary(); Asn1OctetString localId = null; string alias = null; @@ -361,27 +325,25 @@ public void Load( // TODO We might want to "merge" attribute sets with // the same OID - currently, differing values give an error - if (attributes.Contains(aOid.Id)) + if (attributes.TryGetValue(aOid, out var attributeValue)) { // we've found more than one - one might be incorrect - if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID)) + if (PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Equals(aOid)) { - String id = Hex.ToHexString(Asn1OctetString.GetInstance(attr).GetOctets()); - if (!(keys[id] != null || localIds[id] != null)) - { + string id = Hex.ToHexString(Asn1OctetString.GetInstance(attr).GetOctets()); + if (!m_keys.ContainsKey(id) && !m_localIds.ContainsKey(id)) continue; // ignore this one - it's not valid - } } // OK, but the value has to be the same - if (!attributes[aOid.Id].Equals(attr)) + if (!attributeValue.Equals(attr)) { throw new IOException("attempt to add existing attribute with different value"); } } else { - attributes.Add(aOid.Id, attr); + attributes[aOid] = attr; } if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName)) @@ -399,20 +361,20 @@ public void Load( CertId certId = new CertId(cert.GetPublicKey()); X509CertificateEntry certEntry = new X509CertificateEntry(cert, attributes); - chainCerts[certId] = certEntry; + m_chainCerts[certId] = certEntry; if (unmarkedKeyEntry != null) { - if (keyCerts.Count == 0) + if (m_keyCerts.Count == 0) { string name = Hex.ToHexString(certId.Id); - keyCerts[name] = certEntry; - keys[name] = unmarkedKeyEntry; + m_keyCerts[name] = certEntry; + m_keys[name] = unmarkedKeyEntry; } else { - keys["unmarked"] = unmarkedKeyEntry; + m_keys["unmarked"] = unmarkedKeyEntry; } } else @@ -421,309 +383,236 @@ public void Load( { string name = Hex.ToHexString(localId.GetOctets()); - keyCerts[name] = certEntry; + m_keyCerts[name] = certEntry; } if (alias != null) { // TODO There may have been more than one alias - certs[alias] = certEntry; + m_certs[alias] = certEntry; } } } } - public AsymmetricKeyEntry GetKey( - string alias) + public AsymmetricKeyEntry GetKey(string alias) { if (alias == null) - throw new ArgumentNullException("alias"); + throw new ArgumentNullException(nameof(alias)); - return (AsymmetricKeyEntry)keys[alias]; + return CollectionUtilities.GetValueOrNull(m_keys, alias); } - public bool IsCertificateEntry( - string alias) + public bool IsCertificateEntry(string alias) { if (alias == null) - throw new ArgumentNullException("alias"); + throw new ArgumentNullException(nameof(alias)); - return (certs[alias] != null && keys[alias] == null); + return m_certs.ContainsKey(alias) && !m_keys.ContainsKey(alias); } - public bool IsKeyEntry( - string alias) + public bool IsKeyEntry(string alias) { if (alias == null) - throw new ArgumentNullException("alias"); + throw new ArgumentNullException(nameof(alias)); - return (keys[alias] != null); + return m_keys.ContainsKey(alias); } - private IDictionary GetAliasesTable() + public IEnumerable Aliases { - IDictionary tab = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - - foreach (string key in certs.Keys) + get { - tab[key] = "cert"; - } - - foreach (string a in keys.Keys) - { - if (tab[a] == null) - { - tab[a] = "key"; - } + var aliases = new HashSet(m_certs.Keys); + aliases.UnionWith(m_keys.Keys); + return CollectionUtilities.Proxy(aliases); } - - return tab; } - public IEnumerable Aliases + public bool ContainsAlias(string alias) { - get { return new EnumerableProxy(GetAliasesTable().Keys); } - } + if (alias == null) + throw new ArgumentNullException(nameof(alias)); - public bool ContainsAlias( - string alias) - { - return certs[alias] != null || keys[alias] != null; + return m_certs.ContainsKey(alias) || m_keys.ContainsKey(alias); } /** * simply return the cert entry for the private key */ - public X509CertificateEntry GetCertificate( - string alias) + public X509CertificateEntry GetCertificate(string alias) { if (alias == null) - throw new ArgumentNullException("alias"); + throw new ArgumentNullException(nameof(alias)); - X509CertificateEntry c = (X509CertificateEntry) certs[alias]; + if (m_certs.TryGetValue(alias, out var cert)) + return cert; - // - // look up the key table - and try the local key id - // - if (c == null) + var keyCertKey = alias; + if (m_localIds.TryGetValue(alias, out var localId)) { - string id = (string)localIds[alias]; - if (id != null) - { - c = (X509CertificateEntry)keyCerts[id]; - } - else - { - c = (X509CertificateEntry)keyCerts[alias]; - } + keyCertKey = localId; } - return c; + return CollectionUtilities.GetValueOrNull(m_keyCerts, keyCertKey); } - public string GetCertificateAlias( - X509Certificate cert) + public string GetCertificateAlias(X509Certificate cert) { if (cert == null) - throw new ArgumentNullException("cert"); + throw new ArgumentNullException(nameof(cert)); - foreach (DictionaryEntry entry in certs) + foreach (var entry in m_certs) { - X509CertificateEntry entryValue = (X509CertificateEntry) entry.Value; - if (entryValue.Certificate.Equals(cert)) - { - return (string) entry.Key; - } + if (entry.Value.Certificate.Equals(cert)) + return entry.Key; } - foreach (DictionaryEntry entry in keyCerts) + foreach (var entry in m_keyCerts) { - X509CertificateEntry entryValue = (X509CertificateEntry) entry.Value; - if (entryValue.Certificate.Equals(cert)) - { - return (string) entry.Key; - } + if (entry.Value.Certificate.Equals(cert)) + return entry.Key; } return null; } - public X509CertificateEntry[] GetCertificateChain( - string alias) + public X509CertificateEntry[] GetCertificateChain(string alias) { if (alias == null) - throw new ArgumentNullException("alias"); + throw new ArgumentNullException(nameof(alias)); if (!IsKeyEntry(alias)) - { return null; - } X509CertificateEntry c = GetCertificate(alias); + if (c == null) + return null; - if (c != null) + var cs = new List(); + + while (c != null) { - IList cs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + X509Certificate x509c = c.Certificate; + X509CertificateEntry nextC = null; - while (c != null) + Asn1OctetString akiValue = x509c.GetExtensionValue(X509Extensions.AuthorityKeyIdentifier); + if (akiValue != null) { - X509Certificate x509c = c.Certificate; - X509CertificateEntry nextC = null; + AuthorityKeyIdentifier aki = AuthorityKeyIdentifier.GetInstance(akiValue.GetOctets()); - Asn1OctetString akiValue = x509c.GetExtensionValue(X509Extensions.AuthorityKeyIdentifier); - if (akiValue != null) + byte[] keyID = aki.GetKeyIdentifier(); + if (keyID != null) { - AuthorityKeyIdentifier aki = AuthorityKeyIdentifier.GetInstance(akiValue.GetOctets()); - - byte[] keyID = aki.GetKeyIdentifier(); - if (keyID != null) - { - nextC = (X509CertificateEntry)chainCerts[new CertId(keyID)]; - } + nextC = CollectionUtilities.GetValueOrNull(m_chainCerts, new CertId(keyID)); } + } - if (nextC == null) - { - // - // no authority key id, try the Issuer DN - // - X509Name i = x509c.IssuerDN; - X509Name s = x509c.SubjectDN; + if (nextC == null) + { + // + // no authority key id, try the Issuer DN + // + X509Name i = x509c.IssuerDN; + X509Name s = x509c.SubjectDN; - if (!i.Equivalent(s)) + if (!i.Equivalent(s)) + { + foreach (var entry in m_chainCerts) { - foreach (CertId certId in chainCerts.Keys) - { - X509CertificateEntry x509CertEntry = (X509CertificateEntry) chainCerts[certId]; + X509Certificate cert = entry.Value.Certificate; - X509Certificate crt = x509CertEntry.Certificate; + if (cert.SubjectDN.Equivalent(i)) + { + try + { + x509c.Verify(cert.GetPublicKey()); - X509Name sub = crt.SubjectDN; - if (sub.Equivalent(i)) + nextC = entry.Value; + break; + } + catch (InvalidKeyException) { - try - { - x509c.Verify(crt.GetPublicKey()); - - nextC = x509CertEntry; - break; - } - catch (InvalidKeyException) - { - // TODO What if it doesn't verify? - } + // 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) + cs.Add(c); + if (nextC != c) // self signed - end of the chain { - result[i] = (X509CertificateEntry)cs[i]; + c = nextC; + } + else + { + c = null; } - return result; } - return null; + return cs.ToArray(); } - public void SetCertificateEntry( - string alias, - X509CertificateEntry certEntry) + public void SetCertificateEntry(string alias, X509CertificateEntry certEntry) { if (alias == null) - throw new ArgumentNullException("alias"); + throw new ArgumentNullException(nameof(alias)); if (certEntry == null) - throw new ArgumentNullException("certEntry"); - if (keys[alias] != null) + throw new ArgumentNullException(nameof(certEntry)); + if (m_keys.ContainsKey(alias)) throw new ArgumentException("There is a key entry with the name " + alias + "."); - certs[alias] = certEntry; - chainCerts[new CertId(certEntry.Certificate.GetPublicKey())] = certEntry; + m_certs[alias] = certEntry; + m_chainCerts[new CertId(certEntry.Certificate.GetPublicKey())] = certEntry; } - public void SetKeyEntry( - string alias, - AsymmetricKeyEntry keyEntry, - X509CertificateEntry[] chain) + public void SetKeyEntry(string alias, AsymmetricKeyEntry keyEntry, X509CertificateEntry[] chain) { if (alias == null) - throw new ArgumentNullException("alias"); + throw new ArgumentNullException(nameof(alias)); if (keyEntry == null) - throw new ArgumentNullException("keyEntry"); - if (keyEntry.Key.IsPrivate && (chain == null)) + throw new ArgumentNullException(nameof(keyEntry)); + if (keyEntry.Key.IsPrivate && chain == null) throw new ArgumentException("No certificate chain for private key"); - if (keys[alias] != null) + if (m_keys.ContainsKey(alias)) { DeleteEntry(alias); } - keys[alias] = keyEntry; - certs[alias] = chain[0]; + m_keys[alias] = keyEntry; + m_certs[alias] = chain[0]; for (int i = 0; i != chain.Length; i++) { - chainCerts[new CertId(chain[i].Certificate.GetPublicKey())] = chain[i]; + m_chainCerts[new CertId(chain[i].Certificate.GetPublicKey())] = chain[i]; } } - public void DeleteEntry( - string alias) + 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]; + throw new ArgumentNullException(nameof(alias)); - if (c != null) + if (CollectionUtilities.Remove(m_certs, alias, out var cert)) { - certs.Remove(alias); - chainCerts.Remove(new CertId(c.Certificate.GetPublicKey())); + m_chainCerts.Remove(new CertId(cert.Certificate.GetPublicKey())); } - if (k != null) + if (m_keys.Remove(alias)) { - string id = (string)localIds[alias]; - if (id != null) - { - localIds.Remove(alias); - c = (X509CertificateEntry)keyCerts[id]; - } - if (c != null) + if (CollectionUtilities.Remove(m_localIds, alias, out var id)) { - keyCerts.Remove(id); - chainCerts.Remove(new CertId(c.Certificate.GetPublicKey())); + if (CollectionUtilities.Remove(m_keyCerts, id, out var keyCert)) + { + m_chainCerts.Remove(new CertId(keyCert.Certificate.GetPublicKey())); + } } } - - if (c == null && k == null) - { - throw new ArgumentException("no such entry as " + alias); - } } - public bool IsEntryOfType( - string alias, - Type entryType) + public bool IsEntryOfType(string alias, Type entryType) { if (entryType == typeof(X509CertificateEntry)) return IsCertificateEntry(alias); @@ -734,39 +623,43 @@ public bool IsEntryOfType( return false; } - - public int Size() - { - return Count; - } - public int Count { - // TODO Seems a little inefficient - get { return GetAliasesTable().Count; } + get + { + int count = m_certs.Count; + + foreach (var key in m_keys.Keys) + { + if (!m_certs.ContainsKey(key)) + { + ++count; + } + } + + return count; + } } - public void Save( - Stream stream, - char[] password, - SecureRandom random) + public void Save(Stream stream, char[] password, SecureRandom random) { if (stream == null) - throw new ArgumentNullException("stream"); + throw new ArgumentNullException(nameof(stream)); if (random == null) - throw new ArgumentNullException("random"); + throw new ArgumentNullException(nameof(random)); // // handle the keys // Asn1EncodableVector keyBags = new Asn1EncodableVector(); - foreach (string name in keys.Keys) + foreach (var keyEntry in m_keys) { + var name = keyEntry.Key; + var privKey = keyEntry.Value; + byte[] kSalt = new byte[SaltSize]; random.NextBytes(kSalt); - AsymmetricKeyEntry privKey = (AsymmetricKeyEntry)keys[name]; - DerObjectIdentifier bagOid; Asn1Encodable bagData; @@ -780,30 +673,25 @@ public void Save( bagOid = PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag; if (keyPrfAlgorithm != null) { - bagData = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo( - keyAlgorithm, keyPrfAlgorithm, password, kSalt, MinIterations, random, privKey.Key); + bagData = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(keyAlgorithm, + keyPrfAlgorithm, password, kSalt, MinIterations, random, privKey.Key); } else { - bagData = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo( - keyAlgorithm, password, kSalt, MinIterations, privKey.Key); + bagData = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(keyAlgorithm, password, + kSalt, MinIterations, privKey.Key); } } Asn1EncodableVector kName = new Asn1EncodableVector(); - foreach (string oid in privKey.BagAttributeKeys) + foreach (var 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))); + if (!PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Equals(oid)) + { + kName.Add(new DerSequence(oid, new DerSet(privKey[oid]))); + } } // @@ -849,9 +737,9 @@ public void Save( Asn1EncodableVector certBags = new Asn1EncodableVector(); Pkcs12PbeParams cParams = new Pkcs12PbeParams(cSalt, MinIterations); AlgorithmIdentifier cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.ToAsn1Object()); - ISet doneCerts = new HashSet(); + var doneCerts = new HashSet(); - foreach (string name in keys.Keys) + foreach (string name in m_keys.Keys) { X509CertificateEntry certEntry = GetCertificate(name); CertBag cBag = new CertBag( @@ -860,18 +748,13 @@ public void Save( Asn1EncodableVector fName = new Asn1EncodableVector(); - foreach (string oid in certEntry.BagAttributeKeys) + foreach (var 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))); + if (!PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Equals(oid)) + { + fName.Add(new DerSequence(oid, new DerSet(certEntry[oid]))); + } } // @@ -905,11 +788,12 @@ public void Save( doneCerts.Add(certEntry.Certificate); } - foreach (string certId in certs.Keys) + foreach (var certEntry in m_certs) { - X509CertificateEntry cert = (X509CertificateEntry)certs[certId]; + var certId = certEntry.Key; + var cert = certEntry.Value; - if (keys[certId] != null) + if (m_keys.ContainsKey(certId)) continue; CertBag cBag = new CertBag( @@ -918,25 +802,20 @@ public void Save( Asn1EncodableVector fName = new Asn1EncodableVector(); - foreach (string oid in cert.BagAttributeKeys) + foreach (var 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)) + if (PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Equals(oid)) 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))); + if (!PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Equals(oid)) + { + fName.Add(new DerSequence(oid, new DerSet(cert[oid]))); + } } // @@ -951,14 +830,44 @@ public void Save( new DerSet(new DerBmpString(certId)))); } + // the Oracle PKCS12 parser looks for a trusted key usage for named certificates as well + if (cert[MiscObjectIdentifiers.id_oracle_pkcs12_trusted_key_usage] == null) + { + Asn1OctetString ext = cert.Certificate.GetExtensionValue(X509Extensions.ExtendedKeyUsage); + + if (ext != null) + { + ExtendedKeyUsage usage = ExtendedKeyUsage.GetInstance(ext.GetOctets()); + Asn1EncodableVector v = new Asn1EncodableVector(); + IList usages = usage.GetAllUsages(); + for (int i = 0; i != usages.Count; i++) + { + v.Add(usages[i]); + } + + fName.Add( + new DerSequence( + MiscObjectIdentifiers.id_oracle_pkcs12_trusted_key_usage, + new DerSet(v))); + } + else + { + fName.Add( + new DerSequence( + MiscObjectIdentifiers.id_oracle_pkcs12_trusted_key_usage, + new DerSet(KeyPurposeID.AnyExtendedKeyUsage))); + } + } + certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName))); doneCerts.Add(cert.Certificate); } - foreach (CertId certId in chainCerts.Keys) + foreach (var chainCertEntry in m_chainCerts) { - X509CertificateEntry cert = (X509CertificateEntry)chainCerts[certId]; + var certId = chainCertEntry.Key; + var cert = chainCertEntry.Value; if (doneCerts.Contains(cert.Certificate)) continue; @@ -969,19 +878,16 @@ public void Save( Asn1EncodableVector fName = new Asn1EncodableVector(); - foreach (string oid in cert.BagAttributeKeys) + foreach (var 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)) + if (PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Equals(oid)) continue; - fName.Add( - new DerSequence( - new DerObjectIdentifier(oid), - new DerSet(cert[oid]))); + fName.Add(new DerSequence(oid, new DerSet(cert[oid]))); } certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName))); @@ -1082,81 +988,6 @@ private static byte[] CryptPbeData( 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; } - } - - public int Count - { - get { return orig.Count; } - } - } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs8EncryptedPrivateKeyInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs8EncryptedPrivateKeyInfo.cs index 27e3660..9f604cf 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs8EncryptedPrivateKeyInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs8EncryptedPrivateKeyInfo.cs @@ -93,9 +93,11 @@ public PrivateKeyInfo DecryptPrivateKeyInfo(IDecryptorBuilderProvider inputDecry ICipher encIn = decryptorBuilder.BuildCipher(new MemoryInputStream(encryptedPrivateKeyInfo.GetEncryptedData())); - Stream strm = encIn.Stream; - byte[] data = Streams.ReadAll(encIn.Stream); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(strm); + byte[] data; + using (var strm = encIn.Stream) + { + data = Streams.ReadAll(encIn.Stream); + } return PrivateKeyInfo.GetInstance(data); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs8EncryptedPrivateKeyInfoBuilder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs8EncryptedPrivateKeyInfoBuilder.cs index 0b424f8..0636f52 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs8EncryptedPrivateKeyInfoBuilder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/Pkcs8EncryptedPrivateKeyInfoBuilder.cs @@ -38,11 +38,13 @@ public Pkcs8EncryptedPrivateKeyInfo Build( ICipher cOut = encryptor.BuildCipher(bOut); byte[] keyData = privateKeyInfo.GetEncoded(); - Stream str = cOut.Stream; - str.Write(keyData, 0, keyData.Length); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(str); + using (var str = cOut.Stream) + { + str.Write(keyData, 0, keyData.Length); + } - return new Pkcs8EncryptedPrivateKeyInfo(new EncryptedPrivateKeyInfo((AlgorithmIdentifier)encryptor.AlgorithmDetails, bOut.ToArray())); + return new Pkcs8EncryptedPrivateKeyInfo( + new EncryptedPrivateKeyInfo((AlgorithmIdentifier)encryptor.AlgorithmDetails, bOut.ToArray())); } catch (IOException) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/PkcsException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/PkcsException.cs index 2a0931b..364deb9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/PkcsException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/PkcsException.cs @@ -1,25 +1,35 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs { - /// - /// Base exception for PKCS related issues. - /// - public class PkcsException + /// Base exception for PKCS related issues. + [Serializable] + public class PkcsException : Exception { - public PkcsException(string message) - : base(message) - { - } + public PkcsException() + : base() + { + } - public PkcsException(string message, Exception underlying) - : base(message, underlying) - { - } - } + public PkcsException(string message) + : base(message) + { + } + + public PkcsException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected PkcsException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/PkcsIOException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/PkcsIOException.cs index 16ecbe7..d1f1bd1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/PkcsIOException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/PkcsIOException.cs @@ -2,22 +2,35 @@ #pragma warning disable using System; using System.IO; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs { - /// - /// Base exception for parsing related issues in the PKCS namespace. - /// - public class PkcsIOException: IOException + /// Base exception for parsing related issues in the PKCS namespace. + [Serializable] + public class PkcsIOException + : IOException { - public PkcsIOException(String message) : base(message) - { - } + public PkcsIOException() + : base() + { + } - public PkcsIOException(String message, Exception underlying) : base(message, underlying) - { - } - } + public PkcsIOException(string message) + : base(message) + { + } + + public PkcsIOException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected PkcsIOException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/PrivateKeyInfoFactory.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/PrivateKeyInfoFactory.cs index 9e87b08..df51ab7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/PrivateKeyInfoFactory.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/PrivateKeyInfoFactory.cs @@ -20,12 +20,8 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs { - public sealed class PrivateKeyInfoFactory + public static class PrivateKeyInfoFactory { - private PrivateKeyInfoFactory() - { - } - public static PrivateKeyInfo CreatePrivateKeyInfo( AsymmetricKeyParameter privateKey) { @@ -157,7 +153,7 @@ public static PrivateKeyInfo CreatePrivateKeyInfo(AsymmetricKeyParameter private if (priv.AlgorithmName == "ECGOST3410") { if (priv.PublicKeyParamSet == null) - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); + throw new NotImplementedException("Not a CryptoPro parameter set"); Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( priv.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet); @@ -172,7 +168,8 @@ public static PrivateKeyInfo CreatePrivateKeyInfo(AsymmetricKeyParameter private X962Parameters x962; if (priv.PublicKeyParamSet == null) { - X9ECParameters ecP = new X9ECParameters(dp.Curve, dp.G, dp.N, dp.H, dp.GetSeed()); + X9ECParameters ecP = new X9ECParameters(dp.Curve, new X9ECPoint(dp.G, false), dp.N, dp.H, + dp.GetSeed()); x962 = new X962Parameters(ecP); } else @@ -193,7 +190,7 @@ public static PrivateKeyInfo CreatePrivateKeyInfo(AsymmetricKeyParameter private Gost3410PrivateKeyParameters _key = (Gost3410PrivateKeyParameters)privateKey; if (_key.PublicKeyParamSet == null) - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); + throw new NotImplementedException("Not a CryptoPro parameter set"); byte[] keyEnc = _key.X.ToByteArrayUnsigned(); byte[] keyBytes = new byte[keyEnc.Length]; @@ -245,7 +242,7 @@ public static PrivateKeyInfo CreatePrivateKeyInfo(AsymmetricKeyParameter private new DerOctetString(key.GetEncoded()), attributes, key.GeneratePublicKey().GetEncoded()); } - throw new ArgumentException("Class provided is not convertible: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(privateKey)); + throw new ArgumentException("Class provided is not convertible: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(privateKey)); } public static PrivateKeyInfo CreatePrivateKeyInfo( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/X509CertificateEntry.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/X509CertificateEntry.cs index f9b71e7..e1d2f99 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/X509CertificateEntry.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkcs/X509CertificateEntry.cs @@ -1,9 +1,8 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System; -using System.Collections; +using System.Collections.Generic; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.X509; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs @@ -13,27 +12,13 @@ public class X509CertificateEntry { private readonly X509Certificate cert; - public X509CertificateEntry( - X509Certificate cert) - : base(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable()) + public X509CertificateEntry(X509Certificate cert) + : base(new Dictionary()) { 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) + public X509CertificateEntry(X509Certificate cert, IDictionary attributes) : base(attributes) { this.cert = cert; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/CertStatus.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/CertStatus.cs index 13c88d4..4bfdf8a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/CertStatus.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/CertStatus.cs @@ -2,8 +2,6 @@ #pragma warning disable using System; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date; - namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix { public class CertStatus @@ -14,12 +12,12 @@ public class CertStatus private int status = Unrevoked; - DateTimeObject revocationDate = null; + DateTime? revocationDate = null; /// /// Returns the revocationDate. /// - public DateTimeObject RevocationDate + public DateTime? RevocationDate { get { return revocationDate; } set { this.revocationDate = value; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixAttrCertChecker.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixAttrCertChecker.cs index 71cc3cb..ccbf3d6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixAttrCertChecker.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixAttrCertChecker.cs @@ -1,9 +1,9 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.X509; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix @@ -29,7 +29,7 @@ public abstract class PkixAttrCertChecker * PkixAttrCertChecker, or null if no * extensions are supported */ - public abstract ISet GetSupportedExtensions(); + public abstract ISet GetSupportedExtensions(); /** * Performs checks on the specified attribute certificate. Every handled @@ -46,8 +46,8 @@ public abstract class PkixAttrCertChecker * @throws CertPathValidatorException if the specified attribute certificate * does not pass the check. */ - public abstract void Check(IX509AttributeCertificate attrCert, PkixCertPath certPath, - PkixCertPath holderCertPath, ICollection unresolvedCritExts); + public abstract void Check(X509V2AttributeCertificate attrCert, PkixCertPath certPath, + PkixCertPath holderCertPath, ICollection unresolvedCritExts); /** * Returns a clone of this object. diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixAttrCertPathBuilder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixAttrCertPathBuilder.cs index c657ddd..b0dc53b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixAttrCertPathBuilder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixAttrCertPathBuilder.cs @@ -1,11 +1,10 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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; @@ -20,13 +19,11 @@ public class PkixAttrCertPathBuilder * @param params PKIXBuilderParameters object containing all information to * build the CertPath */ - public virtual PkixCertPathBuilderResult Build( - PkixBuilderParameters pkixParams) + public virtual PkixCertPathBuilderResult Build(PkixBuilderParameters pkixParams) { // search target certificates - IX509Selector certSelect = pkixParams.GetTargetConstraints(); - if (!(certSelect is X509AttrCertStoreSelector)) + if (!(pkixParams.GetTargetConstraintsAttrCert() is X509AttrCertStoreSelector attrCertSelector)) { throw new PkixCertPathBuilderException( "TargetConstraints must be an instance of " @@ -35,11 +32,10 @@ public virtual PkixCertPathBuilderResult Build( + typeof(PkixAttrCertPathBuilder).FullName + " class."); } - ICollection targets; + HashSet targets; try { - targets = PkixCertPathValidatorUtilities.FindCertificates( - (X509AttrCertStoreSelector)certSelect, pkixParams.GetStores()); + targets = FindAttributeCertificates(attrCertSelector, pkixParams.GetStoresAttrCert()); } catch (Exception e) { @@ -47,26 +43,24 @@ public virtual PkixCertPathBuilderResult Build( } if (targets.Count == 0) - { - throw new PkixCertPathBuilderException( - "No attribute certificate found matching targetConstraints."); - } + throw new PkixCertPathBuilderException("No attribute certificate found matching targetConstraints."); PkixCertPathBuilderResult result = null; // check all potential target certificates - foreach (IX509AttributeCertificate cert in targets) + foreach (var target in targets) { - X509CertStoreSelector selector = new X509CertStoreSelector(); - X509Name[] principals = cert.Issuer.GetPrincipals(); - ISet issuers = new HashSet(); + X509CertStoreSelector certSelector = new X509CertStoreSelector(); + X509Name[] principals = target.Issuer.GetPrincipals(); + var issuers = new HashSet(); for (int i = 0; i < principals.Length; i++) { + // TODO Replace loop with a single multiprincipal selector (or don't even use selector) try { - selector.Subject = principals[i]; + certSelector.Subject = principals[i]; - issuers.AddAll(PkixCertPathValidatorUtilities.FindCertificates(selector, pkixParams.GetStores())); + CollectionUtilities.CollectMatches(issuers, certSelector, pkixParams.GetStoresCert()); } catch (Exception e) { @@ -76,14 +70,14 @@ public virtual PkixCertPathBuilderResult Build( } } - if (issuers.IsEmpty) + if (issuers.Count < 1) throw new PkixCertPathBuilderException("Public key certificate for attribute certificate cannot be found."); - IList certPathList = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var certPathList = new List(); foreach (X509Certificate issuer in issuers) { - result = Build(cert, issuer, pkixParams, certPathList); + result = Build(target, issuer, pkixParams, certPathList); if (result != null) break; @@ -94,17 +88,11 @@ public virtual PkixCertPathBuilderResult Build( } if (result == null && certPathException != null) - { - throw new PkixCertPathBuilderException( - "Possible certificate chain could not be validated.", + throw new PkixCertPathBuilderException("Possible certificate chain could not be validated.", certPathException); - } if (result == null && certPathException == null) - { - throw new PkixCertPathBuilderException( - "Unable to find certificate chain."); - } + throw new PkixCertPathBuilderException("Unable to find certificate chain."); return result; } @@ -112,10 +100,10 @@ public virtual PkixCertPathBuilderResult Build( private Exception certPathException; private PkixCertPathBuilderResult Build( - IX509AttributeCertificate attrCert, + X509V2AttributeCertificate attrCert, X509Certificate tbvCert, PkixBuilderParameters pkixParams, - IList tbvPath) + IList tbvPath) { // If tbvCert is readily present in tbvPath, it indicates having run // into a cycle in the @@ -175,17 +163,17 @@ private PkixCertPathBuilderResult Build( } // try to get the issuer certificate from one of the stores - ISet issuers = new HashSet(); + ISet issuers; try { - issuers.AddAll(PkixCertPathValidatorUtilities.FindIssuerCerts(tbvCert, pkixParams)); + issuers = PkixCertPathValidatorUtilities.FindIssuerCerts(tbvCert, pkixParams); } catch (Exception e) { throw new Exception("Cannot find issuer certificate for certificate in certification path.", e); } - if (issuers.IsEmpty) + if (issuers.Count < 1) throw new Exception("No issuer certificate for certificate in certification path found."); foreach (X509Certificate issuer in issuers) @@ -213,6 +201,27 @@ private PkixCertPathBuilderResult Build( return builderResult; } + + internal static HashSet FindAttributeCertificates( + ISelector attrCertSelector, + IList> attrCertStores) + { + var attrCerts = new HashSet(); + + foreach (var attrCertStore in attrCertStores) + { + try + { + attrCerts.UnionWith(attrCertStore.EnumerateMatches(attrCertSelector)); + } + catch (Exception e) + { + throw new Exception("Problem while picking certificates from X.509 store.", e); + } + } + + return attrCerts; + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixAttrCertPathValidator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixAttrCertPathValidator.cs index 4e91f63..6224920 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixAttrCertPathValidator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixAttrCertPathValidator.cs @@ -39,19 +39,16 @@ public class PkixAttrCertPathValidator * inappropriate for this validator. * @throws CertPathValidatorException if the verification fails. */ - public virtual PkixCertPathValidatorResult Validate( - PkixCertPath certPath, - PkixParameters pkixParams) + public virtual PkixCertPathValidatorResult Validate(PkixCertPath certPath, PkixParameters pkixParams) { - IX509Selector certSelect = pkixParams.GetTargetConstraints(); - if (!(certSelect is X509AttrCertStoreSelector)) + if (!(pkixParams.GetTargetConstraintsAttrCert() is X509AttrCertStoreSelector attrCertSelector)) { throw new ArgumentException( "TargetConstraints must be an instance of " + typeof(X509AttrCertStoreSelector).FullName, - "pkixParams"); + nameof(pkixParams)); } - IX509AttributeCertificate attrCert = ((X509AttrCertStoreSelector) certSelect).AttributeCert; + var attrCert = attrCertSelector.AttributeCert; PkixCertPath holderCertPath = Rfc3281CertPathUtilities.ProcessAttrCert1(attrCert, pkixParams); PkixCertPathValidatorResult result = Rfc3281CertPathUtilities.ProcessAttrCert2(certPath, pkixParams); X509Certificate issuerCert = (X509Certificate)certPath.Certificates[0]; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixBuilderParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixBuilderParameters.cs index 2f61295..45ce656 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixBuilderParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixBuilderParameters.cs @@ -1,10 +1,11 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Collections.Generic; using System.Text; using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; -using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store; +using BestHTTP.SecureProtocol.Org.BouncyCastle.X509; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; @@ -18,7 +19,7 @@ public class PkixBuilderParameters { private int maxPathLength = 5; - private ISet excludedCerts = new HashSet(); + private ISet excludedCerts = new HashSet(); /** * Returns an instance of PkixBuilderParameters. @@ -36,17 +37,23 @@ public static PkixBuilderParameters GetInstance( { PkixBuilderParameters parameters = new PkixBuilderParameters( pkixParams.GetTrustAnchors(), - new X509CertStoreSelector(pkixParams.GetTargetCertConstraints())); + pkixParams.GetTargetConstraintsCert(), + pkixParams.GetTargetConstraintsAttrCert()); parameters.SetParams(pkixParams); return parameters; } - public PkixBuilderParameters( - ISet trustAnchors, - IX509Selector targetConstraints) + public PkixBuilderParameters(ISet trustAnchors, ISelector targetConstraintsCert) + : this(trustAnchors, targetConstraintsCert, null) + { + } + + public PkixBuilderParameters(ISet trustAnchors, ISelector targetConstraintsCert, + ISelector targetConstraintsAttrCert) : base(trustAnchors) { - SetTargetCertConstraints(targetConstraints); + SetTargetConstraintsCert(targetConstraintsCert); + SetTargetConstraintsAttrCert(targetConstraintsAttrCert); } public virtual int MaxPathLength @@ -67,9 +74,9 @@ public virtual int MaxPathLength /// Excluded certificates are not used for building a certification path. ///
/// the excluded certificates. - public virtual ISet GetExcludedCerts() + public virtual ISet GetExcludedCerts() { - return new HashSet(excludedCerts); + return new HashSet(excludedCerts); } /// @@ -81,16 +88,15 @@ public virtual ISet GetExcludedCerts() /// The given set is cloned to protect it against subsequent modifications. /// /// The excluded certificates to set. - public virtual void SetExcludedCerts( - ISet excludedCerts) + public virtual void SetExcludedCerts(ISet excludedCerts) { if (excludedCerts == null) { - this.excludedCerts = new HashSet(); + this.excludedCerts = new HashSet(); } else { - this.excludedCerts = new HashSet(excludedCerts); + this.excludedCerts = new HashSet(excludedCerts); } } @@ -101,15 +107,13 @@ public virtual void SetExcludedCerts( * @param params Parameters to set. * @see org.bouncycastle.x509.ExtendedPKIXParameters#setParams(java.security.cert.PKIXParameters) */ - protected override void SetParams( - PkixParameters parameters) + protected override void SetParams(PkixParameters parameters) { base.SetParams(parameters); - if (parameters is PkixBuilderParameters) + if (parameters is PkixBuilderParameters _params) { - PkixBuilderParameters _params = (PkixBuilderParameters) parameters; maxPathLength = _params.maxPathLength; - excludedCerts = new HashSet(_params.excludedCerts); + excludedCerts = new HashSet(_params.excludedCerts); } } @@ -122,20 +126,22 @@ protected override void SetParams( public override object Clone() { PkixBuilderParameters parameters = new PkixBuilderParameters( - GetTrustAnchors(), GetTargetCertConstraints()); + GetTrustAnchors(), + GetTargetConstraintsCert(), + GetTargetConstraintsAttrCert()); 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.AppendLine("PkixBuilderParameters ["); s.Append(base.ToString()); s.Append(" Maximum Path Length: "); s.Append(MaxPathLength); - s.Append(nl + "]" + nl); + s.AppendLine(); + s.AppendLine("]"); return s.ToString(); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPath.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPath.cs index 3dc2a64..2283d49 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPath.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPath.cs @@ -1,15 +1,12 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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; @@ -83,38 +80,25 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix public class PkixCertPath // : CertPath { - internal static readonly IList certPathEncodings; + internal static readonly List m_encodings = new List{ "PkiPath", "PEM", "PKCS7" }; - 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 m_certificates; - private readonly IList certificates; - - /** - * @param certs - */ - private static IList SortCerts( - IList certs) + private static IList SortCerts(IList certs) { if (certs.Count < 2) return certs; - X509Name issuer = ((X509Certificate)certs[0]).IssuerDN; + X509Name issuer = certs[0].IssuerDN; bool okay = true; for (int i = 1; i != certs.Count; i++) { - X509Certificate cert = (X509Certificate)certs[i]; + X509Certificate cert = certs[i]; if (issuer.Equivalent(cert.SubjectDN, true)) { - issuer = ((X509Certificate)certs[i]).IssuerDN; + issuer = cert.IssuerDN; } else { @@ -127,13 +111,13 @@ private static IList SortCerts( 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); + var retList = new List(certs.Count); + var orig = new List(certs); for (int i = 0; i < certs.Count; i++) { - X509Certificate cert = (X509Certificate)certs[i]; - bool found = false; + X509Certificate cert = certs[i]; + bool found = false; X509Name subject = cert.SubjectDN; foreach (X509Certificate c in certs) @@ -158,11 +142,11 @@ private static IList SortCerts( for (int i = 0; i != retList.Count; i++) { - issuer = ((X509Certificate)retList[i]).IssuerDN; + issuer = retList[i].IssuerDN; for (int j = 0; j < certs.Count; j++) { - X509Certificate c = (X509Certificate)certs[j]; + X509Certificate c = certs[j]; if (issuer.Equivalent(c.SubjectDN, true)) { retList.Add(c); @@ -185,15 +169,12 @@ private static IList SortCerts( * a CertificateFactory to create CertPaths. * @param type the standard name of the type of Certificatesin this path **/ - public PkixCertPath( - ICollection certificates) -// : base("X.509") + public PkixCertPath(IList certificates) { - this.certificates = SortCerts(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(certificates)); + m_certificates = SortCerts(new List(certificates)); } - public PkixCertPath( - Stream inStream) + public PkixCertPath(Stream inStream) : this(inStream, "PkiPath") { } @@ -205,17 +186,14 @@ public PkixCertPath( * * @param type the standard name of the type of Certificatesin this path **/ - public PkixCertPath( - Stream inStream, - string encoding) -// : base("X.509") + public PkixCertPath(Stream inStream, string encoding) { - string upper = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(encoding); + //string upper = Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(encoding); - IList certs; + IList certs; try { - if (upper.Equals(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant("PkiPath"))) + if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase("PkiPath", encoding)) { Asn1InputStream derInStream = new Asn1InputStream(inStream); Asn1Object derObject = derInStream.ReadObject(); @@ -225,7 +203,7 @@ public PkixCertPath( "input stream does not contain a ASN1 SEQUENCE while reading PkiPath encoded data to load CertPath"); } - certs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + certs = new List(); foreach (Asn1Encodable ae in (Asn1Sequence)derObject) { @@ -236,9 +214,10 @@ public PkixCertPath( certs.Insert(0, new X509CertificateParser().ReadCertificate(certInStream)); } } - else if (upper.Equals("PKCS7") || upper.Equals("PEM")) + else if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase("PEM", encoding) || + Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase("PKCS7", encoding)) { - certs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(new X509CertificateParser().ReadCertificates(inStream)); + certs = new X509CertificateParser().ReadCertificates(inStream); } else { @@ -252,7 +231,7 @@ public PkixCertPath( + ex.ToString()); } - this.certificates = SortCerts(certs); + m_certificates = SortCerts(certs); } /** @@ -263,9 +242,9 @@ public PkixCertPath( * * @return an Iterator over the names of the supported encodings (as Strings) **/ - public virtual IEnumerable Encodings + public virtual IEnumerable Encodings { - get { return new EnumerableProxy(certPathEncodings); } + get { return CollectionUtilities.Proxy(m_encodings); } } /** @@ -285,36 +264,28 @@ public virtual IEnumerable Encodings * * @see Object#hashCode() Object.hashCode() */ - public override bool Equals( - object obj) + public override bool Equals(object obj) { if (this == obj) return true; - PkixCertPath other = obj as PkixCertPath; - if (other == null) + if (!(obj is PkixCertPath that)) return false; -// if (!this.Type.Equals(other.Type)) -// return false; - - //return this.Certificates.Equals(other.Certificates); + var thisCerts = this.Certificates; + var thatCerts = that.Certificates; - // TODO Extract this to a utility class - IList thisCerts = this.Certificates; - IList otherCerts = other.Certificates; - - if (thisCerts.Count != otherCerts.Count) + if (thisCerts.Count != thatCerts.Count) return false; - IEnumerator e1 = thisCerts.GetEnumerator(); - IEnumerator e2 = otherCerts.GetEnumerator(); + var e1 = thisCerts.GetEnumerator(); + var e2 = thatCerts.GetEnumerator(); while (e1.MoveNext()) { e2.MoveNext(); - if (!BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(e1.Current, e2.Current)) + if (!Equals(e1.Current, e2.Current)) return false; } @@ -323,8 +294,7 @@ public override bool Equals( public override int GetHashCode() { - // FIXME? - return this.Certificates.GetHashCode(); + return m_certificates.GetHashCode(); } /** @@ -336,14 +306,7 @@ public override int GetHashCode() **/ public virtual byte[] GetEncoded() { - foreach (object enc in Encodings) - { - if (enc is string) - { - return GetEncoded((string)enc); - } - } - return null; + return GetEncoded(m_encodings[0]); } /** @@ -356,32 +319,29 @@ public virtual byte[] GetEncoded() * occurs or the encoding requested is not supported * */ - public virtual byte[] GetEncoded( - string encoding) + public virtual byte[] GetEncoded(string encoding) { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(encoding, "PkiPath")) + if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(encoding, "PkiPath")) { - Asn1EncodableVector v = new Asn1EncodableVector(); - - for (int i = certificates.Count - 1; i >= 0; i--) + Asn1EncodableVector v = new Asn1EncodableVector(m_certificates.Count); + for (int i = m_certificates.Count - 1; i >= 0; i--) { - v.Add(ToAsn1Object((X509Certificate) certificates[i])); + v.Add(ToAsn1Object(m_certificates[i])); } return ToDerEncoded(new DerSequence(v)); } - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(encoding, "PKCS7")) + else if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(encoding, "PKCS7")) { - Asn1.Pkcs.ContentInfo encInfo = new Asn1.Pkcs.ContentInfo( - PkcsObjectIdentifiers.Data, null); + ContentInfo encInfo = new ContentInfo(PkcsObjectIdentifiers.Data, null); - Asn1EncodableVector v = new Asn1EncodableVector(); - for (int i = 0; i != certificates.Count; i++) - { - v.Add(ToAsn1Object((X509Certificate)certificates[i])); - } + Asn1EncodableVector v = new Asn1EncodableVector(m_certificates.Count); + foreach (var cert in m_certificates) + { + v.Add(ToAsn1Object(cert)); + } - Asn1.Pkcs.SignedData sd = new Asn1.Pkcs.SignedData( + SignedData sd = new SignedData( new DerInteger(1), new DerSet(), encInfo, @@ -389,21 +349,21 @@ public virtual byte[] GetEncoded( null, new DerSet()); - return ToDerEncoded(new Asn1.Pkcs.ContentInfo(PkcsObjectIdentifiers.SignedData, sd)); + return ToDerEncoded(new ContentInfo(PkcsObjectIdentifiers.SignedData, sd)); } - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(encoding, "PEM")) + else if (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++) + using (var pWrt = new PemWriter(new StreamWriter(bOut))) { - pWrt.WriteObject(certificates[i]); - } - - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(pWrt.Writer); + foreach (var cert in m_certificates) + { + pWrt.WriteObject(cert); + } + } } catch (Exception) { @@ -422,9 +382,9 @@ public virtual byte[] GetEncoded( /// Returns the list of certificates in this certification /// path. /// - public virtual IList Certificates + public virtual IList Certificates { - get { return CollectionUtilities.ReadOnly(certificates); } + get { return CollectionUtilities.ReadOnly(m_certificates); } } /** @@ -434,12 +394,11 @@ public virtual IList Certificates * * @return the DERObject **/ - private Asn1Object ToAsn1Object( - X509Certificate cert) + private Asn1Object ToAsn1Object(X509Certificate cert) { try { - return Asn1Object.FromByteArray(cert.GetEncoded()); + return cert.CertificateStructure.ToAsn1Object(); } catch (Exception e) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathBuilder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathBuilder.cs index 2d0be9e..2c6ed99 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathBuilder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathBuilder.cs @@ -1,21 +1,11 @@ #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 System.Collections.Generic; + 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 { @@ -25,7 +15,6 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix * @see CertPathBuilderSpi */ public class PkixCertPathBuilder - // : CertPathBuilderSpi { /** * Build and validate a CertPath using the given parameter. @@ -33,25 +22,16 @@ public class PkixCertPathBuilder * @param params PKIXBuilderParameters object containing all information to * build the CertPath */ - public virtual PkixCertPathBuilderResult Build( - PkixBuilderParameters pkixParams) + 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."); - } + var certSelector = pkixParams.GetTargetConstraintsCert(); - ISet targets = new HashSet(); + var targets = new HashSet(); try { - targets.AddAll(PkixCertPathValidatorUtilities.FindCertificates((X509CertStoreSelector)certSelect, pkixParams.GetStores())); - // TODO Should this include an entry for pkixParams.GetAdditionalStores() too? + CollectionUtilities.CollectMatches(targets, certSelector, pkixParams.GetStoresCert()); } catch (Exception e) { @@ -59,11 +39,11 @@ public virtual PkixCertPathBuilderResult Build( "Error finding target certificate.", e); } - if (targets.IsEmpty) + if (targets.Count < 1) throw new PkixCertPathBuilderException("No certificate found matching targetConstraints."); PkixCertPathBuilderResult result = null; - IList certPathList = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var certPathList = new List(); // check all potential target certificates foreach (X509Certificate cert in targets) @@ -75,14 +55,10 @@ public virtual PkixCertPathBuilderResult Build( } 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; } @@ -92,15 +68,13 @@ public virtual PkixCertPathBuilderResult Build( protected virtual PkixCertPathBuilderResult Build( X509Certificate tbvCert, PkixBuilderParameters pkixParams, - IList tbvPath) + IList tbvPath) { - // If tbvCert is readily present in tbvPath, it indicates having run - // into a cycle in the PKI graph. + // If tbvCert is already 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. + // step out, the certificate is not allowed to appear in a certification chain. if (pkixParams.GetExcludedCerts().Contains(tbvCert)) return null; @@ -113,7 +87,6 @@ protected virtual PkixCertPathBuilderResult Build( tbvPath.Add(tbvCert); -// X509CertificateParser certParser = new X509CertificateParser(); PkixCertPathBuilderResult builderResult = null; PkixCertPathValidator validator = new PkixCertPathValidator(); @@ -122,25 +95,21 @@ protected virtual PkixCertPathBuilderResult Build( // 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; + // exception message from possibly later tried certification chains + PkixCertPath certPath; try { certPath = new PkixCertPath(tbvPath); } catch (Exception e) { - throw new Exception( - "Certification path could not be constructed from certificate list.", - e); + throw new Exception("Certification path could not be constructed from certificate list.", e); } - PkixCertPathValidatorResult result = null; + PkixCertPathValidatorResult result; try { - result = (PkixCertPathValidatorResult)validator.Validate( - certPath, pkixParams); + result = validator.Validate(certPath, pkixParams); } catch (Exception e) { @@ -148,38 +117,33 @@ protected virtual PkixCertPathBuilderResult Build( "Certification path could not be validated.", e); } - return new PkixCertPathBuilderResult(certPath, result.TrustAnchor, - result.PolicyTree, result.SubjectPublicKey); + 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); + PkixCertPathValidatorUtilities.AddAdditionalStoresFromAltNames(tbvCert, pkixParams); } catch (CertificateParsingException e) { - throw new Exception( - "No additiontal X.509 stores can be added from certificate locations.", - 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(); + ISet issuers; try { - issuers.AddAll(PkixCertPathValidatorUtilities.FindIssuerCerts(tbvCert, pkixParams)); + issuers = PkixCertPathValidatorUtilities.FindIssuerCerts(tbvCert, pkixParams); } catch (Exception e) { - throw new Exception( - "Cannot find issuer certificate for certificate in certification path.", - e); + throw new Exception("Cannot find issuer certificate for certificate in certification path.", e); } - if (issuers.IsEmpty) + if (issuers.Count < 1) throw new Exception("No issuer certificate for certificate in certification path found."); foreach (X509Certificate issuer in issuers) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathBuilderException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathBuilderException.cs index 6bf5905..ef6c613 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathBuilderException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathBuilderException.cs @@ -1,25 +1,35 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; 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 class PkixCertPathBuilderException + : GeneralSecurityException { - public PkixCertPathBuilderException() : base() { } - - public PkixCertPathBuilderException(string message) : base(message) { } + public PkixCertPathBuilderException() + : base() + { + } + + public PkixCertPathBuilderException(string message) + : base(message) + { + } + + public PkixCertPathBuilderException(string message, Exception innerException) + : base(message, innerException) + { + } - public PkixCertPathBuilderException(string message, Exception exception) : base(message, exception) { } - + protected PkixCertPathBuilderException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathBuilderResult.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathBuilderResult.cs index 5e93dff..2abdac6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathBuilderResult.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathBuilderResult.cs @@ -36,12 +36,12 @@ public PkixCertPath 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(); + StringBuilder sb = new StringBuilder(); + sb.AppendLine("SimplePKIXCertPathBuilderResult: ["); + sb.Append(" Certification Path: ").Append(CertPath).AppendLine(); + sb.Append(" Trust Anchor: ").Append(TrustAnchor.TrustedCert.IssuerDN).AppendLine(); + sb.Append(" Subject Public Key: ").Append(SubjectPublicKey).AppendLine(); + return sb.ToString(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathChecker.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathChecker.cs index 476ec4c..7b5d6aa 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathChecker.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathChecker.cs @@ -1,6 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; +using System.Collections.Generic; + using BestHTTP.SecureProtocol.Org.BouncyCastle.X509; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix @@ -65,7 +66,7 @@ protected PkixCertPathChecker() * PKIXCertPathChecker, or null if no * extensions are supported */ - public abstract ISet GetSupportedExtensions(); + public abstract ISet GetSupportedExtensions(); /** * Performs the check(s) on the specified certificate using its internal @@ -82,7 +83,7 @@ protected PkixCertPathChecker() * @exception CertPathValidatorException * if the specified certificate does not pass the check */ - public abstract void Check(X509Certificate cert, ISet unresolvedCritExts); + public abstract void Check(X509Certificate cert, ISet unresolvedCritExts); //throws CertPathValidatorException; /** diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathValidator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathValidator.cs index 792bc29..d3c10e8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathValidator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathValidator.cs @@ -1,15 +1,12 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; +using System.Collections.Generic; + 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 { @@ -41,15 +38,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix ///
public class PkixCertPathValidator { - public virtual PkixCertPathValidatorResult Validate( - PkixCertPath certPath, - PkixParameters paramsPkix) + 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"); + nameof(paramsPkix)); } // @@ -59,11 +54,11 @@ public virtual PkixCertPathValidatorResult Validate( // // (a) // - IList certs = certPath.Certificates; + var certs = certPath.Certificates; int n = certs.Count; - if (certs.Count == 0) - throw new PkixCertPathValidatorException("Certification path is empty.", null, certPath, 0); + if (n == 0) + throw new PkixCertPathValidatorException("Certification path is empty.", null, 0); // // (b) @@ -73,7 +68,7 @@ public virtual PkixCertPathValidatorResult Validate( // // (c) // - ISet userInitialPolicySet = paramsPkix.GetInitialPolicies(); + var userInitialPolicySet = paramsPkix.GetInitialPolicies(); // // (d) @@ -81,24 +76,22 @@ public virtual PkixCertPathValidatorResult Validate( TrustAnchor trust; try { - trust = PkixCertPathValidatorUtilities.FindTrustAnchor( - (X509Certificate)certs[certs.Count - 1], - paramsPkix.GetTrustAnchors()); + trust = PkixCertPathValidatorUtilities.FindTrustAnchor(certs[certs.Count - 1], + paramsPkix.GetTrustAnchors()); if (trust == null) - throw new PkixCertPathValidatorException("Trust anchor for certification path not found.", null, certPath, -1); + throw new PkixCertPathValidatorException("Trust anchor for certification path not found.", null, -1); CheckCertificate(trust.TrustedCert); } catch (Exception e) { - throw new PkixCertPathValidatorException(e.Message, e.InnerException, certPath, certs.Count - 1); + throw new PkixCertPathValidatorException(e.Message, e.InnerException, 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 @@ -110,18 +103,18 @@ public virtual PkixCertPathValidatorResult Validate( // // (a) // - IList[] policyNodes = new IList[n + 1]; + var policyNodes = new List[n + 1]; for (int j = 0; j < policyNodes.Length; j++) { - policyNodes[j] = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + policyNodes[j] = new List(); } - ISet policySet = new HashSet(); + var 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); + var validPolicyTree = new PkixPolicyNode(new List(), 0, policySet, null, + new HashSet(), Rfc3280CertPathUtilities.ANY_POLICY, false); policyNodes[0].Add(validPolicyTree); @@ -133,7 +126,7 @@ public virtual PkixCertPathValidatorResult Validate( // (d) // int explicitPolicy; - ISet acceptablePolicies = new HashSet(); + var acceptablePolicies = new HashSet(); if (paramsPkix.IsExplicitPolicyRequired) { @@ -194,8 +187,7 @@ public virtual PkixCertPathValidatorResult Validate( } catch (ArgumentException ex) { - throw new PkixCertPathValidatorException("Subject of trust anchor could not be (re)encoded.", ex, certPath, - -1); + throw new PkixCertPathValidatorException("Subject of trust anchor could not be (re)encoded.", ex, -1); } AlgorithmIdentifier workingAlgId = null; @@ -206,7 +198,7 @@ public virtual PkixCertPathValidatorResult Validate( catch (PkixCertPathValidatorException e) { throw new PkixCertPathValidatorException( - "Algorithm identifier of public key of trust anchor could not be read.", e, certPath, -1); + "Algorithm identifier of public key of trust anchor could not be read.", e, -1); } // DerObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.Algorithm; @@ -221,22 +213,20 @@ public virtual PkixCertPathValidatorResult Validate( // 6.1.3 // - X509CertStoreSelector certConstraints = paramsPkix.GetTargetCertConstraints(); - if (certConstraints != null && !certConstraints.Match((X509Certificate)certs[0])) + var targetConstraints = paramsPkix.GetTargetConstraintsCert(); + if (targetConstraints != null && !targetConstraints.Match((X509Certificate)certs[0])) { throw new PkixCertPathValidatorException( - "Target certificate in certification path does not match targetConstraints.", null, certPath, 0); + "Target certificate in certification path does not match targetConstraints.", null, 0); } // // initialize CertPathChecker's // - IList pathCheckers = paramsPkix.GetCertPathCheckers(); - certIter = pathCheckers.GetEnumerator(); - - while (certIter.MoveNext()) + var certPathCheckers = paramsPkix.GetCertPathCheckers(); + foreach (PkixCertPathChecker certPathChecker in certPathCheckers) { - ((PkixCertPathChecker)certIter.Current).Init(false); + certPathChecker.Init(false); } X509Certificate cert = null; @@ -264,7 +254,7 @@ public virtual PkixCertPathValidatorResult Validate( } catch (Exception e) { - throw new PkixCertPathValidatorException(e.Message, e.InnerException, certPath, index); + throw new PkixCertPathValidatorException(e.Message, e.InnerException, index); } // @@ -296,7 +286,7 @@ public virtual PkixCertPathValidatorResult Validate( continue; throw new PkixCertPathValidatorException( - "Version 1 certificates can't be used as CA ones.", null, certPath, index); + "Version 1 certificates can't be used as CA ones.", null, index); } Rfc3280CertPathUtilities.PrepareNextCertA(certPath, index); @@ -332,11 +322,11 @@ public virtual PkixCertPathValidatorResult Validate( // (n) Rfc3280CertPathUtilities.PrepareNextCertN(certPath, index); - ISet criticalExtensions1 = cert.GetCriticalExtensionOids(); + var criticalExtensions1 = cert.GetCriticalExtensionOids(); if (criticalExtensions1 != null) { - criticalExtensions1 = new HashSet(criticalExtensions1); + criticalExtensions1 = new HashSet(criticalExtensions1); // these extensions are handled by the algorithm criticalExtensions1.Remove(X509Extensions.KeyUsage.Id); @@ -352,11 +342,11 @@ public virtual PkixCertPathValidatorResult Validate( } else { - criticalExtensions1 = new HashSet(); + criticalExtensions1 = new HashSet(); } // (o) - Rfc3280CertPathUtilities.PrepareNextCertO(certPath, index, criticalExtensions1, pathCheckers); + Rfc3280CertPathUtilities.PrepareNextCertO(certPath, index, criticalExtensions1, certPathCheckers); // set signing certificate for next round sign = cert; @@ -371,7 +361,7 @@ public virtual PkixCertPathValidatorResult Validate( } catch (PkixCertPathValidatorException e) { - throw new PkixCertPathValidatorException("Next working key could not be retrieved.", e, certPath, index); + throw new PkixCertPathValidatorException("Next working key could not be retrieved.", e, index); } workingAlgId = PkixCertPathValidatorUtilities.GetAlgorithmIdentifier(workingPublicKey); @@ -397,11 +387,11 @@ public virtual PkixCertPathValidatorResult Validate( // // (f) // - ISet criticalExtensions = cert.GetCriticalExtensionOids(); + var criticalExtensions = cert.GetCriticalExtensionOids(); if (criticalExtensions != null) { - criticalExtensions = new HashSet(criticalExtensions); + criticalExtensions = new HashSet(criticalExtensions); // Requires .Id // these extensions are handled by the algorithm @@ -419,20 +409,20 @@ public virtual PkixCertPathValidatorResult Validate( } else { - criticalExtensions = new HashSet(); + criticalExtensions = new HashSet(); } - Rfc3280CertPathUtilities.WrapupCertF(certPath, index + 1, pathCheckers, criticalExtensions); + Rfc3280CertPathUtilities.WrapupCertF(certPath, index + 1, certPathCheckers, criticalExtensions); - PkixPolicyNode intersection = Rfc3280CertPathUtilities.WrapupCertG(certPath, paramsPkix, userInitialPolicySet, - index + 1, policyNodes, validPolicyTree, acceptablePolicies); + 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); + throw new PkixCertPathValidatorException("Path processing failed on policy.", null, index); } internal static void CheckCertificate(X509Certificate cert) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathValidatorException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathValidatorException.cs index 742ef21..4aa0d31 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathValidatorException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathValidatorException.cs @@ -1,6 +1,8 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; + using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix @@ -29,38 +31,25 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix * * @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; + protected readonly int m_index = -1; - public PkixCertPathValidatorException() : base() { } + 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) { } + 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) + public PkixCertPathValidatorException(string message, Exception innerException) + : base(message, innerException) { - this.cause = cause; } /// @@ -68,157 +57,40 @@ public PkixCertPathValidatorException(string message, Exception cause) : base(me /// 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 cause (or null if none) /// the index of the certificate in the certification path that * - public PkixCertPathValidatorException( - string message, - Exception cause, - PkixCertPath certPath, - int index) - : base(message) + public PkixCertPathValidatorException(string message, Exception innerException, int index) + : base(message, innerException) { - 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()"); - } + if (index < -1) + throw new ArgumentException("cannot be < -1", nameof(index)); - this.cause = cause; - this.certPath = certPath; - this.index = index; + m_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 + protected PkixCertPathValidatorException(SerializationInfo info, StreamingContext context) + : base(info, context) { - get - { - string message = base.Message; - - if (message != null) - { - return message; - } - - if (cause != null) - { - return cause.Message; - } - - return null; - } + m_index = info.GetInt32("index"); } - /** - * 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 + public override void GetObjectData(SerializationInfo info, StreamingContext context) { - get { return certPath; } + base.GetObjectData(info, context); + info.AddValue("index", m_index); } - /** - * 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(); -// } - + /// eturns the index of the certificate in the certification path that caused the exception to be + /// thrown. + /// + /// Note that the list of certificates in a is zero based. If no index has been set, + /// -1 is returned. + /// + /// The index that has been set, or -1 if none has been set. + public int Index + { + get { return m_index; } + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathValidatorResult.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathValidatorResult.cs index c9132df..11de44f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathValidatorResult.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathValidatorResult.cs @@ -33,20 +33,14 @@ public AsymmetricKeyParameter SubjectPublicKey get { return this.subjectPublicKey; } } - public PkixCertPathValidatorResult( - TrustAnchor trustAnchor, - PkixPolicyNode policyTree, - AsymmetricKeyParameter 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"); - } - + if (trustAnchor == null) + throw new ArgumentNullException(nameof(trustAnchor)); + if (subjectPublicKey == null) + throw new ArgumentNullException(nameof(subjectPublicKey)); + this.trustAnchor = trustAnchor; this.policyTree = policyTree; this.subjectPublicKey = subjectPublicKey; @@ -57,16 +51,15 @@ public object Clone() return new PkixCertPathValidatorResult(this.TrustAnchor, this.PolicyTree, this.SubjectPublicKey); } - public override String ToString() + 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(); + StringBuilder sb = new StringBuilder(); + sb.AppendLine("PKIXCertPathValidatorResult: ["); + sb.Append(" Trust Anchor: ").Append(TrustAnchor).AppendLine(); + sb.Append(" Policy Tree: ").Append(PolicyTree).AppendLine(); + sb.Append(" Subject Public Key: ").Append(SubjectPublicKey).AppendLine(); + return sb.ToString(); } - } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathValidatorUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathValidatorUtilities.cs index 6485dab..8e13e30 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathValidatorUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCertPathValidatorUtilities.cs @@ -1,9 +1,8 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; -using System.Text; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.IsisMtt; @@ -14,7 +13,6 @@ 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; @@ -24,7 +22,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix /// /// Summary description for PkixCertPathValidatorUtilities. /// - public class PkixCertPathValidatorUtilities + internal static class PkixCertPathValidatorUtilities { private static readonly PkixCrlUtilities CrlUtilities = new PkixCrlUtilities(); @@ -38,20 +36,20 @@ public class PkixCertPathValidatorUtilities 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" - }; + //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 @@ -63,11 +61,9 @@ public class PkixCertPathValidatorUtilities /// null if not. /// /// @exception - internal static TrustAnchor FindTrustAnchor( - X509Certificate cert, - ISet trustAnchors) + internal static TrustAnchor FindTrustAnchor(X509Certificate cert, ISet trustAnchors) { - IEnumerator iter = trustAnchors.GetEnumerator(); + var iter = trustAnchors.GetEnumerator(); TrustAnchor trust = null; AsymmetricKeyParameter trustPublicKey = null; Exception invalidKeyEx = null; @@ -85,7 +81,7 @@ internal static TrustAnchor FindTrustAnchor( while (iter.MoveNext() && trust == null) { - trust = (TrustAnchor) iter.Current; + trust = iter.Current; if (trust.TrustedCert != null) { if (certSelectX509.Match(trust.TrustedCert)) @@ -145,9 +141,7 @@ internal static TrustAnchor FindTrustAnchor( return trust; } - internal static bool IsIssuerTrustAnchor( - X509Certificate cert, - ISet trustAnchors) + internal static bool IsIssuerTrustAnchor(X509Certificate cert, ISet trustAnchors) { try { @@ -159,25 +153,20 @@ internal static bool IsIssuerTrustAnchor( } } - internal static void AddAdditionalStoresFromAltNames( - X509Certificate cert, - PkixParameters pkixParams) + 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) + var issuerAltNames = cert.GetIssuerAlternativeNames(); + if (issuerAltNames != null) { - IEnumerator it = cert.GetIssuerAlternativeNames().GetEnumerator(); - while (it.MoveNext()) + foreach (var list in issuerAltNames) { // look for URI - IList list = (IList)it.Current; - //if (list[0].Equals(new Integer(GeneralName.UniformResourceIdentifier))) - if (list[0].Equals(GeneralName.UniformResourceIdentifier)) + if (list.Count >= 2 && list[0].Equals(GeneralName.UniformResourceIdentifier)) { - // found - string temp = (string)list[1]; - PkixCertPathValidatorUtilities.AddAdditionalStoreFromLocation(temp, pkixParams); + string location = (string)list[1]; + AddAdditionalStoreFromLocation(location, pkixParams); } } } @@ -185,7 +174,7 @@ internal static void AddAdditionalStoresFromAltNames( internal static DateTime GetValidDate(PkixParameters paramsPKIX) { - DateTimeObject validDate = paramsPKIX.Date; + DateTime? validDate = paramsPKIX.Date; if (validDate == null) return DateTime.UtcNow; @@ -196,19 +185,25 @@ internal static DateTime GetValidDate(PkixParameters paramsPKIX) /// /// Returns the issuer of an attribute certificate or certificate. /// - /// The attribute certificate or certificate. + /// The attribute certificate or certificate. /// The issuer as X500Principal. - internal static X509Name GetIssuerPrincipal( - object cert) + internal static X509Name GetIssuerPrincipal(object obj) { - if (cert is X509Certificate) - { - return ((X509Certificate)cert).IssuerDN; - } - else - { - return ((IX509AttributeCertificate)cert).Issuer.GetPrincipals()[0]; - } + if (obj is X509Certificate cert) + return cert.IssuerDN; + if (obj is X509V2AttributeCertificate attrCert) + return attrCert.Issuer.GetPrincipals()[0]; + throw new InvalidOperationException(); + } + + internal static X509Name GetIssuerPrincipal(X509V2AttributeCertificate attrCert) + { + return attrCert.Issuer.GetPrincipals()[0]; + } + + internal static X509Name GetIssuerPrincipal(X509Certificate cert) + { + return cert.IssuerDN; } internal static bool IsSelfIssued( @@ -232,10 +227,9 @@ internal static AlgorithmIdentifier GetAlgorithmIdentifier( } } - internal static bool IsAnyPolicy( - ISet policySet) + internal static bool IsAnyPolicy(ISet policySet) { - return policySet == null || policySet.Contains(ANY_POLICY) || policySet.Count == 0; + return policySet == null || policySet.Count < 1 || policySet.Contains(ANY_POLICY); } internal static void AddAdditionalStoreFromLocation( @@ -246,7 +240,7 @@ internal static void AddAdditionalStoreFromLocation( { try { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(location, "ldap://")) + if (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 @@ -266,7 +260,7 @@ internal static void AddAdditionalStoreFromLocation( // baseDN = nsull; } - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("LDAP cert/CRL stores"); + throw new NotImplementedException("LDAP cert/CRL stores"); // use all purpose parameters //X509LDAPCertStoreParameters ldapParams = new X509LDAPCertStoreParameters.Builder( @@ -306,37 +300,32 @@ private static BigInteger GetSerialNumber( // policy checking // - internal static ISet GetQualifierSet(Asn1Sequence qualifiers) + internal static ISet GetQualifierSet(Asn1Sequence qualifiers) { - ISet pq = new HashSet(); + var 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) + if (qualifiers != null) + { + foreach (Asn1Encodable ae in qualifiers) { - throw new PkixCertPathValidatorException("Policy qualifier info cannot be decoded.", ex); + try + { + 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) + internal static PkixPolicyNode RemovePolicyNode(PkixPolicyNode validPolicyTree, + IList[] policyNodes, PkixPolicyNode _node) { - PkixPolicyNode _parent = (PkixPolicyNode)_node.Parent; + PkixPolicyNode _parent = _node.Parent; if (validPolicyTree == null) { @@ -347,7 +336,7 @@ internal static PkixPolicyNode RemovePolicyNode( { for (int j = 0; j < policyNodes.Length; j++) { - policyNodes[j] = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + policyNodes[j] = new List(); } return null; @@ -361,7 +350,7 @@ internal static PkixPolicyNode RemovePolicyNode( } } - private static void RemovePolicyNodeRecurse(IList[] policyNodes, PkixPolicyNode _node) + private static void RemovePolicyNodeRecurse(IList[] policyNodes, PkixPolicyNode _node) { policyNodes[_node.Depth].Remove(_node); @@ -374,135 +363,115 @@ private static void RemovePolicyNodeRecurse(IList[] policyNodes, PkixPolicyNode } } - internal static void PrepareNextCertB1( - int i, - IList[] policyNodes, - string id_p, - IDictionary m_idp, - X509Certificate cert) + 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()) + foreach (var node in policyNodes[i]) { - PkixPolicyNode node = (PkixPolicyNode)nodes_i.Current; if (node.ValidPolicy.Equals(id_p)) { - idp_found = true; - node.ExpectedPolicies = (ISet)m_idp[id_p]; - break; + node.ExpectedPolicies = CollectionUtilities.GetValueOrNull(m_idp, id_p); + return; } } - if (!idp_found) + foreach (var node in policyNodes[i]) { - nodes_i = policyNodes[i].GetEnumerator(); - while (nodes_i.MoveNext()) + if (ANY_POLICY.Equals(node.ValidPolicy)) { - PkixPolicyNode node = (PkixPolicyNode)nodes_i.Current; - if (ANY_POLICY.Equals(node.ValidPolicy)) + Asn1Sequence policies; + try { - ISet pq = null; - Asn1Sequence policies = null; + policies = Asn1Sequence.GetInstance( + GetExtensionValue(cert, X509Extensions.CertificatePolicies)); + } + catch (Exception e) + { + throw new Exception("Certificate policies cannot be decoded.", e); + } + + ISet pq = null; + + foreach (var policy in policies) + { + PolicyInformation pinfo; try { - policies = DerSequence.GetInstance(GetExtensionValue(cert, X509Extensions.CertificatePolicies)); + pinfo = PolicyInformation.GetInstance(policy); } - catch (Exception e) + catch (Exception ex) { - throw new Exception("Certificate policies cannot be decoded.", e); + throw new Exception("Policy information cannot be decoded.", ex); } - IEnumerator enm = policies.GetEnumerator(); - while (enm.MoveNext()) + if (ANY_POLICY.Equals(pinfo.PolicyIdentifier.Id)) { - PolicyInformation pinfo = null; - try { - pinfo = PolicyInformation.GetInstance(enm.Current); + pq = GetQualifierSet(pinfo.PolicyQualifiers); } - catch (Exception ex) - { - throw new Exception("Policy information cannot be decoded.", ex); - } - - if (ANY_POLICY.Equals(pinfo.PolicyIdentifier.Id)) + catch (PkixCertPathValidatorException ex) { - try - { - pq = GetQualifierSet(pinfo.PolicyQualifiers); - } - catch (PkixCertPathValidatorException ex) - { - throw new PkixCertPathValidatorException( - "Policy qualifier info set could not be built.", ex); - } - break; + 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; + bool ci = false; + var critExtOids = cert.GetCriticalExtensionOids(); + if (critExtOids != null) + { + ci = critExtOids.Contains(X509Extensions.CertificatePolicies.Id); + } + + PkixPolicyNode p_node = node.Parent; + if (ANY_POLICY.Equals(p_node.ValidPolicy)) + { + PkixPolicyNode c_node = new PkixPolicyNode(new List(), i, + CollectionUtilities.GetValueOrNull(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) + 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])) + foreach (var node in new List(policyNodes[i])) { - if (node.ValidPolicy.Equals(id_p)) - { - PkixPolicyNode p_node = (PkixPolicyNode)node.Parent; - p_node.RemoveChild(node); + if (!node.ValidPolicy.Equals(id_p)) + { + ++pos; + continue; + } + + node.Parent.RemoveChild(node); - // Removal of element at current iterator position not supported in C# - //nodes_i.remove(); - policyNodes[i].RemoveAt(pos); + policyNodes[i].RemoveAt(pos); - for (int k = (i - 1); k >= 0; k--) + for (int k = i - 1; k >= 0; k--) + { + var nodes = policyNodes[k]; + + for (int l = 0; l < nodes.Count; l++) { - IList nodes = policyNodes[k]; - for (int l = 0; l < nodes.Count; l++) + var node2 = nodes[l]; + if (!node2.HasChildren) { - PkixPolicyNode node2 = (PkixPolicyNode)nodes[l]; - if (!node2.HasChildren) - { - validPolicyTree = RemovePolicyNode(validPolicyTree, policyNodes, node2); - if (validPolicyTree == null) - break; - } + validPolicyTree = RemovePolicyNode(validPolicyTree, policyNodes, node2); + if (validPolicyTree == null) + break; } } } - else - { - ++pos; - } } return validPolicyTree; } @@ -510,10 +479,10 @@ internal static PkixPolicyNode PrepareNextCertB2( internal static void GetCertStatus( DateTime validDate, X509Crl crl, - Object cert, + object cert, CertStatus certStatus) { - X509Crl bcCRL = null; + X509Crl bcCRL; try { @@ -521,7 +490,7 @@ internal static void GetCertStatus( } catch (Exception exception) { - throw new Exception("Bouncy Castle X509Crl could not be created.", exception); + throw new Exception("X509Crl could not be created.", exception); } X509CrlEntry crl_entry = (X509CrlEntry)bcCRL.GetRevokedCertificate(GetSerialNumber(cert)); @@ -573,7 +542,7 @@ internal static void GetCertStatus( // (i) or (j) certStatus.Status = reasonCodeValue; - certStatus.RevocationDate = new DateTimeObject(revocationDate); + certStatus.RevocationDate = revocationDate; } /** @@ -597,12 +566,9 @@ internal static void GetCertStatus( * index extended with DSA parameters if applicable. * @throws Exception if DSA parameters cannot be inherited. */ - internal static AsymmetricKeyParameter GetNextWorkingKey( - IList certs, - int index) + internal static AsymmetricKeyParameter GetNextWorkingKey(IList certs, int index) { - //Only X509Certificate - X509Certificate cert = (X509Certificate)certs[index]; + X509Certificate cert = certs[index]; AsymmetricKeyParameter pubKey = cert.GetPublicKey(); @@ -616,7 +582,7 @@ internal static AsymmetricKeyParameter GetNextWorkingKey( for (int i = index + 1; i < certs.Count; i++) { - X509Certificate parentCert = (X509Certificate)certs[i]; + X509Certificate parentCert = certs[i]; pubKey = parentCert.GetPublicKey(); if (!(pubKey is DsaPublicKeyParameters)) @@ -658,19 +624,19 @@ internal static DateTime GetValidCertDateFromValidityModel( // if end cert use given signing/encryption/... time if (index <= 0) { - return PkixCertPathValidatorUtilities.GetValidDate(paramsPkix); + return GetValidDate(paramsPkix); // else use time when previous cert was created } + var cert = certPath.Certificates[index - 1]; + if (index - 1 == 0) { - DerGeneralizedTime dateOfCertgen = null; + Asn1GeneralizedTime dateOfCertgen; try { - X509Certificate cert = (X509Certificate)certPath.Certificates[index - 1]; - Asn1OctetString extVal = cert.GetExtensionValue( - IsisMttObjectIdentifiers.IdIsisMttATDateOfCertGen); - dateOfCertgen = DerGeneralizedTime.GetInstance(extVal); + Asn1OctetString extVal = cert.GetExtensionValue(IsisMttObjectIdentifiers.IdIsisMttATDateOfCertGen); + dateOfCertgen = Asn1GeneralizedTime.GetInstance(extVal); } catch (ArgumentException) { @@ -692,44 +658,7 @@ internal static DateTime GetValidCertDateFromValidityModel( } } - 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; + return cert.NotBefore; } /** @@ -754,11 +683,11 @@ internal static ICollection FindCertificates( */ internal static void GetCrlIssuersFromDistributionPoint( DistributionPoint dp, - ICollection issuerPrincipals, + ICollection issuerPrincipals, X509CrlStoreSelector selector, PkixParameters pkixParams) { - IList issuers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var issuers = new List(); // indirect CRL if (dp.CrlIssuer != null) { @@ -774,9 +703,7 @@ internal static void GetCrlIssuersFromDistributionPoint( } catch (IOException e) { - throw new Exception( - "CRL issuer information from distribution point cannot be decoded.", - e); + throw new Exception("CRL issuer information from distribution point cannot be decoded.", e); } } } @@ -794,10 +721,7 @@ internal static void GetCrlIssuersFromDistributionPoint( } // add and check issuer principals - for (IEnumerator it = issuerPrincipals.GetEnumerator(); it.MoveNext(); ) - { - issuers.Add((X509Name)it.Current); - } + issuers.AddRange(issuerPrincipals); } // 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 @@ -861,60 +785,41 @@ internal static void GetCrlIssuersFromDistributionPoint( * @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) + internal static ISet GetCompleteCrls(DistributionPoint dp, object certObj, DateTime currentDate, + PkixParameters paramsPKIX) { + var certObjIssuer = GetIssuerPrincipal(certObj); + 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); + var issuers = new HashSet(); + issuers.Add(certObjIssuer); + + 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) + { + if (certObj is X509Certificate cert) { - IX509AttributeCertificate aCert = (IX509AttributeCertificate)cert; - - throw new Exception("No CRLs found for issuer \"" + aCert.Issuer.GetPrincipals()[0] + "\""); + crlselect.CertificateChecking = cert; } - else + else if (certObj is X509V2AttributeCertificate attrCert) { - X509Certificate xCert = (X509Certificate)cert; - - throw new Exception("No CRLs found for issuer \"" + xCert.IssuerDN + "\""); + crlselect.AttrCertChecking = attrCert; } } + crlselect.CompleteCrlEnabled = true; + + ISet crls = CrlUtilities.FindCrls(crlselect, paramsPKIX, currentDate); + if (crls.Count < 1) + throw new Exception("No CRLs found for issuer \"" + certObjIssuer + "\""); + return crls; } @@ -928,7 +833,7 @@ internal static ISet GetCompleteCrls( * @throws Exception if an exception occurs while picking the delta * CRLs. */ - internal static ISet GetDeltaCrls( + internal static ISet GetDeltaCrls( DateTime currentDate, PkixParameters paramsPKIX, X509Crl completeCRL) @@ -938,7 +843,7 @@ internal static ISet GetDeltaCrls( // 5.2.4 (a) try { - IList deltaSelectIssuer = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var deltaSelectIssuer = new List(); deltaSelectIssuer.Add(completeCRL.IssuerDN); deltaSelect.Issuers = deltaSelectIssuer; } @@ -993,13 +898,13 @@ internal static ISet GetDeltaCrls( deltaSelect.MaxBaseCrlNumber = completeCRLNumber; // find delta CRLs - ISet temp = CrlUtilities.FindCrls(deltaSelect, paramsPKIX, currentDate); + ISet temp = CrlUtilities.FindCrls(deltaSelect, paramsPKIX, currentDate); - ISet result = new HashSet(); + var result = new HashSet(); foreach (X509Crl crl in temp) { - if (isDeltaCrl(crl)) + if (IsDeltaCrl(crl)) { result.Add(crl); } @@ -1008,40 +913,13 @@ internal static ISet GetDeltaCrls( return result; } - private static bool isDeltaCrl( - X509Crl crl) + private static bool IsDeltaCrl(X509Crl crl) { - ISet critical = crl.GetCriticalExtensionOids(); + var 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) @@ -1073,10 +951,8 @@ internal static void AddAdditionalStoresFromCrlDistributionPoint( { if (genNames[j].TagNo == GeneralName.UniformResourceIdentifier) { - string location = DerIA5String.GetInstance( - genNames[j].Name).GetString(); - PkixCertPathValidatorUtilities.AddAdditionalStoreFromLocation( - location, pkixParams); + string location = DerIA5String.GetInstance(genNames[j].Name).GetString(); + AddAdditionalStoreFromLocation(location, pkixParams); } } } @@ -1085,31 +961,18 @@ internal static void AddAdditionalStoresFromCrlDistributionPoint( } } - internal static bool ProcessCertD1i( - int index, - IList[] policyNodes, - DerObjectIdentifier pOid, - ISet pq) + 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++) + foreach (var node in policyNodes[index - 1]) { - PkixPolicyNode node = (PkixPolicyNode)policyNodeVec[j]; - ISet expectedPolicies = node.ExpectedPolicies; - - if (expectedPolicies.Contains(pOid.Id)) + if (node.ExpectedPolicies.Contains(pOid.Id)) { - ISet childExpectedPolicies = new HashSet(); + var 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); + var child = new PkixPolicyNode(new List(), index, childExpectedPolicies, node, pq, + pOid.Id, false); node.AddChild(child); policyNodes[index].Add(child); @@ -1120,32 +983,21 @@ internal static bool ProcessCertD1i( return false; } - internal static void ProcessCertD1ii( - int index, - IList[] policyNodes, - DerObjectIdentifier _poid, - ISet _pq) + 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++) + foreach (var _node in policyNodes[index - 1]) { - PkixPolicyNode _node = (PkixPolicyNode)policyNodeVec[j]; - if (ANY_POLICY.Equals(_node.ValidPolicy)) { - ISet _childExpectedPolicies = new HashSet(); + var _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); + var _child = new PkixPolicyNode(new List(), index, _childExpectedPolicies, _node, + _pq, _poid.Id, false); _node.AddChild(_child); policyNodes[index].Add(_child); + return; } } @@ -1163,15 +1015,14 @@ internal static void ProcessCertD1ii( * @exception Exception * if an error occurs. */ - internal static ICollection FindIssuerCerts( + internal static HashSet FindIssuerCerts( X509Certificate cert, PkixBuilderParameters pkixParams) { - X509CertStoreSelector certSelect = new X509CertStoreSelector(); - ISet certs = new HashSet(); + X509CertStoreSelector certSelector = new X509CertStoreSelector(); try { - certSelect.Subject = cert.IssuerDN; + certSelector.Subject = cert.IssuerDN; } catch (IOException ex) { @@ -1179,10 +1030,10 @@ internal static ICollection FindIssuerCerts( "Subject criteria for certificate selector to find issuer certificate could not be set.", ex); } + var certs = new HashSet(); try { - certs.AddAll(PkixCertPathValidatorUtilities.FindCertificates(certSelect, pkixParams.GetStores())); - certs.AddAll(PkixCertPathValidatorUtilities.FindCertificates(certSelect, pkixParams.GetAdditionalStores())); + CollectionUtilities.CollectMatches(certs, certSelector, pkixParams.GetStoresCert()); } catch (Exception e) { @@ -1192,23 +1043,9 @@ internal static ICollection FindIssuerCerts( 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) + internal static Asn1Object GetExtensionValue(IX509Extension extensions, DerObjectIdentifier oid) { - Asn1OctetString bytes = ext.GetExtensionValue(oid); - - if (bytes == null) - return null; - - return X509ExtensionUtilities.FromExtensionValue(bytes); + return X509ExtensionUtilities.FromExtensionValue(extensions, oid); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCrlUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCrlUtilities.cs index de1bbc0..d4b5aa1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCrlUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixCrlUtilities.cs @@ -1,10 +1,9 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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; @@ -12,22 +11,22 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix { public class PkixCrlUtilities { - public virtual ISet FindCrls(X509CrlStoreSelector crlselect, PkixParameters paramsPkix, DateTime currentDate) + public virtual ISet FindCrls(X509CrlStoreSelector crlSelector, PkixParameters paramsPkix, + DateTime currentDate) { - ISet initialSet = new HashSet(); + HashSet initialSet; // get complete CRL(s) try { - initialSet.AddAll(FindCrls(crlselect, paramsPkix.GetAdditionalStores())); - initialSet.AddAll(FindCrls(crlselect, paramsPkix.GetStores())); + initialSet = FindCrls(crlSelector, paramsPkix.GetStoresCrl()); } catch (Exception e) { throw new Exception("Exception obtaining complete CRLs.", e); } - ISet finalSet = new HashSet(); + var finalSet = new HashSet(); DateTime validityDate = currentDate; if (paramsPkix.Date != null) @@ -38,11 +37,11 @@ public virtual ISet FindCrls(X509CrlStoreSelector crlselect, PkixParameters para // based on RFC 5280 6.3.3 foreach (X509Crl crl in initialSet) { - DateTimeObject nextUpdate = crl.NextUpdate; + DateTime? nextUpdate = crl.NextUpdate; if (null == nextUpdate || nextUpdate.Value.CompareTo(validityDate) > 0) { - X509Certificate cert = crlselect.CertificateChecking; + X509Certificate cert = crlSelector.CertificateChecking; if (null == cert || crl.ThisUpdate.CompareTo(cert.NotAfter) < 0) { @@ -54,21 +53,17 @@ public virtual ISet FindCrls(X509CrlStoreSelector crlselect, PkixParameters para return finalSet; } - public virtual ISet FindCrls(X509CrlStoreSelector crlselect, PkixParameters paramsPkix) + public virtual ISet FindCrls(X509CrlStoreSelector crlSelector, PkixParameters paramsPkix) { - ISet completeSet = new HashSet(); - // get complete CRL(s) try { - completeSet.AddAll(FindCrls(crlselect, paramsPkix.GetStores())); + return FindCrls(crlSelector, paramsPkix.GetStoresCrl()); } catch (Exception e) { throw new Exception("Exception obtaining complete CRLs.", e); } - - return completeSet; } /// @@ -76,28 +71,28 @@ public virtual ISet FindCrls(X509CrlStoreSelector crlselect, PkixParameters para /// 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 + /// 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) + private HashSet FindCrls(ISelector crlSelector, IList> crlStores) { - ISet crls = new HashSet(); + var crls = new HashSet(); Exception lastException = null; bool foundValidStore = false; - foreach (IX509Store store in crlStores) + foreach (var crlStore in crlStores) { try { - crls.AddAll(store.GetMatches(crlSelect)); + crls.UnionWith(crlStore.EnumerateMatches(crlSelector)); foundValidStore = true; } - catch (X509StoreException e) + catch (Exception e) { lastException = new Exception("Exception searching in X.509 CRL store.", e); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixNameConstraintValidator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixNameConstraintValidator.cs index 63061d6..1172ac5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixNameConstraintValidator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixNameConstraintValidator.cs @@ -1,48 +1,45 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; -using System.IO; +using System.Collections.Generic; +using System.Text; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X500; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X500.Style; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix { public class PkixNameConstraintValidator { - // TODO Implement X500Name and styles - //private static readonly DerObjectIdentifier SerialNumberOid = Rfc4519Style.SerialNumber; - private static readonly DerObjectIdentifier SerialNumberOid = new DerObjectIdentifier("2.5.4.5"); + private static readonly DerObjectIdentifier SerialNumberOid = X509Name.SerialNumber; - private ISet excludedSubtreesDN = new HashSet(); + private ISet excludedSubtreesDN = new HashSet(); - private ISet excludedSubtreesDNS = new HashSet(); + private ISet excludedSubtreesDns = new HashSet(); - private ISet excludedSubtreesEmail = new HashSet(); + private ISet excludedSubtreesEmail = new HashSet(); - private ISet excludedSubtreesURI = new HashSet(); + private ISet excludedSubtreesUri = new HashSet(); - private ISet excludedSubtreesIP = new HashSet(); + private ISet excludedSubtreesIP = new HashSet(); - private ISet excludedSubtreesOtherName = new HashSet(); + private ISet excludedSubtreesOtherName = new HashSet(); - private ISet permittedSubtreesDN; + private ISet permittedSubtreesDN; - private ISet permittedSubtreesDNS; + private ISet permittedSubtreesDns; - private ISet permittedSubtreesEmail; + private ISet permittedSubtreesEmail; - private ISet permittedSubtreesURI; + private ISet permittedSubtreesUri; - private ISet permittedSubtreesIP; + private ISet permittedSubtreesIP; - private ISet permittedSubtreesOtherName; + private ISet permittedSubtreesOtherName; public PkixNameConstraintValidator() { @@ -87,7 +84,7 @@ private static bool WithinDNSubtree( && subtreeRdn.GetFirst().GetType().Equals(SerialNumberOid) && dnsRdn.GetFirst().GetType().Equals(SerialNumberOid)) { - if (!BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(dnsRdn.GetFirst().Value.ToString(), subtreeRdn.GetFirst().Value.ToString())) + if (!Org.BouncyCastle.Utilities.Platform.StartsWith(dnsRdn.GetFirst().Value.ToString(), subtreeRdn.GetFirst().Value.ToString())) return false; } else if (!IetfUtilities.RdnAreEqual(subtreeRdn, dnsRdn)) @@ -109,9 +106,9 @@ public void CheckExcludedDN(Asn1Sequence dn) CheckExcludedDirectory(excludedSubtreesDN, dn); } - private ISet IntersectDN(ISet permitted, ISet dns) + private ISet IntersectDN(ISet permitted, ISet dns) { - ISet intersect = new HashSet(); + var intersect = new HashSet(); foreach (GeneralSubtree subtree1 in dns) { Asn1Sequence dn1 = Asn1Sequence.GetInstance(subtree1.Base.Name); @@ -124,10 +121,8 @@ private ISet IntersectDN(ISet permitted, ISet dns) } else { - foreach (object obj2 in permitted) + foreach (var dn2 in permitted) { - Asn1Sequence dn2 = Asn1Sequence.GetInstance(obj2); - if (WithinDNSubtree(dn1, dn2)) { intersect.Add(dn1); @@ -142,9 +137,9 @@ private ISet IntersectDN(ISet permitted, ISet dns) return intersect; } - private ISet UnionDN(ISet excluded, Asn1Sequence dn) + private ISet UnionDN(ISet excluded, Asn1Sequence dn) { - if (excluded.IsEmpty) + if (excluded.Count < 1) { if (dn == null) return excluded; @@ -152,36 +147,32 @@ private ISet UnionDN(ISet excluded, Asn1Sequence dn) excluded.Add(dn); return excluded; } - else - { - ISet union = new HashSet(); - foreach (object obj in excluded) - { - Asn1Sequence subtree = Asn1Sequence.GetInstance(obj); + var union = new HashSet(); - if (WithinDNSubtree(dn, subtree)) - { - union.Add(subtree); - } - else if (WithinDNSubtree(subtree, dn)) - { - union.Add(dn); - } - else - { - union.Add(subtree); - union.Add(dn); - } + foreach (var subtree in excluded) + { + if (WithinDNSubtree(dn, subtree)) + { + union.Add(subtree); + } + else if (WithinDNSubtree(subtree, dn)) + { + union.Add(dn); + } + else + { + union.Add(subtree); + union.Add(dn); } - - return union; } + + return union; } - private ISet IntersectOtherName(ISet permitted, ISet otherNames) + private ISet IntersectOtherName(ISet permitted, ISet otherNames) { - ISet intersect = new HashSet(); + var intersect = new HashSet(); foreach (GeneralSubtree subtree1 in otherNames) { OtherName otherName1 = OtherName.GetInstance(subtree1.Base.Name); @@ -194,12 +185,8 @@ private ISet IntersectOtherName(ISet permitted, ISet otherNames) } else { - foreach (object obj2 in permitted) + foreach (OtherName otherName2 in permitted) { - OtherName otherName2 = OtherName.GetInstance(obj2); - if (otherName2 == null) - continue; - IntersectOtherName(otherName1, otherName2, intersect); } } @@ -207,7 +194,7 @@ private ISet IntersectOtherName(ISet permitted, ISet otherNames) return intersect; } - private void IntersectOtherName(OtherName otherName1, OtherName otherName2, ISet intersect) + private void IntersectOtherName(OtherName otherName1, OtherName otherName2, ISet intersect) { if (otherName1.Equals(otherName2)) { @@ -215,16 +202,16 @@ private void IntersectOtherName(OtherName otherName1, OtherName otherName2, ISet } } - private ISet UnionOtherName(ISet permitted, OtherName otherName) + private ISet UnionOtherName(ISet permitted, OtherName otherName) { - ISet union = permitted != null ? new HashSet(permitted) : new HashSet(); + var union = permitted != null ? new HashSet(permitted) : new HashSet(); union.Add(otherName); return union; } - private ISet IntersectEmail(ISet permitted, ISet emails) + private ISet IntersectEmail(ISet permitted, ISet emails) { - ISet intersect = new HashSet(); + var intersect = new HashSet(); foreach (GeneralSubtree subtree1 in emails) { string email = ExtractNameAsString(subtree1.Base); @@ -247,26 +234,23 @@ private ISet IntersectEmail(ISet permitted, ISet emails) return intersect; } - private ISet UnionEmail(ISet excluded, string email) + private ISet UnionEmail(ISet excluded, string email) { - if (excluded.IsEmpty) + if (excluded.Count < 1) { if (email == null) - { return excluded; - } + excluded.Add(email); return excluded; } - else + + var union = new HashSet(); + foreach (string _excluded in excluded) { - ISet union = new HashSet(); - foreach (string _excluded in excluded) - { - UnionEmail(_excluded, email, union); - } - return union; + UnionEmail(_excluded, email, union); } + return union; } /** @@ -279,9 +263,9 @@ private ISet UnionEmail(ISet excluded, string email) * @return The Set of permitted IP ranges intersected with * ip. */ - private ISet IntersectIP(ISet permitted, ISet ips) + private ISet IntersectIP(ISet permitted, ISet ips) { - ISet intersect = new HashSet(); + var intersect = new HashSet(); foreach (GeneralSubtree subtree in ips) { byte[] ip = Asn1OctetString.GetInstance(subtree.Base.Name).GetOctets(); @@ -296,7 +280,7 @@ private ISet IntersectIP(ISet permitted, ISet ips) { foreach (byte[] _permitted in permitted) { - intersect.AddAll(IntersectIPRange(_permitted, ip)); + intersect.UnionWith(IntersectIPRange(_permitted, ip)); } } } @@ -313,27 +297,23 @@ private ISet IntersectIP(ISet permitted, ISet ips) * @return The Set of excluded IP ranges unified with * ip as byte arrays. */ - private ISet UnionIP(ISet excluded, byte[] ip) + private ISet UnionIP(ISet excluded, byte[] ip) { - if (excluded.IsEmpty) + if (excluded.Count < 1) { if (ip == null) - { return excluded; - } - excluded.Add(ip); + excluded.Add(ip); return excluded; } - else + + var union = new HashSet(); + foreach (byte[] _excluded in excluded) { - ISet union = new HashSet(); - foreach (byte[] _excluded in excluded) - { - union.AddAll(UnionIPRange(_excluded, ip)); - } - return union; + union.UnionWith(UnionIPRange(_excluded, ip)); } + return union; } /** @@ -343,9 +323,9 @@ private ISet UnionIP(ISet excluded, byte[] ip) * @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) + private ISet UnionIPRange(byte[] ipWithSubmask1, byte[] ipWithSubmask2) { - ISet set = new HashSet(); + var set = new HashSet(); // difficult, adding always all IPs is not wrong if (Arrays.AreEqual(ipWithSubmask1, ipWithSubmask2)) { @@ -367,12 +347,12 @@ private ISet UnionIPRange(byte[] ipWithSubmask1, byte[] ipWithSubmask2) * @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) + private ISet IntersectIPRange(byte[] ipWithSubmask1, byte[] ipWithSubmask2) { if (ipWithSubmask1.Length != ipWithSubmask2.Length) { //Collections.EMPTY_SET; - return new HashSet(); + return new HashSet(); } byte[][] temp = ExtractIPsAndSubnetMasks(ipWithSubmask1, ipWithSubmask2); @@ -391,14 +371,14 @@ private ISet IntersectIPRange(byte[] ipWithSubmask1, byte[] ipWithSubmask2) if (CompareTo(min, max) == 1) { //return Collections.EMPTY_SET; - return new HashSet(); + 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(); + //return new HashSet( ICollectionsingleton(IpWithSubnetMask(ip, subnetmask)); + var hs = new HashSet(); hs.Add(IpWithSubnetMask(ip, subnetmask)); return hs; @@ -488,12 +468,10 @@ private bool IsOtherNameConstrained(OtherName constraint, OtherName otherName) return constraint.Equals(otherName); } - private bool IsOtherNameConstrained(ISet constraints, OtherName otherName) + private bool IsOtherNameConstrained(ISet constraints, OtherName otherName) { - foreach (object obj in constraints) + foreach (OtherName constraint in constraints) { - OtherName constraint = OtherName.GetInstance(obj); - if (IsOtherNameConstrained(constraint, otherName)) return true; } @@ -501,22 +479,16 @@ private bool IsOtherNameConstrained(ISet constraints, OtherName otherName) return false; } - private void CheckPermittedOtherName(ISet permitted, OtherName name) + private void CheckPermittedOtherName(ISet permitted, OtherName name) { if (permitted != null && !IsOtherNameConstrained(permitted, name)) - { - throw new PkixNameConstraintValidatorException( - "Subject OtherName is not from a permitted subtree."); - } + throw new PkixNameConstraintValidatorException("Subject OtherName is not from a permitted subtree."); } - private void CheckExcludedOtherName(ISet excluded, OtherName name) + private void CheckExcludedOtherName(ISet excluded, OtherName name) { if (IsOtherNameConstrained(excluded, name)) - { - throw new PkixNameConstraintValidatorException( - "OtherName is from an excluded subtree."); - } + throw new PkixNameConstraintValidatorException("OtherName is from an excluded subtree."); } private bool IsEmailConstrained(string constraint, string email) @@ -525,18 +497,14 @@ private bool IsEmailConstrained(string constraint, string email) // 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))) - { + if (string.Equals(email, constraint, StringComparison.OrdinalIgnoreCase)) return true; - } } // on particular host - else if (!(constraint[0].Equals('.'))) + else if (constraint[0] != '.') { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(sub).Equals(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(constraint))) - { + if (string.Equals(sub, constraint, StringComparison.OrdinalIgnoreCase)) return true; - } } // address in sub domain else if (WithinDomain(sub, constraint)) @@ -546,7 +514,7 @@ private bool IsEmailConstrained(string constraint, string email) return false; } - private bool IsEmailConstrained(ISet constraints, string email) + private bool IsEmailConstrained(ISet constraints, string email) { foreach (string constraint in constraints) { @@ -557,10 +525,10 @@ private bool IsEmailConstrained(ISet constraints, string email) return false; } - private void CheckPermittedEmail(ISet permitted, string email) + private void CheckPermittedEmail(ISet permitted, string email) { if (permitted != null - && !(email.Length == 0 && permitted.IsEmpty) + && !(email.Length == 0 && permitted.Count < 1) && !IsEmailConstrained(permitted, email)) { throw new PkixNameConstraintValidatorException( @@ -568,23 +536,20 @@ private void CheckPermittedEmail(ISet permitted, string email) } } - private void CheckExcludedEmail(ISet excluded, string email) + private void CheckExcludedEmail(ISet excluded, string email) { if (IsEmailConstrained(excluded, email)) - { - throw new PkixNameConstraintValidatorException( - "Email address is from an excluded subtree."); - } + throw new PkixNameConstraintValidatorException("Email address is from an excluded subtree."); } private bool IsDnsConstrained(string constraint, string dns) { - return WithinDomain(dns, constraint) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(dns, constraint); + return WithinDomain(dns, constraint) || Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(dns, constraint); } - private bool IsDnsConstrained(ISet constraints, string dns) + private bool IsDnsConstrained(ISet constraints, string dns) { - foreach (string constraint in constraints) + foreach (var constraint in constraints) { if (IsDnsConstrained(constraint, dns)) return true; @@ -593,32 +558,26 @@ private bool IsDnsConstrained(ISet constraints, string dns) return false; } - private void CheckPermittedDns(ISet permitted, string dns) + private void CheckPermittedDns(ISet permitted, string dns) { if (permitted != null - && !(dns.Length == 0 && permitted.IsEmpty) + && !(dns.Length == 0 && permitted.Count < 1) && !IsDnsConstrained(permitted, dns)) { - throw new PkixNameConstraintValidatorException( - "DNS is not from a permitted subtree."); + throw new PkixNameConstraintValidatorException("DNS is not from a permitted subtree."); } } - private void CheckExcludedDns(ISet excluded, string dns) + private void CheckExcludedDns(ISet excluded, string dns) { if (IsDnsConstrained(excluded, dns)) - { - throw new PkixNameConstraintValidatorException( - "DNS is from an excluded subtree."); - } + throw new PkixNameConstraintValidatorException("DNS is from an excluded subtree."); } - private bool IsDirectoryConstrained(ISet constraints, Asn1Sequence directory) + private bool IsDirectoryConstrained(ISet constraints, Asn1Sequence directory) { - foreach (object obj in constraints) + foreach (var constraint in constraints) { - Asn1Sequence constraint = Asn1Sequence.GetInstance(obj); - if (WithinDNSubtree(directory, constraint)) return true; } @@ -626,10 +585,10 @@ private bool IsDirectoryConstrained(ISet constraints, Asn1Sequence directory) return false; } - private void CheckPermittedDirectory(ISet permitted, Asn1Sequence directory) + private void CheckPermittedDirectory(ISet permitted, Asn1Sequence directory) { if (permitted != null - && !(directory.Count == 0 && permitted.IsEmpty) + && !(directory.Count == 0 && permitted.Count < 1) && !IsDirectoryConstrained(permitted, directory)) { throw new PkixNameConstraintValidatorException( @@ -637,7 +596,7 @@ private void CheckPermittedDirectory(ISet permitted, Asn1Sequence directory) } } - private void CheckExcludedDirectory(ISet excluded, Asn1Sequence directory) + private void CheckExcludedDirectory(ISet excluded, Asn1Sequence directory) { if (IsDirectoryConstrained(excluded, directory)) { @@ -650,17 +609,17 @@ private bool IsUriConstrained(string constraint, string uri) { string host = ExtractHostFromURL(uri); - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(constraint, ".")) + if (Org.BouncyCastle.Utilities.Platform.StartsWith(constraint, ".")) { // in sub domain or domain return WithinDomain(host, constraint); } // a host - return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(host, constraint); + return Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(host, constraint); } - private bool IsUriConstrained(ISet constraints, string uri) + private bool IsUriConstrained(ISet constraints, string uri) { foreach (string constraint in constraints) { @@ -671,24 +630,20 @@ private bool IsUriConstrained(ISet constraints, string uri) return false; } - private void CheckPermittedUri(ISet permitted, string uri) + private void CheckPermittedUri(ISet permitted, string uri) { if (permitted != null - && !(uri.Length == 0 && permitted.IsEmpty) + && !(uri.Length == 0 && permitted.Count < 1) && !IsUriConstrained(permitted, uri)) { - throw new PkixNameConstraintValidatorException( - "URI is not from a permitted subtree."); + throw new PkixNameConstraintValidatorException("URI is not from a permitted subtree."); } } - private void CheckExcludedUri(ISet excluded, string uri) + private void CheckExcludedUri(ISet excluded, string uri) { if (IsUriConstrained(excluded, uri)) - { - throw new PkixNameConstraintValidatorException( - "URI is from an excluded subtree."); - } + throw new PkixNameConstraintValidatorException("URI is from an excluded subtree."); } /** @@ -705,9 +660,7 @@ private bool IsIPConstrained(byte[] constraint, byte[] ip) { int ipLength = ip.Length; if (ipLength != (constraint.Length / 2)) - { return false; - } byte[] subnetMask = new byte[ipLength]; Array.Copy(constraint, ipLength, subnetMask, 0, ipLength); @@ -726,7 +679,7 @@ private bool IsIPConstrained(byte[] constraint, byte[] ip) return Arrays.AreEqual(permittedSubnetAddress, ipSubnetAddress); } - private bool IsIPConstrained(ISet constraints, byte[] ip) + private bool IsIPConstrained(ISet constraints, byte[] ip) { foreach (byte[] constraint in constraints) { @@ -747,14 +700,13 @@ private bool IsIPConstrained(ISet constraints, byte[] ip) * @throws PkixNameConstraintValidatorException * if the IP is not permitted. */ - private void CheckPermittedIP(ISet permitted, byte[] ip) + private void CheckPermittedIP(ISet permitted, byte[] ip) { if (permitted != null - && !(ip.Length == 0 && permitted.IsEmpty) + && !(ip.Length == 0 && permitted.Count < 1) && !IsIPConstrained(permitted, ip)) { - throw new PkixNameConstraintValidatorException( - "IP is not from a permitted subtree."); + throw new PkixNameConstraintValidatorException("IP is not from a permitted subtree."); } } @@ -768,19 +720,16 @@ private void CheckPermittedIP(ISet permitted, byte[] ip) * @throws PkixNameConstraintValidatorException * if the IP is excluded. */ - private void CheckExcludedIP(ISet excluded, byte[] ip) + private void CheckExcludedIP(ISet excluded, byte[] ip) { if (IsIPConstrained(excluded, ip)) - { - throw new PkixNameConstraintValidatorException( - "IP is from an excluded subtree."); - } + throw new PkixNameConstraintValidatorException("IP is from an excluded subtree."); } private bool WithinDomain(string testDomain, string domain) { string tempDomain = domain; - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(tempDomain, ".")) + if (Org.BouncyCastle.Utilities.Platform.StartsWith(tempDomain, ".")) { tempDomain = tempDomain.Substring(1); } @@ -802,7 +751,7 @@ private bool WithinDomain(string testDomain, string domain) return false; } } - else if (!BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(testDomainParts[i + d], domainParts[i])) + else if (!Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(testDomainParts[i + d], domainParts[i])) { return false; } @@ -819,7 +768,7 @@ private bool WithinDomain(string testDomain, string domain) * @param email2 Email address constraint 2. * @param union The union. */ - private void UnionEmail(string email1, string email2, ISet union) + private void UnionEmail(string email1, string email2, ISet union) { // email1 is a particular address if (email1.IndexOf('@') != -1) @@ -828,7 +777,7 @@ private void UnionEmail(string email1, string email2, ISet union) // both are a particular mailbox if (email2.IndexOf('@') != -1) { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) + if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { union.Add(email1); } @@ -839,7 +788,7 @@ private void UnionEmail(string email1, string email2, ISet union) } } // email2 specifies a domain - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(_sub, email2)) { @@ -854,7 +803,7 @@ private void UnionEmail(string email1, string email2, ISet union) // email2 specifies a particular host else { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email2)) + if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email2)) { union.Add(email2); } @@ -866,7 +815,7 @@ private void UnionEmail(string email1, string email2, ISet union) } } // email1 specifies a domain - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email1, ".")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(email1, ".")) { if (email2.IndexOf('@') != -1) { @@ -882,9 +831,9 @@ private void UnionEmail(string email1, string email2, ISet union) } } // email2 specifies a domain - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { - if (WithinDomain(email1, email2) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) + if (WithinDomain(email1, email2) || Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { union.Add(email2); } @@ -917,7 +866,7 @@ private void UnionEmail(string email1, string email2, ISet union) if (email2.IndexOf('@') != -1) { string _sub = email2.Substring(email1.IndexOf('@') + 1); - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email1)) + if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email1)) { union.Add(email1); } @@ -928,7 +877,7 @@ private void UnionEmail(string email1, string email2, ISet union) } } // email2 specifies a domain - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(email1, email2)) { @@ -943,7 +892,7 @@ private void UnionEmail(string email1, string email2, ISet union) // email2 specifies a particular host else { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) + if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { union.Add(email1); } @@ -956,7 +905,7 @@ private void UnionEmail(string email1, string email2, ISet union) } } - private void unionURI(string email1, string email2, ISet union) + private void UnionUri(string email1, string email2, ISet union) { // email1 is a particular address if (email1.IndexOf('@') != -1) @@ -965,7 +914,7 @@ private void unionURI(string email1, string email2, ISet union) // both are a particular mailbox if (email2.IndexOf('@') != -1) { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) + if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { union.Add(email1); } @@ -976,7 +925,7 @@ private void unionURI(string email1, string email2, ISet union) } } // email2 specifies a domain - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(_sub, email2)) { @@ -991,7 +940,7 @@ private void unionURI(string email1, string email2, ISet union) // email2 specifies a particular host else { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email2)) + if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email2)) { union.Add(email2); } @@ -1004,7 +953,7 @@ private void unionURI(string email1, string email2, ISet union) } } // email1 specifies a domain - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email1, ".")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(email1, ".")) { if (email2.IndexOf('@') != -1) { @@ -1020,9 +969,9 @@ private void unionURI(string email1, string email2, ISet union) } } // email2 specifies a domain - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { - if (WithinDomain(email1, email2) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) + if (WithinDomain(email1, email2) || Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { union.Add(email2); } @@ -1055,7 +1004,7 @@ private void unionURI(string email1, string email2, ISet union) if (email2.IndexOf('@') != -1) { string _sub = email2.Substring(email1.IndexOf('@') + 1); - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email1)) + if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email1)) { union.Add(email1); } @@ -1066,7 +1015,7 @@ private void unionURI(string email1, string email2, ISet union) } } // email2 specifies a domain - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(email1, email2)) { @@ -1081,7 +1030,7 @@ private void unionURI(string email1, string email2, ISet union) // email2 specifies a particular host else { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) + if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { union.Add(email1); } @@ -1094,9 +1043,9 @@ private void unionURI(string email1, string email2, ISet union) } } - private ISet IntersectDns(ISet permitted, ISet dnss) + private ISet IntersectDns(ISet permitted, ISet dnss) { - ISet intersect = new HashSet(); + var intersect = new HashSet(); foreach (GeneralSubtree subtree in dnss) { string dns = ExtractNameAsString(subtree.Base); @@ -1122,13 +1071,12 @@ private ISet IntersectDns(ISet permitted, ISet dnss) } } } - return intersect; } - private ISet UnionDns(ISet excluded, string dns) + private ISet UnionDns(ISet excluded, string dns) { - if (excluded.IsEmpty) + if (excluded.Count < 1) { if (dns == null) return excluded; @@ -1136,27 +1084,25 @@ private ISet UnionDns(ISet excluded, string dns) excluded.Add(dns); return excluded; } - else + + var union = new HashSet(); + foreach (string _excluded in excluded) { - ISet union = new HashSet(); - foreach (string _excluded in excluded) + if (WithinDomain(_excluded, dns)) { - if (WithinDomain(_excluded, dns)) - { - union.Add(dns); - } - else if (WithinDomain(dns, _excluded)) - { - union.Add(_excluded); - } - else - { - union.Add(_excluded); - union.Add(dns); - } + union.Add(dns); + } + else if (WithinDomain(dns, _excluded)) + { + union.Add(_excluded); + } + else + { + union.Add(_excluded); + union.Add(dns); } - return union; } + return union; } /** @@ -1167,7 +1113,7 @@ private ISet UnionDns(ISet excluded, string dns) * @param email2 Email address constraint 2. * @param intersect The intersection. */ - private void IntersectEmail(string email1, string email2, ISet intersect) + private void IntersectEmail(string email1, string email2, ISet intersect) { // email1 is a particular address if (email1.IndexOf('@') != -1) @@ -1176,13 +1122,13 @@ private void IntersectEmail(string email1, string email2, ISet intersect) // both are a particular mailbox if (email2.IndexOf('@') != -1) { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) + if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { intersect.Add(email1); } } // email2 specifies a domain - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(_sub, email2)) { @@ -1192,14 +1138,14 @@ private void IntersectEmail(string email1, string email2, ISet intersect) // email2 specifies a particular host else { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email2)) + if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email2)) { intersect.Add(email1); } } } // email specifies a domain - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email1, ".")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(email1, ".")) { if (email2.IndexOf('@') != -1) { @@ -1210,9 +1156,9 @@ private void IntersectEmail(string email1, string email2, ISet intersect) } } // email2 specifies a domain - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { - if (WithinDomain(email1, email2) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) + if (WithinDomain(email1, email2) || Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { intersect.Add(email1); } @@ -1235,13 +1181,13 @@ private void IntersectEmail(string email1, string email2, ISet intersect) if (email2.IndexOf('@') != -1) { string _sub = email2.Substring(email2.IndexOf('@') + 1); - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email1)) + if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email1)) { intersect.Add(email2); } } // email2 specifies a domain - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(email1, email2)) { @@ -1251,7 +1197,7 @@ private void IntersectEmail(string email1, string email2, ISet intersect) // email2 specifies a particular host else { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) + if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { intersect.Add(email1); } @@ -1259,9 +1205,9 @@ private void IntersectEmail(string email1, string email2, ISet intersect) } } - private ISet IntersectUri(ISet permitted, ISet uris) + private ISet IntersectUri(ISet permitted, ISet uris) { - ISet intersect = new HashSet(); + var intersect = new HashSet(); foreach (GeneralSubtree subtree in uris) { string uri = ExtractNameAsString(subtree.Base); @@ -1283,9 +1229,9 @@ private ISet IntersectUri(ISet permitted, ISet uris) return intersect; } - private ISet UnionUri(ISet excluded, string uri) + private ISet UnionUri(ISet excluded, string uri) { - if (excluded.IsEmpty) + if (excluded.Count < 1) { if (uri == null) return excluded; @@ -1293,18 +1239,16 @@ private ISet UnionUri(ISet excluded, string uri) excluded.Add(uri); return excluded; } - else + + var union = new HashSet(); + foreach (string _excluded in excluded) { - ISet union = new HashSet(); - foreach (string _excluded in excluded) - { - unionURI(_excluded, uri, union); - } - return union; + UnionUri(_excluded, uri, union); } + return union; } - private void IntersectUri(string email1, string email2, ISet intersect) + private void IntersectUri(string email1, string email2, ISet intersect) { // email1 is a particular address if (email1.IndexOf('@') != -1) @@ -1313,13 +1257,13 @@ private void IntersectUri(string email1, string email2, ISet intersect) // both are a particular mailbox if (email2.IndexOf('@') != -1) { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) + if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { intersect.Add(email1); } } // email2 specifies a domain - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(_sub, email2)) { @@ -1329,14 +1273,14 @@ private void IntersectUri(string email1, string email2, ISet intersect) // email2 specifies a particular host else { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email2)) + if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email2)) { intersect.Add(email1); } } } // email specifies a domain - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email1, ".")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(email1, ".")) { if (email2.IndexOf('@') != -1) { @@ -1347,9 +1291,9 @@ private void IntersectUri(string email1, string email2, ISet intersect) } } // email2 specifies a domain - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { - if (WithinDomain(email1, email2) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) + if (WithinDomain(email1, email2) || Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { intersect.Add(email1); } @@ -1372,13 +1316,13 @@ private void IntersectUri(string email1, string email2, ISet intersect) if (email2.IndexOf('@') != -1) { string _sub = email2.Substring(email2.IndexOf('@') + 1); - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email1)) + if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(_sub, email1)) { intersect.Add(email2); } } // email2 specifies a domain - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(email2, ".")) { if (WithinDomain(email1, email2)) { @@ -1388,7 +1332,7 @@ private void IntersectUri(string email1, string email2, ISet intersect) // email2 specifies a particular host else { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) + if (Org.BouncyCastle.Utilities.Platform.EqualsIgnoreCase(email1, email2)) { intersect.Add(email1); } @@ -1402,7 +1346,7 @@ private static string ExtractHostFromURL(string url) // 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, "//"); + int idxOfSlashes = Org.BouncyCastle.Utilities.Platform.IndexOf(sub, "//"); if (idxOfSlashes != -1) { sub = sub.Substring(idxOfSlashes + 2); @@ -1442,13 +1386,13 @@ public void checkPermitted(GeneralName name) CheckPermittedEmail(permittedSubtreesEmail, ExtractNameAsString(name)); break; case GeneralName.DnsName: - CheckPermittedDns(permittedSubtreesDNS, ExtractNameAsString(name)); + CheckPermittedDns(permittedSubtreesDns, ExtractNameAsString(name)); break; case GeneralName.DirectoryName: CheckPermittedDN(Asn1Sequence.GetInstance(name.Name.ToAsn1Object())); break; case GeneralName.UniformResourceIdentifier: - CheckPermittedUri(permittedSubtreesURI, ExtractNameAsString(name)); + CheckPermittedUri(permittedSubtreesUri, ExtractNameAsString(name)); break; case GeneralName.IPAddress: CheckPermittedIP(permittedSubtreesIP, Asn1OctetString.GetInstance(name.Name).GetOctets()); @@ -1476,13 +1420,13 @@ public void checkExcluded(GeneralName name) CheckExcludedEmail(excludedSubtreesEmail, ExtractNameAsString(name)); break; case GeneralName.DnsName: - CheckExcludedDns(excludedSubtreesDNS, ExtractNameAsString(name)); + CheckExcludedDns(excludedSubtreesDns, ExtractNameAsString(name)); break; case GeneralName.DirectoryName: CheckExcludedDN(Asn1Sequence.GetInstance(name.Name.ToAsn1Object())); break; case GeneralName.UniformResourceIdentifier: - CheckExcludedUri(excludedSubtreesURI, ExtractNameAsString(name)); + CheckExcludedUri(excludedSubtreesUri, ExtractNameAsString(name)); break; case GeneralName.IPAddress: CheckExcludedIP(excludedSubtreesIP, Asn1OctetString.GetInstance(name.Name).GetOctets()); @@ -1499,50 +1443,47 @@ public void checkExcluded(GeneralName name) public void IntersectPermittedSubtree(Asn1Sequence permitted) { - IDictionary subtreesMap = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + var subtreesMap = new Dictionary>(); // group in ISets in a map ordered by tag no. - foreach (object obj in permitted) + foreach (var element in permitted) { - GeneralSubtree subtree = GeneralSubtree.GetInstance(obj); + GeneralSubtree subtree = GeneralSubtree.GetInstance(element); int tagNo = subtree.Base.TagNo; - if (subtreesMap[tagNo] == null) + + ISet subtrees; + if (!subtreesMap.TryGetValue(tagNo, out subtrees)) { - subtreesMap[tagNo] = new HashSet(); + subtrees = new HashSet(); + subtreesMap[tagNo] = subtrees; } - ((ISet)subtreesMap[tagNo]).Add(subtree); + subtrees.Add(subtree); } - foreach (DictionaryEntry entry in subtreesMap) + foreach (var entry in subtreesMap) { // go through all subtree groups - switch ((int)entry.Key) + switch (entry.Key) { case GeneralName.OtherName: - permittedSubtreesOtherName = IntersectOtherName(permittedSubtreesOtherName, - (ISet)entry.Value); + permittedSubtreesOtherName = IntersectOtherName(permittedSubtreesOtherName, entry.Value); break; case GeneralName.Rfc822Name: - permittedSubtreesEmail = IntersectEmail(permittedSubtreesEmail, - (ISet)entry.Value); + permittedSubtreesEmail = IntersectEmail(permittedSubtreesEmail, entry.Value); break; case GeneralName.DnsName: - permittedSubtreesDNS = IntersectDns(permittedSubtreesDNS, - (ISet)entry.Value); + permittedSubtreesDns = IntersectDns(permittedSubtreesDns, entry.Value); break; case GeneralName.DirectoryName: - permittedSubtreesDN = IntersectDN(permittedSubtreesDN, - (ISet)entry.Value); + permittedSubtreesDN = IntersectDN(permittedSubtreesDN, entry.Value); break; case GeneralName.UniformResourceIdentifier: - permittedSubtreesURI = IntersectUri(permittedSubtreesURI, - (ISet)entry.Value); + permittedSubtreesUri = IntersectUri(permittedSubtreesUri, entry.Value); break; case GeneralName.IPAddress: - permittedSubtreesIP = IntersectIP(permittedSubtreesIP, - (ISet)entry.Value); + permittedSubtreesIP = IntersectIP(permittedSubtreesIP, entry.Value); break; } } @@ -1558,22 +1499,22 @@ public void IntersectEmptyPermittedSubtree(int nameType) switch (nameType) { case GeneralName.OtherName: - permittedSubtreesOtherName = new HashSet(); + permittedSubtreesOtherName = new HashSet(); break; case GeneralName.Rfc822Name: - permittedSubtreesEmail = new HashSet(); + permittedSubtreesEmail = new HashSet(); break; case GeneralName.DnsName: - permittedSubtreesDNS = new HashSet(); + permittedSubtreesDns = new HashSet(); break; case GeneralName.DirectoryName: - permittedSubtreesDN = new HashSet(); + permittedSubtreesDN = new HashSet(); break; case GeneralName.UniformResourceIdentifier: - permittedSubtreesURI = new HashSet(); + permittedSubtreesUri = new HashSet(); break; case GeneralName.IPAddress: - permittedSubtreesIP = new HashSet(); + permittedSubtreesIP = new HashSet(); break; } } @@ -1598,7 +1539,7 @@ public void AddExcludedSubtree(GeneralSubtree subtree) ExtractNameAsString(subTreeBase)); break; case GeneralName.DnsName: - excludedSubtreesDNS = UnionDns(excludedSubtreesDNS, + excludedSubtreesDns = UnionDns(excludedSubtreesDns, ExtractNameAsString(subTreeBase)); break; case GeneralName.DirectoryName: @@ -1606,7 +1547,7 @@ public void AddExcludedSubtree(GeneralSubtree subtree) (Asn1Sequence)subTreeBase.Name.ToAsn1Object()); break; case GeneralName.UniformResourceIdentifier: - excludedSubtreesURI = UnionUri(excludedSubtreesURI, + excludedSubtreesUri = UnionUri(excludedSubtreesUri, ExtractNameAsString(subTreeBase)); break; case GeneralName.IPAddress: @@ -1694,41 +1635,41 @@ private static byte[] Or(byte[] ip1, byte[] ip2) return temp; } - - public int HashCode() - { - return GetHashCode(); - } - public override int GetHashCode() { return HashCollection(excludedSubtreesDN) - + HashCollection(excludedSubtreesDNS) + + HashCollection(excludedSubtreesDns) + HashCollection(excludedSubtreesEmail) + HashCollection(excludedSubtreesIP) - + HashCollection(excludedSubtreesURI) + + HashCollection(excludedSubtreesUri) + HashCollection(excludedSubtreesOtherName) + HashCollection(permittedSubtreesDN) - + HashCollection(permittedSubtreesDNS) + + HashCollection(permittedSubtreesDns) + HashCollection(permittedSubtreesEmail) + HashCollection(permittedSubtreesIP) - + HashCollection(permittedSubtreesURI) + + HashCollection(permittedSubtreesUri) + HashCollection(permittedSubtreesOtherName); } - private int HashCollection(ICollection c) + private int HashCollection(IEnumerable c) { - if (c == null) - return 0; - int hash = 0; - foreach (Object o in c) + if (c != null) { - if (o is byte[]) + foreach (byte[] o in c) { - hash += Arrays.GetHashCode((byte[])o); + hash += Arrays.GetHashCode(o); } - else + } + return hash; + } + + private int HashCollection(IEnumerable c) + { + int hash = 0; + if (c != null) + { + foreach (object o in c) { hash += o.GetHashCode(); } @@ -1736,40 +1677,38 @@ private int HashCollection(ICollection c) return hash; } - public override bool Equals(Object o) + public override bool Equals(object o) { - if (!(o is PkixNameConstraintValidator)) + if (!(o is PkixNameConstraintValidator that)) 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.excludedSubtreesOtherName, excludedSubtreesOtherName) - && CollectionsAreEqual(constraintValidator.permittedSubtreesDN, permittedSubtreesDN) - && CollectionsAreEqual(constraintValidator.permittedSubtreesDNS, permittedSubtreesDNS) - && CollectionsAreEqual(constraintValidator.permittedSubtreesEmail, permittedSubtreesEmail) - && CollectionsAreEqual(constraintValidator.permittedSubtreesIP, permittedSubtreesIP) - && CollectionsAreEqual(constraintValidator.permittedSubtreesURI, permittedSubtreesURI) - && CollectionsAreEqual(constraintValidator.permittedSubtreesOtherName, permittedSubtreesOtherName); + return AreEqualSets(that.excludedSubtreesDN, excludedSubtreesDN) + && AreEqualSets(that.excludedSubtreesDns, excludedSubtreesDns) + && AreEqualSets(that.excludedSubtreesEmail, excludedSubtreesEmail) + && AreEqualSets(that.excludedSubtreesIP, excludedSubtreesIP) + && AreEqualSets(that.excludedSubtreesUri, excludedSubtreesUri) + && AreEqualSets(that.excludedSubtreesOtherName, excludedSubtreesOtherName) + && AreEqualSets(that.permittedSubtreesDN, permittedSubtreesDN) + && AreEqualSets(that.permittedSubtreesDns, permittedSubtreesDns) + && AreEqualSets(that.permittedSubtreesEmail, permittedSubtreesEmail) + && AreEqualSets(that.permittedSubtreesIP, permittedSubtreesIP) + && AreEqualSets(that.permittedSubtreesUri, permittedSubtreesUri) + && AreEqualSets(that.permittedSubtreesOtherName, permittedSubtreesOtherName); } - private bool CollectionsAreEqual(ICollection coll1, ICollection coll2) + private bool AreEqualSets(ISet set1, ISet set2) { - if (coll1 == coll2) + if (set1 == set2) return true; - if (coll1 == null || coll2 == null || coll1.Count != coll2.Count) + if (set1 == null || set2 == null || set1.Count != set2.Count) return false; - foreach (Object a in coll1) + foreach (byte[] a in set1) { bool found = false; - foreach (Object b in coll2) + foreach (byte[] b in set2) { - if (SpecialEquals(a, b)) + if (Arrays.AreEqual(a, b)) { found = true; break; @@ -1782,24 +1721,19 @@ private bool CollectionsAreEqual(ICollection coll1, ICollection coll2) return true; } - private bool SpecialEquals(Object o1, Object o2) + private bool AreEqualSets(ISet set1, ISet set2) { - if (o1 == o2) - { + if (set1 == set2) return true; - } - if (o1 == null || o2 == null) - { + if (set1 == null || set2 == null || set1.Count != set2.Count) return false; - } - if ((o1 is byte[]) && (o2 is byte[])) - { - return Arrays.AreEqual((byte[])o1, (byte[])o2); - } - else + + foreach (T a in set1) { - return o1.Equals(o2); + if (!set2.Contains(a)) + return false; } + return true; } /** @@ -1813,21 +1747,19 @@ 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) + private string StringifyIPCollection(ISet ips) { string temp = ""; temp += "["; @@ -1843,99 +1775,84 @@ private string StringifyIPCollection(ISet ips) return temp; } - private string StringifyOtherNameCollection(ISet otherNames) + private string StringifyOtherNameCollection(ISet otherNames) { - string temp = ""; - temp += "["; - foreach (object obj in otherNames) + StringBuilder sb = new StringBuilder('['); + foreach (OtherName name in otherNames) { - OtherName name = OtherName.GetInstance(obj); - if (temp.Length > 1) - { - temp += ","; - } - temp += name.TypeID.Id; - temp += ":"; - try - { - temp += Hex.ToHexString(name.Value.ToAsn1Object().GetEncoded()); - } - catch (IOException e) + if (sb.Length > 1) { - temp += e.ToString(); + sb.Append(','); } + sb.Append(name.TypeID.Id); + sb.Append(':'); + sb.Append(Hex.ToHexString(name.Value.GetEncoded())); } - temp += "]"; - return temp; + sb.Append(']'); + return sb.ToString(); } public override string ToString() { - string temp = ""; - - temp += "permitted:\n"; + StringBuilder sb = new StringBuilder("permitted:\n"); if (permittedSubtreesDN != null) { - temp += "DN:\n"; - temp += permittedSubtreesDN.ToString() + "\n"; + Append(sb, "DN", permittedSubtreesDN); } - if (permittedSubtreesDNS != null) + if (permittedSubtreesDns != null) { - temp += "DNS:\n"; - temp += permittedSubtreesDNS.ToString() + "\n"; + Append(sb, "DNS", permittedSubtreesDns); } if (permittedSubtreesEmail != null) { - temp += "Email:\n"; - temp += permittedSubtreesEmail.ToString() + "\n"; + Append(sb, "Email", permittedSubtreesEmail); } - if (permittedSubtreesURI != null) + if (permittedSubtreesUri != null) { - temp += "URI:\n"; - temp += permittedSubtreesURI.ToString() + "\n"; + Append(sb, "URI", permittedSubtreesUri); } if (permittedSubtreesIP != null) { - temp += "IP:\n"; - temp += StringifyIPCollection(permittedSubtreesIP) + "\n"; + Append(sb, "IP", StringifyIPCollection(permittedSubtreesIP)); } if (permittedSubtreesOtherName != null) { - temp += "OtherName:\n"; - temp += StringifyOtherNameCollection(permittedSubtreesOtherName); + Append(sb, "OtherName", StringifyOtherNameCollection(permittedSubtreesOtherName)); } - temp += "excluded:\n"; - if (!(excludedSubtreesDN.IsEmpty)) + sb.Append("excluded:\n"); + if (excludedSubtreesDN.Count > 0) { - temp += "DN:\n"; - temp += excludedSubtreesDN.ToString() + "\n"; + Append(sb, "DN", excludedSubtreesDN); } - if (!excludedSubtreesDNS.IsEmpty) + if (excludedSubtreesDns.Count > 0) { - temp += "DNS:\n"; - temp += excludedSubtreesDNS.ToString() + "\n"; + Append(sb, "DNS", excludedSubtreesDns); } - if (!excludedSubtreesEmail.IsEmpty) + if (excludedSubtreesEmail.Count > 0) { - temp += "Email:\n"; - temp += excludedSubtreesEmail.ToString() + "\n"; + Append(sb, "Email", excludedSubtreesEmail); } - if (!excludedSubtreesURI.IsEmpty) + if (excludedSubtreesUri.Count > 0) { - temp += "URI:\n"; - temp += excludedSubtreesURI.ToString() + "\n"; + Append(sb, "URI", excludedSubtreesUri); } - if (!excludedSubtreesIP.IsEmpty) + if (excludedSubtreesIP.Count > 0) { - temp += "IP:\n"; - temp += StringifyIPCollection(excludedSubtreesIP) + "\n"; + Append(sb, "IP", StringifyIPCollection(excludedSubtreesIP)); } - if (!excludedSubtreesOtherName.IsEmpty) + if (excludedSubtreesOtherName.Count > 0) { - temp += "OtherName:\n"; - temp += StringifyOtherNameCollection(excludedSubtreesOtherName); + Append(sb, "OtherName", StringifyOtherNameCollection(excludedSubtreesOtherName)); } - return temp; + return sb.ToString(); + } + + private static void Append(StringBuilder sb, string name, object value) + { + sb.Append(name); + sb.AppendLine(":"); + sb.Append(value); + sb.AppendLine(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixNameConstraintValidatorException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixNameConstraintValidatorException.cs index 89157ed..822aff3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixNameConstraintValidatorException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixNameConstraintValidatorException.cs @@ -1,19 +1,33 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; 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) - { - } + public PkixNameConstraintValidatorException() + : base() + { + } + + public PkixNameConstraintValidatorException(string message) + : base(message) + { + } + + public PkixNameConstraintValidatorException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected PkixNameConstraintValidatorException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixParameters.cs index 45e20bc..5956da2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixParameters.cs @@ -1,12 +1,10 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; -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; +using BestHTTP.SecureProtocol.Org.BouncyCastle.X509; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix { @@ -14,7 +12,6 @@ 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 @@ -41,25 +38,29 @@ public class PkixParameters */ public const int ChainValidityModel = 1; - private ISet trustAnchors; - private DateTimeObject date; - private IList certPathCheckers; + private HashSet trustAnchors; + private DateTime? date; + private List m_checkers; private bool revocationEnabled = true; - private ISet initialPolicies; + private HashSet 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 List> m_storesAttrCert; + private List> m_storesCert; + private List> m_storesCrl; + + private ISelector m_targetConstraintsAttrCert; + private ISelector m_targetConstraintsCert; + private bool additionalLocationsEnabled; - private IList additionalStores; - private ISet trustedACIssuers; - private ISet necessaryACAttributes; - private ISet prohibitedACAttributes; - private ISet attrCertCheckers; + private ISet trustedACIssuers; + private ISet necessaryACAttributes; + private ISet prohibitedACAttributes; + private ISet attrCertCheckers; private int validityModel = PkixValidityModel; private bool useDeltas = false; @@ -81,19 +82,19 @@ public class PkixParameters * if any of the elements in the Set are not of type * java.security.cert.TrustAnchor */ - public PkixParameters( - ISet trustAnchors) + 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(); + this.initialPolicies = new HashSet(); + this.m_checkers = new List(); + this.m_storesAttrCert = new List>(); + this.m_storesCert = new List>(); + this.m_storesCrl = new List>(); + this.trustedACIssuers = new HashSet(); + this.necessaryACAttributes = new HashSet(); + this.prohibitedACAttributes = new HashSet(); + this.attrCertCheckers = new HashSet(); } // // TODO implement for other keystores (see Java build)? @@ -174,30 +175,29 @@ public virtual bool IsPolicyQualifiersRejected // set { this.checkOnlyEECertificateCrl = value; } //} - public virtual DateTimeObject Date + public virtual DateTime? Date { get { return this.date; } set { this.date = value; } } // Returns a Set of the most-trusted CAs. - public virtual ISet GetTrustAnchors() + public virtual ISet GetTrustAnchors() { - return new HashSet(this.trustAnchors); + 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) + public virtual void SetTrustAnchors(ISet tas) { if (tas == null) throw new ArgumentNullException("value"); - if (tas.IsEmpty) + if (tas.Count < 1) throw new ArgumentException("non-empty set required", "value"); // Explicit copy to enforce type-safety - this.trustAnchors = new HashSet(); + this.trustAnchors = new HashSet(); foreach (TrustAnchor ta in tas) { if (ta != null) @@ -207,6 +207,55 @@ public virtual void SetTrustAnchors( } } + /** + * 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 ISelector GetTargetConstraintsAttrCert() + { + return (ISelector)m_targetConstraintsAttrCert?.Clone(); + } + + /** + * 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 SetTargetConstraintsAttrCert(ISelector targetConstraintsAttrCert) + { + this.m_targetConstraintsAttrCert = (ISelector)targetConstraintsAttrCert?.Clone(); + } + /** * Returns the required constraints on the target certificate. The * constraints are returned as an instance of CertSelector. If @@ -220,14 +269,9 @@ public virtual void SetTrustAnchors( * * @see #setTargetCertConstraints(CertSelector) */ - public virtual X509CertStoreSelector GetTargetCertConstraints() + public virtual ISelector GetTargetConstraintsCert() { - if (certSelector == null) - { - return null; - } - - return (X509CertStoreSelector)certSelector.Clone(); + return (ISelector)m_targetConstraintsCert?.Clone(); } /** @@ -244,17 +288,9 @@ public virtual X509CertStoreSelector GetTargetCertConstraints() * * @see #getTargetCertConstraints() */ - public virtual void SetTargetCertConstraints( - IX509Selector selector) + public virtual void SetTargetConstraintsCert(ISelector targetConstraintsCert) { - if (selector == null) - { - certSelector = null; - } - else - { - certSelector = (IX509Selector)selector.Clone(); - } + m_targetConstraintsCert = (ISelector)targetConstraintsCert?.Clone(); } /** @@ -270,17 +306,13 @@ public virtual void SetTargetCertConstraints( * * @see #setInitialPolicies(java.util.Set) */ - public virtual ISet GetInitialPolicies() + public virtual ISet GetInitialPolicies() { - ISet returnSet = initialPolicies; - // TODO Can it really be null? if (initialPolicies == null) - { - returnSet = new HashSet(); - } + return new HashSet(); - return new HashSet(returnSet); + return new HashSet(initialPolicies); } /** @@ -304,10 +336,9 @@ public virtual ISet GetInitialPolicies() * * @see #getInitialPolicies() */ - public virtual void SetInitialPolicies( - ISet initialPolicies) + public virtual void SetInitialPolicies(ISet initialPolicies) { - this.initialPolicies = new HashSet(); + this.initialPolicies = new HashSet(); if (initialPolicies != null) { foreach (string obj in initialPolicies) @@ -355,14 +386,15 @@ public virtual void SetInitialPolicies( * java.security.cert.PKIXCertPathChecker * @see #getCertPathCheckers() */ - public virtual void SetCertPathCheckers(IList checkers) + public virtual void SetCertPathCheckers(IList checkers) { - certPathCheckers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + m_checkers = new List(); + if (checkers != null) { - foreach (PkixCertPathChecker obj in checkers) + foreach (var checker in checkers) { - certPathCheckers.Add(obj.Clone()); + m_checkers.Add((PkixCertPathChecker)checker.Clone()); } } } @@ -376,14 +408,14 @@ public virtual void SetCertPathCheckers(IList checkers) * * @see #setCertPathCheckers(java.util.List) */ - public virtual IList GetCertPathCheckers() + public virtual IList GetCertPathCheckers() { - IList checkers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); - foreach (PkixCertPathChecker obj in certPathCheckers) - { - checkers.Add(obj.Clone()); + var result = new List(m_checkers.Count); + foreach (var checker in m_checkers) + { + result.Add((PkixCertPathChecker)checker.Clone()); } - return checkers; + return result; } /** @@ -397,12 +429,11 @@ public virtual IList GetCertPathCheckers() * @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) + public virtual void AddCertPathChecker(PkixCertPathChecker checker) { if (checker != null) { - certPathCheckers.Add(checker.Clone()); + m_checkers.Add((PkixCertPathChecker)checker.Clone()); } } @@ -449,8 +480,7 @@ public virtual object Clone() * @param params Parameters to set. If this are * ExtendedPkixParameters they are copied to. */ - protected virtual void SetParams( - PkixParameters parameters) + protected virtual void SetParams(PkixParameters parameters) { Date = parameters.Date; SetCertPathCheckers(parameters.GetCertPathCheckers()); @@ -460,20 +490,22 @@ protected virtual void SetParams( IsRevocationEnabled = parameters.IsRevocationEnabled; SetInitialPolicies(parameters.GetInitialPolicies()); IsPolicyQualifiersRejected = parameters.IsPolicyQualifiersRejected; - SetTargetCertConstraints(parameters.GetTargetCertConstraints()); SetTrustAnchors(parameters.GetTrustAnchors()); + m_storesAttrCert = new List>(parameters.m_storesAttrCert); + m_storesCert = new List>(parameters.m_storesCert); + m_storesCrl = new List>(parameters.m_storesCrl); + + SetTargetConstraintsAttrCert(parameters.GetTargetConstraintsAttrCert()); + SetTargetConstraintsCert(parameters.GetTargetConstraintsCert()); + 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); + trustedACIssuers = new HashSet(parameters.trustedACIssuers); + prohibitedACAttributes = new HashSet(parameters.prohibitedACAttributes); + necessaryACAttributes = new HashSet(parameters.necessaryACAttributes); + attrCertCheckers = new HashSet(parameters.attrCertCheckers); } /** @@ -497,115 +529,79 @@ public virtual int 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) + public virtual IList> GetStoresAttrCert() { - if (stores == null) + return new List>(m_storesAttrCert); + } + + public virtual IList> GetStoresCert() + { + return new List>(m_storesCert); + } + + public virtual IList> GetStoresCrl() + { + return new List>(m_storesCrl); + } + + public virtual void SetAttrStoresCert(IList> storesAttrCert) + { + if (storesAttrCert == null) { - this.stores = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + m_storesAttrCert = new List>(); } 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); + m_storesAttrCert = new List>(storesAttrCert); } } - /** - * 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) + public virtual void SetStoresCert(IList> storesCert) { - if (store != null) + if (storesCert == null) { - stores.Add(store); + m_storesCert = new List>(); + } + else + { + m_storesCert = new List>(storesCert); } } - /** - * 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) + public virtual void SetStoresCrl(IList> storesCrl) { - if (store != null) + if (storesCrl == null) + { + m_storesCrl = new List>(); + } + else { - additionalStores.Add(store); + m_storesCrl = new List>(storesCrl); } } - /** - * 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() + public virtual void AddStoreAttrCert(IStore storeAttrCert) + { + if (storeAttrCert != null) + { + m_storesAttrCert.Add(storeAttrCert); + } + } + + public virtual void AddStoreCert(IStore storeCert) { - return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(additionalStores); + if (storeCert != null) + { + m_storesCert.Add(storeCert); + } } - /** - * 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() + public virtual void AddStoreCrl(IStore storeCrl) { - return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(stores); + if (storeCrl != null) + { + m_storesCrl.Add(storeCrl); + } } /** @@ -631,69 +627,6 @@ public virtual void SetAdditionalLocationsEnabled( 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. @@ -705,9 +638,9 @@ public virtual void SetTargetConstraints(IX509Selector selector) * * @return Returns an immutable set of the trusted AC issuers. */ - public virtual ISet GetTrustedACIssuers() + public virtual ISet GetTrustedACIssuers() { - return new HashSet(trustedACIssuers); + return new HashSet(trustedACIssuers); } /** @@ -725,24 +658,15 @@ public virtual ISet GetTrustedACIssuers() * @throws ClassCastException if an element of stores is not * a TrustAnchor. */ - public virtual void SetTrustedACIssuers( - ISet trustedACIssuers) + public virtual void SetTrustedACIssuers(ISet trustedACIssuers) { if (trustedACIssuers == null) { - this.trustedACIssuers = new HashSet(); + 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); + this.trustedACIssuers = new HashSet(trustedACIssuers); } } @@ -756,9 +680,9 @@ public virtual void SetTrustedACIssuers( * * @return Returns the necessary AC attributes. */ - public virtual ISet GetNecessaryACAttributes() + public virtual ISet GetNecessaryACAttributes() { - return new HashSet(necessaryACAttributes); + return new HashSet(necessaryACAttributes); } /** @@ -775,24 +699,15 @@ public virtual ISet GetNecessaryACAttributes() * necessaryACAttributes is not a * String. */ - public virtual void SetNecessaryACAttributes( - ISet necessaryACAttributes) + public virtual void SetNecessaryACAttributes(ISet necessaryACAttributes) { if (necessaryACAttributes == null) { - this.necessaryACAttributes = new HashSet(); + 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); + this.necessaryACAttributes = new HashSet(necessaryACAttributes); } } @@ -805,9 +720,9 @@ public virtual void SetNecessaryACAttributes( * * @return Returns the prohibited AC attributes. Is never null. */ - public virtual ISet GetProhibitedACAttributes() + public virtual ISet GetProhibitedACAttributes() { - return new HashSet(prohibitedACAttributes); + return new HashSet(prohibitedACAttributes); } /** @@ -824,24 +739,15 @@ public virtual ISet GetProhibitedACAttributes() * prohibitedACAttributes is not a * String. */ - public virtual void SetProhibitedACAttributes( - ISet prohibitedACAttributes) + public virtual void SetProhibitedACAttributes(ISet prohibitedACAttributes) { if (prohibitedACAttributes == null) { - this.prohibitedACAttributes = new HashSet(); + 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); + this.prohibitedACAttributes = new HashSet(prohibitedACAttributes); } } @@ -852,9 +758,9 @@ public virtual void SetProhibitedACAttributes( * @return Returns the attribute certificate checker. Is never * null. */ - public virtual ISet GetAttrCertCheckers() + public virtual ISet GetAttrCertCheckers() { - return new HashSet(attrCertCheckers); + return new HashSet(attrCertCheckers); } /** @@ -871,24 +777,15 @@ public virtual ISet GetAttrCertCheckers() * @throws ClassCastException if an element of attrCertCheckers * is not a PKIXAttrCertChecker. */ - public virtual void SetAttrCertCheckers( - ISet attrCertCheckers) + public virtual void SetAttrCertCheckers(ISet attrCertCheckers) { if (attrCertCheckers == null) { - this.attrCertCheckers = new HashSet(); + 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); + this.attrCertCheckers = new HashSet(attrCertCheckers); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixPolicyNode.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixPolicyNode.cs index 60a58c3..f736c18 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixPolicyNode.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/PkixPolicyNode.cs @@ -1,9 +1,10 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.Text; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; @@ -15,11 +16,11 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix public class PkixPolicyNode // : IPolicyNode { - protected IList mChildren; + protected IList mChildren; protected int mDepth; - protected ISet mExpectedPolicies; + protected ISet mExpectedPolicies; protected PkixPolicyNode mParent; - protected ISet mPolicyQualifiers; + protected ISet mPolicyQualifiers; protected string mValidPolicy; protected bool mCritical; @@ -28,9 +29,9 @@ public virtual int Depth get { return this.mDepth; } } - public virtual IEnumerable Children + public virtual IEnumerable Children { - get { return new EnumerableProxy(mChildren); } + get { return CollectionUtilities.Proxy(mChildren); } } public virtual bool IsCritical @@ -39,9 +40,9 @@ public virtual bool IsCritical set { this.mCritical = value; } } - public virtual ISet PolicyQualifiers + public virtual ISet PolicyQualifiers { - get { return new HashSet(this.mPolicyQualifiers); } + get { return new HashSet(this.mPolicyQualifiers); } } public virtual string ValidPolicy @@ -54,10 +55,10 @@ public virtual bool HasChildren get { return mChildren.Count != 0; } } - public virtual ISet ExpectedPolicies + public virtual ISet ExpectedPolicies { - get { return new HashSet(this.mExpectedPolicies); } - set { this.mExpectedPolicies = new HashSet(value); } + get { return new HashSet(this.mExpectedPolicies); } + set { this.mExpectedPolicies = new HashSet(value); } } public virtual PkixPolicyNode Parent @@ -68,21 +69,21 @@ public virtual PkixPolicyNode Parent /// Constructors public PkixPolicyNode( - IList children, + IEnumerable children, int depth, - ISet expectedPolicies, + ISet expectedPolicies, PkixPolicyNode parent, - ISet policyQualifiers, + ISet policyQualifiers, string validPolicy, bool critical) { if (children == null) { - this.mChildren = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + this.mChildren = new List(); } else { - this.mChildren = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(children); + this.mChildren = new List(children); } this.mDepth = depth; @@ -111,14 +112,12 @@ public override string ToString() return ToString(""); } - public virtual string ToString( - string indent) + 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); + buf.AppendLine(" {"); foreach (PkixPolicyNode child in mChildren) { @@ -126,8 +125,7 @@ public virtual string ToString( } buf.Append(indent); - buf.Append("}"); - buf.Append(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine); + buf.AppendLine("}"); return buf.ToString(); } @@ -139,11 +137,11 @@ public virtual object Clone() public virtual PkixPolicyNode Copy() { PkixPolicyNode node = new PkixPolicyNode( - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(), + new List(), mDepth, - new HashSet(mExpectedPolicies), + new HashSet(mExpectedPolicies), null, - new HashSet(mPolicyQualifiers), + new HashSet(mPolicyQualifiers), mValidPolicy, mCritical); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/Rfc3280CertPathUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/Rfc3280CertPathUtilities.cs index f9cad4c..190986f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/Rfc3280CertPathUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/Rfc3280CertPathUtilities.cs @@ -1,8 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; -using System.Globalization; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; @@ -13,13 +12,12 @@ 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 + internal static class Rfc3280CertPathUtilities { private static readonly PkixCrlUtilities CrlUtilities = new PkixCrlUtilities(); @@ -60,12 +58,9 @@ public class Rfc3280CertPathUtilities * @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) + internal static void ProcessCrlB2(DistributionPoint dp, object cert, X509Crl crl) { - IssuingDistributionPoint idp = null; + IssuingDistributionPoint idp; try { idp = IssuingDistributionPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(crl, X509Extensions.IssuingDistributionPoint)); @@ -74,6 +69,7 @@ internal static void ProcessCrlB2( { throw new Exception("0 Issuing distribution point extension could not be decoded.", e); } + // (b) (2) (i) // distribution point name is present if (idp != null) @@ -82,7 +78,7 @@ internal static void ProcessCrlB2( { // make list of names DistributionPointName dpName = IssuingDistributionPoint.GetInstance(idp).DistributionPoint; - IList names = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var names = new List(); if (dpName.PointType == DistributionPointName.FullName) { @@ -94,21 +90,15 @@ internal static void ProcessCrlB2( } 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) + var seq = Asn1Sequence.GetInstance(crl.IssuerDN.ToAsn1Object()); + + Asn1EncodableVector vec = new Asn1EncodableVector(seq.Count + 1); + foreach (var element in seq) { - throw new Exception("Could not read CRL issuer.", e); + vec.Add(element); } vec.Add(dpName.Name); + names.Add(new GeneralName(X509Name.GetInstance(new DerSequence(vec)))); } bool matches = false; @@ -143,13 +133,15 @@ internal static void ProcessCrlB2( } for (int j = 0; j < genNames.Length; j++) { - IEnumerator e = Asn1Sequence.GetInstance(genNames[j].Name.ToAsn1Object()).GetEnumerator(); - Asn1EncodableVector vec = new Asn1EncodableVector(); - while (e.MoveNext()) + var seq = Asn1Sequence.GetInstance(genNames[j].Name.ToAsn1Object()); + + Asn1EncodableVector vec = new Asn1EncodableVector(seq.Count + 1); + foreach (var element in seq) { - vec.Add((Asn1Encodable)e.Current); + vec.Add(element); } vec.Add(dpName.Name); + genNames[j] = new GeneralName(X509Name.GetInstance(new DerSequence(vec))); } } @@ -230,14 +222,14 @@ internal static void ProcessCrlB2( } } + /// internal static void ProcessCertBC( PkixCertPath certPath, int index, PkixNameConstraintValidator nameConstraintValidator) - //throws CertPathValidatorException { - IList certs = certPath.Certificates; - X509Certificate cert = (X509Certificate)certs[index]; + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; int n = certs.Count; // i as defined in the algorithm description int i = n - index; @@ -256,7 +248,7 @@ internal static void ProcessCertBC( catch (Exception e) { throw new PkixCertPathValidatorException( - "Exception extracting subject name when checking subtrees.", e, certPath, index); + "Exception extracting subject name when checking subtrees.", e, index); } try @@ -267,7 +259,7 @@ internal static void ProcessCertBC( catch (PkixNameConstraintValidatorException e) { throw new PkixCertPathValidatorException( - "Subtree check for certificate subject failed.", e, certPath, index); + "Subtree check for certificate subject failed.", e, index); } GeneralNames altName = null; @@ -279,10 +271,10 @@ internal static void ProcessCertBC( catch (Exception e) { throw new PkixCertPathValidatorException( - "Subject alternative name extension could not be decoded.", e, certPath, index); + "Subject alternative name extension could not be decoded.", e, index); } - IList emails = X509Name.GetInstance(dns).GetValueList(X509Name.EmailAddress); + var emails = X509Name.GetInstance(dns).GetValueList(X509Name.EmailAddress); foreach (string email in emails) { GeneralName emailAsGeneralName = new GeneralName(GeneralName.Rfc822Name, email); @@ -294,7 +286,7 @@ internal static void ProcessCertBC( catch (PkixNameConstraintValidatorException ex) { throw new PkixCertPathValidatorException( - "Subtree check for certificate subject alternative email failed.", ex, certPath, index); + "Subtree check for certificate subject alternative email failed.", ex, index); } } if (altName != null) @@ -307,7 +299,7 @@ internal static void ProcessCertBC( catch (Exception e) { throw new PkixCertPathValidatorException( - "Subject alternative name contents could not be decoded.", e, certPath, index); + "Subject alternative name contents could not be decoded.", e, index); } foreach (GeneralName genName in genNames) { @@ -319,25 +311,23 @@ internal static void ProcessCertBC( catch (PkixNameConstraintValidatorException e) { throw new PkixCertPathValidatorException( - "Subtree check for certificate subject alternative name failed.", e, certPath, index); + "Subtree check for certificate subject alternative name failed.", e, index); } } } } } - internal static void PrepareNextCertA( - PkixCertPath certPath, - int index) - //throws CertPathValidatorException + /// + internal static void PrepareNextCertA(PkixCertPath certPath, int index) { - IList certs = certPath.Certificates; - X509Certificate cert = (X509Certificate)certs[index]; + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; // // // (a) check the policy mappings // - Asn1Sequence pm = null; + Asn1Sequence pm; try { pm = Asn1Sequence.GetInstance( @@ -346,7 +336,7 @@ internal static void PrepareNextCertA( catch (Exception ex) { throw new PkixCertPathValidatorException( - "Policy mappings extension could not be decoded.", ex, certPath, index); + "Policy mappings extension could not be decoded.", ex, index); } if (pm != null) { @@ -354,8 +344,8 @@ internal static void PrepareNextCertA( for (int j = 0; j < mappings.Count; j++) { - DerObjectIdentifier issuerDomainPolicy = null; - DerObjectIdentifier subjectDomainPolicy = null; + DerObjectIdentifier issuerDomainPolicy; + DerObjectIdentifier subjectDomainPolicy; try { Asn1Sequence mapping = Asn1Sequence.GetInstance(mappings[j]); @@ -366,31 +356,26 @@ internal static void PrepareNextCertA( catch (Exception e) { throw new PkixCertPathValidatorException( - "Policy mappings extension contents could not be decoded.", e, certPath, index); + "Policy mappings extension contents could not be decoded.", e, index); } - if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(issuerDomainPolicy.Id)) + if (ANY_POLICY.Equals(issuerDomainPolicy.Id)) throw new PkixCertPathValidatorException( - "IssuerDomainPolicy is anyPolicy", null, certPath, index); + "IssuerDomainPolicy is anyPolicy", null, index); - if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(subjectDomainPolicy.Id)) + if (ANY_POLICY.Equals(subjectDomainPolicy.Id)) throw new PkixCertPathValidatorException( - "SubjectDomainPolicy is anyPolicy,", null, certPath, index); + "SubjectDomainPolicy is anyPolicy,", null, index); } } } - internal static PkixPolicyNode ProcessCertD( - PkixCertPath certPath, - int index, - ISet acceptablePolicies, - PkixPolicyNode validPolicyTree, - IList[] policyNodes, - int inhibitAnyPolicy) - //throws CertPathValidatorException + /// + internal static PkixPolicyNode ProcessCertD(PkixCertPath certPath, int index, ISet acceptablePolicies, + PkixPolicyNode validPolicyTree, IList[] policyNodes, int inhibitAnyPolicy) { - IList certs = certPath.Certificates; - X509Certificate cert = (X509Certificate)certs[index]; + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; int n = certs.Count; // i as defined in the algorithm description int i = n - index; @@ -398,7 +383,7 @@ internal static PkixPolicyNode ProcessCertD( // (d) policy Information checking against initial policy and // policy mapping // - Asn1Sequence certPolicies = null; + Asn1Sequence certPolicies; try { certPolicies = Asn1Sequence.GetInstance( @@ -407,14 +392,14 @@ internal static PkixPolicyNode ProcessCertD( catch (Exception e) { throw new PkixCertPathValidatorException( - "Could not read certificate policies extension from certificate.", e, certPath, index); + "Could not read certificate policies extension from certificate.", e, index); } if (certPolicies != null && validPolicyTree != null) { // // (d) (1) // - ISet pols = new HashSet(); + var pols = new HashSet(); foreach (Asn1Encodable ae in certPolicies) { @@ -423,9 +408,9 @@ internal static PkixPolicyNode ProcessCertD( pols.Add(pOid.Id); - if (!Rfc3280CertPathUtilities.ANY_POLICY.Equals(pOid.Id)) + if (!ANY_POLICY.Equals(pOid.Id)) { - ISet pq = null; + ISet pq; try { pq = PkixCertPathValidatorUtilities.GetQualifierSet(pInfo.PolicyQualifiers); @@ -433,7 +418,7 @@ internal static PkixPolicyNode ProcessCertD( catch (PkixCertPathValidatorException ex) { throw new PkixCertPathValidatorException( - "Policy qualifier info set could not be build.", ex, certPath, index); + "Policy qualifier info set could not be build.", ex, index); } bool match = PkixCertPathValidatorUtilities.ProcessCertD1i(i, policyNodes, pOid, pq); @@ -445,16 +430,16 @@ internal static PkixPolicyNode ProcessCertD( } } - if (acceptablePolicies.IsEmpty || acceptablePolicies.Contains(Rfc3280CertPathUtilities.ANY_POLICY)) + if (acceptablePolicies.Count < 1 || acceptablePolicies.Contains(ANY_POLICY)) { acceptablePolicies.Clear(); - acceptablePolicies.AddAll(pols); + acceptablePolicies.UnionWith(pols); } else { - ISet t1 = new HashSet(); + var t1 = new HashSet(); - foreach (object o in acceptablePolicies) + foreach (var o in acceptablePolicies) { if (pols.Contains(o)) { @@ -462,7 +447,7 @@ internal static PkixPolicyNode ProcessCertD( } } acceptablePolicies.Clear(); - acceptablePolicies.AddAll(t1); + acceptablePolicies.UnionWith(t1); } // @@ -473,34 +458,14 @@ internal static PkixPolicyNode ProcessCertD( foreach (Asn1Encodable ae in certPolicies) { PolicyInformation pInfo = PolicyInformation.GetInstance(ae.ToAsn1Object()); - if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(pInfo.PolicyIdentifier.Id)) + if (ANY_POLICY.Equals(pInfo.PolicyIdentifier.Id)) { - ISet _apq = PkixCertPathValidatorUtilities.GetQualifierSet(pInfo.PolicyQualifiers); - IList _nodes = policyNodes[i - 1]; + var _apq = PkixCertPathValidatorUtilities.GetQualifierSet(pInfo.PolicyQualifiers); - for (int k = 0; k < _nodes.Count; k++) + foreach (var _node in policyNodes[i - 1]) { - PkixPolicyNode _node = (PkixPolicyNode)_nodes[k]; - - IEnumerator _policySetIter = _node.ExpectedPolicies.GetEnumerator(); - while (_policySetIter.MoveNext()) + foreach (var _policy in _node.ExpectedPolicies) { - 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) @@ -508,15 +473,16 @@ internal static PkixPolicyNode ProcessCertD( if (_policy.Equals(_child.ValidPolicy)) { _found = true; + break; } } if (!_found) { - ISet _newChildExpectedPolicies = new HashSet(); + var _newChildExpectedPolicies = new HashSet(); _newChildExpectedPolicies.Add(_policy); - PkixPolicyNode _newChild = new PkixPolicyNode(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(), i, + var _newChild = new PkixPolicyNode(new List(), i, _newChildExpectedPolicies, _node, _apq, _policy, false); _node.AddChild(_newChild); policyNodes[i].Add(_newChild); @@ -532,21 +498,19 @@ internal static PkixPolicyNode ProcessCertD( // // (d) (3) // - for (int j = (i - 1); j >= 0; j--) + for (int j = i - 1; j >= 0; j--) { - IList nodes = policyNodes[j]; + var nodes = policyNodes[j]; for (int k = 0; k < nodes.Count; k++) { - PkixPolicyNode node = (PkixPolicyNode)nodes[k]; + var node = nodes[k]; if (!node.HasChildren) { - _validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(_validPolicyTree, policyNodes, - node); + _validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(_validPolicyTree, + policyNodes, node); if (_validPolicyTree == null) - { break; - } } } } @@ -554,16 +518,14 @@ internal static PkixPolicyNode ProcessCertD( // // d (4) // - ISet criticalExtensionOids = cert.GetCriticalExtensionOids(); + var 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++) + foreach (var node in policyNodes[i]) { - PkixPolicyNode node = (PkixPolicyNode)nodes[j]; node.IsCritical = critical; } } @@ -586,10 +548,7 @@ internal static PkixPolicyNode ProcessCertD( * @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) + internal static void ProcessCrlB1(DistributionPoint dp, object cert, X509Crl crl) { Asn1Object idp = PkixCertPathValidatorUtilities.GetExtensionValue( crl, X509Extensions.IssuingDistributionPoint); @@ -602,6 +561,7 @@ internal static void ProcessCrlB1( isIndirect = true; } } + byte[] issuerBytes = crl.IssuerDN.GetEncoded(); bool matchIssuer = false; @@ -614,7 +574,7 @@ internal static void ProcessCrlB1( { try { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Arrays.AreEqual(genNames[j].Name.ToAsn1Object().GetEncoded(), issuerBytes)) + if (Arrays.AreEqual(genNames[j].Name.GetEncoded(), issuerBytes)) { matchIssuer = true; } @@ -648,12 +608,10 @@ internal static void ProcessCrlB1( } } - internal static ReasonsMask ProcessCrlD( - X509Crl crl, - DistributionPoint dp) + internal static ReasonsMask ProcessCrlD(X509Crl crl, DistributionPoint dp) //throws AnnotatedException { - IssuingDistributionPoint idp = null; + IssuingDistributionPoint idp; try { idp = IssuingDistributionPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(crl, X509Extensions.IssuingDistributionPoint)); @@ -666,8 +624,7 @@ internal static ReasonsMask ProcessCrlD( // (d) (1) if (idp != null && idp.OnlySomeReasons != null && dp.Reasons != null) { - return new ReasonsMask(dp.Reasons.IntValue).Intersect(new ReasonsMask(idp.OnlySomeReasons - .IntValue)); + return new ReasonsMask(dp.Reasons.IntValue).Intersect(new ReasonsMask(idp.OnlySomeReasons.IntValue)); } // (d) (4) if ((idp == null || idp.OnlySomeReasons == null) && dp.Reasons == null) @@ -677,8 +634,7 @@ internal static ReasonsMask ProcessCrlD( // (d) (2) and (d)(3) - ReasonsMask dpReasons = null; - + ReasonsMask dpReasons; if (dp.Reasons == null) { dpReasons = ReasonsMask.AllReasons; @@ -688,8 +644,7 @@ internal static ReasonsMask ProcessCrlD( dpReasons = new ReasonsMask(dp.Reasons.IntValue); } - ReasonsMask idpReasons = null; - + ReasonsMask idpReasons; if (idp == null) { idpReasons = ReasonsMask.AllReasons; @@ -721,21 +676,21 @@ internal static ReasonsMask ProcessCrlD( * @throws AnnotatedException if the CRL is not valid or the status cannot be checked or * some error occurs. */ - internal static ISet ProcessCrlF( + internal static ISet ProcessCrlF( X509Crl crl, object cert, X509Certificate defaultCRLSignCert, AsymmetricKeyParameter defaultCRLSignKey, PkixParameters paramsPKIX, - IList certPathCerts) + IList certPathCerts) { // (f) // get issuer from CRL - X509CertStoreSelector selector = new X509CertStoreSelector(); + X509CertStoreSelector certSelector = new X509CertStoreSelector(); try { - selector.Subject = crl.IssuerDN; + certSelector.Subject = crl.IssuerDN; } catch (IOException e) { @@ -744,29 +699,25 @@ internal static ISet ProcessCrlF( } // get CRL signing certs - IList coll = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var signingCerts = new HashSet(); try { - CollectionUtilities.AddRange(coll, PkixCertPathValidatorUtilities.FindCertificates(selector, paramsPKIX.GetStores())); - CollectionUtilities.AddRange(coll, PkixCertPathValidatorUtilities.FindCertificates(selector, paramsPKIX.GetAdditionalStores())); + CollectionUtilities.CollectMatches(signingCerts, certSelector, paramsPKIX.GetStoresCert()); } catch (Exception e) { throw new Exception("Issuer certificate for CRL cannot be searched.", e); } - coll.Add(defaultCRLSignCert); + signingCerts.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(); + var validCerts = new List(); + var validKeys = new List(); - while (cert_it.MoveNext()) + foreach (X509Certificate signingCert in signingCerts) { - 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 @@ -779,16 +730,13 @@ internal static ISet ProcessCrlF( } try { -// CertPathBuilder builder = CertPathBuilder.GetInstance("PKIX"); PkixCertPathBuilder builder = new PkixCertPathBuilder(); - selector = new X509CertStoreSelector(); - selector.Certificate = signingCert; - PkixParameters temp = (PkixParameters)paramsPKIX.Clone(); - temp.SetTargetCertConstraints(selector); + certSelector = new X509CertStoreSelector(); + certSelector.Certificate = signingCert; - PkixBuilderParameters parameters = (PkixBuilderParameters) - PkixBuilderParameters.GetInstance(temp); + PkixBuilderParameters parameters = PkixBuilderParameters.GetInstance(paramsPKIX); + parameters.SetTargetConstraintsCert(certSelector); /* * if signingCert is placed not higher on the cert path a @@ -807,7 +755,7 @@ internal static ISet ProcessCrlF( { parameters.IsRevocationEnabled = true; } - IList certs = builder.Build(parameters).CertPath.Certificates; + var certs = builder.Build(parameters).CertPath.Certificates; validCerts.Add(signingCert); validKeys.Add(PkixCertPathValidatorUtilities.GetNextWorkingKey(certs, 0)); } @@ -819,13 +767,9 @@ internal static ISet ProcessCrlF( { 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(); + var checkKeys = new HashSet(); Exception lastException = null; for (int i = 0; i < validCerts.Count; i++) @@ -856,9 +800,7 @@ internal static ISet ProcessCrlF( return checkKeys; } - internal static AsymmetricKeyParameter ProcessCrlG( - X509Crl crl, - ISet keys) + internal static AsymmetricKeyParameter ProcessCrlG(X509Crl crl, ISet keys) { Exception lastException = null; foreach (AsymmetricKeyParameter key in keys) @@ -876,9 +818,7 @@ internal static AsymmetricKeyParameter ProcessCrlG( throw new Exception("Cannot verify CRL.", lastException); } - internal static X509Crl ProcessCrlH( - ISet deltaCrls, - AsymmetricKeyParameter key) + internal static X509Crl ProcessCrlH(ISet deltaCrls, AsymmetricKeyParameter key) { Exception lastException = null; foreach (X509Crl crl in deltaCrls) @@ -927,8 +867,7 @@ private static void CheckCrl( AsymmetricKeyParameter defaultCRLSignKey, CertStatus certStatus, ReasonsMask reasonMask, - IList certPathCerts) - //throws AnnotatedException + IList certPathCerts) { DateTime currentDate = DateTime.UtcNow; @@ -945,20 +884,20 @@ private static void CheckCrl( * getAdditionalStore() */ - ISet crls = PkixCertPathValidatorUtilities.GetCompleteCrls(dp, cert, currentDate, paramsPKIX); + ISet crls = PkixCertPathValidatorUtilities.GetCompleteCrls(dp, cert, currentDate, paramsPKIX); bool validCrlFound = false; Exception lastException = null; - IEnumerator crl_iter = crls.GetEnumerator(); + var crl_iter = crls.GetEnumerator(); while (crl_iter.MoveNext() && certStatus.Status == CertStatus.Unrevoked && !reasonMask.IsAllReasons) { try { - X509Crl crl = (X509Crl)crl_iter.Current; + X509Crl crl = crl_iter.Current; // (d) - ReasonsMask interimReasonsMask = Rfc3280CertPathUtilities.ProcessCrlD(crl, dp); + ReasonsMask interimReasonsMask = ProcessCrlD(crl, dp); // (e) /* @@ -972,20 +911,19 @@ private static void CheckCrl( } // (f) - ISet keys = Rfc3280CertPathUtilities.ProcessCrlF(crl, cert, defaultCRLSignCert, defaultCRLSignKey, - paramsPKIX, certPathCerts); + var keys = ProcessCrlF(crl, cert, defaultCRLSignCert, defaultCRLSignKey, paramsPKIX, certPathCerts); // (g) - AsymmetricKeyParameter key = Rfc3280CertPathUtilities.ProcessCrlG(crl, keys); + AsymmetricKeyParameter key = ProcessCrlG(crl, keys); X509Crl deltaCRL = null; if (paramsPKIX.IsUseDeltasEnabled) { // get delta CRLs - ISet deltaCRLs = PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl); + ISet deltaCRLs = PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl); // we only want one valid delta CRL // (h) - deltaCRL = Rfc3280CertPathUtilities.ProcessCrlH(deltaCRLs, key); + deltaCRL = ProcessCrlH(deltaCRLs, key); } /* @@ -1014,19 +952,19 @@ private static void CheckCrl( } } - Rfc3280CertPathUtilities.ProcessCrlB1(dp, cert, crl); + ProcessCrlB1(dp, cert, crl); // (b) (2) - Rfc3280CertPathUtilities.ProcessCrlB2(dp, cert, crl); + ProcessCrlB2(dp, cert, crl); // (c) - Rfc3280CertPathUtilities.ProcessCrlC(deltaCRL, crl, paramsPKIX); + ProcessCrlC(deltaCRL, crl, paramsPKIX); // (i) - Rfc3280CertPathUtilities.ProcessCrlI(validDate, deltaCRL, cert, certStatus, paramsPKIX); + ProcessCrlI(validDate, deltaCRL, cert, certStatus, paramsPKIX); // (j) - Rfc3280CertPathUtilities.ProcessCrlJ(validDate, crl, cert, certStatus); + ProcessCrlJ(validDate, crl, cert, certStatus); // (k) if (certStatus.Status == CrlReason.RemoveFromCrl) @@ -1037,15 +975,15 @@ private static void CheckCrl( // update reasons mask reasonMask.AddReasons(interimReasonsMask); - ISet criticalExtensions = crl.GetCriticalExtensionOids(); + var criticalExtensions = crl.GetCriticalExtensionOids(); if (criticalExtensions != null) { - criticalExtensions = new HashSet(criticalExtensions); + criticalExtensions = new HashSet(criticalExtensions); criticalExtensions.Remove(X509Extensions.IssuingDistributionPoint.Id); criticalExtensions.Remove(X509Extensions.DeltaCrlIndicator.Id); - if (!criticalExtensions.IsEmpty) + if (criticalExtensions.Count > 0) throw new Exception("CRL contains unsupported critical extensions."); } @@ -1054,11 +992,11 @@ private static void CheckCrl( criticalExtensions = deltaCRL.GetCriticalExtensionOids(); if (criticalExtensions != null) { - criticalExtensions = new HashSet(criticalExtensions); + criticalExtensions = new HashSet(criticalExtensions); criticalExtensions.Remove(X509Extensions.IssuingDistributionPoint.Id); criticalExtensions.Remove(X509Extensions.DeltaCrlIndicator.Id); - if (!criticalExtensions.IsEmpty) + if (criticalExtensions.Count > 0) throw new Exception("Delta CRL contains unsupported critical extension."); } } @@ -1089,16 +1027,16 @@ private static void CheckCrl( * @throws AnnotatedException if the certificate is revoked or the status cannot be checked * or some error occurs. */ - protected static void CheckCrls( + internal static void CheckCrls( PkixParameters paramsPKIX, X509Certificate cert, DateTime validDate, X509Certificate sign, AsymmetricKeyParameter workingPublicKey, - IList certPathCerts) + IList certPathCerts) { Exception lastException = null; - CrlDistPoint crldp = null; + CrlDistPoint crldp; try { @@ -1126,7 +1064,7 @@ protected static void CheckCrls( // for each distribution point if (crldp != null) { - DistributionPoint[] dps = null; + DistributionPoint[] dps; try { dps = crldp.GetDistributionPoints(); @@ -1142,7 +1080,8 @@ protected static void CheckCrls( PkixParameters paramsPKIXClone = (PkixParameters)paramsPKIX.Clone(); try { - CheckCrl(dps[i], paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus, reasonsMask, certPathCerts); + CheckCrl(dps[i], paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus, + reasonsMask, certPathCerts); validCrlFound = true; } catch (Exception e) @@ -1217,92 +1156,80 @@ protected static void CheckCrls( } } - internal static PkixPolicyNode PrepareCertB( - PkixCertPath certPath, - int index, - IList[] policyNodes, - PkixPolicyNode validPolicyTree, - int policyMapping) - //throws CertPathValidatorException + /// + internal static PkixPolicyNode PrepareCertB(PkixCertPath certPath, int index, + IList[] policyNodes, PkixPolicyNode validPolicyTree, int policyMapping) { - IList certs = certPath.Certificates; - X509Certificate cert = (X509Certificate)certs[index]; + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; int n = certs.Count; // i as defined in the algorithm description int i = n - index; // (b) // - Asn1Sequence pm = null; + Asn1Sequence pm; try { - pm = (Asn1Sequence)Asn1Sequence.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.PolicyMappings)); + pm = Asn1Sequence.GetInstance( + PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.PolicyMappings)); } catch (Exception ex) { throw new PkixCertPathValidatorException( - "Policy mappings extension could not be decoded.", ex, certPath, index); + "Policy mappings extension could not be decoded.", ex, 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(); + Asn1Sequence mappings = pm; + var m_idp = new Dictionary>(); + var 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; + Asn1Sequence mapping = (Asn1Sequence)mappings[j]; + string id_p = ((DerObjectIdentifier)mapping[0]).Id; + string sd_p = ((DerObjectIdentifier)mapping[1]).Id; - if (!m_idp.Contains(id_p)) - { - tmp = new HashSet(); - tmp.Add(sd_p); - m_idp[id_p] = tmp; - s_idp.Add(id_p); - } + ISet tmp; + if (m_idp.TryGetValue(id_p, out tmp)) + { + tmp.Add(sd_p); + } else - { - tmp = (ISet)m_idp[id_p]; - tmp.Add(sd_p); - } + { + tmp = new HashSet(); + tmp.Add(sd_p); + m_idp[id_p] = tmp; + s_idp.Add(id_p); + } } - IEnumerator it_idp = s_idp.GetEnumerator(); - while (it_idp.MoveNext()) + foreach (var id_p in s_idp) { - 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()) + foreach (PkixPolicyNode node in policyNodes[i]) { - PkixPolicyNode node = (PkixPolicyNode)nodes_i.Current; if (node.ValidPolicy.Equals(id_p)) { idp_found = true; - node.ExpectedPolicies = (ISet)m_idp[id_p]; + node.ExpectedPolicies = CollectionUtilities.GetValueOrNull(m_idp, id_p); break; } } if (!idp_found) { - nodes_i = policyNodes[i].GetEnumerator(); - while (nodes_i.MoveNext()) + foreach (PkixPolicyNode node in policyNodes[i]) { - PkixPolicyNode node = (PkixPolicyNode)nodes_i.Current; - if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(node.ValidPolicy)) + if (ANY_POLICY.Equals(node.ValidPolicy)) { - ISet pq = null; Asn1Sequence policies = null; try { @@ -1312,9 +1239,11 @@ internal static PkixPolicyNode PrepareCertB( catch (Exception e) { throw new PkixCertPathValidatorException( - "Certificate policies extension could not be decoded.", e, certPath, index); + "Certificate policies extension could not be decoded.", e, index); } + ISet pq = null; + foreach (Asn1Encodable ae in policies) { PolicyInformation pinfo = null; @@ -1325,9 +1254,9 @@ internal static PkixPolicyNode PrepareCertB( catch (Exception ex) { throw new PkixCertPathValidatorException( - "Policy information could not be decoded.", ex, certPath, index); + "Policy information could not be decoded.", ex, index); } - if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(pinfo.PolicyIdentifier.Id)) + if (ANY_POLICY.Equals(pinfo.PolicyIdentifier.Id)) { try { @@ -1337,24 +1266,23 @@ internal static PkixPolicyNode PrepareCertB( catch (PkixCertPathValidatorException ex) { throw new PkixCertPathValidatorException( - "Policy qualifier info set could not be decoded.", ex, certPath, - index); + "Policy qualifier info set could not be decoded.", ex, index); } break; } } bool ci = false; - ISet critExtOids = cert.GetCriticalExtensionOids(); + var 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 p_node = 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); + var c_node = new PkixPolicyNode(new List(), i, + CollectionUtilities.GetValueOrNull(m_idp, id_p), p_node, pq, id_p, ci); p_node.AddChild(c_node); policyNodes[i].Add(c_node); } @@ -1369,7 +1297,7 @@ internal static PkixPolicyNode PrepareCertB( } else if (policyMapping <= 0) { - foreach (PkixPolicyNode node in BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(policyNodes[i])) + foreach (var node in new List(policyNodes[i])) { if (node.ValidPolicy.Equals(id_p)) { @@ -1377,7 +1305,7 @@ internal static PkixPolicyNode PrepareCertB( for (int k = i - 1; k >= 0; k--) { - foreach (PkixPolicyNode node2 in BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(policyNodes[k])) + foreach (var node2 in new List(policyNodes[k])) { if (!node2.HasChildren) { @@ -1397,19 +1325,18 @@ internal static PkixPolicyNode PrepareCertB( return _validPolicyTree; } - internal static ISet[] ProcessCrlA1ii( + 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(); + var issuer = new List(); issuer.Add(crl.IssuerDN); crlselect.Issuers = issuer; } @@ -1419,14 +1346,15 @@ internal static ISet[] ProcessCrlA1ii( } crlselect.CompleteCrlEnabled = true; - ISet completeSet = CrlUtilities.FindCrls(crlselect, paramsPKIX, currentDate); + ISet completeSet = CrlUtilities.FindCrls(crlselect, paramsPKIX, currentDate); + var deltaSet = new HashSet(); if (paramsPKIX.IsUseDeltasEnabled) { // get delta CRL(s) try { - deltaSet.AddAll(PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl)); + deltaSet.UnionWith(PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl)); } catch (Exception e) { @@ -1434,19 +1362,19 @@ internal static ISet[] ProcessCrlA1ii( } } - return new ISet[]{ completeSet, deltaSet }; + return new []{ completeSet, deltaSet }; } - internal static ISet ProcessCrlA1i( + internal static ISet ProcessCrlA1i( DateTime currentDate, PkixParameters paramsPKIX, X509Certificate cert, X509Crl crl) { - ISet deltaSet = new HashSet(); + var deltaSet = new HashSet(); if (paramsPKIX.IsUseDeltasEnabled) { - CrlDistPoint freshestCRL = null; + CrlDistPoint freshestCRL; try { freshestCRL = CrlDistPoint.GetInstance( @@ -1461,7 +1389,8 @@ internal static ISet ProcessCrlA1i( { try { - freshestCRL = CrlDistPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(crl, X509Extensions.FreshestCrl)); + freshestCRL = CrlDistPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(crl, + X509Extensions.FreshestCrl)); } catch (Exception e) { @@ -1472,7 +1401,8 @@ internal static ISet ProcessCrlA1i( { try { - PkixCertPathValidatorUtilities.AddAdditionalStoresFromCrlDistributionPoint(freshestCRL, paramsPKIX); + PkixCertPathValidatorUtilities.AddAdditionalStoresFromCrlDistributionPoint(freshestCRL, + paramsPKIX); } catch (Exception e) { @@ -1482,7 +1412,7 @@ internal static ISet ProcessCrlA1i( // get delta CRL(s) try { - deltaSet.AddAll(PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl)); + deltaSet.UnionWith(PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl)); } catch (Exception e) { @@ -1505,7 +1435,7 @@ internal static void ProcessCertF( if (explicitPolicy <= 0 && validPolicyTree == null) { throw new PkixCertPathValidatorException( - "No valid policy tree found when one expected.", null, certPath, index); + "No valid policy tree found when one expected.", null, index); } } @@ -1517,8 +1447,8 @@ internal static void ProcessCertA( X509Name workingIssuerName, X509Certificate sign) { - IList certs = certPath.Certificates; - X509Certificate cert = (X509Certificate)certs[index]; + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; // // (a) verify // @@ -1530,7 +1460,7 @@ internal static void ProcessCertA( } catch (GeneralSecurityException e) { - throw new PkixCertPathValidatorException("Could not validate certificate signature.", e, certPath, index); + throw new PkixCertPathValidatorException("Could not validate certificate signature.", e, index); } try @@ -1542,15 +1472,15 @@ internal static void ProcessCertA( } catch (CertificateExpiredException e) { - throw new PkixCertPathValidatorException("Could not validate certificate: " + e.Message, e, certPath, index); + throw new PkixCertPathValidatorException("Could not validate certificate: " + e.Message, e, index); } catch (CertificateNotYetValidException e) { - throw new PkixCertPathValidatorException("Could not validate certificate: " + e.Message, e, certPath, index); + throw new PkixCertPathValidatorException("Could not validate certificate: " + e.Message, e, index); } catch (Exception e) { - throw new PkixCertPathValidatorException("Could not validate time of certificate.", e, certPath, index); + throw new PkixCertPathValidatorException("Could not validate time of certificate.", e, index); } // @@ -1570,7 +1500,7 @@ internal static void ProcessCertA( { cause = e; } - throw new PkixCertPathValidatorException(e.Message, cause, certPath, index); + throw new PkixCertPathValidatorException(e.Message, cause, index); } } @@ -1581,22 +1511,18 @@ internal static void ProcessCertA( if (!issuer.Equivalent(workingIssuerName, true)) { throw new PkixCertPathValidatorException("IssuerName(" + issuer - + ") does not match SubjectName(" + workingIssuerName + ") of signing certificate.", null, - certPath, index); + + ") does not match SubjectName(" + workingIssuerName + ") of signing certificate.", null, index); } } - internal static int PrepareNextCertI1( - PkixCertPath certPath, - int index, - int explicitPolicy) + internal static int PrepareNextCertI1(PkixCertPath certPath, int index, int explicitPolicy) { - IList certs = certPath.Certificates; - X509Certificate cert = (X509Certificate)certs[index]; + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; // // (i) // - Asn1Sequence pc = null; + Asn1Sequence pc; try { pc = Asn1Sequence.GetInstance( @@ -1605,48 +1531,43 @@ internal static int PrepareNextCertI1( catch (Exception e) { throw new PkixCertPathValidatorException( - "Policy constraints extension cannot be decoded.", e, certPath, index); + "Policy constraints extension cannot be decoded.", e, index); } - int tmpInt; - if (pc != null) { - IEnumerator policyConstraints = pc.GetEnumerator(); - - while (policyConstraints.MoveNext()) + foreach (var policyConstraint in pc) { try { - Asn1TaggedObject constraint = Asn1TaggedObject.GetInstance(policyConstraints.Current); - if (constraint.TagNo == 0) + Asn1TaggedObject constraint = Asn1TaggedObject.GetInstance(policyConstraint); + if (constraint.HasContextTag(0)) { - tmpInt = DerInteger.GetInstance(constraint, false).IntValueExact; + int tmpInt = DerInteger.GetInstance(constraint, false).IntValueExact; if (tmpInt < explicitPolicy) - { return tmpInt; - } + break; } } catch (ArgumentException e) { throw new PkixCertPathValidatorException( - "Policy constraints extension contents cannot be decoded.", e, certPath, index); + "Policy constraints extension contents cannot be decoded.", e, index); } } } return explicitPolicy; } + /// internal static int PrepareNextCertI2( PkixCertPath certPath, int index, int policyMapping) - //throws CertPathValidatorException { - IList certs = certPath.Certificates; - X509Certificate cert = (X509Certificate)certs[index]; + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; // // (i) @@ -1659,49 +1580,43 @@ internal static int PrepareNextCertI2( } catch (Exception e) { - throw new PkixCertPathValidatorException( - "Policy constraints extension cannot be decoded.", e, certPath, index); + throw new PkixCertPathValidatorException("Policy constraints extension cannot be decoded.", e, index); } - int tmpInt; - if (pc != null) { - IEnumerator policyConstraints = pc.GetEnumerator(); - - while (policyConstraints.MoveNext()) + foreach (var policyConstraint in pc) { try { - Asn1TaggedObject constraint = Asn1TaggedObject.GetInstance(policyConstraints.Current); - if (constraint.TagNo == 1) + Asn1TaggedObject constraint = Asn1TaggedObject.GetInstance(policyConstraint); + if (constraint.HasContextTag(1)) { - tmpInt = DerInteger.GetInstance(constraint, false).IntValueExact; + int tmpInt = DerInteger.GetInstance(constraint, false).IntValueExact; if (tmpInt < policyMapping) - { return tmpInt; - } + break; } } catch (ArgumentException e) { throw new PkixCertPathValidatorException( - "Policy constraints extension contents cannot be decoded.", e, certPath, index); + "Policy constraints extension contents cannot be decoded.", e, index); } } } return policyMapping; } + /// internal static void PrepareNextCertG( PkixCertPath certPath, int index, PkixNameConstraintValidator nameConstraintValidator) - //throws CertPathValidatorException { - IList certs = certPath.Certificates; - X509Certificate cert = (X509Certificate)certs[index]; + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; // // (g) handle the name constraints extension @@ -1719,7 +1634,7 @@ internal static void PrepareNextCertG( catch (Exception e) { throw new PkixCertPathValidatorException( - "Name constraints extension could not be decoded.", e, certPath, index); + "Name constraints extension could not be decoded.", e, index); } if (nc != null) { @@ -1736,7 +1651,7 @@ internal static void PrepareNextCertG( catch (Exception ex) { throw new PkixCertPathValidatorException( - "Permitted subtrees cannot be build from name constraints extension.", ex, certPath, index); + "Permitted subtrees cannot be build from name constraints extension.", ex, index); } } @@ -1746,32 +1661,31 @@ internal static void PrepareNextCertG( Asn1Sequence excluded = nc.ExcludedSubtrees; if (excluded != null) { - IEnumerator e = excluded.GetEnumerator(); try { - while (e.MoveNext()) + foreach (var excludedSubtree in excluded) { - GeneralSubtree subtree = GeneralSubtree.GetInstance(e.Current); + GeneralSubtree subtree = GeneralSubtree.GetInstance(excludedSubtree); nameConstraintValidator.AddExcludedSubtree(subtree); } } catch (Exception ex) { throw new PkixCertPathValidatorException( - "Excluded subtrees cannot be build from name constraints extension.", ex, certPath, index); + "Excluded subtrees cannot be build from name constraints extension.", ex, index); } } } } + /// internal static int PrepareNextCertJ( PkixCertPath certPath, int index, int inhibitAnyPolicy) - //throws CertPathValidatorException { - IList certs = certPath.Certificates; - X509Certificate cert = (X509Certificate)certs[index]; + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; // // (j) @@ -1784,8 +1698,7 @@ internal static int PrepareNextCertJ( } catch (Exception e) { - throw new PkixCertPathValidatorException( - "Inhibit any-policy extension cannot be decoded.", e, certPath, index); + throw new PkixCertPathValidatorException("Inhibit any-policy extension cannot be decoded.", e, index); } if (iap != null) @@ -1798,17 +1711,17 @@ internal static int PrepareNextCertJ( return inhibitAnyPolicy; } + /// internal static void PrepareNextCertK( PkixCertPath certPath, int index) - //throws CertPathValidatorException { - IList certs = certPath.Certificates; - X509Certificate cert = (X509Certificate)certs[index]; + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; // // (k) // - BasicConstraints bc = null; + BasicConstraints bc; try { bc = BasicConstraints.GetInstance( @@ -1816,8 +1729,7 @@ internal static void PrepareNextCertK( } catch (Exception e) { - throw new PkixCertPathValidatorException("Basic constraints extension cannot be decoded.", e, certPath, - index); + throw new PkixCertPathValidatorException("Basic constraints extension cannot be decoded.", e, index); } if (bc != null) { @@ -1830,42 +1742,40 @@ internal static void PrepareNextCertK( } } + /// internal static int PrepareNextCertL( PkixCertPath certPath, int index, int maxPathLength) - //throws CertPathValidatorException { - IList certs = certPath.Certificates; - X509Certificate cert = (X509Certificate)certs[index]; + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; // // (l) // if (!PkixCertPathValidatorUtilities.IsSelfIssued(cert)) { if (maxPathLength <= 0) - { - throw new PkixCertPathValidatorException("Max path length not greater than zero", null, certPath, index); - } + throw new PkixCertPathValidatorException("Max path length not greater than zero", null, 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]; + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; // // (m) // - BasicConstraints bc = null; + BasicConstraints bc; try { bc = BasicConstraints.GetInstance( @@ -1873,8 +1783,7 @@ internal static int PrepareNextCertM( } catch (Exception e) { - throw new PkixCertPathValidatorException("Basic constraints extension cannot be decoded.", e, certPath, - index); + throw new PkixCertPathValidatorException("Basic constraints extension cannot be decoded.", e, index); } if (bc != null) { @@ -1893,56 +1802,50 @@ internal static int PrepareNextCertM( return maxPathLength; } + /// internal static void PrepareNextCertN( PkixCertPath certPath, int index) - //throws CertPathValidatorException { - IList certs = certPath.Certificates; - X509Certificate cert = (X509Certificate)certs[index]; + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; // // (n) // bool[] _usage = cert.GetKeyUsage(); - if ((_usage != null) && !_usage[Rfc3280CertPathUtilities.KEY_CERT_SIGN]) + if ((_usage != null) && !_usage[KEY_CERT_SIGN]) { throw new PkixCertPathValidatorException( - "Issuer certificate keyusage extension is critical and does not permit key signing.", null, - certPath, index); + "Issuer certificate keyusage extension is critical and does not permit key signing.", null, index); } } - internal static void PrepareNextCertO( - PkixCertPath certPath, - int index, - ISet criticalExtensions, - IList pathCheckers) - //throws CertPathValidatorException + /// + internal static void PrepareNextCertO(PkixCertPath certPath, int index, ISet criticalExtensions, + IList checkers) { - IList certs = certPath.Certificates; - X509Certificate cert = (X509Certificate)certs[index]; + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; // // (o) // - IEnumerator tmpIter = pathCheckers.GetEnumerator(); - while (tmpIter.MoveNext()) + foreach (var checker in checkers) { try { - ((PkixCertPathChecker)tmpIter.Current).Check(cert, criticalExtensions); + checker.Check(cert, criticalExtensions); } catch (PkixCertPathValidatorException e) { - throw new PkixCertPathValidatorException(e.Message, e.InnerException, certPath, index); + throw new PkixCertPathValidatorException(e.Message, e.InnerException, index); } } - if (!criticalExtensions.IsEmpty) + if (criticalExtensions.Count > 0) { - throw new PkixCertPathValidatorException("Certificate has unsupported critical extension.", null, certPath, - index); + throw new PkixCertPathValidatorException("Certificate has unsupported critical extension.", null, index); } } @@ -1951,8 +1854,8 @@ internal static int PrepareNextCertH1( int index, int explicitPolicy) { - IList certs = certPath.Certificates; - X509Certificate cert = (X509Certificate)certs[index]; + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; // // (h) @@ -1973,8 +1876,8 @@ internal static int PrepareNextCertH2( int index, int policyMapping) { - IList certs = certPath.Certificates; - X509Certificate cert = (X509Certificate)certs[index]; + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; // // (h) @@ -1996,8 +1899,8 @@ internal static int PrepareNextCertH3( int index, int inhibitAnyPolicy) { - IList certs = certPath.Certificates; - X509Certificate cert = (X509Certificate)certs[index]; + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; // // (h) @@ -2027,20 +1930,19 @@ internal static int WrapupCertA( return explicitPolicy; } + /// internal static int WrapupCertB( PkixCertPath certPath, int index, int explicitPolicy) - //throws CertPathValidatorException { - IList certs = certPath.Certificates; - X509Certificate cert = (X509Certificate)certs[index]; + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; // // (b) // - int tmpInt; - Asn1Sequence pc = null; + Asn1Sequence pc; try { pc = Asn1Sequence.GetInstance( @@ -2048,79 +1950,65 @@ internal static int WrapupCertB( } catch (Exception e) { - throw new PkixCertPathValidatorException("Policy constraints could not be decoded.", e, certPath, index); + throw new PkixCertPathValidatorException("Policy constraints could not be decoded.", e, index); } if (pc != null) { - IEnumerator policyConstraints = pc.GetEnumerator(); - - while (policyConstraints.MoveNext()) + foreach (var policyConstraint in pc) { - Asn1TaggedObject constraint = (Asn1TaggedObject)policyConstraints.Current; - switch (constraint.TagNo) - { - case 0: - try - { - tmpInt = DerInteger.GetInstance(constraint, false).IntValueExact; - } - catch (Exception e) - { - throw new PkixCertPathValidatorException( - "Policy constraints requireExplicitPolicy field could not be decoded.", e, certPath, - index); - } - if (tmpInt == 0) - { - return 0; - } - break; + Asn1TaggedObject constraint = Asn1TaggedObject.GetInstance(policyConstraint); + if (constraint.HasContextTag(0)) + { + int tmpInt; + try + { + tmpInt = DerInteger.GetInstance(constraint, false).IntValueExact; + } + catch (Exception e) + { + throw new PkixCertPathValidatorException( + "Policy constraints requireExplicitPolicy field could not be decoded.", e, index); + } + if (tmpInt == 0) + return 0; + + break; } } } return explicitPolicy; } - internal static void WrapupCertF( - PkixCertPath certPath, - int index, - IList pathCheckers, - ISet criticalExtensions) - //throws CertPathValidatorException + /// + internal static void WrapupCertF(PkixCertPath certPath, int index, IList checkers, + ISet criticalExtensions) { - IList certs = certPath.Certificates; - X509Certificate cert = (X509Certificate)certs[index]; - IEnumerator tmpIter = pathCheckers.GetEnumerator(); + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; - while (tmpIter.MoveNext()) + foreach (var checker in checkers) { try { - ((PkixCertPathChecker)tmpIter.Current).Check(cert, criticalExtensions); + checker.Check(cert, criticalExtensions); } catch (PkixCertPathValidatorException e) { - throw new PkixCertPathValidatorException("Additional certificate path checker failed.", e, certPath, - index); + throw new PkixCertPathValidatorException("Additional certificate path checker failed.", e, index); } } - if (!criticalExtensions.IsEmpty) + if (criticalExtensions.Count > 0) { throw new PkixCertPathValidatorException("Certificate has unsupported critical extension", - null, certPath, index); + null, index); } } - internal static PkixPolicyNode WrapupCertG( - PkixCertPath certPath, - PkixParameters paramsPKIX, - ISet userInitialPolicySet, - int index, - IList[] policyNodes, - PkixPolicyNode validPolicyTree, - ISet acceptablePolicies) + internal static PkixPolicyNode WrapupCertG(PkixCertPath certPath, PkixParameters paramsPKIX, + ISet userInitialPolicySet, int index, IList[] policyNodes, + PkixPolicyNode validPolicyTree, ISet acceptablePolicies) { int n = certPath.Certificates.Count; @@ -2137,68 +2025,59 @@ internal static PkixPolicyNode WrapupCertG( if (paramsPKIX.IsExplicitPolicyRequired) { throw new PkixCertPathValidatorException( - "Explicit policy requested but none available.", null, certPath, index); + "Explicit policy requested but none available.", null, index); } intersection = null; } - else if (PkixCertPathValidatorUtilities.IsAnyPolicy(userInitialPolicySet)) // (g) - // (ii) + else if (PkixCertPathValidatorUtilities.IsAnyPolicy(userInitialPolicySet)) // (g) (ii) { if (paramsPKIX.IsExplicitPolicyRequired) { - if (acceptablePolicies.IsEmpty) + if (acceptablePolicies.Count < 1) { throw new PkixCertPathValidatorException( - "Explicit policy requested but none available.", null, certPath, index); + "Explicit policy requested but none available.", null, index); } - else - { - ISet _validPolicyNodeSet = new HashSet(); - for (int j = 0; j < policyNodes.Length; j++) - { - IList _nodeDepth = policyNodes[j]; + var _validPolicyNodeSet = new HashSet(); - for (int k = 0; k < _nodeDepth.Count; k++) + foreach (var _nodeDepth in policyNodes) + { + foreach (var _node in _nodeDepth) + { + if (ANY_POLICY.Equals(_node.ValidPolicy)) { - PkixPolicyNode _node = (PkixPolicyNode)_nodeDepth[k]; - - if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(_node.ValidPolicy)) + foreach (var o in _node.Children) { - foreach (object o in _node.Children) - { - _validPolicyNodeSet.Add(o); - } + _validPolicyNodeSet.Add(o); } } } + } - foreach (PkixPolicyNode _node in _validPolicyNodeSet) + foreach (var _node in _validPolicyNodeSet) + { + if (!acceptablePolicies.Contains(_node.ValidPolicy)) { - string _validPolicy = _node.ValidPolicy; - - if (!acceptablePolicies.Contains(_validPolicy)) - { - // TODO? - // validPolicyTree = - // removePolicyNode(validPolicyTree, policyNodes, - // _node); - } + // TODO? + // validPolicyTree = + // removePolicyNode(validPolicyTree, policyNodes, + // _node); } - if (validPolicyTree != null) + } + if (validPolicyTree != null) + { + for (int j = n - 1; j >= 0; j--) { - for (int j = (n - 1); j >= 0; j--) - { - IList nodes = policyNodes[j]; + var nodes = policyNodes[j]; - for (int k = 0; k < nodes.Count; k++) + for (int k = 0; k < nodes.Count; k++) + { + var node = nodes[k]; + if (!node.HasChildren) { - PkixPolicyNode node = (PkixPolicyNode)nodes[k]; - if (!node.HasChildren) - { - validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(validPolicyTree, - policyNodes, node); - } + validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode( + validPolicyTree, policyNodes, node); } } } @@ -2222,21 +2101,17 @@ internal static PkixPolicyNode WrapupCertG( // // (g) (iii) 1 // - ISet _validPolicyNodeSet = new HashSet(); + var _validPolicyNodeSet = new HashSet(); - for (int j = 0; j < policyNodes.Length; j++) + foreach (var _nodeDepth in policyNodes) { - IList _nodeDepth = policyNodes[j]; - - for (int k = 0; k < _nodeDepth.Count; k++) + foreach (var _node in _nodeDepth) { - PkixPolicyNode _node = (PkixPolicyNode)_nodeDepth[k]; - - if (Rfc3280CertPathUtilities.ANY_POLICY.Equals(_node.ValidPolicy)) + if (ANY_POLICY.Equals(_node.ValidPolicy)) { foreach (PkixPolicyNode _c_node in _node.Children) { - if (!Rfc3280CertPathUtilities.ANY_POLICY.Equals(_c_node.ValidPolicy)) + if (!ANY_POLICY.Equals(_c_node.ValidPolicy)) { _validPolicyNodeSet.Add(_c_node); } @@ -2248,15 +2123,12 @@ internal static PkixPolicyNode WrapupCertG( // // (g) (iii) 2 // - IEnumerator _vpnsIter = _validPolicyNodeSet.GetEnumerator(); - while (_vpnsIter.MoveNext()) + foreach (var _node in _validPolicyNodeSet) { - PkixPolicyNode _node = (PkixPolicyNode)_vpnsIter.Current; - string _validPolicy = _node.ValidPolicy; - - if (!userInitialPolicySet.Contains(_validPolicy)) + if (!userInitialPolicySet.Contains(_node.ValidPolicy)) { - validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(validPolicyTree, policyNodes, _node); + validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(validPolicyTree, policyNodes, + _node); } } @@ -2265,17 +2137,17 @@ internal static PkixPolicyNode WrapupCertG( // if (validPolicyTree != null) { - for (int j = (n - 1); j >= 0; j--) + for (int j = n - 1; j >= 0; j--) { - IList nodes = policyNodes[j]; + var nodes = policyNodes[j]; for (int k = 0; k < nodes.Count; k++) { - PkixPolicyNode node = (PkixPolicyNode)nodes[k]; + var node = nodes[k]; if (!node.HasChildren) { - validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(validPolicyTree, policyNodes, - node); + validPolicyTree = PkixCertPathValidatorUtilities.RemovePolicyNode(validPolicyTree, + policyNodes, node); } } } @@ -2332,7 +2204,7 @@ internal static void ProcessCrlC( "Issuing distribution point extension from delta CRL could not be decoded.", e); } - if (!BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(completeidp, deltaidp)) + if (!Org.BouncyCastle.Utilities.Platform.Equals(completeidp, deltaidp)) { throw new Exception( "Issuing distribution point extension from delta CRL and complete CRL does not match."); @@ -2407,8 +2279,8 @@ internal static PkixPolicyNode ProcessCertE( int index, PkixPolicyNode validPolicyTree) { - IList certs = certPath.Certificates; - X509Certificate cert = (X509Certificate)certs[index]; + var certs = certPath.Certificates; + X509Certificate cert = certs[index]; // // (e) @@ -2422,7 +2294,7 @@ internal static PkixPolicyNode ProcessCertE( catch (Exception e) { throw new PkixCertPathValidatorException("Could not read certificate policies extension from certificate.", - e, certPath, index); + e, index); } if (certPolicies == null) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/Rfc3281CertPathUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/Rfc3281CertPathUtilities.cs index 0bd8824..46c5ae8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/Rfc3281CertPathUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/Rfc3281CertPathUtilities.cs @@ -1,11 +1,8 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; -using System.Globalization; -using System.IO; +using System.Collections.Generic; -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; @@ -15,10 +12,10 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Pkix { - internal class Rfc3281CertPathUtilities + internal static class Rfc3281CertPathUtilities { internal static void ProcessAttrCert7( - IX509AttributeCertificate attrCert, + X509V2AttributeCertificate attrCert, PkixCertPath certPath, PkixCertPath holderCertPath, PkixParameters pkixParams) @@ -27,7 +24,7 @@ internal static void ProcessAttrCert7( // AA Controls // Attribute encryption // Proxy - ISet critExtOids = attrCert.GetCriticalExtensionOids(); + var critExtOids = attrCert.GetCriticalExtensionOids(); // 7.1 // process extensions @@ -51,11 +48,10 @@ internal static void ProcessAttrCert7( { checker.Check(attrCert, certPath, holderCertPath, critExtOids); } - if (!critExtOids.IsEmpty) + if (critExtOids.Count > 0) { throw new PkixCertPathValidatorException( - "Attribute certificate contains unsupported critical extensions: " - + critExtOids); + "Attribute certificate contains unsupported critical extensions: " + critExtOids); } } @@ -75,22 +71,20 @@ internal static void ProcessAttrCert7( * status cannot be checked or some error occurs. */ internal static void CheckCrls( - IX509AttributeCertificate attrCert, + X509V2AttributeCertificate attrCert, PkixParameters paramsPKIX, X509Certificate issuerCert, DateTime validDate, - IList certPathCerts) + IList certPathCerts) { if (!paramsPKIX.IsRevocationEnabled) - { return; - } // check if revocation is available if (attrCert.GetExtensionValue(X509Extensions.NoRevAvail) != null) { - if (attrCert.GetExtensionValue(X509Extensions.CrlDistributionPoints) != null - || attrCert.GetExtensionValue(X509Extensions.AuthorityInfoAccess) != null) + 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."); @@ -99,22 +93,20 @@ internal static void CheckCrls( return; } - CrlDistPoint crldp = null; + CrlDistPoint crldp; try { crldp = CrlDistPoint.GetInstance( - PkixCertPathValidatorUtilities.GetExtensionValue( - attrCert, X509Extensions.CrlDistributionPoints)); + PkixCertPathValidatorUtilities.GetExtensionValue(attrCert, X509Extensions.CrlDistributionPoints)); } catch (Exception e) { - throw new PkixCertPathValidatorException( - "CRL distribution point extension could not be read.", e); + throw new PkixCertPathValidatorException("CRL distribution point extension could not be read.", e); } + try { - PkixCertPathValidatorUtilities - .AddAdditionalStoresFromCrlDistributionPoint(crldp, paramsPKIX); + PkixCertPathValidatorUtilities.AddAdditionalStoresFromCrlDistributionPoint(crldp, paramsPKIX); } catch (Exception e) { @@ -130,34 +122,30 @@ internal static void CheckCrls( // for each distribution point if (crldp != null) { - DistributionPoint[] dps = null; + DistributionPoint[] dps; try { dps = crldp.GetDistributionPoints(); } catch (Exception e) { - throw new PkixCertPathValidatorException( - "Distribution points could not be read.", 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++) + 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, + 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); + lastException = new Exception("No valid CRL for distribution point found.", e); } } @@ -167,8 +155,7 @@ internal static void CheckCrls( * distribution point but issued by the certificate issuer. */ - if (certStatus.Status == CertStatus.Unrevoked - && !reasonsMask.IsAllReasons) + if (certStatus.Status == CertStatus.Unrevoked && !reasonsMask.IsAllReasons) { try { @@ -184,9 +171,7 @@ internal static void CheckCrls( } catch (Exception e) { - throw new Exception( - "Issuer from certificate for CRL could not be reencoded.", - e); + throw new Exception("Issuer from certificate for CRL could not be reencoded.", e); } DistributionPoint dp = new DistributionPoint( new DistributionPointName(0, new GeneralNames( @@ -198,24 +183,18 @@ internal static void CheckCrls( } catch (Exception e) { - lastException = new Exception( - "No valid CRL for distribution point found.", e); + lastException = new Exception("No valid CRL for distribution point found.", e); } } if (!validCrlFound) - { - throw new PkixCertPathValidatorException( - "No valid CRL found.", lastException); - } + 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: " + string formattedDate = certStatus.RevocationDate.Value.ToString("ddd MMM dd HH:mm:ss K yyyy"); + string message = "Attribute certificate revocation after " + formattedDate + ", reason: " + Rfc3280CertPathUtilities.CrlReasons[certStatus.Status]; throw new PkixCertPathValidatorException(message); } @@ -232,7 +211,7 @@ internal static void CheckCrls( } internal static void AdditionalChecks( - IX509AttributeCertificate attrCert, + X509V2AttributeCertificate attrCert, PkixParameters pkixParams) { // 1 @@ -257,7 +236,7 @@ internal static void AdditionalChecks( } internal static void ProcessAttrCert5( - IX509AttributeCertificate attrCert, + X509V2AttributeCertificate attrCert, PkixParameters pkixParams) { try @@ -280,11 +259,11 @@ internal static void ProcessAttrCert4( X509Certificate acIssuerCert, PkixParameters pkixParams) { - ISet set = pkixParams.GetTrustedACIssuers(); + var set = pkixParams.GetTrustedACIssuers(); bool trusted = false; foreach (TrustAnchor anchor in set) { - IDictionary symbols = X509Name.RFC2253Symbols; + var symbols = X509Name.RFC2253Symbols; if (acIssuerCert.SubjectDN.ToString(false, symbols).Equals(anchor.CAName) || acIssuerCert.Equals(anchor.TrustedCert)) { @@ -351,12 +330,12 @@ internal static PkixCertPathValidatorResult ProcessAttrCert2( * */ internal static PkixCertPath ProcessAttrCert1( - IX509AttributeCertificate attrCert, + X509V2AttributeCertificate attrCert, PkixParameters pkixParams) { PkixCertPathBuilderResult result = null; // find holder PKCs - ISet holderPKCs = new HashSet(); + var holderPKCs = new HashSet(); if (attrCert.Holder.GetIssuer() != null) { X509CertStoreSelector selector = new X509CertStoreSelector(); @@ -364,14 +343,12 @@ internal static PkixCertPath ProcessAttrCert1( X509Name[] principals = attrCert.Holder.GetIssuer(); for (int i = 0; i < principals.Length; i++) { + // TODO Replace loop with a single multiprincipal selector (or don't even use selector) try { -// if (principals[i] is X500Principal) - { - selector.Issuer = principals[i]; - } - holderPKCs.AddAll(PkixCertPathValidatorUtilities - .FindCertificates(selector, pkixParams.GetStores())); + selector.Issuer = principals[i]; + + CollectionUtilities.CollectMatches(holderPKCs, selector, pkixParams.GetStoresCert()); } catch (Exception e) { @@ -380,7 +357,7 @@ internal static PkixCertPath ProcessAttrCert1( e); } } - if (holderPKCs.IsEmpty) + if (holderPKCs.Count < 1) { throw new PkixCertPathValidatorException( "Public key certificate specified in base certificate ID for attribute certificate cannot be found."); @@ -392,14 +369,12 @@ internal static PkixCertPath ProcessAttrCert1( X509Name[] principals = attrCert.Holder.GetEntityNames(); for (int i = 0; i < principals.Length; i++) { + // TODO Replace loop with a single multiprincipal selector (or don't even use selector) try { -// if (principals[i] is X500Principal) - { - selector.Issuer = principals[i]; - } - holderPKCs.AddAll(PkixCertPathValidatorUtilities - .FindCertificates(selector, pkixParams.GetStores())); + selector.Issuer = principals[i]; + + CollectionUtilities.CollectMatches(holderPKCs, selector, pkixParams.GetStoresCert()); } catch (Exception e) { @@ -408,7 +383,7 @@ internal static PkixCertPath ProcessAttrCert1( e); } } - if (holderPKCs.IsEmpty) + if (holderPKCs.Count < 1) { throw new PkixCertPathValidatorException( "Public key certificate specified in entity name for attribute certificate cannot be found."); @@ -416,21 +391,21 @@ internal static PkixCertPath ProcessAttrCert1( } // verify cert paths for PKCs - PkixBuilderParameters parameters = (PkixBuilderParameters) - PkixBuilderParameters.GetInstance(pkixParams); + PkixBuilderParameters parameters = PkixBuilderParameters.GetInstance(pkixParams); PkixCertPathValidatorException lastException = null; foreach (X509Certificate cert in holderPKCs) { - X509CertStoreSelector selector = new X509CertStoreSelector(); - selector.Certificate = cert; - parameters.SetTargetConstraints(selector); + X509CertStoreSelector certSelector = new X509CertStoreSelector(); + certSelector.Certificate = cert; + + parameters.SetTargetConstraintsCert(certSelector); PkixCertPathBuilder builder = new PkixCertPathBuilder(); try { - result = builder.Build(PkixBuilderParameters.GetInstance(parameters)); + result = builder.Build(parameters); } catch (PkixCertPathBuilderException e) { @@ -465,13 +440,13 @@ internal static PkixCertPath ProcessAttrCert1( */ private static void CheckCrl( DistributionPoint dp, - IX509AttributeCertificate attrCert, + X509V2AttributeCertificate attrCert, PkixParameters paramsPKIX, DateTime validDate, X509Certificate issuerCert, CertStatus certStatus, ReasonsMask reasonMask, - IList certPathCerts) + IList certPathCerts) { /* * 4.3.6 No Revocation Available @@ -481,15 +456,11 @@ private static void CheckCrl( * 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) /* @@ -498,12 +469,11 @@ private static void CheckCrl( * CRLs must be enabled in the ExtendedPkixParameters and are in * getAdditionalStore() */ - ISet crls = PkixCertPathValidatorUtilities.GetCompleteCrls(dp, attrCert, - currentDate, paramsPKIX); + var crls = PkixCertPathValidatorUtilities.GetCompleteCrls(dp, attrCert, currentDate, paramsPKIX); bool validCrlFound = false; Exception lastException = null; - IEnumerator crl_iter = crls.GetEnumerator(); + var crl_iter = crls.GetEnumerator(); while (crl_iter.MoveNext() && certStatus.Status == CertStatus.Unrevoked @@ -511,7 +481,7 @@ private static void CheckCrl( { try { - X509Crl crl = (X509Crl) crl_iter.Current; + X509Crl crl = crl_iter.Current; // (d) ReasonsMask interimReasonsMask = Rfc3280CertPathUtilities.ProcessCrlD(crl, dp); @@ -523,13 +493,12 @@ private static void CheckCrl( * must be ignored. */ if (!interimReasonsMask.HasNewReasons(reasonMask)) - { continue; - } // (f) - ISet keys = Rfc3280CertPathUtilities.ProcessCrlF(crl, attrCert, - null, null, paramsPKIX, certPathCerts); + var keys = Rfc3280CertPathUtilities.ProcessCrlF(crl, attrCert,null, null, paramsPKIX, + certPathCerts); + // (g) AsymmetricKeyParameter pubKey = Rfc3280CertPathUtilities.ProcessCrlG(crl, keys); @@ -538,8 +507,8 @@ private static void CheckCrl( if (paramsPKIX.IsUseDeltasEnabled) { // get delta CRLs - ISet deltaCRLs = PkixCertPathValidatorUtilities.GetDeltaCrls( - currentDate, paramsPKIX, crl); + var deltaCRLs = PkixCertPathValidatorUtilities.GetDeltaCrls(currentDate, paramsPKIX, crl); + // we only want one valid delta CRL // (h) deltaCRL = Rfc3280CertPathUtilities.ProcessCrlH(deltaCRLs, pubKey); @@ -565,10 +534,7 @@ private static void CheckCrl( * first check is not done */ if (attrCert.NotAfter.CompareTo(crl.ThisUpdate) < 0) - { - throw new Exception( - "No valid CRL for current time found."); - } + throw new Exception("No valid CRL for current time found."); } Rfc3280CertPathUtilities.ProcessCrlB1(dp, attrCert, crl); @@ -602,10 +568,9 @@ private static void CheckCrl( lastException = e; } } + if (!validCrlFound) - { throw lastException; - } } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/TrustAnchor.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/TrustAnchor.cs index acc654a..66ddfb2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/TrustAnchor.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/pkix/TrustAnchor.cs @@ -238,22 +238,20 @@ public byte[] GetNameConstraints 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); + sb.AppendLine("["); 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); + sb.Append(" Trusted CA Public Key: ").Append(this.pubKey).AppendLine(); + sb.Append(" Trusted CA Issuer Name: ").Append(this.caName).AppendLine(); } else { - sb.Append(" Trusted CA cert: ").Append(this.TrustedCert).Append(nl); + sb.Append(" Trusted CA cert: ").Append(this.TrustedCert).AppendLine(); } if (nc != null) { - sb.Append(" Name Constraints: ").Append(nc).Append(nl); + sb.Append(" Name Constraints: ").Append(nc).AppendLine(); } return sb.ToString(); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/AgreementUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/AgreementUtilities.cs index 792f34b..a24f173 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/AgreementUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/AgreementUtilities.cs @@ -1,6 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System.Collections; +using System; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.EdEC; @@ -9,30 +10,26 @@ 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; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security { /// /// Utility class for creating IBasicAgreement objects from their names/Oids /// - public sealed class AgreementUtilities + public static 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(); + private static readonly IDictionary Algorithms = + new Dictionary(StringComparer.OrdinalIgnoreCase); static AgreementUtilities() { - algorithms[X9ObjectIdentifiers.DHSinglePassCofactorDHSha1KdfScheme.Id] = "ECCDHWITHSHA1KDF"; - algorithms[X9ObjectIdentifiers.DHSinglePassStdDHSha1KdfScheme.Id] = "ECDHWITHSHA1KDF"; - algorithms[X9ObjectIdentifiers.MqvSinglePassSha1KdfScheme.Id] = "ECMQVWITHSHA1KDF"; + 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"; + Algorithms[EdECObjectIdentifiers.id_X25519.Id] = "X25519"; + Algorithms[EdECObjectIdentifiers.id_X448.Id] = "X448"; } public static IBasicAgreement GetBasicAgreement( @@ -96,8 +93,7 @@ public static IRawAgreement GetRawAgreement( return GetRawAgreement(oid.Id); } - public static IRawAgreement GetRawAgreement( - string algorithm) + public static IRawAgreement GetRawAgreement(string algorithm) { string mechanism = GetMechanism(algorithm); @@ -110,17 +106,16 @@ public static IRawAgreement GetRawAgreement( throw new SecurityUtilityException("Raw Agreement " + algorithm + " not recognised."); } - public static string GetAlgorithmName( - DerObjectIdentifier oid) + public static string GetAlgorithmName(DerObjectIdentifier oid) { - return (string)algorithms[oid.Id]; + return CollectionUtilities.GetValueOrNull(Algorithms, oid.Id); } - private static string GetMechanism(string algorithm) + 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; + var mechanism = CollectionUtilities.GetValueOrKey(Algorithms, algorithm); + + return mechanism.ToUpperInvariant(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/CipherUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/CipherUtilities.cs index 398d011..a296bb2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/CipherUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/CipherUtilities.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro; @@ -21,13 +21,14 @@ using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Modes; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security { /// /// Cipher Utility class contains methods that can not be specifically grouped into other classes. /// - public sealed class CipherUtilities + public static class CipherUtilities { private enum CipherAlgorithm { AES, @@ -113,184 +114,154 @@ private enum CipherPadding 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(); + private static readonly Dictionary Algorithms = + new Dictionary(StringComparer.OrdinalIgnoreCase); 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(); + Enums.GetArbitraryValue().ToString(); + Enums.GetArbitraryValue().ToString(); + Enums.GetArbitraryValue().ToString(); // TODO Flesh out the list of aliases - algorithms[NistObjectIdentifiers.IdAes128Cbc.Id] = "AES/CBC/PKCS7PADDING"; - algorithms[NistObjectIdentifiers.IdAes192Cbc.Id] = "AES/CBC/PKCS7PADDING"; - algorithms[NistObjectIdentifiers.IdAes256Cbc.Id] = "AES/CBC/PKCS7PADDING"; - - algorithms[NistObjectIdentifiers.IdAes128Ccm.Id] = "AES/CCM/NOPADDING"; - algorithms[NistObjectIdentifiers.IdAes192Ccm.Id] = "AES/CCM/NOPADDING"; - algorithms[NistObjectIdentifiers.IdAes256Ccm.Id] = "AES/CCM/NOPADDING"; - - algorithms[NistObjectIdentifiers.IdAes128Cfb.Id] = "AES/CFB/NOPADDING"; - algorithms[NistObjectIdentifiers.IdAes192Cfb.Id] = "AES/CFB/NOPADDING"; - algorithms[NistObjectIdentifiers.IdAes256Cfb.Id] = "AES/CFB/NOPADDING"; - - 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.IdAes128Ccm.Id] = "AES/CCM/NOPADDING"; + Algorithms[NistObjectIdentifiers.IdAes192Ccm.Id] = "AES/CCM/NOPADDING"; + Algorithms[NistObjectIdentifiers.IdAes256Ccm.Id] = "AES/CCM/NOPADDING"; + + Algorithms[NistObjectIdentifiers.IdAes128Cfb.Id] = "AES/CFB/NOPADDING"; + Algorithms[NistObjectIdentifiers.IdAes192Cfb.Id] = "AES/CFB/NOPADDING"; + Algorithms[NistObjectIdentifiers.IdAes256Cfb.Id] = "AES/CFB/NOPADDING"; + + 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.IdAes128Gcm.Id] = "AES/GCM/NOPADDING"; - algorithms[NistObjectIdentifiers.IdAes192Gcm.Id] = "AES/GCM/NOPADDING"; - algorithms[NistObjectIdentifiers.IdAes256Gcm.Id] = "AES/GCM/NOPADDING"; + Algorithms[NistObjectIdentifiers.IdAes128Gcm.Id] = "AES/GCM/NOPADDING"; + Algorithms[NistObjectIdentifiers.IdAes192Gcm.Id] = "AES/GCM/NOPADDING"; + Algorithms[NistObjectIdentifiers.IdAes256Gcm.Id] = "AES/GCM/NOPADDING"; - algorithms[NistObjectIdentifiers.IdAes128Ofb.Id] = "AES/OFB/NOPADDING"; - algorithms[NistObjectIdentifiers.IdAes192Ofb.Id] = "AES/OFB/NOPADDING"; - algorithms[NistObjectIdentifiers.IdAes256Ofb.Id] = "AES/OFB/NOPADDING"; + Algorithms[NistObjectIdentifiers.IdAes128Ofb.Id] = "AES/OFB/NOPADDING"; + Algorithms[NistObjectIdentifiers.IdAes192Ofb.Id] = "AES/OFB/NOPADDING"; + Algorithms[NistObjectIdentifiers.IdAes256Ofb.Id] = "AES/OFB/NOPADDING"; - algorithms[NsriObjectIdentifiers.id_aria128_cbc.Id] = "ARIA/CBC/PKCS7PADDING"; - algorithms[NsriObjectIdentifiers.id_aria192_cbc.Id] = "ARIA/CBC/PKCS7PADDING"; - algorithms[NsriObjectIdentifiers.id_aria256_cbc.Id] = "ARIA/CBC/PKCS7PADDING"; + Algorithms[NsriObjectIdentifiers.id_aria128_cbc.Id] = "ARIA/CBC/PKCS7PADDING"; + Algorithms[NsriObjectIdentifiers.id_aria192_cbc.Id] = "ARIA/CBC/PKCS7PADDING"; + Algorithms[NsriObjectIdentifiers.id_aria256_cbc.Id] = "ARIA/CBC/PKCS7PADDING"; - algorithms[NsriObjectIdentifiers.id_aria128_ccm.Id] = "ARIA/CCM/NOPADDING"; - algorithms[NsriObjectIdentifiers.id_aria192_ccm.Id] = "ARIA/CCM/NOPADDING"; - algorithms[NsriObjectIdentifiers.id_aria256_ccm.Id] = "ARIA/CCM/NOPADDING"; + Algorithms[NsriObjectIdentifiers.id_aria128_ccm.Id] = "ARIA/CCM/NOPADDING"; + Algorithms[NsriObjectIdentifiers.id_aria192_ccm.Id] = "ARIA/CCM/NOPADDING"; + Algorithms[NsriObjectIdentifiers.id_aria256_ccm.Id] = "ARIA/CCM/NOPADDING"; - algorithms[NsriObjectIdentifiers.id_aria128_cfb.Id] = "ARIA/CFB/NOPADDING"; - algorithms[NsriObjectIdentifiers.id_aria192_cfb.Id] = "ARIA/CFB/NOPADDING"; - algorithms[NsriObjectIdentifiers.id_aria256_cfb.Id] = "ARIA/CFB/NOPADDING"; + Algorithms[NsriObjectIdentifiers.id_aria128_cfb.Id] = "ARIA/CFB/NOPADDING"; + Algorithms[NsriObjectIdentifiers.id_aria192_cfb.Id] = "ARIA/CFB/NOPADDING"; + Algorithms[NsriObjectIdentifiers.id_aria256_cfb.Id] = "ARIA/CFB/NOPADDING"; - algorithms[NsriObjectIdentifiers.id_aria128_ctr.Id] = "ARIA/CTR/NOPADDING"; - algorithms[NsriObjectIdentifiers.id_aria192_ctr.Id] = "ARIA/CTR/NOPADDING"; - algorithms[NsriObjectIdentifiers.id_aria256_ctr.Id] = "ARIA/CTR/NOPADDING"; + Algorithms[NsriObjectIdentifiers.id_aria128_ctr.Id] = "ARIA/CTR/NOPADDING"; + Algorithms[NsriObjectIdentifiers.id_aria192_ctr.Id] = "ARIA/CTR/NOPADDING"; + Algorithms[NsriObjectIdentifiers.id_aria256_ctr.Id] = "ARIA/CTR/NOPADDING"; - algorithms[NsriObjectIdentifiers.id_aria128_ecb.Id] = "ARIA/ECB/PKCS7PADDING"; - algorithms[NsriObjectIdentifiers.id_aria192_ecb.Id] = "ARIA/ECB/PKCS7PADDING"; - algorithms[NsriObjectIdentifiers.id_aria256_ecb.Id] = "ARIA/ECB/PKCS7PADDING"; - algorithms["ARIA//PKCS7"] = "ARIA/ECB/PKCS7PADDING"; - algorithms["ARIA//PKCS7PADDING"] = "ARIA/ECB/PKCS7PADDING"; - algorithms["ARIA//PKCS5"] = "ARIA/ECB/PKCS7PADDING"; - algorithms["ARIA//PKCS5PADDING"] = "ARIA/ECB/PKCS7PADDING"; + Algorithms[NsriObjectIdentifiers.id_aria128_ecb.Id] = "ARIA/ECB/PKCS7PADDING"; + Algorithms[NsriObjectIdentifiers.id_aria192_ecb.Id] = "ARIA/ECB/PKCS7PADDING"; + Algorithms[NsriObjectIdentifiers.id_aria256_ecb.Id] = "ARIA/ECB/PKCS7PADDING"; + Algorithms["ARIA//PKCS7"] = "ARIA/ECB/PKCS7PADDING"; + Algorithms["ARIA//PKCS7PADDING"] = "ARIA/ECB/PKCS7PADDING"; + Algorithms["ARIA//PKCS5"] = "ARIA/ECB/PKCS7PADDING"; + Algorithms["ARIA//PKCS5PADDING"] = "ARIA/ECB/PKCS7PADDING"; - algorithms[NsriObjectIdentifiers.id_aria128_gcm.Id] = "ARIA/GCM/NOPADDING"; - algorithms[NsriObjectIdentifiers.id_aria192_gcm.Id] = "ARIA/GCM/NOPADDING"; - algorithms[NsriObjectIdentifiers.id_aria256_gcm.Id] = "ARIA/GCM/NOPADDING"; + Algorithms[NsriObjectIdentifiers.id_aria128_gcm.Id] = "ARIA/GCM/NOPADDING"; + Algorithms[NsriObjectIdentifiers.id_aria192_gcm.Id] = "ARIA/GCM/NOPADDING"; + Algorithms[NsriObjectIdentifiers.id_aria256_gcm.Id] = "ARIA/GCM/NOPADDING"; - algorithms[NsriObjectIdentifiers.id_aria128_ofb.Id] = "ARIA/OFB/NOPADDING"; - algorithms[NsriObjectIdentifiers.id_aria192_ofb.Id] = "ARIA/OFB/NOPADDING"; - algorithms[NsriObjectIdentifiers.id_aria256_ofb.Id] = "ARIA/OFB/NOPADDING"; + Algorithms[NsriObjectIdentifiers.id_aria128_ofb.Id] = "ARIA/OFB/NOPADDING"; + Algorithms[NsriObjectIdentifiers.id_aria192_ofb.Id] = "ARIA/OFB/NOPADDING"; + Algorithms[NsriObjectIdentifiers.id_aria256_ofb.Id] = "ARIA/OFB/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["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[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["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["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["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["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["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["PBEWITHSHA1AND128BITRC2-CBC"] = "PBEWITHSHAAND128BITRC2-CBC"; + Algorithms[PkcsObjectIdentifiers.PbeWithShaAnd128BitRC2Cbc.Id] = "PBEWITHSHAAND128BITRC2-CBC"; - algorithms["PBEWITHSHA1AND40BITRC2-CBC"] = "PBEWITHSHAAND40BITRC2-CBC"; - algorithms[PkcsObjectIdentifiers.PbewithShaAnd40BitRC2Cbc.Id] = "PBEWITHSHAAND40BITRC2-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["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["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["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["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["GOST"] = "GOST28147"; + Algorithms["GOST-28147"] = "GOST28147"; + Algorithms[CryptoProObjectIdentifiers.GostR28147Gcfb.Id] = "GOST28147/CBC/PKCS7PADDING"; - algorithms["RC5-32"] = "RC5"; + 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[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[KisaObjectIdentifiers.IdSeedCbc.Id] = "SEED/CBC/PKCS7PADDING"; - algorithms["1.3.6.1.4.1.3029.1.2"] = "BLOWFISH/CBC"; + Algorithms["1.3.6.1.4.1.3029.1.2"] = "BLOWFISH/CBC"; - algorithms["CHACHA20"] = "CHACHA7539"; - algorithms[PkcsObjectIdentifiers.IdAlgAeadChaCha20Poly1305.Id] = "CHACHA20-POLY1305"; - } - - 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; } + Algorithms["CHACHA20"] = "CHACHA7539"; + Algorithms[PkcsObjectIdentifiers.IdAlgAeadChaCha20Poly1305.Id] = "CHACHA20-POLY1305"; } public static IBufferedCipher GetCipher( @@ -299,20 +270,12 @@ public static IBufferedCipher GetCipher( return GetCipher(oid.Id); } - public static IBufferedCipher GetCipher( - string algorithm) + public static IBufferedCipher GetCipher(string algorithm) { if (algorithm == null) - throw new ArgumentNullException("algorithm"); + throw new ArgumentNullException(nameof(algorithm)); - algorithm = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm); - - { - string aliased = (string) algorithms[algorithm]; - - if (aliased != null) - algorithm = aliased; - } + algorithm = CollectionUtilities.GetValueOrKey(Algorithms, algorithm).ToUpperInvariant(); IBasicAgreement iesAgreement = null; if (algorithm == "IES") @@ -337,9 +300,9 @@ public static IBufferedCipher GetCipher( - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(algorithm, "PBE")) + if (Org.BouncyCastle.Utilities.Platform.StartsWith(algorithm, "PBE")) { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(algorithm, "-CBC")) + if (Org.BouncyCastle.Utilities.Platform.EndsWith(algorithm, "-CBC")) { if (algorithm == "PBEWITHSHA1ANDDES-CBC") { @@ -364,7 +327,7 @@ public static IBufferedCipher GetCipher( new CbcBlockCipher(new RC2Engine())); } } - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(algorithm, "-BC") || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(algorithm, "-OPENSSL")) + else if (Org.BouncyCastle.Utilities.Platform.EndsWith(algorithm, "-BC") || Org.BouncyCastle.Utilities.Platform.EndsWith(algorithm, "-OPENSSL")) { if (Strings.IsOneOf(algorithm, "PBEWITHSHAAND128BITAES-CBC-BC", @@ -378,7 +341,7 @@ public static IBufferedCipher GetCipher( "PBEWITHMD5AND256BITAES-CBC-OPENSSL")) { return new PaddedBufferedBlockCipher( - new CbcBlockCipher(new AesEngine())); + new CbcBlockCipher(AesUtilities.CreateEngine())); } } } @@ -392,19 +355,12 @@ public static IBufferedCipher GetCipher( IAsymmetricBlockCipher asymBlockCipher = null; IStreamCipher streamCipher = null; - string algorithmName = parts[0]; - - { - string aliased = (string)algorithms[algorithmName]; - - if (aliased != null) - algorithmName = aliased; - } + string algorithmName = CollectionUtilities.GetValueOrKey(Algorithms, parts[0]).ToUpperInvariant(); CipherAlgorithm cipherAlgorithm; try { - cipherAlgorithm = (CipherAlgorithm)Enums.GetEnumValue(typeof(CipherAlgorithm), algorithmName); + cipherAlgorithm = Enums.GetEnumValue(algorithmName); } catch (ArgumentException) { @@ -413,126 +369,126 @@ public static IBufferedCipher GetCipher( switch (cipherAlgorithm) { - case CipherAlgorithm.AES: - blockCipher = new AesEngine(); - break; - case CipherAlgorithm.ARC4: - streamCipher = new RC4Engine(); - break; - case CipherAlgorithm.ARIA: - blockCipher = new AriaEngine(); - 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.CHACHA: - streamCipher = new ChaChaEngine(); - break; - case CipherAlgorithm.CHACHA20_POLY1305: - aeadCipher = new ChaCha20Poly1305(); - break; - case CipherAlgorithm.CHACHA7539: - streamCipher = new ChaCha7539Engine(); - 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."); + case CipherAlgorithm.AES: + blockCipher = AesUtilities.CreateEngine(); + break; + case CipherAlgorithm.ARC4: + streamCipher = new RC4Engine(); + break; + case CipherAlgorithm.ARIA: + blockCipher = new AriaEngine(); + 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.CHACHA: + streamCipher = new ChaChaEngine(); + break; + case CipherAlgorithm.CHACHA20_POLY1305: + aeadCipher = new ChaCha20Poly1305(); + break; + case CipherAlgorithm.CHACHA7539: + streamCipher = new ChaCha7539Engine(); + 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 (aeadCipher != null) @@ -577,7 +533,7 @@ public static IBufferedCipher GetCipher( { try { - cipherPadding = (CipherPadding)Enums.GetEnumValue(typeof(CipherPadding), paddingName); + cipherPadding = Enums.GetEnumValue(paddingName); } catch (ArgumentException) { @@ -587,85 +543,86 @@ public static IBufferedCipher GetCipher( 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: - case CipherPadding.OAEPWITHSHA256ANDMGF1WITHSHA256PADDING: - case CipherPadding.OAEPWITHSHA_256ANDMGF1WITHSHA_256PADDING: - asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha256Digest()); - break; - case CipherPadding.OAEPWITHSHA256ANDMGF1WITHSHA1PADDING: - case CipherPadding.OAEPWITHSHA_256ANDMGF1WITHSHA_1PADDING: - asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha256Digest(), new Sha1Digest(), null); - 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."); + 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: + case CipherPadding.OAEPWITHSHA256ANDMGF1WITHSHA256PADDING: + case CipherPadding.OAEPWITHSHA_256ANDMGF1WITHSHA_256PADDING: + asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha256Digest()); + break; + case CipherPadding.OAEPWITHSHA256ANDMGF1WITHSHA1PADDING: + case CipherPadding.OAEPWITHSHA_256ANDMGF1WITHSHA_1PADDING: + asymBlockCipher = new OaepEncoding(asymBlockCipher, new Sha256Digest(), new Sha1Digest(), null); + 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 = ""; + IBlockCipherMode blockCipherMode = null; if (parts.Length > 1) { mode = parts[1]; @@ -677,68 +634,68 @@ public static IBufferedCipher GetCipher( { CipherMode cipherMode = modeName == "" ? CipherMode.NONE - : (CipherMode)Enums.GetEnumValue(typeof(CipherMode), modeName); + : Enums.GetEnumValue(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)); + case CipherMode.ECB: + case CipherMode.NONE: + break; + case CipherMode.CBC: + blockCipherMode = 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)); + blockCipherMode = new CfbBlockCipher(blockCipher, bits); + break; + } + case CipherMode.CTR: + blockCipherMode = new SicBlockCipher(blockCipher); + break; + case CipherMode.CTS: + cts = true; + blockCipherMode = new CbcBlockCipher(blockCipher); + break; + case CipherMode.EAX: + aeadBlockCipher = new EaxBlockCipher(blockCipher); + break; + case CipherMode.GCM: + aeadBlockCipher = new GcmBlockCipher(blockCipher); + break; + case CipherMode.GOFB: + blockCipherMode = 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; + blockCipherMode = new OfbBlockCipher(blockCipher, bits); + break; + } + case CipherMode.OPENPGPCFB: + blockCipherMode = 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)"); } - 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."); + blockCipherMode = new SicBlockCipher(blockCipher); + break; + default: + throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } } catch (ArgumentException) @@ -759,22 +716,27 @@ public static IBufferedCipher GetCipher( if (blockCipher != null) { + if (blockCipherMode == null) + { + blockCipherMode = EcbBlockCipher.GetBlockCipherMode(blockCipher); + } + if (cts) { - return new CtsBlockCipher(blockCipher); + return new CtsBlockCipher(blockCipherMode); } if (padding != null) { - return new PaddedBufferedBlockCipher(blockCipher, padding); + return new PaddedBufferedBlockCipher(blockCipherMode, padding); } - if (!padded || blockCipher.IsPartialBlockOkay) + if (!padded || blockCipherMode.IsPartialBlockOkay) { - return new BufferedBlockCipher(blockCipher); + return new BufferedBlockCipher(blockCipherMode); } - return new PaddedBufferedBlockCipher(blockCipher); + return new PaddedBufferedBlockCipher(blockCipherMode); } if (asymBlockCipher != null) @@ -785,14 +747,12 @@ public static IBufferedCipher GetCipher( throw new SecurityUtilityException("Cipher " + algorithm + " not recognised."); } - public static string GetAlgorithmName( - DerObjectIdentifier oid) + public static string GetAlgorithmName(DerObjectIdentifier oid) { - return (string) algorithms[oid.Id]; + return CollectionUtilities.GetValueOrNull(Algorithms, oid.Id); } - private static int GetDigitIndex( - string s) + private static int GetDigitIndex(string s) { for (int i = 0; i < s.Length; ++i) { @@ -807,35 +767,35 @@ private static IBlockCipher CreateBlockCipher(CipherAlgorithm cipherAlgorithm) { switch (cipherAlgorithm) { - case CipherAlgorithm.AES: return new AesEngine(); - case CipherAlgorithm.ARIA: return new AriaEngine(); - 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"); + case CipherAlgorithm.AES: return AesUtilities.CreateEngine(); + case CipherAlgorithm.ARIA: return new AriaEngine(); + 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"); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/DigestUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/DigestUtilities.cs index 22b8999..13e07b0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/DigestUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/DigestUtilities.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro; @@ -13,21 +13,22 @@ 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.Crypto.Digests; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security { /// /// Utility class for creating IDigest objects from their names/Oids /// - public sealed class DigestUtilities + public static class DigestUtilities { private enum DigestAlgorithm { BLAKE2B_160, BLAKE2B_256, BLAKE2B_384, BLAKE2B_512, BLAKE2S_128, BLAKE2S_160, BLAKE2S_224, BLAKE2S_256, + BLAKE3_256, DSTU7564_256, DSTU7564_384, DSTU7564_512, GOST3411, GOST3411_2012_256, GOST3411_2012_512, @@ -44,130 +45,130 @@ private enum DigestAlgorithm { 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(); + private static readonly IDictionary Aliases = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly IDictionary Oids = + new Dictionary(StringComparer.OrdinalIgnoreCase); 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[PkcsObjectIdentifiers.IdHmacWithSha1.Id] = "SHA-1"; - algorithms[MiscObjectIdentifiers.HMAC_SHA1.Id] = "SHA-1"; - algorithms["SHA224"] = "SHA-224"; - algorithms[NistObjectIdentifiers.IdSha224.Id] = "SHA-224"; - algorithms[PkcsObjectIdentifiers.IdHmacWithSha224.Id] = "SHA-224"; - algorithms["SHA256"] = "SHA-256"; - algorithms[NistObjectIdentifiers.IdSha256.Id] = "SHA-256"; - algorithms[PkcsObjectIdentifiers.IdHmacWithSha256.Id] = "SHA-256"; - algorithms["SHA384"] = "SHA-384"; - algorithms[NistObjectIdentifiers.IdSha384.Id] = "SHA-384"; - algorithms[PkcsObjectIdentifiers.IdHmacWithSha384.Id] = "SHA-384"; - algorithms["SHA512"] = "SHA-512"; - algorithms[NistObjectIdentifiers.IdSha512.Id] = "SHA-512"; - algorithms[PkcsObjectIdentifiers.IdHmacWithSha512.Id] = "SHA-512"; - - algorithms["SHA512/224"] = "SHA-512/224"; - algorithms["SHA512(224)"] = "SHA-512/224"; - algorithms["SHA-512(224)"] = "SHA-512/224"; - algorithms[NistObjectIdentifiers.IdSha512_224.Id] = "SHA-512/224"; - algorithms["SHA512/256"] = "SHA-512/256"; - algorithms["SHA512(256)"] = "SHA-512/256"; - algorithms["SHA-512(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.IdHMacWithSha3_224.Id] = "SHA3-224"; - algorithms[NistObjectIdentifiers.IdSha3_256.Id] = "SHA3-256"; - algorithms[NistObjectIdentifiers.IdHMacWithSha3_256.Id] = "SHA3-256"; - algorithms[NistObjectIdentifiers.IdSha3_384.Id] = "SHA3-384"; - algorithms[NistObjectIdentifiers.IdHMacWithSha3_384.Id] = "SHA3-384"; - algorithms[NistObjectIdentifiers.IdSha3_512.Id] = "SHA3-512"; - algorithms[NistObjectIdentifiers.IdHMacWithSha3_512.Id] = "SHA3-512"; - algorithms["SHAKE128"] = "SHAKE128-256"; - algorithms[NistObjectIdentifiers.IdShake128.Id] = "SHAKE128-256"; - algorithms["SHAKE256"] = "SHAKE256-512"; - algorithms[NistObjectIdentifiers.IdShake256.Id] = "SHAKE256-512"; - - 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-256"] = NistObjectIdentifiers.IdShake128; - oids["SHAKE256-512"] = 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; + Enums.GetArbitraryValue().ToString(); + + Aliases[PkcsObjectIdentifiers.MD2.Id] = "MD2"; + Aliases[PkcsObjectIdentifiers.MD4.Id] = "MD4"; + Aliases[PkcsObjectIdentifiers.MD5.Id] = "MD5"; + + Aliases["SHA1"] = "SHA-1"; + Aliases[OiwObjectIdentifiers.IdSha1.Id] = "SHA-1"; + Aliases[PkcsObjectIdentifiers.IdHmacWithSha1.Id] = "SHA-1"; + Aliases[MiscObjectIdentifiers.HMAC_SHA1.Id] = "SHA-1"; + Aliases["SHA224"] = "SHA-224"; + Aliases[NistObjectIdentifiers.IdSha224.Id] = "SHA-224"; + Aliases[PkcsObjectIdentifiers.IdHmacWithSha224.Id] = "SHA-224"; + Aliases["SHA256"] = "SHA-256"; + Aliases[NistObjectIdentifiers.IdSha256.Id] = "SHA-256"; + Aliases[PkcsObjectIdentifiers.IdHmacWithSha256.Id] = "SHA-256"; + Aliases["SHA384"] = "SHA-384"; + Aliases[NistObjectIdentifiers.IdSha384.Id] = "SHA-384"; + Aliases[PkcsObjectIdentifiers.IdHmacWithSha384.Id] = "SHA-384"; + Aliases["SHA512"] = "SHA-512"; + Aliases[NistObjectIdentifiers.IdSha512.Id] = "SHA-512"; + Aliases[PkcsObjectIdentifiers.IdHmacWithSha512.Id] = "SHA-512"; + + Aliases["SHA512/224"] = "SHA-512/224"; + Aliases["SHA512(224)"] = "SHA-512/224"; + Aliases["SHA-512(224)"] = "SHA-512/224"; + Aliases[NistObjectIdentifiers.IdSha512_224.Id] = "SHA-512/224"; + Aliases["SHA512/256"] = "SHA-512/256"; + Aliases["SHA512(256)"] = "SHA-512/256"; + Aliases["SHA-512(256)"] = "SHA-512/256"; + Aliases[NistObjectIdentifiers.IdSha512_256.Id] = "SHA-512/256"; + + Aliases["RIPEMD-128"] = "RIPEMD128"; + Aliases[TeleTrusTObjectIdentifiers.RipeMD128.Id] = "RIPEMD128"; + Aliases["RIPEMD-160"] = "RIPEMD160"; + Aliases[TeleTrusTObjectIdentifiers.RipeMD160.Id] = "RIPEMD160"; + Aliases["RIPEMD-256"] = "RIPEMD256"; + Aliases[TeleTrusTObjectIdentifiers.RipeMD256.Id] = "RIPEMD256"; + Aliases["RIPEMD-320"] = "RIPEMD320"; + //Aliases[TeleTrusTObjectIdentifiers.RipeMD320.Id] = "RIPEMD320"; + + Aliases[CryptoProObjectIdentifiers.GostR3411.Id] = "GOST3411"; + + Aliases["KECCAK224"] = "KECCAK-224"; + Aliases["KECCAK256"] = "KECCAK-256"; + Aliases["KECCAK288"] = "KECCAK-288"; + Aliases["KECCAK384"] = "KECCAK-384"; + Aliases["KECCAK512"] = "KECCAK-512"; + + Aliases[NistObjectIdentifiers.IdSha3_224.Id] = "SHA3-224"; + Aliases[NistObjectIdentifiers.IdHMacWithSha3_224.Id] = "SHA3-224"; + Aliases[NistObjectIdentifiers.IdSha3_256.Id] = "SHA3-256"; + Aliases[NistObjectIdentifiers.IdHMacWithSha3_256.Id] = "SHA3-256"; + Aliases[NistObjectIdentifiers.IdSha3_384.Id] = "SHA3-384"; + Aliases[NistObjectIdentifiers.IdHMacWithSha3_384.Id] = "SHA3-384"; + Aliases[NistObjectIdentifiers.IdSha3_512.Id] = "SHA3-512"; + Aliases[NistObjectIdentifiers.IdHMacWithSha3_512.Id] = "SHA3-512"; + Aliases["SHAKE128"] = "SHAKE128-256"; + Aliases[NistObjectIdentifiers.IdShake128.Id] = "SHAKE128-256"; + Aliases["SHAKE256"] = "SHAKE256-512"; + Aliases[NistObjectIdentifiers.IdShake256.Id] = "SHAKE256-512"; + + Aliases[GMObjectIdentifiers.sm3.Id] = "SM3"; + + Aliases[MiscObjectIdentifiers.id_blake2b160.Id] = "BLAKE2B-160"; + Aliases[MiscObjectIdentifiers.id_blake2b256.Id] = "BLAKE2B-256"; + Aliases[MiscObjectIdentifiers.id_blake2b384.Id] = "BLAKE2B-384"; + Aliases[MiscObjectIdentifiers.id_blake2b512.Id] = "BLAKE2B-512"; + Aliases[MiscObjectIdentifiers.id_blake2s128.Id] = "BLAKE2S-128"; + Aliases[MiscObjectIdentifiers.id_blake2s160.Id] = "BLAKE2S-160"; + Aliases[MiscObjectIdentifiers.id_blake2s224.Id] = "BLAKE2S-224"; + Aliases[MiscObjectIdentifiers.id_blake2s256.Id] = "BLAKE2S-256"; + Aliases[MiscObjectIdentifiers.blake3_256.Id] = "BLAKE3-256"; + + Aliases[RosstandartObjectIdentifiers.id_tc26_gost_3411_12_256.Id] = "GOST3411-2012-256"; + Aliases[RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512.Id] = "GOST3411-2012-512"; + + Aliases[UAObjectIdentifiers.dstu7564digest_256.Id] = "DSTU7564-256"; + Aliases[UAObjectIdentifiers.dstu7564digest_384.Id] = "DSTU7564-384"; + Aliases[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-256"] = NistObjectIdentifiers.IdShake128; + Oids["SHAKE256-512"] = 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["BLAKE3-256"] = MiscObjectIdentifiers.blake3_256; + 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; } /// @@ -176,93 +177,78 @@ static DigestUtilities() /// A string representation of the digest meanism. /// A DerObjectIdentifier, null if the Oid is not available. - public static DerObjectIdentifier GetObjectIdentifier( - string mechanism) + 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]; + throw new ArgumentNullException(nameof(mechanism)); - if (aliased != null) - mechanism = aliased; - - return (DerObjectIdentifier) oids[mechanism]; - } + mechanism = CollectionUtilities.GetValueOrKey(Aliases, mechanism).ToUpperInvariant(); - public static ICollection Algorithms - { - get { return oids.Keys; } + return CollectionUtilities.GetValueOrNull(Oids, mechanism); } - public static IDigest GetDigest( - DerObjectIdentifier id) + public static IDigest GetDigest(DerObjectIdentifier id) { return GetDigest(id.Id); } - public static IDigest GetDigest( - string algorithm) + public static IDigest GetDigest(string algorithm) { - string upper = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm); - string mechanism = (string) algorithms[upper]; + if (algorithm == null) + throw new ArgumentNullException(nameof(algorithm)); - if (mechanism == null) - { - mechanism = upper; - } + string mechanism = CollectionUtilities.GetValueOrKey(Aliases, algorithm).ToUpperInvariant(); try { - DigestAlgorithm digestAlgorithm = (DigestAlgorithm)Enums.GetEnumValue( - typeof(DigestAlgorithm), mechanism); + DigestAlgorithm digestAlgorithm = Enums.GetEnumValue(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_256: return new ShakeDigest(128); - case DigestAlgorithm.SHAKE256_512: return new ShakeDigest(256); - case DigestAlgorithm.SM3: return new SM3Digest(); - case DigestAlgorithm.TIGER: return new TigerDigest(); - case DigestAlgorithm.WHIRLPOOL: return new WhirlpoolDigest(); + 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.BLAKE3_256: return new Blake3Digest(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_256: return new ShakeDigest(128); + case DigestAlgorithm.SHAKE256_512: return new ShakeDigest(256); + case DigestAlgorithm.SM3: return new SM3Digest(); + case DigestAlgorithm.TIGER: return new TigerDigest(); + case DigestAlgorithm.WHIRLPOOL: return new WhirlpoolDigest(); } } catch (ArgumentException) @@ -272,10 +258,9 @@ public static IDigest GetDigest( throw new SecurityUtilityException("Digest " + mechanism + " not recognised."); } - public static string GetAlgorithmName( - DerObjectIdentifier oid) + public static string GetAlgorithmName(DerObjectIdentifier oid) { - return (string) algorithms[oid.Id]; + return CollectionUtilities.GetValueOrNull(Aliases, oid.Id); } public static byte[] CalculateDigest(DerObjectIdentifier id, byte[] input) @@ -286,25 +271,49 @@ public static byte[] CalculateDigest(DerObjectIdentifier id, byte[] input) public static byte[] CalculateDigest(string algorithm, byte[] input) { IDigest digest = GetDigest(algorithm); - digest.BlockUpdate(input, 0, input.Length); - return DoFinal(digest); + return DoFinal(digest, input); + } + + public static byte[] CalculateDigest(string algorithm, byte[] buf, int off, int len) + { + IDigest digest = GetDigest(algorithm); + return DoFinal(digest, buf, off, len); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static byte[] CalculateDigest(string algorithm, ReadOnlySpan buffer) + { + IDigest digest = GetDigest(algorithm); + return DoFinal(digest, buffer); } +#endif - public static byte[] DoFinal( - IDigest 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) + public static byte[] DoFinal(IDigest digest, byte[] input) { digest.BlockUpdate(input, 0, input.Length); return DoFinal(digest); } + + public static byte[] DoFinal(IDigest digest, byte[] buf, int off, int len) + { + digest.BlockUpdate(buf, off, len); + return DoFinal(digest); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static byte[] DoFinal(IDigest digest, ReadOnlySpan buffer) + { + digest.BlockUpdate(buffer); + return DoFinal(digest); + } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/DotNetUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/DotNetUtilities.cs index c0620d0..25b6461 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/DotNetUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/DotNetUtilities.cs @@ -1,16 +1,21 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -#if !(NETCF_1_0 || SILVERLIGHT || PORTABLE || NETFX_CORE) - using System; +#if NET5_0_OR_GREATER +using System.Runtime.Versioning; +#endif using System.Security.Cryptography; using SystemX509 = System.Security.Cryptography.X509Certificates; +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.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.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.X509; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security @@ -18,12 +23,8 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security /// /// A class containing methods to interface the BouncyCastle world to the .NET Crypto world. /// - public sealed class DotNetUtilities + public static class DotNetUtilities { - private DotNetUtilities() - { - } - /// /// Create an System.Security.Cryptography.X509Certificate from an X509Certificate Structure. /// @@ -54,23 +55,11 @@ public static AsymmetricCipherKeyPair GetDsaKeyPair(DSA dsa) 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); + DsaPublicKeyParameters pubKey = GetDsaPublicKey(dp); DsaPrivateKeyParameters privKey = new DsaPrivateKeyParameters( new BigInteger(1, dp.X), - parameters); + pubKey.Parameters); return new AsymmetricCipherKeyPair(pubKey, privKey); } @@ -97,6 +86,62 @@ public static DsaPublicKeyParameters GetDsaPublicKey(DSAParameters dp) parameters); } +#if NETCOREAPP1_0_OR_GREATER || NET47_OR_GREATER || NETSTANDARD1_6_OR_GREATER || UNITY_2021_2_OR_NEWER + public static AsymmetricCipherKeyPair GetECDsaKeyPair(ECDsa ecDsa) + { + return GetECKeyPair("ECDSA", ecDsa.ExportParameters(true)); + } + + public static ECPublicKeyParameters GetECDsaPublicKey(ECDsa ecDsa) + { + return GetECPublicKey("ECDSA", ecDsa.ExportParameters(false)); + } + + public static AsymmetricCipherKeyPair GetECKeyPair(string algorithm, ECParameters ec) + { + ECPublicKeyParameters pubKey = GetECPublicKey(algorithm, ec); + + ECPrivateKeyParameters privKey = new ECPrivateKeyParameters( + pubKey.AlgorithmName, + new BigInteger(1, ec.D), + pubKey.Parameters); + + return new AsymmetricCipherKeyPair(pubKey, privKey); + } + + public static ECPublicKeyParameters GetECPublicKey(string algorithm, ECParameters ec) + { + X9ECParameters x9 = GetX9ECParameters(ec.Curve); + if (x9 == null) + throw new NotSupportedException("Unrecognized curve"); + + return new ECPublicKeyParameters( + algorithm, + GetECPoint(x9.Curve, ec.Q), + new ECDomainParameters(x9)); + } + + private static Math.EC.ECPoint GetECPoint(Math.EC.ECCurve curve, ECPoint point) + { + return curve.CreatePoint(new BigInteger(1, point.X), new BigInteger(1, point.Y)); + } + + private static X9ECParameters GetX9ECParameters(ECCurve curve) + { + if (!curve.IsNamed) + throw new NotSupportedException("Only named curves are supported"); + + Oid oid = curve.Oid; + if (oid != null) + { + string oidValue = oid.Value; + if (oidValue != null) + return ECKeyPairGenerator.FindECCurveByOid(new DerObjectIdentifier(oidValue)); + } + return null; + } +#endif + public static AsymmetricCipherKeyPair GetRsaKeyPair(RSA rsa) { return GetRsaKeyPair(rsa.ExportParameters(true)); @@ -104,17 +149,11 @@ public static AsymmetricCipherKeyPair GetRsaKeyPair(RSA rsa) 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); + RsaKeyParameters pubKey = GetRsaPublicKey(rp); RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters( - modulus, - pubExp, + pubKey.Modulus, + pubKey.Exponent, new BigInteger(1, rp.D), new BigInteger(1, rp.P), new BigInteger(1, rp.Q), @@ -141,46 +180,65 @@ public static RsaKeyParameters GetRsaPublicKey( public static AsymmetricCipherKeyPair GetKeyPair(AsymmetricAlgorithm privateKey) { - if (privateKey is DSA) - { - return GetDsaKeyPair((DSA)privateKey); - } + if (privateKey is DSA dsa) + return GetDsaKeyPair(dsa); - if (privateKey is RSA) - { - return GetRsaKeyPair((RSA)privateKey); - } +#if NETCOREAPP1_0_OR_GREATER || NET47_OR_GREATER || NETSTANDARD1_6_OR_GREATER || UNITY_2021_2_OR_NEWER + if (privateKey is ECDsa ecDsa) + return GetECDsaKeyPair(ecDsa); +#endif + + if (privateKey is RSA rsa) + return GetRsaKeyPair(rsa); - throw new ArgumentException("Unsupported algorithm specified", "privateKey"); + throw new ArgumentException("Unsupported algorithm specified", nameof(privateKey)); } +#if NET5_0_OR_GREATER + [SupportedOSPlatform("windows")] +#endif public static RSA ToRSA(RsaKeyParameters rsaKey) { // TODO This appears to not work for private keys (when no CRT info) return CreateRSAProvider(ToRSAParameters(rsaKey)); } +#if NET5_0_OR_GREATER + [SupportedOSPlatform("windows")] +#endif 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); } +#if NET5_0_OR_GREATER + [SupportedOSPlatform("windows")] +#endif public static RSA ToRSA(RsaPrivateCrtKeyParameters privKey) { return CreateRSAProvider(ToRSAParameters(privKey)); } +#if NET5_0_OR_GREATER + [SupportedOSPlatform("windows")] +#endif public static RSA ToRSA(RsaPrivateCrtKeyParameters privKey, CspParameters csp) { return CreateRSAProvider(ToRSAParameters(privKey), csp); } +#if NET5_0_OR_GREATER + [SupportedOSPlatform("windows")] +#endif public static RSA ToRSA(RsaPrivateKeyStructure privKey) { return CreateRSAProvider(ToRSAParameters(privKey)); } +#if NET5_0_OR_GREATER + [SupportedOSPlatform("windows")] +#endif public static RSA ToRSA(RsaPrivateKeyStructure privKey, CspParameters csp) { return CreateRSAProvider(ToRSAParameters(privKey), csp); @@ -225,32 +283,37 @@ public static RSAParameters ToRSAParameters(RsaPrivateKeyStructure privKey) 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; + return BigIntegers.AsUnsignedByteArray(size, n); } - private static RSA CreateRSAProvider(RSAParameters rp) + // TODO Why do we use CspParameters instead of just RSA.Create in methods below? +// private static RSA CreateRSA(RSAParameters rp) +// { +//#if NETCOREAPP2_0_OR_GREATER || NET472_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER +// return RSA.Create(rp); +//#else +// var rsa = RSA.Create(); +// rsa.ImportParameters(rp); +// return rsa; +//#endif +// } + +#if NET5_0_OR_GREATER + [SupportedOSPlatform("windows")] +#endif + private static RSACryptoServiceProvider 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; + return CreateRSAProvider(rp, csp); } - private static RSA CreateRSAProvider(RSAParameters rp, CspParameters csp) +#if NET5_0_OR_GREATER + [SupportedOSPlatform("windows")] +#endif + private static RSACryptoServiceProvider CreateRSAProvider(RSAParameters rp, CspParameters csp) { RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider(csp); rsaCsp.ImportParameters(rp); @@ -258,7 +321,5 @@ private static RSA CreateRSAProvider(RSAParameters rp, CspParameters csp) } } } - -#endif #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/GeneralSecurityException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/GeneralSecurityException.cs index ec37dc7..fff2b54 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/GeneralSecurityException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/GeneralSecurityException.cs @@ -1,12 +1,11 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security { -#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE) [Serializable] -#endif public class GeneralSecurityException : Exception { @@ -15,16 +14,18 @@ public GeneralSecurityException() { } - public GeneralSecurityException( - string message) + public GeneralSecurityException(string message) : base(message) { } - public GeneralSecurityException( - string message, - Exception exception) - : base(message, exception) + public GeneralSecurityException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected GeneralSecurityException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/GeneratorUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/GeneratorUtilities.cs index 45bbbd0..5cb6792 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/GeneratorUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/GeneratorUtilities.cs @@ -1,6 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System.Collections; +using System; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro; @@ -17,18 +18,18 @@ 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 + public static 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(); + private static readonly IDictionary KgAlgorithms = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly IDictionary KpgAlgorithms = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly IDictionary DefaultKeySizes = + new Dictionary(StringComparer.OrdinalIgnoreCase); static GeneratorUtilities() { @@ -128,7 +129,7 @@ static GeneratorUtilities() AddKgAlgorithm("GOST28147", "GOST", "GOST-28147", - CryptoProObjectIdentifiers.GostR28147Cbc); + CryptoProObjectIdentifiers.GostR28147Gcfb); AddKgAlgorithm("HC128"); AddKgAlgorithm("HC256"); AddKgAlgorithm("IDEA", @@ -223,6 +224,8 @@ static GeneratorUtilities() AddKpgAlgorithm("ECGOST3410", "ECGOST-3410", "GOST-3410-2001"); + AddKpgAlgorithm("ECGOST3410-2012", + "GOST-3410-2012"); AddKpgAlgorithm("Ed25519", "Ed25519ctx", "Ed25519ph", @@ -265,72 +268,62 @@ private static void AddDefaultKeySizeEntries(int size, params string[] algorithm { foreach (string algorithm in algorithms) { - defaultKeySizes.Add(algorithm, size); + DefaultKeySizes.Add(algorithm, size); } } - private static void AddKgAlgorithm( - string canonicalName, - params object[] aliases) + private static void AddKgAlgorithm(string canonicalName, params object[] aliases) { - kgAlgorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(canonicalName)] = canonicalName; + KgAlgorithms[canonicalName] = canonicalName; foreach (object alias in aliases) { - kgAlgorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(alias.ToString())] = canonicalName; + KgAlgorithms[alias.ToString()] = canonicalName; } } - private static void AddKpgAlgorithm( - string canonicalName, - params object[] aliases) + private static void AddKpgAlgorithm(string canonicalName, params object[] aliases) { - kpgAlgorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(canonicalName)] = canonicalName; + KpgAlgorithms[canonicalName] = canonicalName; foreach (object alias in aliases) { - kpgAlgorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(alias.ToString())] = canonicalName; + KpgAlgorithms[alias.ToString()] = canonicalName; } } - private static void AddHMacKeyGenerator( - string algorithm, - params object[] aliases) + private static void AddHMacKeyGenerator(string algorithm, params object[] aliases) { string mainName = "HMAC" + algorithm; - kgAlgorithms[mainName] = mainName; - kgAlgorithms["HMAC-" + algorithm] = mainName; - kgAlgorithms["HMAC/" + algorithm] = mainName; + 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; + KgAlgorithms[alias.ToString()] = mainName; } } // TODO Consider making this public - internal static string GetCanonicalKeyGeneratorAlgorithm( - string algorithm) + internal static string GetCanonicalKeyGeneratorAlgorithm(string algorithm) { - return (string) kgAlgorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm)]; + return CollectionUtilities.GetValueOrNull(KgAlgorithms, algorithm); } // TODO Consider making this public - internal static string GetCanonicalKeyPairGeneratorAlgorithm( - string algorithm) + internal static string GetCanonicalKeyPairGeneratorAlgorithm(string algorithm) { - return (string)kpgAlgorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm)]; + return CollectionUtilities.GetValueOrNull(KpgAlgorithms, algorithm); } - public static CipherKeyGenerator GetKeyGenerator( - DerObjectIdentifier oid) + public static CipherKeyGenerator GetKeyGenerator(DerObjectIdentifier oid) { return GetKeyGenerator(oid.Id); } - public static CipherKeyGenerator GetKeyGenerator( - string algorithm) + public static CipherKeyGenerator GetKeyGenerator(string algorithm) { string canonicalName = GetCanonicalKeyGeneratorAlgorithm(algorithm); @@ -351,14 +344,12 @@ public static CipherKeyGenerator GetKeyGenerator( return new CipherKeyGenerator(defaultKeySize); } - public static IAsymmetricCipherKeyPairGenerator GetKeyPairGenerator( - DerObjectIdentifier oid) + public static IAsymmetricCipherKeyPairGenerator GetKeyPairGenerator(DerObjectIdentifier oid) { return GetKeyPairGenerator(oid.Id); } - public static IAsymmetricCipherKeyPairGenerator GetKeyPairGenerator( - string algorithm) + public static IAsymmetricCipherKeyPairGenerator GetKeyPairGenerator(string algorithm) { string canonicalName = GetCanonicalKeyPairGeneratorAlgorithm(algorithm); @@ -371,8 +362,8 @@ public static IAsymmetricCipherKeyPairGenerator GetKeyPairGenerator( if (canonicalName == "DSA") return new DsaKeyPairGenerator(); - // "EC", "ECDH", "ECDHC", "ECDSA", "ECGOST3410", "ECMQV" - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(canonicalName, "EC")) + // "EC", "ECDH", "ECDHC", "ECDSA", "ECGOST3410", "ECGOST3410-2012", "ECMQV" + if (Org.BouncyCastle.Utilities.Platform.StartsWith(canonicalName, "EC")) return new ECKeyPairGenerator(canonicalName); if (canonicalName == "Ed25519") @@ -400,14 +391,12 @@ public static IAsymmetricCipherKeyPairGenerator GetKeyPairGenerator( + " (" + canonicalName + ") not supported."); } - internal static int GetDefaultKeySize( - DerObjectIdentifier oid) + internal static int GetDefaultKeySize(DerObjectIdentifier oid) { return GetDefaultKeySize(oid.Id); } - internal static int GetDefaultKeySize( - string algorithm) + internal static int GetDefaultKeySize(string algorithm) { string canonicalName = GetCanonicalKeyGeneratorAlgorithm(algorithm); @@ -422,13 +411,9 @@ internal static int GetDefaultKeySize( return defaultKeySize; } - private static int FindDefaultKeySize( - string canonicalName) + private static int FindDefaultKeySize(string canonicalName) { - if (!defaultKeySizes.Contains(canonicalName)) - return -1; - - return (int)defaultKeySizes[canonicalName]; + return DefaultKeySizes.TryGetValue(canonicalName, out int keySize) ? keySize : -1; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/InvalidKeyException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/InvalidKeyException.cs index 0b9a79d..dfeb4a5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/InvalidKeyException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/InvalidKeyException.cs @@ -1,17 +1,33 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security { -#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE) [Serializable] -#endif - public class InvalidKeyException : KeyException + public class InvalidKeyException + : KeyException { - public InvalidKeyException() : base() { } - public InvalidKeyException(string message) : base(message) { } - public InvalidKeyException(string message, Exception exception) : base(message, exception) { } + public InvalidKeyException() + : base() + { + } + + public InvalidKeyException(string message) + : base(message) + { + } + + public InvalidKeyException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected InvalidKeyException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/InvalidParameterException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/InvalidParameterException.cs index 5bce04a..966ef66 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/InvalidParameterException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/InvalidParameterException.cs @@ -1,17 +1,33 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security { -#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE) [Serializable] -#endif - public class InvalidParameterException : KeyException + public class InvalidParameterException + : KeyException { - public InvalidParameterException() : base() { } - public InvalidParameterException(string message) : base(message) { } - public InvalidParameterException(string message, Exception exception) : base(message, exception) { } + public InvalidParameterException() + : base() + { + } + + public InvalidParameterException(string message) + : base(message) + { + } + + public InvalidParameterException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected InvalidParameterException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/JksStore.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/JksStore.cs new file mode 100644 index 0000000..8b773ce --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/JksStore.cs @@ -0,0 +1,600 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.Collections.Generic; +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.Crypto; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.IO; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Pkcs; +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.IO; +using BestHTTP.SecureProtocol.Org.BouncyCastle.X509; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security +{ + public class JksStore + { + private static readonly int Magic = unchecked((int)0xFEEDFEED); + + private static readonly AlgorithmIdentifier JksObfuscationAlg = new AlgorithmIdentifier( + new DerObjectIdentifier("1.3.6.1.4.1.42.2.17.1.1"), DerNull.Instance); + + private readonly Dictionary m_certificateEntries = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary m_keyEntries = + new Dictionary(StringComparer.OrdinalIgnoreCase); + + public JksStore() + { + } + + /// + public bool Probe(Stream stream) + { + using (var br = new BinaryReader(stream)) + try + { + return Magic == BinaryReaders.ReadInt32BigEndian(br); + } + catch (EndOfStreamException) + { + return false; + } + } + + /// + public AsymmetricKeyParameter GetKey(string alias, char[] password) + { + if (alias == null) + throw new ArgumentNullException(nameof(alias)); + if (password == null) + throw new ArgumentNullException(nameof(password)); + + if (!m_keyEntries.TryGetValue(alias, out JksKeyEntry keyEntry)) + return null; + + if (!JksObfuscationAlg.Equals(keyEntry.keyData.EncryptionAlgorithm)) + throw new IOException("unknown encryption algorithm"); + + byte[] encryptedData = keyEntry.keyData.GetEncryptedData(); + + // key length is encryptedData - salt - checksum + int pkcs8Len = encryptedData.Length - 40; + + IDigest digest = DigestUtilities.GetDigest("SHA-1"); + + // key decryption + byte[] keyStream = CalculateKeyStream(digest, password, encryptedData, pkcs8Len); + byte[] pkcs8Key = new byte[pkcs8Len]; + for (int i = 0; i < pkcs8Len; ++i) + { + pkcs8Key[i] = (byte)(encryptedData[20 + i] ^ keyStream[i]); + } + Array.Clear(keyStream, 0, keyStream.Length); + + // integrity check + byte[] checksum = GetKeyChecksum(digest, password, pkcs8Key); + + if (!Arrays.ConstantTimeAreEqual(20, encryptedData, pkcs8Len + 20, checksum, 0)) + throw new IOException("cannot recover key"); + + return PrivateKeyFactory.CreateKey(pkcs8Key); + } + + private byte[] GetKeyChecksum(IDigest digest, char[] password, byte[] pkcs8Key) + { + AddPassword(digest, password); + + return DigestUtilities.DoFinal(digest, pkcs8Key); + } + + private byte[] CalculateKeyStream(IDigest digest, char[] password, byte[] salt, int count) + { + byte[] keyStream = new byte[count]; + byte[] hash = Arrays.CopyOf(salt, 20); + + int index = 0; + while (index < count) + { + AddPassword(digest, password); + + digest.BlockUpdate(hash, 0, hash.Length); + digest.DoFinal(hash, 0); + + int length = System.Math.Min(hash.Length, keyStream.Length - index); + Array.Copy(hash, 0, keyStream, index, length); + index += length; + } + + return keyStream; + } + + public X509Certificate[] GetCertificateChain(string alias) + { + if (m_keyEntries.TryGetValue(alias, out var keyEntry)) + return CloneChain(keyEntry.chain); + + return null; + } + + public X509Certificate GetCertificate(string alias) + { + if (m_certificateEntries.TryGetValue(alias, out var certEntry)) + return certEntry.cert; + + if (m_keyEntries.TryGetValue(alias, out var keyEntry)) + return keyEntry.chain?[0]; + + return null; + } + + public DateTime? GetCreationDate(string alias) + { + if (m_certificateEntries.TryGetValue(alias, out var certEntry)) + return certEntry.date; + + if (m_keyEntries.TryGetValue(alias, out var keyEntry)) + return keyEntry.date; + + return null; + } + + /// + public void SetKeyEntry(string alias, AsymmetricKeyParameter key, char[] password, X509Certificate[] chain) + { + alias = ConvertAlias(alias); + + if (ContainsAlias(alias)) + throw new IOException("alias [" + alias + "] already in use"); + + byte[] pkcs8Key = PrivateKeyInfoFactory.CreatePrivateKeyInfo(key).GetEncoded(); + byte[] protectedKey = new byte[pkcs8Key.Length + 40]; + + SecureRandom rnd = CryptoServicesRegistrar.GetSecureRandom(); + rnd.NextBytes(protectedKey, 0, 20); + + IDigest digest = DigestUtilities.GetDigest("SHA-1"); + + byte[] checksum = GetKeyChecksum(digest, password, pkcs8Key); + Array.Copy(checksum, 0, protectedKey, 20 + pkcs8Key.Length, 20); + + byte[] keyStream = CalculateKeyStream(digest, password, protectedKey, pkcs8Key.Length); + for (int i = 0; i != keyStream.Length; i++) + { + protectedKey[20 + i] = (byte)(pkcs8Key[i] ^ keyStream[i]); + } + Array.Clear(keyStream, 0, keyStream.Length); + + try + { + var epki = new EncryptedPrivateKeyInfo(JksObfuscationAlg, protectedKey); + m_keyEntries.Add(alias, new JksKeyEntry(DateTime.UtcNow, epki.GetEncoded(), CloneChain(chain))); + } + catch (Exception e) + { + throw new IOException("unable to encode encrypted private key", e); + } + } + + /// + public void SetKeyEntry(string alias, byte[] key, X509Certificate[] chain) + { + alias = ConvertAlias(alias); + + if (ContainsAlias(alias)) + throw new IOException("alias [" + alias + "] already in use"); + + m_keyEntries.Add(alias, new JksKeyEntry(DateTime.UtcNow, key, CloneChain(chain))); + } + + /// + public void SetCertificateEntry(string alias, X509Certificate cert) + { + alias = ConvertAlias(alias); + + if (ContainsAlias(alias)) + throw new IOException("alias [" + alias + "] already in use"); + + m_certificateEntries.Add(alias, new JksTrustedCertEntry(DateTime.UtcNow, cert)); + } + + public void DeleteEntry(string alias) + { + if (!m_keyEntries.Remove(alias)) + { + m_certificateEntries.Remove(alias); + } + } + + public IEnumerable Aliases + { + get + { + var aliases = new HashSet(m_certificateEntries.Keys); + aliases.UnionWith(m_keyEntries.Keys); + return CollectionUtilities.Proxy(aliases); + } + } + + public bool ContainsAlias(string alias) + { + return IsCertificateEntry(alias) || IsKeyEntry(alias); + } + + public int Count + { + get { return m_certificateEntries.Count + m_keyEntries.Count; } + } + + public bool IsKeyEntry(string alias) + { + return m_keyEntries.ContainsKey(alias); + } + + public bool IsCertificateEntry(string alias) + { + return m_certificateEntries.ContainsKey(alias); + } + + public string GetCertificateAlias(X509Certificate cert) + { + foreach (var entry in m_certificateEntries) + { + if (entry.Value.cert.Equals(cert)) + return entry.Key; + } + return null; + } + + /// + public void Save(Stream stream, char[] password) + { + if (stream == null) + throw new ArgumentNullException(nameof(stream)); + if (password == null) + throw new ArgumentNullException(nameof(password)); + + IDigest checksumDigest = CreateChecksumDigest(password); + BinaryWriter bw = new BinaryWriter(new DigestStream(stream, null, checksumDigest)); + + BinaryWriters.WriteInt32BigEndian(bw, Magic); + BinaryWriters.WriteInt32BigEndian(bw, 2); + + BinaryWriters.WriteInt32BigEndian(bw, Count); + + foreach (var entry in m_keyEntries) + { + string alias = entry.Key; + JksKeyEntry keyEntry = entry.Value; + + BinaryWriters.WriteInt32BigEndian(bw, 1); + WriteUtf(bw, alias); + WriteDateTime(bw, keyEntry.date); + WriteBufferWithInt32Length(bw, keyEntry.keyData.GetEncoded()); + + X509Certificate[] chain = keyEntry.chain; + int chainLength = chain == null ? 0 : chain.Length; + BinaryWriters.WriteInt32BigEndian(bw, chainLength); + for (int i = 0; i < chainLength; ++i) + { + WriteTypedCertificate(bw, chain[i]); + } + } + + foreach (var entry in m_certificateEntries) + { + string alias = entry.Key; + JksTrustedCertEntry certEntry = entry.Value; + + BinaryWriters.WriteInt32BigEndian(bw, 2); + WriteUtf(bw, alias); + WriteDateTime(bw, certEntry.date); + WriteTypedCertificate(bw, certEntry.cert); + } + + byte[] checksum = DigestUtilities.DoFinal(checksumDigest); + bw.Write(checksum); + bw.Flush(); + } + + /// + public void Load(Stream stream, char[] password) + { + if (stream == null) + throw new ArgumentNullException(nameof(stream)); + + m_certificateEntries.Clear(); + m_keyEntries.Clear(); + + using (var storeStream = ValidateStream(stream, password)) + { + BinaryReader br = new BinaryReader(storeStream); + + int magic = BinaryReaders.ReadInt32BigEndian(br); + int storeVersion = BinaryReaders.ReadInt32BigEndian(br); + + if (!(magic == Magic && (storeVersion == 1 || storeVersion == 2))) + throw new IOException("Invalid keystore format"); + + int numEntries = BinaryReaders.ReadInt32BigEndian(br); + + for (int t = 0; t < numEntries; t++) + { + int tag = BinaryReaders.ReadInt32BigEndian(br); + + switch (tag) + { + case 1: // keys + { + string alias = ReadUtf(br); + DateTime date = ReadDateTime(br); + + // encrypted key data + byte[] keyData = ReadBufferWithInt32Length(br); + + // certificate chain + int chainLength = BinaryReaders.ReadInt32BigEndian(br); + X509Certificate[] chain = null; + if (chainLength > 0) + { + var certs = new List(System.Math.Min(10, chainLength)); + for (int certNo = 0; certNo != chainLength; certNo++) + { + certs.Add(ReadTypedCertificate(br, storeVersion)); + } + chain = certs.ToArray(); + } + m_keyEntries.Add(alias, new JksKeyEntry(date, keyData, chain)); + break; + } + case 2: // certificate + { + string alias = ReadUtf(br); + DateTime date = ReadDateTime(br); + + X509Certificate cert = ReadTypedCertificate(br, storeVersion); + + m_certificateEntries.Add(alias, new JksTrustedCertEntry(date, cert)); + break; + } + default: + throw new IOException("unable to discern entry type"); + } + } + + if (storeStream.Position != storeStream.Length) + throw new IOException("password incorrect or store tampered with"); + } + } + + /* + * Validate password takes the checksum of the store and will either. + * 1. If password is null, load the store into memory, return the result. + * 2. If password is not null, load the store into memory, test the checksum, and if successful return + * a new input stream instance of the store. + * 3. Fail if there is a password and an invalid checksum. + * + * @param inputStream The input stream. + * @param password the password. + * @return Either the passed in input stream or a new input stream. + */ + /// + private ErasableByteStream ValidateStream(Stream inputStream, char[] password) + { + byte[] rawStore = Streams.ReadAll(inputStream); + int checksumPos = rawStore.Length - 20; + + if (password != null) + { + byte[] checksum = CalculateChecksum(password, rawStore, 0, checksumPos); + + if (!Arrays.ConstantTimeAreEqual(20, checksum, 0, rawStore, checksumPos)) + { + Array.Clear(rawStore, 0, rawStore.Length); + throw new IOException("password incorrect or store tampered with"); + } + } + + return new ErasableByteStream(rawStore, 0, checksumPos); + } + + private static void AddPassword(IDigest digest, char[] password) + { + // Encoding.BigEndianUnicode + for (int i = 0; i < password.Length; ++i) + { + digest.Update((byte)(password[i] >> 8)); + digest.Update((byte)password[i]); + } + } + + private static byte[] CalculateChecksum(char[] password, byte[] buffer, int offset, int length) + { + IDigest checksumDigest = CreateChecksumDigest(password); + checksumDigest.BlockUpdate(buffer, offset, length); + return DigestUtilities.DoFinal(checksumDigest); + } + + private static X509Certificate[] CloneChain(X509Certificate[] chain) + { + return (X509Certificate[])chain?.Clone(); + } + + private static string ConvertAlias(string alias) + { + return alias.ToLowerInvariant(); + } + + private static IDigest CreateChecksumDigest(char[] password) + { + IDigest digest = DigestUtilities.GetDigest("SHA-1"); + AddPassword(digest, password); + + // + // This "Mighty Aphrodite" string goes all the way back to the + // first java betas in the mid 90's, why who knows? But see + // https://cryptosense.com/mighty-aphrodite-dark-secrets-of-the-java-keystore/ + // + byte[] prefix = Encoding.UTF8.GetBytes("Mighty Aphrodite"); + digest.BlockUpdate(prefix, 0, prefix.Length); + return digest; + } + + private static byte[] ReadBufferWithInt16Length(BinaryReader br) + { + int length = BinaryReaders.ReadInt16BigEndian(br); + return BinaryReaders.ReadBytesFully(br, length); + } + + private static byte[] ReadBufferWithInt32Length(BinaryReader br) + { + int length = BinaryReaders.ReadInt32BigEndian(br); + return BinaryReaders.ReadBytesFully(br, length); + } + + private static DateTime ReadDateTime(BinaryReader br) + { + long unixMS = BinaryReaders.ReadInt64BigEndian(br); + return DateTimeUtilities.UnixMsToDateTime(unixMS); + } + + private static X509Certificate ReadTypedCertificate(BinaryReader br, int storeVersion) + { + if (storeVersion == 2) + { + string certFormat = ReadUtf(br); + if ("X.509" != certFormat) + throw new IOException("Unsupported certificate format: " + certFormat); + } + + byte[] certData = ReadBufferWithInt32Length(br); + try + { + return new X509Certificate(certData); + } + finally + { + Array.Clear(certData, 0, certData.Length); + } + } + + private static string ReadUtf(BinaryReader br) + { + byte[] utfBytes = ReadBufferWithInt16Length(br); + + /* + * FIXME JKS actually uses a "modified UTF-8" format. For the moment we will just support single-byte + * encodings that aren't null bytes. + */ + for (int i = 0; i < utfBytes.Length; ++i) + { + byte utfByte = utfBytes[i]; + if (utfByte == 0 || (utfByte & 0x80) != 0) + throw new NotSupportedException("Currently missing support for modified UTF-8 encoding in JKS"); + } + + return Encoding.UTF8.GetString(utfBytes); + } + + private static void WriteBufferWithInt16Length(BinaryWriter bw, byte[] buffer) + { + BinaryWriters.WriteInt16BigEndian(bw, Convert.ToInt16(buffer.Length)); + bw.Write(buffer); + } + + private static void WriteBufferWithInt32Length(BinaryWriter bw, byte[] buffer) + { + BinaryWriters.WriteInt32BigEndian(bw, buffer.Length); + bw.Write(buffer); + } + + private static void WriteDateTime(BinaryWriter bw, DateTime dateTime) + { + long unixMS = DateTimeUtilities.DateTimeToUnixMs(dateTime); + BinaryWriters.WriteInt64BigEndian(bw, unixMS); + } + + private static void WriteTypedCertificate(BinaryWriter bw, X509Certificate cert) + { + WriteUtf(bw, "X.509"); + WriteBufferWithInt32Length(bw, cert.GetEncoded()); + } + + private static void WriteUtf(BinaryWriter bw, string s) + { + byte[] utfBytes = Encoding.UTF8.GetBytes(s); + + /* + * FIXME JKS actually uses a "modified UTF-8" format. For the moment we will just support single-byte + * encodings that aren't null bytes. + */ + for (int i = 0; i < utfBytes.Length; ++i) + { + byte utfByte = utfBytes[i]; + if (utfByte == 0 || (utfByte & 0x80) != 0) + throw new NotSupportedException("Currently missing support for modified UTF-8 encoding in JKS"); + } + + WriteBufferWithInt16Length(bw, utfBytes); + } + + /** + * JksTrustedCertEntry is a internal container for the certificate entry. + */ + private sealed class JksTrustedCertEntry + { + internal readonly DateTime date; + internal readonly X509Certificate cert; + + internal JksTrustedCertEntry(DateTime date, X509Certificate cert) + { + this.date = date; + this.cert = cert; + } + } + + private sealed class JksKeyEntry + { + internal readonly DateTime date; + internal readonly EncryptedPrivateKeyInfo keyData; + internal readonly X509Certificate[] chain; + + internal JksKeyEntry(DateTime date, byte[] keyData, X509Certificate[] chain) + { + this.date = date; + this.keyData = EncryptedPrivateKeyInfo.GetInstance(Asn1Sequence.GetInstance(keyData)); + this.chain = chain; + } + } + + private sealed class ErasableByteStream + : MemoryStream + { + internal ErasableByteStream(byte[] buffer, int index, int count) + : base(buffer, index, count, false, true) + { + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + Position = 0L; + + byte[] rawStore = GetBuffer(); + Array.Clear(rawStore, 0, rawStore.Length); + } + base.Dispose(disposing); + } + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/JksStore.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/security/JksStore.cs.meta new file mode 100644 index 0000000..5fd90d6 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/JksStore.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 76c504517a951fc4e8508cc041cd8ec8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/KeyException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/KeyException.cs index 91872fc..0489420 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/KeyException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/KeyException.cs @@ -1,17 +1,33 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security { -#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE) [Serializable] -#endif - public class KeyException : GeneralSecurityException + public class KeyException + : GeneralSecurityException { - public KeyException() : base() { } - public KeyException(string message) : base(message) { } - public KeyException(string message, Exception exception) : base(message, exception) { } + public KeyException() + : base() + { + } + + public KeyException(string message) + : base(message) + { + } + + public KeyException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected KeyException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/MacUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/MacUtilities.cs index 145d223..01ec232 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/MacUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/MacUtilities.cs @@ -1,11 +1,8 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; -using System.Globalization; -using System.Security.Cryptography; +using System.Collections.Generic; -using BestHTTP.PlatformSupport.Memory; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Iana; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Misc; @@ -17,128 +14,96 @@ using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Macs; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Paddings; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security { /// /// Utility class for creating HMac object from their names/Oids /// - public sealed class MacUtilities + public static 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(); + private static readonly IDictionary Algorithms = + new Dictionary(StringComparer.OrdinalIgnoreCase); 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[MiscObjectIdentifiers.HMAC_SHA1.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"; + 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[MiscObjectIdentifiers.HMAC_SHA1.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"; + 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) + public static IMac GetMac(DerObjectIdentifier id) { return GetMac(id.Id); } - public static IMac GetMac( - string algorithm) + public static IMac GetMac(string algorithm) { - string upper = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm); - - string mechanism = (string) algorithms[upper]; + if (algorithm == null) + throw new ArgumentNullException(nameof(algorithm)); - if (mechanism == null) - { - mechanism = upper; - } + string mechanism = CollectionUtilities.GetValueOrKey(Algorithms, algorithm).ToUpperInvariant(); - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEWITH")) + if (Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEWITH")) { mechanism = mechanism.Substring("PBEWITH".Length); } - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "HMAC")) + if (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/")) + if (Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "HMAC-") || Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "HMAC/")) { digestName = mechanism.Substring(5); } @@ -152,7 +117,7 @@ public static IMac GetMac( if (mechanism == "AESCMAC") { - return new CMac(new AesEngine()); + return new CMac(AesUtilities.CreateEngine()); } if (mechanism == "DESMAC") { @@ -242,10 +207,9 @@ public static IMac GetMac( throw new SecurityUtilityException("Mac " + mechanism + " not recognised."); } - public static string GetAlgorithmName( - DerObjectIdentifier oid) + public static string GetAlgorithmName(DerObjectIdentifier oid) { - return (string) algorithms[oid.Id]; + return CollectionUtilities.GetValueOrNull(Algorithms, oid.Id); } public static byte[] CalculateMac(string algorithm, ICipherParameters cp, byte[] input) @@ -263,14 +227,6 @@ public static byte[] DoFinal(IMac mac) return b; } - public static BufferSegment DoFinalOptimized(IMac mac) - { - int length = mac.GetMacSize(); - byte[] b = BufferPool.Get(length, true); - mac.DoFinal(b, 0); - return new BufferSegment(b, 0, length); - } - public static byte[] DoFinal(IMac mac, byte[] input) { mac.BlockUpdate(input, 0, input.Length); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/ParameterUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/ParameterUtilities.cs index e046dcb..564d7f4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/ParameterUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/ParameterUtilities.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro; @@ -14,18 +14,16 @@ 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; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security { - public sealed class ParameterUtilities + public static 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(); + private static readonly IDictionary Algorithms = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly IDictionary BasicIVSizes = + new Dictionary(StringComparer.OrdinalIgnoreCase); static ParameterUtilities() { @@ -122,7 +120,7 @@ static ParameterUtilities() AddAlgorithm("GOST28147", "GOST", "GOST-28147", - CryptoProObjectIdentifiers.GostR28147Cbc); + CryptoProObjectIdentifiers.GostR28147Gcfb); AddAlgorithm("HC128"); AddAlgorithm("HC256"); AddAlgorithm("IDEA", @@ -166,15 +164,13 @@ static ParameterUtilities() // "RIJNDAEL", "SKIPJACK", "TWOFISH" } - private static void AddAlgorithm( - string canonicalName, - params object[] aliases) + private static void AddAlgorithm(string canonicalName, params object[] aliases) { - algorithms[canonicalName] = canonicalName; + Algorithms[canonicalName] = canonicalName; foreach (object alias in aliases) { - algorithms[alias.ToString()] = canonicalName; + Algorithms[alias.ToString()] = canonicalName; } } @@ -182,26 +178,21 @@ private static void AddBasicIVSizeEntries(int size, params string[] algorithms) { foreach (string algorithm in algorithms) { - basicIVSizes.Add(algorithm, size); + BasicIVSizes.Add(algorithm, size); } } - public static string GetCanonicalAlgorithmName( - string algorithm) + public static string GetCanonicalAlgorithmName(string algorithm) { - return (string) algorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm)]; + return CollectionUtilities.GetValueOrNull(Algorithms, algorithm); } - public static KeyParameter CreateKeyParameter( - DerObjectIdentifier algOid, - byte[] keyBytes) + public static KeyParameter CreateKeyParameter(DerObjectIdentifier algOid, byte[] keyBytes) { return CreateKeyParameter(algOid.Id, keyBytes, 0, keyBytes.Length); } - public static KeyParameter CreateKeyParameter( - string algorithm, - byte[] keyBytes) + public static KeyParameter CreateKeyParameter(string algorithm, byte[] keyBytes) { return CreateKeyParameter(algorithm, keyBytes, 0, keyBytes.Length); } @@ -222,7 +213,7 @@ public static KeyParameter CreateKeyParameter( int length) { if (algorithm == null) - throw new ArgumentNullException("algorithm"); + throw new ArgumentNullException(nameof(algorithm)); string canonical = GetCanonicalAlgorithmName(algorithm); @@ -350,9 +341,7 @@ public static ICipherParameters WithRandom(ICipherParameters cp, SecureRandom ra return cp; } - private static Asn1OctetString CreateIVOctetString( - SecureRandom random, - int ivLength) + private static Asn1OctetString CreateIVOctetString(SecureRandom random, int ivLength) { return new DerOctetString(CreateIV(random, ivLength)); } @@ -362,13 +351,9 @@ private static byte[] CreateIV(SecureRandom random, int ivLength) return SecureRandom.GetNextBytes(random, ivLength); } - private static int FindBasicIVSize( - string canonicalName) + private static int FindBasicIVSize(string canonicalName) { - if (!basicIVSizes.Contains(canonicalName)) - return -1; - - return (int)basicIVSizes[canonicalName]; + return BasicIVSizes.TryGetValue(canonicalName, out int keySize) ? keySize : -1; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/PbeUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/PbeUtilities.cs index 5cb2e08..ef432a7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/PbeUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/PbeUtilities.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.BC; @@ -12,40 +12,36 @@ 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; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security { /// /// /// - public sealed class PbeUtilities + public static 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(); + private static readonly IDictionary Algorithms = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly IDictionary AlgorithmType = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly IDictionary Oids = + new Dictionary(StringComparer.OrdinalIgnoreCase); static PbeUtilities() { - algorithms["PKCS5SCHEME1"] = "Pkcs5scheme1"; - algorithms["PKCS5SCHEME2"] = "Pkcs5scheme2"; - algorithms["PBKDF2"] = "Pkcs5scheme2"; - algorithms[PkcsObjectIdentifiers.IdPbeS2.Id] = "Pkcs5scheme2"; + Algorithms["PKCS5SCHEME1"] = "Pkcs5scheme1"; + Algorithms["PKCS5SCHEME2"] = "Pkcs5scheme2"; + Algorithms["PBKDF2"] = "Pkcs5scheme2"; + Algorithms[PkcsObjectIdentifiers.IdPbeS2.Id] = "Pkcs5scheme2"; // algorithms[PkcsObjectIdentifiers.IdPbkdf2.Id] = "Pkcs5scheme2"; // FIXME Add support for these? (see Pkcs8Generator) @@ -54,155 +50,155 @@ static PbeUtilities() // 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; + 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( @@ -244,60 +240,65 @@ static PbeParametersGenerator MakePbeGenerator( /// /// A string representation of the encoding. /// A DerObjectIdentifier, null if the Oid is not available. - public static DerObjectIdentifier GetObjectIdentifier( - string mechanism) + 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; - } + if (!Algorithms.TryGetValue(mechanism, out var algorithm)) + return null; - public static ICollection Algorithms - { - get { return oids.Keys; } + return CollectionUtilities.GetValueOrNull(Oids, algorithm); } - public static bool IsPkcs12( - string algorithm) + //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)]; + if (!Algorithms.TryGetValue(algorithm, out var mechanism)) + return false; + if (!AlgorithmType.TryGetValue(mechanism, out var algorithmType)) + return false; - return mechanism != null && Pkcs12.Equals(algorithmType[mechanism]); + return Pkcs12.Equals(algorithmType); } - public static bool IsPkcs5Scheme1( - string algorithm) + public static bool IsPkcs5Scheme1(string algorithm) { - string mechanism = (string)algorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm)]; + if (!Algorithms.TryGetValue(algorithm, out var mechanism)) + return false; + if (!AlgorithmType.TryGetValue(mechanism, out var algorithmType)) + return false; - return mechanism != null && Pkcs5S1.Equals(algorithmType[mechanism]); + return Pkcs5S1.Equals(algorithmType); } - public static bool IsPkcs5Scheme2( - string algorithm) + public static bool IsPkcs5Scheme2(string algorithm) { - string mechanism = (string)algorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm)]; + if (!Algorithms.TryGetValue(algorithm, out var mechanism)) + return false; + if (!AlgorithmType.TryGetValue(mechanism, out var algorithmType)) + return false; - return mechanism != null && Pkcs5S2.Equals(algorithmType[mechanism]); + return Pkcs5S2.Equals(algorithmType); } - public static bool IsOpenSsl( - string algorithm) + public static bool IsOpenSsl(string algorithm) { - string mechanism = (string)algorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm)]; + if (!Algorithms.TryGetValue(algorithm, out var mechanism)) + return false; + if (!AlgorithmType.TryGetValue(mechanism, out var algorithmType)) + return false; - return mechanism != null && OpenSsl.Equals(algorithmType[mechanism]); + return OpenSsl.Equals(algorithmType); } - public static bool IsPbeAlgorithm( - string algorithm) + public static bool IsPbeAlgorithm(string algorithm) { - string mechanism = (string)algorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm)]; + if (!Algorithms.TryGetValue(algorithm, out var mechanism)) + return false; - return mechanism != null && algorithmType[mechanism] != null; + return AlgorithmType.ContainsKey(mechanism); } public static Asn1Encodable GenerateAlgorithmParameters( @@ -402,7 +403,7 @@ public static ICipherParameters GenerateCipherParameters( bool wrongPkcs12Zero, Asn1Encodable pbeParameters) { - string mechanism = (string)algorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm)]; + string mechanism = CollectionUtilities.GetValueOrNull(Algorithms, algorithm); byte[] keyBytes = null; byte[] salt = null; @@ -459,7 +460,7 @@ public static ICipherParameters GenerateCipherParameters( : GeneratorUtilities.GetDefaultKeySize(encOid); PbeParametersGenerator gen = MakePbeGenerator( - (string)algorithmType[mechanism], digest, keyBytes, salt, iterationCount); + AlgorithmType[mechanism], digest, keyBytes, salt, iterationCount); parameters = gen.GenerateDerivedParameters(encOid.Id, keyLength); @@ -476,10 +477,10 @@ public static ICipherParameters GenerateCipherParameters( } } } - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithSHA-1")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithSHA-1")) { PbeParametersGenerator generator = MakePbeGenerator( - (string) algorithmType[mechanism], new Sha1Digest(), keyBytes, salt, iterationCount); + AlgorithmType[mechanism], new Sha1Digest(), keyBytes, salt, iterationCount); if (mechanism.Equals("PBEwithSHA-1and128bitAES-CBC-BC")) { @@ -526,10 +527,10 @@ public static ICipherParameters GenerateCipherParameters( parameters = generator.GenerateDerivedParameters("RC2", 64, 64); } } - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithSHA-256")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithSHA-256")) { PbeParametersGenerator generator = MakePbeGenerator( - (string) algorithmType[mechanism], new Sha256Digest(), keyBytes, salt, iterationCount); + AlgorithmType[mechanism], new Sha256Digest(), keyBytes, salt, iterationCount); if (mechanism.Equals("PBEwithSHA-256and128bitAES-CBC-BC")) { @@ -544,10 +545,10 @@ public static ICipherParameters GenerateCipherParameters( parameters = generator.GenerateDerivedParameters("AES", 256, 128); } } - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithMD5")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithMD5")) { PbeParametersGenerator generator = MakePbeGenerator( - (string)algorithmType[mechanism], new MD5Digest(), keyBytes, salt, iterationCount); + AlgorithmType[mechanism], new MD5Digest(), keyBytes, salt, iterationCount); if (mechanism.Equals("PBEwithMD5andDES-CBC")) { @@ -570,10 +571,10 @@ public static ICipherParameters GenerateCipherParameters( parameters = generator.GenerateDerivedParameters("AES", 256, 128); } } - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithMD2")) + else if (Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithMD2")) { PbeParametersGenerator generator = MakePbeGenerator( - (string)algorithmType[mechanism], new MD2Digest(), keyBytes, salt, iterationCount); + AlgorithmType[mechanism], new MD2Digest(), keyBytes, salt, iterationCount); if (mechanism.Equals("PBEwithMD2andDES-CBC")) { parameters = generator.GenerateDerivedParameters("DES", 64, 64); @@ -583,13 +584,13 @@ public static ICipherParameters GenerateCipherParameters( parameters = generator.GenerateDerivedParameters("RC2", 64, 64); } } - else if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithHmac")) + else if (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); + AlgorithmType[mechanism], digest, keyBytes, salt, iterationCount); int bitLen = digest.GetDigestSize() * 8; parameters = generator.GenerateDerivedMacParameters(bitLen); @@ -621,44 +622,43 @@ public static object CreateEngine( return CreateEngine(algorithm); } - public static object CreateEngine( - string algorithm) + public static object CreateEngine(string algorithm) { - string mechanism = (string)algorithms[BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm)]; + string mechanism = CollectionUtilities.GetValueOrNull(Algorithms, algorithm); - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithHmac")) + if (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 (Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithMD2") + || Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithMD5") + || Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "PBEwithSHA-1") + || 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")) + if (Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "AES-CBC-BC") || 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")) + if (Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "DES-CBC")) { return CipherUtilities.GetCipher("DES/CBC"); } - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "DESEDE-CBC")) + if (Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "DESEDE-CBC")) { return CipherUtilities.GetCipher("DESEDE/CBC"); } - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "RC2-CBC")) + if (Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "RC2-CBC")) { return CipherUtilities.GetCipher("RC2/CBC"); } - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "RC4")) + if (Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "RC4")) { return CipherUtilities.GetCipher("RC4"); } @@ -667,15 +667,14 @@ public static object CreateEngine( return null; } - public static string GetEncodingName( - DerObjectIdentifier oid) + public static string GetEncodingName(DerObjectIdentifier oid) { - return (string) algorithms[oid.Id]; + return CollectionUtilities.GetValueOrNull(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")) + if (!Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "DES-CBC") && !Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "DESEDE-CBC")) { return parameters; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/PrivateKeyFactory.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/PrivateKeyFactory.cs index 6558685..f440096 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/PrivateKeyFactory.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/PrivateKeyFactory.cs @@ -1,13 +1,13 @@ #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.Cryptlib; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.EdEC; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Gnu; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Rosstandart; @@ -23,12 +23,8 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security { - public sealed class PrivateKeyFactory + public static class PrivateKeyFactory { - private PrivateKeyFactory() - { - } - public static AsymmetricKeyParameter CreateKey( byte[] privateKeyInfoData) { @@ -132,29 +128,99 @@ public static AsymmetricKeyParameter CreateKey( 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)) + else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001) || + algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512) || + algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256)) { - Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance( - algID.Parameters.ToAsn1Object()); + Asn1Object p = algID.Parameters.ToAsn1Object(); + Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(p); - X9ECParameters ecP = ECGost3410NamedCurves.GetByOidX9(gostParams.PublicKeyParamSet); + ECGost3410Parameters ecSpec; + BigInteger d; - if (ecP == null) - throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key"); + if (p is Asn1Sequence seq && (seq.Count == 2 || seq.Count == 3)) + { + X9ECParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); + if (ecP == null) + throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key"); - Asn1Object privKey = keyInfo.ParsePrivateKey(); - ECPrivateKeyStructure ec; + ecSpec = new ECGost3410Parameters( + new ECNamedDomainParameters(gostParams.PublicKeyParamSet, ecP), + gostParams.PublicKeyParamSet, + gostParams.DigestParamSet, + gostParams.EncryptionParamSet); - if (privKey is DerInteger) - { - ec = new ECPrivateKeyStructure(ecP.N.BitLength, ((DerInteger)privKey).PositiveValue); + Asn1OctetString privEnc = keyInfo.PrivateKeyData; + if (privEnc.GetOctets().Length == 32 || privEnc.GetOctets().Length == 64) + { + d = new BigInteger(1, Arrays.Reverse(privEnc.GetOctets())); + } + else + { + Asn1Object privKey = keyInfo.ParsePrivateKey(); + if (privKey is DerInteger derInteger) + { + d = derInteger.PositiveValue; + } + else + { + byte[] dVal = Arrays.Reverse(Asn1OctetString.GetInstance(privKey).GetOctets()); + d = new BigInteger(1, dVal); + } + } } else { - ec = ECPrivateKeyStructure.GetInstance(privKey); + X962Parameters x962Parameters = X962Parameters.GetInstance(p); + + if (x962Parameters.IsNamedCurve) + { + DerObjectIdentifier oid = DerObjectIdentifier.GetInstance(x962Parameters.Parameters); + X9ECParameters ecP = ECNamedCurveTable.GetByOid(oid); + if (ecP == null) + throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key"); + + ecSpec = new ECGost3410Parameters( + new ECNamedDomainParameters(oid, ecP), + gostParams.PublicKeyParamSet, + gostParams.DigestParamSet, + gostParams.EncryptionParamSet); + } + else if (x962Parameters.IsImplicitlyCA) + { + ecSpec = null; + } + else + { + X9ECParameters ecP = X9ECParameters.GetInstance(x962Parameters.Parameters); + + ecSpec = new ECGost3410Parameters( + new ECNamedDomainParameters(algOid, ecP), + gostParams.PublicKeyParamSet, + gostParams.DigestParamSet, + gostParams.EncryptionParamSet); + } + + Asn1Object privKey = keyInfo.ParsePrivateKey(); + if (privKey is DerInteger derD) + { + d = derD.Value; + } + else + { + ECPrivateKeyStructure ec = ECPrivateKeyStructure.GetInstance(privKey); + + d = ec.GetKey(); + } } - return new ECPrivateKeyParameters("ECGOST3410", ec.GetKey(), gostParams.PublicKeyParamSet); + return new ECPrivateKeyParameters( + d, + new ECGost3410Parameters( + ecSpec, + gostParams.PublicKeyParamSet, + gostParams.DigestParamSet, + gostParams.EncryptionParamSet)); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { @@ -174,7 +240,8 @@ public static AsymmetricKeyParameter CreateKey( return new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet); } - else if (algOid.Equals(EdECObjectIdentifiers.id_X25519)) + else if (algOid.Equals(EdECObjectIdentifiers.id_X25519) + || algOid.Equals(CryptlibObjectIdentifiers.curvey25519)) { return new X25519PrivateKeyParameters(GetRawKey(keyInfo)); } @@ -182,7 +249,8 @@ public static AsymmetricKeyParameter CreateKey( { return new X448PrivateKeyParameters(GetRawKey(keyInfo)); } - else if (algOid.Equals(EdECObjectIdentifiers.id_Ed25519)) + else if (algOid.Equals(EdECObjectIdentifiers.id_Ed25519) + || algOid.Equals(GnuObjectIdentifiers.Ed25519)) { return new Ed25519PrivateKeyParameters(GetRawKey(keyInfo)); } @@ -190,17 +258,19 @@ public static AsymmetricKeyParameter CreateKey( { return new Ed448PrivateKeyParameters(GetRawKey(keyInfo)); } - else if (algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512) - || algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256)) + else if (algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256) + || algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512) + || algOid.Equals(RosstandartObjectIdentifiers.id_tc26_agreement_gost_3410_12_256) + || algOid.Equals(RosstandartObjectIdentifiers.id_tc26_agreement_gost_3410_12_512)) { - Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(keyInfo.PrivateKeyAlgorithm.Parameters); + Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance( + keyInfo.PrivateKeyAlgorithm.Parameters); ECGost3410Parameters ecSpec; BigInteger d; Asn1Object p = keyInfo.PrivateKeyAlgorithm.Parameters.ToAsn1Object(); if (p is Asn1Sequence && (Asn1Sequence.GetInstance(p).Count == 2 || Asn1Sequence.GetInstance(p).Count == 3)) { - - X9ECParameters ecP = ECGost3410NamedCurves.GetByOidX9(gostParams.PublicKeyParamSet); + X9ECParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); ecSpec = new ECGost3410Parameters( new ECNamedDomainParameters( @@ -236,7 +306,7 @@ public static AsymmetricKeyParameter CreateKey( if (parameters.IsNamedCurve) { DerObjectIdentifier oid = DerObjectIdentifier.GetInstance(parameters.Parameters); - X9ECParameters ecP = ECNamedCurveTable.GetByOid(oid); + X9ECParameters ecP = ECKeyPairGenerator.FindECCurveByOid(oid); ecSpec = new ECGost3410Parameters(new ECNamedDomainParameters(oid, ecP), gostParams.PublicKeyParamSet, gostParams.DigestParamSet, diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/PublicKeyFactory.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/PublicKeyFactory.cs index a942b4b..062d5bb 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/PublicKeyFactory.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/PublicKeyFactory.cs @@ -1,17 +1,16 @@ #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.Cryptlib; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.EdEC; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Gnu; 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.Sec; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; @@ -20,16 +19,11 @@ using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.EC; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security { - public sealed class PublicKeyFactory + public static class PublicKeyFactory { - private PublicKeyFactory() - { - } - public static AsymmetricKeyParameter CreateKey( byte[] keyInfoData) { @@ -164,7 +158,7 @@ public static AsymmetricKeyParameter CreateKey( Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters); DerObjectIdentifier publicKeyParamSet = gostParams.PublicKeyParamSet; - X9ECParameters ecP = ECGost3410NamedCurves.GetByOidX9(publicKeyParamSet); + X9ECParameters ecP = ECGost3410NamedCurves.GetByOid(publicKeyParamSet); if (ecP == null) return null; @@ -217,7 +211,8 @@ public static AsymmetricKeyParameter CreateKey( return new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet); } - else if (algOid.Equals(EdECObjectIdentifiers.id_X25519)) + else if (algOid.Equals(EdECObjectIdentifiers.id_X25519) + || algOid.Equals(CryptlibObjectIdentifiers.curvey25519)) { return new X25519PublicKeyParameters(GetRawKey(keyInfo)); } @@ -225,7 +220,8 @@ public static AsymmetricKeyParameter CreateKey( { return new X448PublicKeyParameters(GetRawKey(keyInfo)); } - else if (algOid.Equals(EdECObjectIdentifiers.id_Ed25519)) + else if (algOid.Equals(EdECObjectIdentifiers.id_Ed25519) + || algOid.Equals(GnuObjectIdentifiers.Ed25519)) { return new Ed25519PublicKeyParameters(GetRawKey(keyInfo)); } @@ -234,13 +230,15 @@ public static AsymmetricKeyParameter CreateKey( return new Ed448PublicKeyParameters(GetRawKey(keyInfo)); } else if (algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256) - || algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512)) + || algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512) + || algOid.Equals(RosstandartObjectIdentifiers.id_tc26_agreement_gost_3410_12_256) + || algOid.Equals(RosstandartObjectIdentifiers.id_tc26_agreement_gost_3410_12_512)) { Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters); DerObjectIdentifier publicKeyParamSet = gostParams.PublicKeyParamSet; ECGost3410Parameters ecDomainParameters =new ECGost3410Parameters( - new ECNamedDomainParameters(publicKeyParamSet, ECGost3410NamedCurves.GetByOidX9(publicKeyParamSet)), + new ECNamedDomainParameters(publicKeyParamSet, ECGost3410NamedCurves.GetByOid(publicKeyParamSet)), publicKeyParamSet, gostParams.DigestParamSet, gostParams.EncryptionParamSet); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/SecureRandom.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/SecureRandom.cs index a4c8143..1536977 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/SecureRandom.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/SecureRandom.cs @@ -4,63 +4,23 @@ 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.Crypto.Utilities; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security { public class SecureRandom : Random { - private static long counter = Times.NanoTime(); + private static long counter = DateTime.UtcNow.Ticks; -#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 readonly SecureRandom MasterRandom = new SecureRandom(new CryptoApiRandomGenerator()); + internal static readonly SecureRandom ArbitraryRandom = new SecureRandom(new VmpcRandomGenerator(), 16); private static DigestRandomGenerator CreatePrng(string digestName, bool autoSeed) { @@ -70,8 +30,7 @@ private static DigestRandomGenerator CreatePrng(string digestName, bool autoSeed DigestRandomGenerator prng = new DigestRandomGenerator(digest); if (autoSeed) { - prng.AddSeedMaterial(NextCounterValue()); - prng.AddSeedMaterial(GetNextBytes(Master, digest.GetDigestSize())); + AutoSeed(prng, digest.GetDigestSize()); } return prng; } @@ -100,26 +59,21 @@ public static SecureRandom GetInstance(string algorithm) /// 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")) + if (algorithm == null) + throw new ArgumentNullException(nameof(algorithm)); + + if (algorithm.EndsWith("PRNG", StringComparison.OrdinalIgnoreCase)) { - string digestName = upper.Substring(0, upper.Length - "PRNG".Length); + string digestName = algorithm.Substring(0, algorithm.Length - "PRNG".Length); + DigestRandomGenerator prng = CreatePrng(digestName, autoSeed); if (prng != null) - { return new SecureRandom(prng); - } } throw new ArgumentException("Unrecognised PRNG algorithm: " + algorithm, "algorithm"); } - - public static byte[] GetSeed(int length) - { - return GetNextBytes(Master, length); - } - protected readonly IRandomGenerator generator; public SecureRandom() @@ -127,16 +81,6 @@ public SecureRandom() { } - /// - /// To replicate existing predictable output, replace with GetInstance("SHA1PRNG", false), followed by SetSeed(seed) - /// - - 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 @@ -151,16 +95,38 @@ public SecureRandom(IRandomGenerator generator) this.generator = generator; } + public SecureRandom(IRandomGenerator generator, int autoSeedLengthInBytes) + : base(0) + { + AutoSeed(generator, autoSeedLengthInBytes); + + this.generator = generator; + } + public virtual byte[] GenerateSeed(int length) { - return GetNextBytes(Master, length); + return GetNextBytes(MasterRandom, length); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void GenerateSeed(Span seed) + { + MasterRandom.NextBytes(seed); } +#endif public virtual void SetSeed(byte[] seed) { generator.AddSeedMaterial(seed); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void SetSeed(Span seed) + { + generator.AddSeedMaterial(seed); + } +#endif + public virtual void SetSeed(long seed) { generator.AddSeedMaterial(seed); @@ -173,7 +139,6 @@ public override int Next() public override int Next(int maxValue) { - if (maxValue < 2) { if (maxValue < 0) @@ -235,6 +200,22 @@ public virtual void NextBytes(byte[] buf, int off, int len) generator.NextBytes(buf, off, len); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void NextBytes(Span buffer) + { + if (generator != null) + { + generator.NextBytes(buffer); + } + else + { + byte[] tmp = new byte[buffer.Length]; + NextBytes(tmp); + tmp.CopyTo(buffer); + } + } +#endif + private static readonly double DoubleScale = 1.0 / Convert.ToDouble(1L << 53); public override double NextDouble() @@ -246,16 +227,39 @@ public override double NextDouble() public virtual int NextInt() { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span bytes = stackalloc byte[4]; +#else byte[] bytes = new byte[4]; +#endif NextBytes(bytes); - return (int)Pack.BE_To_UInt32(bytes, 0); + return (int)Pack.BE_To_UInt32(bytes); } public virtual long NextLong() { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span bytes = stackalloc byte[8]; +#else byte[] bytes = new byte[8]; +#endif NextBytes(bytes); - return (long)Pack.BE_To_UInt64(bytes, 0); + return (long)Pack.BE_To_UInt64(bytes); + } + + private static void AutoSeed(IRandomGenerator generator, int seedLength) + { + generator.AddSeedMaterial(NextCounterValue()); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span seed = seedLength <= 128 + ? stackalloc byte[seedLength] + : new byte[seedLength]; +#else + byte[] seed = new byte[seedLength]; +#endif + MasterRandom.NextBytes(seed); + generator.AddSeedMaterial(seed); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/SecurityUtilityException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/SecurityUtilityException.cs index d5a19d8..0e3c62a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/SecurityUtilityException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/SecurityUtilityException.cs @@ -1,40 +1,34 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; 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() - { - } + public SecurityUtilityException() + : base() + { + } - /** - * create a SecurityUtilityException with the given message. - * - * @param message the message to be carried with the exception. - */ - public SecurityUtilityException( - string message) + public SecurityUtilityException(string message) : base(message) - { - } + { + } + + public SecurityUtilityException(string message, Exception innerException) + : base(message, innerException) + { + } - public SecurityUtilityException( - string message, - Exception exception) - : base(message, exception) - { - } - } + protected SecurityUtilityException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/SignatureException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/SignatureException.cs index 1284965..13e7de9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/SignatureException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/SignatureException.cs @@ -1,17 +1,33 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security { -#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE) [Serializable] -#endif - public class SignatureException : GeneralSecurityException + public class SignatureException + : GeneralSecurityException { - public SignatureException() : base() { } - public SignatureException(string message) : base(message) { } - public SignatureException(string message, Exception exception) : base(message, exception) { } + public SignatureException() + : base() + { + } + + public SignatureException(string message) + : base(message) + { + } + + public SignatureException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected SignatureException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/SignerUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/SignerUtilities.cs index 3cce132..d37cf26 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/SignerUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/SignerUtilities.cs @@ -1,8 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; -using System.IO; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Bsi; @@ -16,439 +15,461 @@ 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; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Rosstandart; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security { /// /// Signer Utility class contains methods that can not be specifically grouped into other classes. /// - public sealed class SignerUtilities + public static 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(); + internal static readonly IDictionary AlgorithmMap = + new Dictionary(StringComparer.OrdinalIgnoreCase); + internal static readonly IDictionary Oids = + new Dictionary(StringComparer.OrdinalIgnoreCase); 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["SHA-1WITHRSA"] = "SHA-1withRSA"; - algorithms["SHA1WITHRSAENCRYPTION"] = "SHA-1withRSA"; - algorithms["SHA-1WITHRSAENCRYPTION"] = "SHA-1withRSA"; - algorithms[PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id] = "SHA-1withRSA"; - algorithms[OiwObjectIdentifiers.Sha1WithRsa.Id] = "SHA-1withRSA"; - - algorithms["SHA224WITHRSA"] = "SHA-224withRSA"; - algorithms["SHA-224WITHRSA"] = "SHA-224withRSA"; - algorithms["SHA224WITHRSAENCRYPTION"] = "SHA-224withRSA"; - algorithms["SHA-224WITHRSAENCRYPTION"] = "SHA-224withRSA"; - algorithms[PkcsObjectIdentifiers.Sha224WithRsaEncryption.Id] = "SHA-224withRSA"; - - algorithms["SHA256WITHRSA"] = "SHA-256withRSA"; - algorithms["SHA-256WITHRSA"] = "SHA-256withRSA"; - algorithms["SHA256WITHRSAENCRYPTION"] = "SHA-256withRSA"; - algorithms["SHA-256WITHRSAENCRYPTION"] = "SHA-256withRSA"; - algorithms[PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id] = "SHA-256withRSA"; - - algorithms["SHA384WITHRSA"] = "SHA-384withRSA"; - algorithms["SHA-384WITHRSA"] = "SHA-384withRSA"; - algorithms["SHA384WITHRSAENCRYPTION"] = "SHA-384withRSA"; - algorithms["SHA-384WITHRSAENCRYPTION"] = "SHA-384withRSA"; - algorithms[PkcsObjectIdentifiers.Sha384WithRsaEncryption.Id] = "SHA-384withRSA"; - - algorithms["SHA512WITHRSA"] = "SHA-512withRSA"; - algorithms["SHA-512WITHRSA"] = "SHA-512withRSA"; - algorithms["SHA512WITHRSAENCRYPTION"] = "SHA-512withRSA"; - algorithms["SHA-512WITHRSAENCRYPTION"] = "SHA-512withRSA"; - algorithms[PkcsObjectIdentifiers.Sha512WithRsaEncryption.Id] = "SHA-512withRSA"; - - algorithms["SHA512(224)WITHRSA"] = "SHA-512(224)withRSA"; - algorithms["SHA-512(224)WITHRSA"] = "SHA-512(224)withRSA"; - algorithms["SHA512(224)WITHRSAENCRYPTION"] = "SHA-512(224)withRSA"; - algorithms["SHA-512(224)WITHRSAENCRYPTION"] = "SHA-512(224)withRSA"; - algorithms[PkcsObjectIdentifiers.Sha512_224WithRSAEncryption.Id] = "SHA-512(224)withRSA"; - - algorithms["SHA512(256)WITHRSA"] = "SHA-512(256)withRSA"; - algorithms["SHA-512(256)WITHRSA"] = "SHA-512(256)withRSA"; - algorithms["SHA512(256)WITHRSAENCRYPTION"] = "SHA-512(256)withRSA"; - algorithms["SHA-512(256)WITHRSAENCRYPTION"] = "SHA-512(256)withRSA"; - algorithms[PkcsObjectIdentifiers.Sha512_256WithRSAEncryption.Id] = "SHA-512(256)withRSA"; - - algorithms["SHA3-224WITHRSA"] = "SHA3-224withRSA"; - algorithms["SHA3-224WITHRSAENCRYPTION"] = "SHA3-224withRSA"; - algorithms[NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_224.Id] = "SHA3-224withRSA"; - algorithms["SHA3-256WITHRSA"] = "SHA3-256withRSA"; - algorithms["SHA3-256WITHRSAENCRYPTION"] = "SHA3-256withRSA"; - algorithms[NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_256.Id] = "SHA3-256withRSA"; - algorithms["SHA3-384WITHRSA"] = "SHA3-384withRSA"; - algorithms["SHA3-384WITHRSAENCRYPTION"] = "SHA3-384withRSA"; - algorithms[NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_384.Id] = "SHA3-384withRSA"; - algorithms["SHA3-512WITHRSA"] = "SHA3-512withRSA"; - algorithms["SHA3-512WITHRSAENCRYPTION"] = "SHA3-512withRSA"; - algorithms[NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_512.Id] = "SHA3-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["SHA1WITHRSASSA-PSS"] = "SHA-1withRSAandMGF1"; - algorithms["SHA-1WITHRSASSA-PSS"] = "SHA-1withRSAandMGF1"; - - algorithms["SHA224WITHRSAANDMGF1"] = "SHA-224withRSAandMGF1"; - algorithms["SHA-224WITHRSAANDMGF1"] = "SHA-224withRSAandMGF1"; - algorithms["SHA224WITHRSA/PSS"] = "SHA-224withRSAandMGF1"; - algorithms["SHA-224WITHRSA/PSS"] = "SHA-224withRSAandMGF1"; - algorithms["SHA224WITHRSASSA-PSS"] = "SHA-224withRSAandMGF1"; - algorithms["SHA-224WITHRSASSA-PSS"] = "SHA-224withRSAandMGF1"; - - algorithms["SHA256WITHRSAANDMGF1"] = "SHA-256withRSAandMGF1"; - algorithms["SHA-256WITHRSAANDMGF1"] = "SHA-256withRSAandMGF1"; - algorithms["SHA256WITHRSA/PSS"] = "SHA-256withRSAandMGF1"; - algorithms["SHA-256WITHRSA/PSS"] = "SHA-256withRSAandMGF1"; - algorithms["SHA256WITHRSASSA-PSS"] = "SHA-256withRSAandMGF1"; - algorithms["SHA-256WITHRSASSA-PSS"] = "SHA-256withRSAandMGF1"; - - algorithms["SHA384WITHRSAANDMGF1"] = "SHA-384withRSAandMGF1"; - algorithms["SHA-384WITHRSAANDMGF1"] = "SHA-384withRSAandMGF1"; - algorithms["SHA384WITHRSA/PSS"] = "SHA-384withRSAandMGF1"; - algorithms["SHA-384WITHRSA/PSS"] = "SHA-384withRSAandMGF1"; - algorithms["SHA384WITHRSASSA-PSS"] = "SHA-384withRSAandMGF1"; - algorithms["SHA-384WITHRSASSA-PSS"] = "SHA-384withRSAandMGF1"; - - algorithms["SHA512WITHRSAANDMGF1"] = "SHA-512withRSAandMGF1"; - algorithms["SHA-512WITHRSAANDMGF1"] = "SHA-512withRSAandMGF1"; - algorithms["SHA512WITHRSA/PSS"] = "SHA-512withRSAandMGF1"; - algorithms["SHA-512WITHRSA/PSS"] = "SHA-512withRSAandMGF1"; - algorithms["SHA512WITHRSASSA-PSS"] = "SHA-512withRSAandMGF1"; - algorithms["SHA-512WITHRSASSA-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"; - - algorithms["SHA256WITHSM2"] = "SHA256withSM2"; - algorithms[GMObjectIdentifiers.sm2sign_with_sha256.Id] = "SHA256withSM2"; - algorithms["SM3WITHSM2"] = "SM3withSM2"; - algorithms[GMObjectIdentifiers.sm2sign_with_sm3.Id] = "SM3withSM2"; - - 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["SHA-512(224)withRSA"] = PkcsObjectIdentifiers.Sha512_224WithRSAEncryption; - oids["SHA-512(256)withRSA"] = PkcsObjectIdentifiers.Sha512_256WithRSAEncryption; - oids["SHA3-224withRSA"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_224; - oids["SHA3-256withRSA"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_256; - oids["SHA3-384withRSA"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_384; - oids["SHA3-512withRSA"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_512; - - 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; - - oids["SHA256withSM2"] = GMObjectIdentifiers.sm2sign_with_sha256; - oids["SM3withSM2"] = GMObjectIdentifiers.sm2sign_with_sm3; + AlgorithmMap["MD2WITHRSA"] = "MD2withRSA"; + AlgorithmMap["MD2WITHRSAENCRYPTION"] = "MD2withRSA"; + AlgorithmMap[PkcsObjectIdentifiers.MD2WithRsaEncryption.Id] = "MD2withRSA"; + + AlgorithmMap["MD4WITHRSA"] = "MD4withRSA"; + AlgorithmMap["MD4WITHRSAENCRYPTION"] = "MD4withRSA"; + AlgorithmMap[PkcsObjectIdentifiers.MD4WithRsaEncryption.Id] = "MD4withRSA"; + AlgorithmMap[OiwObjectIdentifiers.MD4WithRsa.Id] = "MD4withRSA"; + AlgorithmMap[OiwObjectIdentifiers.MD4WithRsaEncryption.Id] = "MD4withRSA"; + + AlgorithmMap["MD5WITHRSA"] = "MD5withRSA"; + AlgorithmMap["MD5WITHRSAENCRYPTION"] = "MD5withRSA"; + AlgorithmMap[PkcsObjectIdentifiers.MD5WithRsaEncryption.Id] = "MD5withRSA"; + AlgorithmMap[OiwObjectIdentifiers.MD5WithRsa.Id] = "MD5withRSA"; + + AlgorithmMap["SHA1WITHRSA"] = "SHA-1withRSA"; + AlgorithmMap["SHA-1WITHRSA"] = "SHA-1withRSA"; + AlgorithmMap["SHA1WITHRSAENCRYPTION"] = "SHA-1withRSA"; + AlgorithmMap["SHA-1WITHRSAENCRYPTION"] = "SHA-1withRSA"; + AlgorithmMap[PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id] = "SHA-1withRSA"; + AlgorithmMap[OiwObjectIdentifiers.Sha1WithRsa.Id] = "SHA-1withRSA"; + + AlgorithmMap["SHA224WITHRSA"] = "SHA-224withRSA"; + AlgorithmMap["SHA-224WITHRSA"] = "SHA-224withRSA"; + AlgorithmMap["SHA224WITHRSAENCRYPTION"] = "SHA-224withRSA"; + AlgorithmMap["SHA-224WITHRSAENCRYPTION"] = "SHA-224withRSA"; + AlgorithmMap[PkcsObjectIdentifiers.Sha224WithRsaEncryption.Id] = "SHA-224withRSA"; + + AlgorithmMap["SHA256WITHRSA"] = "SHA-256withRSA"; + AlgorithmMap["SHA-256WITHRSA"] = "SHA-256withRSA"; + AlgorithmMap["SHA256WITHRSAENCRYPTION"] = "SHA-256withRSA"; + AlgorithmMap["SHA-256WITHRSAENCRYPTION"] = "SHA-256withRSA"; + AlgorithmMap[PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id] = "SHA-256withRSA"; + + AlgorithmMap["SHA384WITHRSA"] = "SHA-384withRSA"; + AlgorithmMap["SHA-384WITHRSA"] = "SHA-384withRSA"; + AlgorithmMap["SHA384WITHRSAENCRYPTION"] = "SHA-384withRSA"; + AlgorithmMap["SHA-384WITHRSAENCRYPTION"] = "SHA-384withRSA"; + AlgorithmMap[PkcsObjectIdentifiers.Sha384WithRsaEncryption.Id] = "SHA-384withRSA"; + + AlgorithmMap["SHA512WITHRSA"] = "SHA-512withRSA"; + AlgorithmMap["SHA-512WITHRSA"] = "SHA-512withRSA"; + AlgorithmMap["SHA512WITHRSAENCRYPTION"] = "SHA-512withRSA"; + AlgorithmMap["SHA-512WITHRSAENCRYPTION"] = "SHA-512withRSA"; + AlgorithmMap[PkcsObjectIdentifiers.Sha512WithRsaEncryption.Id] = "SHA-512withRSA"; + + AlgorithmMap["SHA512(224)WITHRSA"] = "SHA-512(224)withRSA"; + AlgorithmMap["SHA-512(224)WITHRSA"] = "SHA-512(224)withRSA"; + AlgorithmMap["SHA512(224)WITHRSAENCRYPTION"] = "SHA-512(224)withRSA"; + AlgorithmMap["SHA-512(224)WITHRSAENCRYPTION"] = "SHA-512(224)withRSA"; + AlgorithmMap[PkcsObjectIdentifiers.Sha512_224WithRSAEncryption.Id] = "SHA-512(224)withRSA"; + + AlgorithmMap["SHA512(256)WITHRSA"] = "SHA-512(256)withRSA"; + AlgorithmMap["SHA-512(256)WITHRSA"] = "SHA-512(256)withRSA"; + AlgorithmMap["SHA512(256)WITHRSAENCRYPTION"] = "SHA-512(256)withRSA"; + AlgorithmMap["SHA-512(256)WITHRSAENCRYPTION"] = "SHA-512(256)withRSA"; + AlgorithmMap[PkcsObjectIdentifiers.Sha512_256WithRSAEncryption.Id] = "SHA-512(256)withRSA"; + + AlgorithmMap["SHA3-224WITHRSA"] = "SHA3-224withRSA"; + AlgorithmMap["SHA3-224WITHRSAENCRYPTION"] = "SHA3-224withRSA"; + AlgorithmMap[NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_224.Id] = "SHA3-224withRSA"; + AlgorithmMap["SHA3-256WITHRSA"] = "SHA3-256withRSA"; + AlgorithmMap["SHA3-256WITHRSAENCRYPTION"] = "SHA3-256withRSA"; + AlgorithmMap[NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_256.Id] = "SHA3-256withRSA"; + AlgorithmMap["SHA3-384WITHRSA"] = "SHA3-384withRSA"; + AlgorithmMap["SHA3-384WITHRSAENCRYPTION"] = "SHA3-384withRSA"; + AlgorithmMap[NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_384.Id] = "SHA3-384withRSA"; + AlgorithmMap["SHA3-512WITHRSA"] = "SHA3-512withRSA"; + AlgorithmMap["SHA3-512WITHRSAENCRYPTION"] = "SHA3-512withRSA"; + AlgorithmMap[NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_512.Id] = "SHA3-512withRSA"; + + AlgorithmMap["PSSWITHRSA"] = "PSSwithRSA"; + AlgorithmMap["RSASSA-PSS"] = "PSSwithRSA"; + AlgorithmMap[PkcsObjectIdentifiers.IdRsassaPss.Id] = "PSSwithRSA"; + AlgorithmMap["RSAPSS"] = "PSSwithRSA"; + + AlgorithmMap["SHA1WITHRSAANDMGF1"] = "SHA-1withRSAandMGF1"; + AlgorithmMap["SHA-1WITHRSAANDMGF1"] = "SHA-1withRSAandMGF1"; + AlgorithmMap["SHA1WITHRSA/PSS"] = "SHA-1withRSAandMGF1"; + AlgorithmMap["SHA-1WITHRSA/PSS"] = "SHA-1withRSAandMGF1"; + AlgorithmMap["SHA1WITHRSASSA-PSS"] = "SHA-1withRSAandMGF1"; + AlgorithmMap["SHA-1WITHRSASSA-PSS"] = "SHA-1withRSAandMGF1"; + + AlgorithmMap["SHA224WITHRSAANDMGF1"] = "SHA-224withRSAandMGF1"; + AlgorithmMap["SHA-224WITHRSAANDMGF1"] = "SHA-224withRSAandMGF1"; + AlgorithmMap["SHA224WITHRSA/PSS"] = "SHA-224withRSAandMGF1"; + AlgorithmMap["SHA-224WITHRSA/PSS"] = "SHA-224withRSAandMGF1"; + AlgorithmMap["SHA224WITHRSASSA-PSS"] = "SHA-224withRSAandMGF1"; + AlgorithmMap["SHA-224WITHRSASSA-PSS"] = "SHA-224withRSAandMGF1"; + + AlgorithmMap["SHA256WITHRSAANDMGF1"] = "SHA-256withRSAandMGF1"; + AlgorithmMap["SHA-256WITHRSAANDMGF1"] = "SHA-256withRSAandMGF1"; + AlgorithmMap["SHA256WITHRSA/PSS"] = "SHA-256withRSAandMGF1"; + AlgorithmMap["SHA-256WITHRSA/PSS"] = "SHA-256withRSAandMGF1"; + AlgorithmMap["SHA256WITHRSASSA-PSS"] = "SHA-256withRSAandMGF1"; + AlgorithmMap["SHA-256WITHRSASSA-PSS"] = "SHA-256withRSAandMGF1"; + + AlgorithmMap["SHA384WITHRSAANDMGF1"] = "SHA-384withRSAandMGF1"; + AlgorithmMap["SHA-384WITHRSAANDMGF1"] = "SHA-384withRSAandMGF1"; + AlgorithmMap["SHA384WITHRSA/PSS"] = "SHA-384withRSAandMGF1"; + AlgorithmMap["SHA-384WITHRSA/PSS"] = "SHA-384withRSAandMGF1"; + AlgorithmMap["SHA384WITHRSASSA-PSS"] = "SHA-384withRSAandMGF1"; + AlgorithmMap["SHA-384WITHRSASSA-PSS"] = "SHA-384withRSAandMGF1"; + + AlgorithmMap["SHA512WITHRSAANDMGF1"] = "SHA-512withRSAandMGF1"; + AlgorithmMap["SHA-512WITHRSAANDMGF1"] = "SHA-512withRSAandMGF1"; + AlgorithmMap["SHA512WITHRSA/PSS"] = "SHA-512withRSAandMGF1"; + AlgorithmMap["SHA-512WITHRSA/PSS"] = "SHA-512withRSAandMGF1"; + AlgorithmMap["SHA512WITHRSASSA-PSS"] = "SHA-512withRSAandMGF1"; + AlgorithmMap["SHA-512WITHRSASSA-PSS"] = "SHA-512withRSAandMGF1"; + + AlgorithmMap["RIPEMD128WITHRSA"] = "RIPEMD128withRSA"; + AlgorithmMap["RIPEMD128WITHRSAENCRYPTION"] = "RIPEMD128withRSA"; + AlgorithmMap[TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128.Id] = "RIPEMD128withRSA"; + + AlgorithmMap["RIPEMD160WITHRSA"] = "RIPEMD160withRSA"; + AlgorithmMap["RIPEMD160WITHRSAENCRYPTION"] = "RIPEMD160withRSA"; + AlgorithmMap[TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160.Id] = "RIPEMD160withRSA"; + + AlgorithmMap["RIPEMD256WITHRSA"] = "RIPEMD256withRSA"; + AlgorithmMap["RIPEMD256WITHRSAENCRYPTION"] = "RIPEMD256withRSA"; + AlgorithmMap[TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256.Id] = "RIPEMD256withRSA"; + + AlgorithmMap["NONEWITHRSA"] = "RSA"; + AlgorithmMap["RSAWITHNONE"] = "RSA"; + AlgorithmMap["RAWRSA"] = "RSA"; + + AlgorithmMap["RAWRSAPSS"] = "RAWRSASSA-PSS"; + AlgorithmMap["NONEWITHRSAPSS"] = "RAWRSASSA-PSS"; + AlgorithmMap["NONEWITHRSASSA-PSS"] = "RAWRSASSA-PSS"; + + AlgorithmMap["NONEWITHDSA"] = "NONEwithDSA"; + AlgorithmMap["DSAWITHNONE"] = "NONEwithDSA"; + AlgorithmMap["RAWDSA"] = "NONEwithDSA"; + + AlgorithmMap["DSA"] = "SHA-1withDSA"; + AlgorithmMap["DSAWITHSHA1"] = "SHA-1withDSA"; + AlgorithmMap["DSAWITHSHA-1"] = "SHA-1withDSA"; + AlgorithmMap["SHA/DSA"] = "SHA-1withDSA"; + AlgorithmMap["SHA1/DSA"] = "SHA-1withDSA"; + AlgorithmMap["SHA-1/DSA"] = "SHA-1withDSA"; + AlgorithmMap["SHA1WITHDSA"] = "SHA-1withDSA"; + AlgorithmMap["SHA-1WITHDSA"] = "SHA-1withDSA"; + AlgorithmMap[X9ObjectIdentifiers.IdDsaWithSha1.Id] = "SHA-1withDSA"; + AlgorithmMap[OiwObjectIdentifiers.DsaWithSha1.Id] = "SHA-1withDSA"; + + AlgorithmMap["DSAWITHSHA224"] = "SHA-224withDSA"; + AlgorithmMap["DSAWITHSHA-224"] = "SHA-224withDSA"; + AlgorithmMap["SHA224/DSA"] = "SHA-224withDSA"; + AlgorithmMap["SHA-224/DSA"] = "SHA-224withDSA"; + AlgorithmMap["SHA224WITHDSA"] = "SHA-224withDSA"; + AlgorithmMap["SHA-224WITHDSA"] = "SHA-224withDSA"; + AlgorithmMap[NistObjectIdentifiers.DsaWithSha224.Id] = "SHA-224withDSA"; + + AlgorithmMap["DSAWITHSHA256"] = "SHA-256withDSA"; + AlgorithmMap["DSAWITHSHA-256"] = "SHA-256withDSA"; + AlgorithmMap["SHA256/DSA"] = "SHA-256withDSA"; + AlgorithmMap["SHA-256/DSA"] = "SHA-256withDSA"; + AlgorithmMap["SHA256WITHDSA"] = "SHA-256withDSA"; + AlgorithmMap["SHA-256WITHDSA"] = "SHA-256withDSA"; + AlgorithmMap[NistObjectIdentifiers.DsaWithSha256.Id] = "SHA-256withDSA"; + + AlgorithmMap["DSAWITHSHA384"] = "SHA-384withDSA"; + AlgorithmMap["DSAWITHSHA-384"] = "SHA-384withDSA"; + AlgorithmMap["SHA384/DSA"] = "SHA-384withDSA"; + AlgorithmMap["SHA-384/DSA"] = "SHA-384withDSA"; + AlgorithmMap["SHA384WITHDSA"] = "SHA-384withDSA"; + AlgorithmMap["SHA-384WITHDSA"] = "SHA-384withDSA"; + AlgorithmMap[NistObjectIdentifiers.DsaWithSha384.Id] = "SHA-384withDSA"; + + AlgorithmMap["DSAWITHSHA512"] = "SHA-512withDSA"; + AlgorithmMap["DSAWITHSHA-512"] = "SHA-512withDSA"; + AlgorithmMap["SHA512/DSA"] = "SHA-512withDSA"; + AlgorithmMap["SHA-512/DSA"] = "SHA-512withDSA"; + AlgorithmMap["SHA512WITHDSA"] = "SHA-512withDSA"; + AlgorithmMap["SHA-512WITHDSA"] = "SHA-512withDSA"; + AlgorithmMap[NistObjectIdentifiers.DsaWithSha512.Id] = "SHA-512withDSA"; + + AlgorithmMap["NONEWITHECDSA"] = "NONEwithECDSA"; + AlgorithmMap["ECDSAWITHNONE"] = "NONEwithECDSA"; + + AlgorithmMap["ECDSA"] = "SHA-1withECDSA"; + AlgorithmMap["SHA1/ECDSA"] = "SHA-1withECDSA"; + AlgorithmMap["SHA-1/ECDSA"] = "SHA-1withECDSA"; + AlgorithmMap["ECDSAWITHSHA1"] = "SHA-1withECDSA"; + AlgorithmMap["ECDSAWITHSHA-1"] = "SHA-1withECDSA"; + AlgorithmMap["SHA1WITHECDSA"] = "SHA-1withECDSA"; + AlgorithmMap["SHA-1WITHECDSA"] = "SHA-1withECDSA"; + AlgorithmMap[X9ObjectIdentifiers.ECDsaWithSha1.Id] = "SHA-1withECDSA"; + AlgorithmMap[TeleTrusTObjectIdentifiers.ECSignWithSha1.Id] = "SHA-1withECDSA"; + + AlgorithmMap["SHA224/ECDSA"] = "SHA-224withECDSA"; + AlgorithmMap["SHA-224/ECDSA"] = "SHA-224withECDSA"; + AlgorithmMap["ECDSAWITHSHA224"] = "SHA-224withECDSA"; + AlgorithmMap["ECDSAWITHSHA-224"] = "SHA-224withECDSA"; + AlgorithmMap["SHA224WITHECDSA"] = "SHA-224withECDSA"; + AlgorithmMap["SHA-224WITHECDSA"] = "SHA-224withECDSA"; + AlgorithmMap[X9ObjectIdentifiers.ECDsaWithSha224.Id] = "SHA-224withECDSA"; + + AlgorithmMap["SHA256/ECDSA"] = "SHA-256withECDSA"; + AlgorithmMap["SHA-256/ECDSA"] = "SHA-256withECDSA"; + AlgorithmMap["ECDSAWITHSHA256"] = "SHA-256withECDSA"; + AlgorithmMap["ECDSAWITHSHA-256"] = "SHA-256withECDSA"; + AlgorithmMap["SHA256WITHECDSA"] = "SHA-256withECDSA"; + AlgorithmMap["SHA-256WITHECDSA"] = "SHA-256withECDSA"; + AlgorithmMap[X9ObjectIdentifiers.ECDsaWithSha256.Id] = "SHA-256withECDSA"; + + AlgorithmMap["SHA384/ECDSA"] = "SHA-384withECDSA"; + AlgorithmMap["SHA-384/ECDSA"] = "SHA-384withECDSA"; + AlgorithmMap["ECDSAWITHSHA384"] = "SHA-384withECDSA"; + AlgorithmMap["ECDSAWITHSHA-384"] = "SHA-384withECDSA"; + AlgorithmMap["SHA384WITHECDSA"] = "SHA-384withECDSA"; + AlgorithmMap["SHA-384WITHECDSA"] = "SHA-384withECDSA"; + AlgorithmMap[X9ObjectIdentifiers.ECDsaWithSha384.Id] = "SHA-384withECDSA"; + + AlgorithmMap["SHA512/ECDSA"] = "SHA-512withECDSA"; + AlgorithmMap["SHA-512/ECDSA"] = "SHA-512withECDSA"; + AlgorithmMap["ECDSAWITHSHA512"] = "SHA-512withECDSA"; + AlgorithmMap["ECDSAWITHSHA-512"] = "SHA-512withECDSA"; + AlgorithmMap["SHA512WITHECDSA"] = "SHA-512withECDSA"; + AlgorithmMap["SHA-512WITHECDSA"] = "SHA-512withECDSA"; + AlgorithmMap[X9ObjectIdentifiers.ECDsaWithSha512.Id] = "SHA-512withECDSA"; + + AlgorithmMap["RIPEMD160/ECDSA"] = "RIPEMD160withECDSA"; + AlgorithmMap["ECDSAWITHRIPEMD160"] = "RIPEMD160withECDSA"; + AlgorithmMap["RIPEMD160WITHECDSA"] = "RIPEMD160withECDSA"; + AlgorithmMap[TeleTrusTObjectIdentifiers.ECSignWithRipeMD160.Id] = "RIPEMD160withECDSA"; + + AlgorithmMap["NONEWITHCVC-ECDSA"] = "NONEwithCVC-ECDSA"; + AlgorithmMap["CVC-ECDSAWITHNONE"] = "NONEwithCVC-ECDSA"; + + AlgorithmMap["SHA1/CVC-ECDSA"] = "SHA-1withCVC-ECDSA"; + AlgorithmMap["SHA-1/CVC-ECDSA"] = "SHA-1withCVC-ECDSA"; + AlgorithmMap["CVC-ECDSAWITHSHA1"] = "SHA-1withCVC-ECDSA"; + AlgorithmMap["CVC-ECDSAWITHSHA-1"] = "SHA-1withCVC-ECDSA"; + AlgorithmMap["SHA1WITHCVC-ECDSA"] = "SHA-1withCVC-ECDSA"; + AlgorithmMap["SHA-1WITHCVC-ECDSA"] = "SHA-1withCVC-ECDSA"; + AlgorithmMap[EacObjectIdentifiers.id_TA_ECDSA_SHA_1.Id] = "SHA-1withCVC-ECDSA"; + + AlgorithmMap["SHA224/CVC-ECDSA"] = "SHA-224withCVC-ECDSA"; + AlgorithmMap["SHA-224/CVC-ECDSA"] = "SHA-224withCVC-ECDSA"; + AlgorithmMap["CVC-ECDSAWITHSHA224"] = "SHA-224withCVC-ECDSA"; + AlgorithmMap["CVC-ECDSAWITHSHA-224"] = "SHA-224withCVC-ECDSA"; + AlgorithmMap["SHA224WITHCVC-ECDSA"] = "SHA-224withCVC-ECDSA"; + AlgorithmMap["SHA-224WITHCVC-ECDSA"] = "SHA-224withCVC-ECDSA"; + AlgorithmMap[EacObjectIdentifiers.id_TA_ECDSA_SHA_224.Id] = "SHA-224withCVC-ECDSA"; + + AlgorithmMap["SHA256/CVC-ECDSA"] = "SHA-256withCVC-ECDSA"; + AlgorithmMap["SHA-256/CVC-ECDSA"] = "SHA-256withCVC-ECDSA"; + AlgorithmMap["CVC-ECDSAWITHSHA256"] = "SHA-256withCVC-ECDSA"; + AlgorithmMap["CVC-ECDSAWITHSHA-256"] = "SHA-256withCVC-ECDSA"; + AlgorithmMap["SHA256WITHCVC-ECDSA"] = "SHA-256withCVC-ECDSA"; + AlgorithmMap["SHA-256WITHCVC-ECDSA"] = "SHA-256withCVC-ECDSA"; + AlgorithmMap[EacObjectIdentifiers.id_TA_ECDSA_SHA_256.Id] = "SHA-256withCVC-ECDSA"; + + AlgorithmMap["SHA384/CVC-ECDSA"] = "SHA-384withCVC-ECDSA"; + AlgorithmMap["SHA-384/CVC-ECDSA"] = "SHA-384withCVC-ECDSA"; + AlgorithmMap["CVC-ECDSAWITHSHA384"] = "SHA-384withCVC-ECDSA"; + AlgorithmMap["CVC-ECDSAWITHSHA-384"] = "SHA-384withCVC-ECDSA"; + AlgorithmMap["SHA384WITHCVC-ECDSA"] = "SHA-384withCVC-ECDSA"; + AlgorithmMap["SHA-384WITHCVC-ECDSA"] = "SHA-384withCVC-ECDSA"; + AlgorithmMap[EacObjectIdentifiers.id_TA_ECDSA_SHA_384.Id] = "SHA-384withCVC-ECDSA"; + + AlgorithmMap["SHA512/CVC-ECDSA"] = "SHA-512withCVC-ECDSA"; + AlgorithmMap["SHA-512/CVC-ECDSA"] = "SHA-512withCVC-ECDSA"; + AlgorithmMap["CVC-ECDSAWITHSHA512"] = "SHA-512withCVC-ECDSA"; + AlgorithmMap["CVC-ECDSAWITHSHA-512"] = "SHA-512withCVC-ECDSA"; + AlgorithmMap["SHA512WITHCVC-ECDSA"] = "SHA-512withCVC-ECDSA"; + AlgorithmMap["SHA-512WITHCVC-ECDSA"] = "SHA-512withCVC-ECDSA"; + AlgorithmMap[EacObjectIdentifiers.id_TA_ECDSA_SHA_512.Id] = "SHA-512withCVC-ECDSA"; + + AlgorithmMap["NONEWITHPLAIN-ECDSA"] = "NONEwithPLAIN-ECDSA"; + AlgorithmMap["PLAIN-ECDSAWITHNONE"] = "NONEwithPLAIN-ECDSA"; + + AlgorithmMap["SHA1/PLAIN-ECDSA"] = "SHA-1withPLAIN-ECDSA"; + AlgorithmMap["SHA-1/PLAIN-ECDSA"] = "SHA-1withPLAIN-ECDSA"; + AlgorithmMap["PLAIN-ECDSAWITHSHA1"] = "SHA-1withPLAIN-ECDSA"; + AlgorithmMap["PLAIN-ECDSAWITHSHA-1"] = "SHA-1withPLAIN-ECDSA"; + AlgorithmMap["SHA1WITHPLAIN-ECDSA"] = "SHA-1withPLAIN-ECDSA"; + AlgorithmMap["SHA-1WITHPLAIN-ECDSA"] = "SHA-1withPLAIN-ECDSA"; + AlgorithmMap[BsiObjectIdentifiers.ecdsa_plain_SHA1.Id] = "SHA-1withPLAIN-ECDSA"; + + AlgorithmMap["SHA224/PLAIN-ECDSA"] = "SHA-224withPLAIN-ECDSA"; + AlgorithmMap["SHA-224/PLAIN-ECDSA"] = "SHA-224withPLAIN-ECDSA"; + AlgorithmMap["PLAIN-ECDSAWITHSHA224"] = "SHA-224withPLAIN-ECDSA"; + AlgorithmMap["PLAIN-ECDSAWITHSHA-224"] = "SHA-224withPLAIN-ECDSA"; + AlgorithmMap["SHA224WITHPLAIN-ECDSA"] = "SHA-224withPLAIN-ECDSA"; + AlgorithmMap["SHA-224WITHPLAIN-ECDSA"] = "SHA-224withPLAIN-ECDSA"; + AlgorithmMap[BsiObjectIdentifiers.ecdsa_plain_SHA224.Id] = "SHA-224withPLAIN-ECDSA"; + + AlgorithmMap["SHA256/PLAIN-ECDSA"] = "SHA-256withPLAIN-ECDSA"; + AlgorithmMap["SHA-256/PLAIN-ECDSA"] = "SHA-256withPLAIN-ECDSA"; + AlgorithmMap["PLAIN-ECDSAWITHSHA256"] = "SHA-256withPLAIN-ECDSA"; + AlgorithmMap["PLAIN-ECDSAWITHSHA-256"] = "SHA-256withPLAIN-ECDSA"; + AlgorithmMap["SHA256WITHPLAIN-ECDSA"] = "SHA-256withPLAIN-ECDSA"; + AlgorithmMap["SHA-256WITHPLAIN-ECDSA"] = "SHA-256withPLAIN-ECDSA"; + AlgorithmMap[BsiObjectIdentifiers.ecdsa_plain_SHA256.Id] = "SHA-256withPLAIN-ECDSA"; + + AlgorithmMap["SHA384/PLAIN-ECDSA"] = "SHA-384withPLAIN-ECDSA"; + AlgorithmMap["SHA-384/PLAIN-ECDSA"] = "SHA-384withPLAIN-ECDSA"; + AlgorithmMap["PLAIN-ECDSAWITHSHA384"] = "SHA-384withPLAIN-ECDSA"; + AlgorithmMap["PLAIN-ECDSAWITHSHA-384"] = "SHA-384withPLAIN-ECDSA"; + AlgorithmMap["SHA384WITHPLAIN-ECDSA"] = "SHA-384withPLAIN-ECDSA"; + AlgorithmMap["SHA-384WITHPLAIN-ECDSA"] = "SHA-384withPLAIN-ECDSA"; + AlgorithmMap[BsiObjectIdentifiers.ecdsa_plain_SHA384.Id] = "SHA-384withPLAIN-ECDSA"; + + AlgorithmMap["SHA512/PLAIN-ECDSA"] = "SHA-512withPLAIN-ECDSA"; + AlgorithmMap["SHA-512/PLAIN-ECDSA"] = "SHA-512withPLAIN-ECDSA"; + AlgorithmMap["PLAIN-ECDSAWITHSHA512"] = "SHA-512withPLAIN-ECDSA"; + AlgorithmMap["PLAIN-ECDSAWITHSHA-512"] = "SHA-512withPLAIN-ECDSA"; + AlgorithmMap["SHA512WITHPLAIN-ECDSA"] = "SHA-512withPLAIN-ECDSA"; + AlgorithmMap["SHA-512WITHPLAIN-ECDSA"] = "SHA-512withPLAIN-ECDSA"; + AlgorithmMap[BsiObjectIdentifiers.ecdsa_plain_SHA512.Id] = "SHA-512withPLAIN-ECDSA"; + + AlgorithmMap["RIPEMD160/PLAIN-ECDSA"] = "RIPEMD160withPLAIN-ECDSA"; + AlgorithmMap["PLAIN-ECDSAWITHRIPEMD160"] = "RIPEMD160withPLAIN-ECDSA"; + AlgorithmMap["RIPEMD160WITHPLAIN-ECDSA"] = "RIPEMD160withPLAIN-ECDSA"; + AlgorithmMap[BsiObjectIdentifiers.ecdsa_plain_RIPEMD160.Id] = "RIPEMD160withPLAIN-ECDSA"; + + AlgorithmMap["SHA1WITHECNR"] = "SHA-1withECNR"; + AlgorithmMap["SHA-1WITHECNR"] = "SHA-1withECNR"; + AlgorithmMap["SHA224WITHECNR"] = "SHA-224withECNR"; + AlgorithmMap["SHA-224WITHECNR"] = "SHA-224withECNR"; + AlgorithmMap["SHA256WITHECNR"] = "SHA-256withECNR"; + AlgorithmMap["SHA-256WITHECNR"] = "SHA-256withECNR"; + AlgorithmMap["SHA384WITHECNR"] = "SHA-384withECNR"; + AlgorithmMap["SHA-384WITHECNR"] = "SHA-384withECNR"; + AlgorithmMap["SHA512WITHECNR"] = "SHA-512withECNR"; + AlgorithmMap["SHA-512WITHECNR"] = "SHA-512withECNR"; + + AlgorithmMap["GOST-3410"] = "GOST3410"; + AlgorithmMap["GOST-3410-94"] = "GOST3410"; + AlgorithmMap["GOST3411WITHGOST3410"] = "GOST3410"; + AlgorithmMap["GOST3411/GOST3410"] = "GOST3410"; + AlgorithmMap[CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94.Id] = "GOST3410"; + + AlgorithmMap["ECGOST-3410"] = "ECGOST3410"; + AlgorithmMap["GOST-3410-2001"] = "ECGOST3410"; + AlgorithmMap["GOST3411WITHECGOST3410"] = "ECGOST3410"; + AlgorithmMap["GOST3411/ECGOST3410"] = "ECGOST3410"; + AlgorithmMap[CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001.Id] = "ECGOST3410"; + + AlgorithmMap["GOST-3410-2012-256"] = "ECGOST3410-2012-256"; + AlgorithmMap["GOST3411WITHECGOST3410-2012-256"] = "ECGOST3410-2012-256"; + AlgorithmMap["GOST3411-2012-256WITHECGOST3410"] = "ECGOST3410-2012-256"; + AlgorithmMap["GOST3411-2012-256WITHECGOST3410-2012-256"] = "ECGOST3410-2012-256"; + AlgorithmMap["GOST3411-2012-256/ECGOST3410"] = "ECGOST3410-2012-256"; + AlgorithmMap["GOST3411-2012-256/ECGOST3410-2012-256"] = "ECGOST3410-2012-256"; + AlgorithmMap[RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256.Id] = + "ECGOST3410-2012-256"; + + AlgorithmMap["GOST-3410-2012-512"] = "ECGOST3410-2012-512"; + AlgorithmMap["GOST3411WITHECGOST3410-2012-512"] = "ECGOST3410-2012-512"; + AlgorithmMap["GOST3411-2012-512WITHECGOST3410"] = "ECGOST3410-2012-512"; + AlgorithmMap["GOST3411-2012-512WITHECGOST3410-2012-512"] = "ECGOST3410-2012-512"; + AlgorithmMap["GOST3411-2012-512/ECGOST3410"] = "ECGOST3410-2012-512"; + AlgorithmMap["GOST3411-2012-512/ECGOST3410-2012-512"] = "ECGOST3410-2012-512"; + AlgorithmMap[RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512.Id] = + "ECGOST3410-2012-512"; + + AlgorithmMap["ED25519"] = "Ed25519"; + AlgorithmMap[EdECObjectIdentifiers.id_Ed25519.Id] = "Ed25519"; + AlgorithmMap["ED25519CTX"] = "Ed25519ctx"; + AlgorithmMap["ED25519PH"] = "Ed25519ph"; + AlgorithmMap["ED448"] = "Ed448"; + AlgorithmMap[EdECObjectIdentifiers.id_Ed448.Id] = "Ed448"; + AlgorithmMap["ED448PH"] = "Ed448ph"; + + AlgorithmMap["SHA256WITHSM2"] = "SHA256withSM2"; + AlgorithmMap[GMObjectIdentifiers.sm2sign_with_sha256.Id] = "SHA256withSM2"; + AlgorithmMap["SM3WITHSM2"] = "SM3withSM2"; + AlgorithmMap[GMObjectIdentifiers.sm2sign_with_sm3.Id] = "SM3withSM2"; + + 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["SHA-512(224)withRSA"] = PkcsObjectIdentifiers.Sha512_224WithRSAEncryption; + Oids["SHA-512(256)withRSA"] = PkcsObjectIdentifiers.Sha512_256WithRSAEncryption; + Oids["SHA3-224withRSA"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_224; + Oids["SHA3-256withRSA"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_256; + Oids["SHA3-384withRSA"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_384; + Oids["SHA3-512withRSA"] = NistObjectIdentifiers.IdRsassaPkcs1V15WithSha3_512; + + 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["ECGOST3410-2012-256"] = RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_256; + Oids["ECGOST3410-2012-512"] = RosstandartObjectIdentifiers.id_tc26_signwithdigest_gost_3410_12_512; + + Oids["Ed25519"] = EdECObjectIdentifiers.id_Ed25519; + Oids["Ed448"] = EdECObjectIdentifiers.id_Ed448; + + Oids["SHA256withSM2"] = GMObjectIdentifiers.sm2sign_with_sha256; + Oids["SM3withSM2"] = GMObjectIdentifiers.sm2sign_with_sm3; } /// @@ -457,44 +478,32 @@ static SignerUtilities() /// 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) + 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]; + throw new ArgumentNullException(nameof(mechanism)); - if (aliased != null) - mechanism = aliased; + string algorithm = CollectionUtilities.GetValueOrKey(AlgorithmMap, mechanism); - return (DerObjectIdentifier) oids[mechanism]; + return CollectionUtilities.GetValueOrNull(Oids, algorithm); } - public static ICollection Algorithms + public static ICollection Algorithms { - get { return oids.Keys; } + get { return CollectionUtilities.ReadOnly(Oids.Keys); } } - public static Asn1Encodable GetDefaultX509Parameters( - DerObjectIdentifier id) + public static Asn1Encodable GetDefaultX509Parameters(DerObjectIdentifier id) { return GetDefaultX509Parameters(id.Id); } - public static Asn1Encodable GetDefaultX509Parameters( - string algorithm) + public static Asn1Encodable GetDefaultX509Parameters(string algorithm) { if (algorithm == null) - throw new ArgumentNullException("algorithm"); + throw new ArgumentNullException(nameof(algorithm)); - algorithm = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm); - - string mechanism = (string) algorithms[algorithm]; - - if (mechanism == null) - mechanism = algorithm; + string mechanism = CollectionUtilities.GetValueOrKey(AlgorithmMap, algorithm); if (mechanism == "PSSwithRSA") { @@ -503,7 +512,7 @@ public static Asn1Encodable GetDefaultX509Parameters( return GetPssX509Parameters("SHA-1"); } - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "withRSAandMGF1")) + if (Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "withRSAandMGF1")) { string digestName = mechanism.Substring(0, mechanism.Length - "withRSAandMGF1".Length); return GetPssX509Parameters(digestName); @@ -527,26 +536,19 @@ private static Asn1Encodable GetPssX509Parameters( new DerInteger(saltLen), new DerInteger(1)); } - public static ISigner GetSigner( - DerObjectIdentifier id) + public static ISigner GetSigner(DerObjectIdentifier id) { return GetSigner(id.Id); } - public static ISigner GetSigner( - string algorithm) + public static ISigner GetSigner(string algorithm) { if (algorithm == null) - throw new ArgumentNullException("algorithm"); + throw new ArgumentNullException(nameof(algorithm)); - algorithm = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithm); + string mechanism = CollectionUtilities.GetValueOrKey(AlgorithmMap, algorithm.ToUpperInvariant()); - string mechanism = (string) algorithms[algorithm]; - - if (mechanism == null) - mechanism = algorithm; - - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "Ed")) + if (Org.BouncyCastle.Utilities.Platform.StartsWith(mechanism, "Ed")) { if (mechanism.Equals("Ed25519")) { @@ -585,49 +587,49 @@ public static ISigner GetSigner( // 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")) + if (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")) + if (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")) + if (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")) + if (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")) + if (Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "withCVC-ECDSA") + || 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")) + if (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 (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "withSM2")) + if (Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "withSM2")) { string digestName = mechanism.Substring(0, mechanism.LastIndexOf("with")); IDigest digest = DigestUtilities.GetDigest(digestName); @@ -642,6 +644,14 @@ public static ISigner GetSigner( { return new Gost3410DigestSigner(new ECGost3410Signer(), new Gost3411Digest()); } + if (mechanism.Equals("ECGOST3410-2012-256")) + { + return new Gost3410DigestSigner(new ECGost3410Signer(), new Gost3411_2012_256Digest()); + } + if (mechanism.Equals("ECGOST3410-2012-512")) + { + return new Gost3410DigestSigner(new ECGost3410Signer(), new Gost3411_2012_512Digest()); + } if (mechanism.Equals("SHA1WITHRSA/ISO9796-2")) { @@ -656,10 +666,10 @@ public static ISigner GetSigner( return new Iso9796d2Signer(new RsaBlindedEngine(), new RipeMD160Digest(), true); } - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(mechanism, "/X9.31")) + if (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"); + int withPos = Org.BouncyCastle.Utilities.Platform.IndexOf(x931, "WITH"); if (withPos > 0) { int endPos = withPos + "WITH".Length; @@ -679,10 +689,9 @@ public static ISigner GetSigner( throw new SecurityUtilityException("Signer " + algorithm + " not recognised."); } - public static string GetEncodingName( - DerObjectIdentifier oid) + public static string GetEncodingName(DerObjectIdentifier oid) { - return (string) algorithms[oid.Id]; + return CollectionUtilities.GetValueOrNull(AlgorithmMap, oid.Id); } public static ISigner InitSigner(DerObjectIdentifier algorithmOid, bool forSigning, AsymmetricKeyParameter privateKey, SecureRandom random) @@ -692,7 +701,7 @@ public static ISigner InitSigner(DerObjectIdentifier algorithmOid, bool forSigni public static ISigner InitSigner(string algorithm, bool forSigning, AsymmetricKeyParameter privateKey, SecureRandom random) { - ISigner signer = SignerUtilities.GetSigner(algorithm); + ISigner signer = GetSigner(algorithm); signer.Init(forSigning, ParameterUtilities.WithRandom(privateKey, random)); return signer; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/WrapperUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/WrapperUtilities.cs index 18e581d..d1fadf7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/WrapperUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/WrapperUtilities.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Kisa; @@ -11,77 +11,65 @@ using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Security { /// /// Utility class for creating IWrapper objects from their names/Oids /// - public sealed class WrapperUtilities + public static 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(); + private static readonly IDictionary Algorithms = + new Dictionary(StringComparer.OrdinalIgnoreCase); static WrapperUtilities() { // Signal to obfuscation tools not to change enum constants - ((WrapAlgorithm)Enums.GetArbitraryValue(typeof(WrapAlgorithm))).ToString(); + Enums.GetArbitraryValue().ToString(); - algorithms[NistObjectIdentifiers.IdAes128Wrap.Id] = "AESWRAP"; - algorithms[NistObjectIdentifiers.IdAes192Wrap.Id] = "AESWRAP"; - algorithms[NistObjectIdentifiers.IdAes256Wrap.Id] = "AESWRAP"; + 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[NttObjectIdentifiers.IdCamellia128Wrap.Id] = "CAMELLIAWRAP"; + Algorithms[NttObjectIdentifiers.IdCamellia192Wrap.Id] = "CAMELLIAWRAP"; + Algorithms[NttObjectIdentifiers.IdCamellia256Wrap.Id] = "CAMELLIAWRAP"; - algorithms[PkcsObjectIdentifiers.IdAlgCms3DesWrap.Id] = "DESEDEWRAP"; - algorithms["TDEAWRAP"] = "DESEDEWRAP"; + Algorithms[PkcsObjectIdentifiers.IdAlgCms3DesWrap.Id] = "DESEDEWRAP"; + Algorithms["TDEAWRAP"] = "DESEDEWRAP"; - algorithms[PkcsObjectIdentifiers.IdAlgCmsRC2Wrap.Id] = "RC2WRAP"; + Algorithms[PkcsObjectIdentifiers.IdAlgCmsRC2Wrap.Id] = "RC2WRAP"; - algorithms[KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap.Id] = "SEEDWRAP"; + Algorithms[KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap.Id] = "SEEDWRAP"; } - public static IWrapper GetWrapper( - DerObjectIdentifier oid) + public static IWrapper GetWrapper(DerObjectIdentifier oid) { return GetWrapper(oid.Id); } - public static IWrapper GetWrapper( - string algorithm) + 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; - } + string mechanism = CollectionUtilities.GetValueOrKey(Algorithms, algorithm).ToUpperInvariant(); try { - WrapAlgorithm wrapAlgorithm = (WrapAlgorithm)Enums.GetEnumValue( - typeof(WrapAlgorithm), mechanism); + WrapAlgorithm wrapAlgorithm = Enums.GetEnumValue(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()); + 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(AesUtilities.CreateEngine()); + case WrapAlgorithm.CAMELLIARFC3211WRAP: return new Rfc3211WrapEngine(new CamelliaEngine()); } } catch (ArgumentException) @@ -97,10 +85,9 @@ public static IWrapper GetWrapper( throw new SecurityUtilityException("Wrapper " + algorithm + " not recognised."); } - public static string GetAlgorithmName( - DerObjectIdentifier oid) + public static string GetAlgorithmName(DerObjectIdentifier oid) { - return (string) algorithms[oid.Id]; + return CollectionUtilities.GetValueOrNull(Algorithms, oid.Id); } private class BufferedCipherWrapper diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateEncodingException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateEncodingException.cs index b4589cb..83c89b9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateEncodingException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateEncodingException.cs @@ -1,17 +1,33 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; 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 class CertificateEncodingException + : CertificateException { - public CertificateEncodingException() : base() { } - public CertificateEncodingException(string msg) : base(msg) { } - public CertificateEncodingException(string msg, Exception e) : base(msg, e) { } + public CertificateEncodingException() + : base() + { + } + + public CertificateEncodingException(string message) + : base(message) + { + } + + public CertificateEncodingException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected CertificateEncodingException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateException.cs index 2d56966..2269caa 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateException.cs @@ -1,17 +1,33 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; 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 class CertificateException + : GeneralSecurityException { - public CertificateException() : base() { } - public CertificateException(string message) : base(message) { } - public CertificateException(string message, Exception exception) : base(message, exception) { } + public CertificateException() + : base() + { + } + + public CertificateException(string message) + : base(message) + { + } + + public CertificateException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected CertificateException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateExpiredException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateExpiredException.cs index c73639a..8b3891a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateExpiredException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateExpiredException.cs @@ -1,17 +1,33 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; 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 class CertificateExpiredException + : CertificateException { - public CertificateExpiredException() : base() { } - public CertificateExpiredException(string message) : base(message) { } - public CertificateExpiredException(string message, Exception exception) : base(message, exception) { } + public CertificateExpiredException() + : base() + { + } + + public CertificateExpiredException(string message) + : base(message) + { + } + + public CertificateExpiredException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected CertificateExpiredException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateNotYetValidException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateNotYetValidException.cs index 391b744..beeecec 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateNotYetValidException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateNotYetValidException.cs @@ -1,17 +1,33 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; 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 class CertificateNotYetValidException + : CertificateException { - public CertificateNotYetValidException() : base() { } - public CertificateNotYetValidException(string message) : base(message) { } - public CertificateNotYetValidException(string message, Exception exception) : base(message, exception) { } + public CertificateNotYetValidException() + : base() + { + } + + public CertificateNotYetValidException(string message) + : base(message) + { + } + + public CertificateNotYetValidException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected CertificateNotYetValidException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateParsingException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateParsingException.cs index 6f6e09d..17c1577 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateParsingException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CertificateParsingException.cs @@ -1,17 +1,33 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; 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 class CertificateParsingException + : CertificateException { - public CertificateParsingException() : base() { } - public CertificateParsingException(string message) : base(message) { } - public CertificateParsingException(string message, Exception exception) : base(message, exception) { } + public CertificateParsingException() + : base() + { + } + + public CertificateParsingException(string message) + : base(message) + { + } + + public CertificateParsingException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected CertificateParsingException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CrlException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CrlException.cs index 6557a3c..09712f0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CrlException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/security/cert/CrlException.cs @@ -1,17 +1,33 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; 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 class CrlException + : GeneralSecurityException { - public CrlException() : base() { } - public CrlException(string msg) : base(msg) {} - public CrlException(string msg, Exception e) : base(msg, e) {} + public CrlException() + : base() + { + } + + public CrlException(string message) + : base(message) + { + } + + public CrlException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected CrlException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/AbstractTlsClient.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/AbstractTlsClient.cs index 2d60c59..6077c68 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/AbstractTlsClient.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/AbstractTlsClient.cs @@ -1,9 +1,10 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -17,9 +18,9 @@ public abstract class AbstractTlsClient protected ProtocolVersion[] m_protocolVersions; protected int[] m_cipherSuites; - protected IList m_supportedGroups; - protected IList m_supportedSignatureAlgorithms; - protected IList m_supportedSignatureAlgorithmsCert; + protected IList m_supportedGroups; + protected IList m_supportedSignatureAlgorithms; + protected IList m_supportedSignatureAlgorithmsCert; protected AbstractTlsClient(TlsCrypto crypto) : base(crypto) @@ -54,14 +55,14 @@ protected virtual bool AllowUnexpectedServerExtension(int extensionType, byte[] } } - protected virtual IList GetNamedGroupRoles() + protected virtual IList GetNamedGroupRoles() { - IList namedGroupRoles = TlsUtilities.GetNamedGroupRoles(GetCipherSuites()); - IList sigAlgs = m_supportedSignatureAlgorithms, sigAlgsCert = m_supportedSignatureAlgorithmsCert; + var namedGroupRoles = TlsUtilities.GetNamedGroupRoles(GetCipherSuites()); + var sigAlgs = m_supportedSignatureAlgorithms; + var sigAlgsCert = m_supportedSignatureAlgorithmsCert; - if ((null == sigAlgs || TlsUtilities.ContainsAnySignatureAlgorithm(sigAlgs, SignatureAlgorithm.ecdsa)) - || (null != sigAlgsCert - && TlsUtilities.ContainsAnySignatureAlgorithm(sigAlgsCert, SignatureAlgorithm.ecdsa))) + if ((null == sigAlgs || TlsUtilities.ContainsAnySignatureAlgorithm(sigAlgs, SignatureAlgorithm.ecdsa)) || + (null != sigAlgsCert && TlsUtilities.ContainsAnySignatureAlgorithm(sigAlgsCert, SignatureAlgorithm.ecdsa))) { TlsUtilities.AddToSet(namedGroupRoles, NamedGroupRole.ecdsa); } @@ -70,7 +71,8 @@ protected virtual IList GetNamedGroupRoles() } /// - protected virtual void CheckForUnexpectedServerExtension(IDictionary serverExtensions, int extensionType) + protected virtual void CheckForUnexpectedServerExtension(IDictionary serverExtensions, + int extensionType) { byte[] extensionData = TlsUtilities.GetExtensionData(serverExtensions, extensionType); if (extensionData != null && !AllowUnexpectedServerExtension(extensionType, extensionData)) @@ -99,12 +101,12 @@ public virtual TlsSrpConfigVerifier GetSrpConfigVerifier() return new DefaultTlsSrpConfigVerifier(); } - protected virtual IList GetCertificateAuthorities() + protected virtual IList GetCertificateAuthorities() { return null; } - protected virtual IList GetProtocolNames() + protected virtual IList GetProtocolNames() { return null; } @@ -114,13 +116,13 @@ protected virtual CertificateStatusRequest GetCertificateStatusRequest() return new CertificateStatusRequest(CertificateStatusType.ocsp, new OcspStatusRequest(null, null)); } - /// an of (or null). - protected virtual IList GetMultiCertStatusRequest() + /// an of (or null). + protected virtual IList GetMultiCertStatusRequest() { return null; } - protected virtual IList GetSniServerNames() + protected virtual IList GetSniServerNames() { return null; } @@ -130,12 +132,12 @@ protected virtual IList GetSniServerNames() /// The named group roles for which there should /// be at least one supported group. By default this is inferred from the offered cipher suites and signature /// algorithms. - /// an of . See for group constants. + /// an of . See for group constants. /// - protected virtual IList GetSupportedGroups(IList namedGroupRoles) + protected virtual IList GetSupportedGroups(IList namedGroupRoles) { TlsCrypto crypto = Crypto; - IList supportedGroups = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var supportedGroups = new List(); if (namedGroupRoles.Contains(NamedGroupRole.ecdh)) { @@ -159,17 +161,27 @@ protected virtual IList GetSupportedGroups(IList namedGroupRoles) return supportedGroups; } - protected virtual IList GetSupportedSignatureAlgorithms() + protected virtual IList GetSupportedSignatureAlgorithms() { return TlsUtilities.GetDefaultSupportedSignatureAlgorithms(m_context); } - protected virtual IList GetSupportedSignatureAlgorithmsCert() + protected virtual IList GetSupportedSignatureAlgorithmsCert() { return null; } - protected virtual IList GetTrustedCAIndication() + protected virtual IList GetTrustedCAIndication() + { + return null; + } + + protected virtual short[] GetAllowedClientCertificateTypes() + { + return null; + } + + protected virtual short[] GetAllowedServerCertificateTypes() { return null; } @@ -207,7 +219,7 @@ public virtual TlsSession GetSessionToResume() return null; } - public virtual IList GetExternalPsks() + public virtual IList GetExternalPsks() { return null; } @@ -223,9 +235,9 @@ public virtual bool IsFallback() } /// - public virtual IDictionary GetClientExtensions() + public virtual IDictionary GetClientExtensions() { - IDictionary clientExtensions = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + var clientExtensions = new Dictionary(); bool offeringTlsV13Plus = false; bool offeringPreTlsV13 = false; @@ -244,13 +256,13 @@ public virtual IDictionary GetClientExtensions() } } - IList protocolNames = GetProtocolNames(); + var protocolNames = GetProtocolNames(); if (protocolNames != null) { TlsExtensionsUtilities.AddAlpnExtensionClient(clientExtensions, protocolNames); } - IList sniServerNames = GetSniServerNames(); + var sniServerNames = GetSniServerNames(); if (sniServerNames != null) { TlsExtensionsUtilities.AddServerNameExtensionClient(clientExtensions, sniServerNames); @@ -264,7 +276,7 @@ public virtual IDictionary GetClientExtensions() if (offeringTlsV13Plus) { - IList certificateAuthorities = GetCertificateAuthorities(); + var certificateAuthorities = GetCertificateAuthorities(); if (certificateAuthorities != null) { TlsExtensionsUtilities.AddCertificateAuthoritiesExtension(clientExtensions, certificateAuthorities); @@ -276,13 +288,13 @@ public virtual IDictionary GetClientExtensions() // TODO Shouldn't add if no offered cipher suite uses a block cipher? TlsExtensionsUtilities.AddEncryptThenMacExtension(clientExtensions); - IList statusRequestV2 = GetMultiCertStatusRequest(); + var statusRequestV2 = GetMultiCertStatusRequest(); if (statusRequestV2 != null) { TlsExtensionsUtilities.AddStatusRequestV2Extension(clientExtensions, statusRequestV2); } - IList trustedCAKeys = GetTrustedCAIndication(); + var trustedCAKeys = GetTrustedCAIndication(); if (trustedCAKeys != null) { TlsExtensionsUtilities.AddTrustedCAKeysExtensionClient(clientExtensions, trustedCAKeys); @@ -297,7 +309,7 @@ public virtual IDictionary GetClientExtensions() */ if (TlsUtilities.IsSignatureAlgorithmsExtensionAllowed(clientVersion)) { - IList supportedSigAlgs = GetSupportedSignatureAlgorithms(); + var supportedSigAlgs = GetSupportedSignatureAlgorithms(); if (null != supportedSigAlgs && supportedSigAlgs.Count > 0) { this.m_supportedSignatureAlgorithms = supportedSigAlgs; @@ -305,7 +317,7 @@ public virtual IDictionary GetClientExtensions() TlsExtensionsUtilities.AddSignatureAlgorithmsExtension(clientExtensions, supportedSigAlgs); } - IList supportedSigAlgsCert = GetSupportedSignatureAlgorithmsCert(); + var supportedSigAlgsCert = GetSupportedSignatureAlgorithmsCert(); if (null != supportedSigAlgsCert && supportedSigAlgsCert.Count > 0) { this.m_supportedSignatureAlgorithmsCert = supportedSigAlgsCert; @@ -314,9 +326,9 @@ public virtual IDictionary GetClientExtensions() } } - IList namedGroupRoles = GetNamedGroupRoles(); + var namedGroupRoles = GetNamedGroupRoles(); - IList supportedGroups = GetSupportedGroups(namedGroupRoles); + var supportedGroups = GetSupportedGroups(namedGroupRoles); if (supportedGroups != null && supportedGroups.Count > 0) { this.m_supportedGroups = supportedGroups; @@ -334,10 +346,37 @@ public virtual IDictionary GetClientExtensions() } } + /* + * RFC 7250 4.1: + * + * If the client has no remaining certificate types to send in + * the client hello, other than the default X.509 type, it MUST omit the + * client_certificate_type extension in the client hello. + */ + short[] clientCertTypes = GetAllowedClientCertificateTypes(); + if (clientCertTypes != null && (clientCertTypes.Length > 1 || clientCertTypes[0] != CertificateType.X509)) + { + TlsExtensionsUtilities.AddClientCertificateTypeExtensionClient(clientExtensions, clientCertTypes); + } + + /* + * RFC 7250 4.1: + * + * If the client has no remaining certificate types to send in + * the client hello, other than the default X.509 certificate type, it + * MUST omit the entire server_certificate_type extension from the + * client hello. + */ + short[] serverCertTypes = GetAllowedServerCertificateTypes(); + if (serverCertTypes != null && (serverCertTypes.Length > 1 || serverCertTypes[0] != CertificateType.X509)) + { + TlsExtensionsUtilities.AddServerCertificateTypeExtensionClient(clientExtensions, serverCertTypes); + } + return clientExtensions; } - public virtual IList GetEarlyKeyShareGroups() + public virtual IList GetEarlyKeyShareGroups() { /* * RFC 8446 4.2.8. Each KeyShareEntry value MUST correspond to a group offered in the @@ -381,7 +420,7 @@ public virtual void NotifySelectedPsk(TlsPsk selectedPsk) } /// - public virtual void ProcessServerExtensions(IDictionary serverExtensions) + public virtual void ProcessServerExtensions(IDictionary serverExtensions) { if (null == serverExtensions) return; @@ -425,7 +464,7 @@ public virtual void ProcessServerExtensions(IDictionary serverExtensions) } /// - public virtual void ProcessServerSupplementalData(IList serverSupplementalData) + public virtual void ProcessServerSupplementalData(IList serverSupplementalData) { if (serverSupplementalData != null) throw new TlsFatalAlert(AlertDescription.unexpected_message); @@ -434,7 +473,7 @@ public virtual void ProcessServerSupplementalData(IList serverSupplementalData) public abstract TlsAuthentication GetAuthentication(); /// - public virtual IList GetClientSupplementalData() + public virtual IList GetClientSupplementalData() { return null; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/AbstractTlsContext.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/AbstractTlsContext.cs index 508cb91..b2713f2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/AbstractTlsContext.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/AbstractTlsContext.cs @@ -13,29 +13,24 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls internal abstract class AbstractTlsContext : TlsContext { - private static long counter = Times.NanoTime(); + private static long counter = DateTime.UtcNow.Ticks; -#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 static TlsNonceGenerator CreateNonceGenerator(TlsCrypto crypto, int connectionEnd) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span additionalSeedMaterial = stackalloc byte[16]; + Pack.UInt64_To_BE((ulong)NextCounterValue(), additionalSeedMaterial); + Pack.UInt64_To_BE((ulong)DateTime.UtcNow.Ticks, additionalSeedMaterial[8..]); +#else byte[] additionalSeedMaterial = new byte[16]; Pack.UInt64_To_BE((ulong)NextCounterValue(), additionalSeedMaterial, 0); - Pack.UInt64_To_BE((ulong)Times.NanoTime(), additionalSeedMaterial, 8); + Pack.UInt64_To_BE((ulong)DateTime.UtcNow.Ticks, additionalSeedMaterial, 8); +#endif additionalSeedMaterial[0] &= 0x7F; additionalSeedMaterial[0] |= (byte)(connectionEnd << 7); @@ -196,6 +191,9 @@ public virtual byte[] ExportChannelBinding(int channelBinding) SecurityParameters securityParameters = SecurityParameters; + if (ChannelBinding.tls_exporter == channelBinding) + return ExportKeyingMaterial("EXPORTER-Channel-Binding", TlsUtilities.EmptyBytes, 32); + if (TlsUtilities.IsTlsV13(securityParameters.NegotiatedVersion)) return null; @@ -276,8 +274,21 @@ protected virtual byte[] ExportKeyingMaterial13(TlsSecret secret, int cryptoHash throw new ArgumentException("must have length less than 2^16 (or be null)", "context"); } - return TlsCryptoUtilities.HkdfExpandLabel(secret, cryptoHashAlgorithm, asciiLabel, context, length) - .Extract(); + TlsHash exporterHash = Crypto.CreateHash(cryptoHashAlgorithm); + byte[] emptyTranscriptHash = exporterHash.CalculateHash(); + + TlsSecret exporterSecret = TlsUtilities.DeriveSecret(SecurityParameters, secret, asciiLabel, + emptyTranscriptHash); + + byte[] exporterContext = emptyTranscriptHash; + if (context.Length > 0) + { + exporterHash.Update(context, 0, context.Length); + exporterContext = exporterHash.CalculateHash(); + } + + return TlsCryptoUtilities + .HkdfExpandLabel(exporterSecret, cryptoHashAlgorithm, "exporter", exporterContext, length).Extract(); } protected virtual TlsSecret CheckEarlyExportSecret(TlsSecret secret) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/AbstractTlsPeer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/AbstractTlsPeer.cs index 75baf43..65bd820 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/AbstractTlsPeer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/AbstractTlsPeer.cs @@ -28,8 +28,7 @@ protected AbstractTlsPeer(TlsCrypto crypto) /// an array of supported values. protected virtual ProtocolVersion[] GetSupportedVersions() { - // TODO[tls13] Enable TLSv13 by default in due course - return ProtocolVersion.TLSv12.DownTo(ProtocolVersion.TLSv10); + return ProtocolVersion.TLSv13.DownTo(ProtocolVersion.TLSv12); } protected abstract int[] GetSupportedCipherSuites(); @@ -160,6 +159,8 @@ public virtual short GetHeartbeatPolicy() { return HeartbeatMode.peer_not_allowed_to_send; } + + public virtual bool IgnoreCorruptDtlsRecords => false; } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/AbstractTlsServer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/AbstractTlsServer.cs index 9ecf056..2263c60 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/AbstractTlsServer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/AbstractTlsServer.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; @@ -18,21 +18,21 @@ public abstract class AbstractTlsServer protected int[] m_cipherSuites; protected int[] m_offeredCipherSuites; - protected IDictionary m_clientExtensions; + protected IDictionary m_clientExtensions; protected bool m_encryptThenMACOffered; protected short m_maxFragmentLengthOffered; protected bool m_truncatedHMacOffered; protected bool m_clientSentECPointFormats; protected CertificateStatusRequest m_certificateStatusRequest; - protected IList m_statusRequestV2; - protected IList m_trustedCAKeys; + protected IList m_statusRequestV2; + protected IList m_trustedCAKeys; protected int m_selectedCipherSuite; - protected IList m_clientProtocolNames; + protected IList m_clientProtocolNames; protected ProtocolName m_selectedProtocolName; - protected readonly IDictionary m_serverExtensions = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + protected readonly IDictionary m_serverExtensions = new Dictionary(); public AbstractTlsServer(TlsCrypto crypto) : base(crypto) @@ -101,13 +101,13 @@ protected virtual int GetMaximumNegotiableFiniteFieldBits() return maxBits; } - protected virtual IList GetProtocolNames() + protected virtual IList GetProtocolNames() { return null; } protected virtual bool IsSelectableCipherSuite(int cipherSuite, int availCurveBits, int availFiniteFieldBits, - IList sigAlgs) + IList sigAlgs) { // TODO[tls13] The version check should be separated out (eventually select ciphersuite before version) return TlsUtilities.IsValidVersionForCipherSuite(cipherSuite, m_context.ServerVersion) @@ -182,7 +182,7 @@ protected virtual int SelectECDHDefault(int minimumCurveBits) protected virtual ProtocolName SelectProtocolName() { - IList serverProtocolNames = GetProtocolNames(); + IList serverProtocolNames = GetProtocolNames(); if (null == serverProtocolNames || serverProtocolNames.Count < 1) return null; @@ -193,7 +193,8 @@ protected virtual ProtocolName SelectProtocolName() return result; } - protected virtual ProtocolName SelectProtocolName(IList clientProtocolNames, IList serverProtocolNames) + protected virtual ProtocolName SelectProtocolName(IList clientProtocolNames, + IList serverProtocolNames) { foreach (ProtocolName serverProtocolName in serverProtocolNames) { @@ -208,6 +209,16 @@ protected virtual bool ShouldSelectProtocolNameEarly() return true; } + protected virtual bool PreferLocalClientCertificateTypes() + { + return false; + } + + protected virtual short[] GetAllowedClientCertificateTypes() + { + return null; + } + public virtual void Init(TlsServerContext context) { this.m_context = context; @@ -252,7 +263,7 @@ public virtual byte[] GetNewSessionID() return null; } - public virtual TlsPskExternal GetExternalPsk(IList identities) + public virtual TlsPskExternal GetExternalPsk(IList identities) { return null; } @@ -304,7 +315,7 @@ public virtual void NotifyOfferedCipherSuites(int[] offeredCipherSuites) this.m_offeredCipherSuites = offeredCipherSuites; } - public virtual void ProcessClientExtensions(IDictionary clientExtensions) + public virtual void ProcessClientExtensions(IDictionary clientExtensions) { this.m_clientExtensions = clientExtensions; @@ -384,7 +395,7 @@ public virtual int GetSelectedCipherSuite() * somewhat inelegant but is a compromise designed to minimize changes to the original * cipher suite design. */ - IList sigAlgs = TlsUtilities.GetUsableSignatureAlgorithms(securityParameters.ClientSigAlgs); + var sigAlgs = TlsUtilities.GetUsableSignatureAlgorithms(securityParameters.ClientSigAlgs); /* * RFC 4429 5.1. A server that receives a ClientHello containing one or both of these @@ -414,7 +425,7 @@ public virtual int GetSelectedCipherSuite() } // IDictionary is (Int32 -> byte[]) - public virtual IDictionary GetServerExtensions() + public virtual IDictionary GetServerExtensions() { bool isTlsV13 = TlsUtilities.IsTlsV13(m_context); @@ -492,10 +503,70 @@ public virtual IDictionary GetServerExtensions() TlsExtensionsUtilities.AddMaxFragmentLengthExtension(m_serverExtensions, m_maxFragmentLengthOffered); } + // RFC 7250 4.2 for server_certificate_type + short[] serverCertTypes = TlsExtensionsUtilities.GetServerCertificateTypeExtensionClient( + m_clientExtensions); + if (serverCertTypes != null) + { + TlsCredentials credentials = GetCredentials(); + + if (credentials == null || !Arrays.Contains(serverCertTypes, credentials.Certificate.CertificateType)) + { + // outcome 2: we support the extension but have no common types + throw new TlsFatalAlert(AlertDescription.unsupported_certificate); + } + + // outcome 3: we support the extension and have a common type + TlsExtensionsUtilities.AddServerCertificateTypeExtensionServer(m_serverExtensions, + credentials.Certificate.CertificateType); + } + + // RFC 7250 4.2 for client_certificate_type + short[] remoteClientCertTypes = TlsExtensionsUtilities.GetClientCertificateTypeExtensionClient( + m_clientExtensions); + if (remoteClientCertTypes != null) + { + short[] localClientCertTypes = GetAllowedClientCertificateTypes(); + if (localClientCertTypes != null) + { + short[] preferredTypes; + short[] nonPreferredTypes; + if (PreferLocalClientCertificateTypes()) + { + preferredTypes = localClientCertTypes; + nonPreferredTypes = remoteClientCertTypes; + } + else + { + preferredTypes = remoteClientCertTypes; + nonPreferredTypes = localClientCertTypes; + } + + short selectedType = -1; + for (int i = 0; i < preferredTypes.Length; i++) + { + if (Arrays.Contains(nonPreferredTypes, preferredTypes[i])) + { + selectedType = preferredTypes[i]; + break; + } + } + + if (selectedType == -1) + { + // outcome 2: we support the extension but have no common types + throw new TlsFatalAlert(AlertDescription.unsupported_certificate); + } + + // outcome 3: we support the extension and have a common type + TlsExtensionsUtilities.AddClientCertificateTypeExtensionServer(m_serverExtensions, selectedType); + } // else outcome 1: we don't support the extension + } + return m_serverExtensions; } - public virtual void GetServerExtensionsForConnection(IDictionary serverExtensions) + public virtual void GetServerExtensionsForConnection(IDictionary serverExtensions) { if (!ShouldSelectProtocolNameEarly()) { @@ -520,7 +591,7 @@ public virtual void GetServerExtensionsForConnection(IDictionary serverExtension } } - public virtual IList GetServerSupplementalData() + public virtual IList GetServerSupplementalData() { return null; } @@ -561,7 +632,7 @@ public virtual TlsECConfig GetECDHConfig() return TlsEccUtilities.CreateNamedECConfig(m_context, namedGroup); } - public virtual void ProcessClientSupplementalData(IList clientSupplementalData) + public virtual void ProcessClientSupplementalData(IList clientSupplementalData) { if (clientSupplementalData != null) throw new TlsFatalAlert(AlertDescription.unexpected_message); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ByteQueue.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ByteQueue.cs index 1fb4a64..c71c246 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ByteQueue.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ByteQueue.cs @@ -3,24 +3,17 @@ using System; using System.IO; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; + namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls { /// A queue for bytes. This file could be more optimized. public sealed class ByteQueue { /// The smallest number which can be written as 2^x which is bigger than i. - public static int NextTwoPow(int i) + private static int GetAllocationSize(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; + return Integers.HighestOneBit((256 | i) << 1); } /// The buffer where we store our data. @@ -58,12 +51,24 @@ public ByteQueue(byte[] buf, int off, int len) /// How many bytes to read from the array. public void AddData(byte[] buf, int off, int len) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + AddData(buf.AsSpan(off, len)); +#else if (m_readOnlyBuf) throw new InvalidOperationException("Cannot add data to read-only buffer"); - if ((m_skipped + m_available + len) > m_databuf.Length) + if (m_available == 0) + { + if (len > m_databuf.Length) + { + int desiredSize = GetAllocationSize(len); + m_databuf = new byte[desiredSize]; + } + m_skipped = 0; + } + else if ((m_skipped + m_available + len) > m_databuf.Length) { - int desiredSize = ByteQueue.NextTwoPow(m_available + len); + int desiredSize = GetAllocationSize(m_available + len); if (desiredSize > m_databuf.Length) { byte[] tmp = new byte[desiredSize]; @@ -79,8 +84,46 @@ public void AddData(byte[] buf, int off, int len) Array.Copy(buf, off, m_databuf, m_skipped + m_available, len); m_available += len; +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void AddData(ReadOnlySpan buffer) + { + if (m_readOnlyBuf) + throw new InvalidOperationException("Cannot add data to read-only buffer"); + + int len = buffer.Length; + if (m_available == 0) + { + if (len > m_databuf.Length) + { + int desiredSize = GetAllocationSize(len); + m_databuf = new byte[desiredSize]; + } + m_skipped = 0; + } + else if ((m_skipped + m_available + len) > m_databuf.Length) + { + int desiredSize = GetAllocationSize(m_available + len); + if (desiredSize > m_databuf.Length) + { + byte[] tmp = new byte[desiredSize]; + Array.Copy(m_databuf, m_skipped, tmp, 0, m_available); + m_databuf = tmp; + } + else + { + Array.Copy(m_databuf, m_skipped, m_databuf, 0, m_available); + } + m_skipped = 0; + } + + buffer.CopyTo(m_databuf.AsSpan(m_skipped + m_available)); + m_available += len; + } +#endif + /// The number of bytes which are available in this buffer. public int Available { @@ -117,6 +160,16 @@ public void Read(byte[] buf, int offset, int len, int skip) Array.Copy(m_databuf, m_skipped + skip, buf, offset, len); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Read(Span buffer, int skip) + { + if ((m_available - skip) < buffer.Length) + throw new InvalidOperationException("Not enough data to read"); + + buffer.CopyFrom(m_databuf.AsSpan(m_skipped + skip)); + } +#endif + /// Return a over some bytes at the beginning of the data. /// /// How many bytes will be readable. @@ -142,6 +195,14 @@ public int ReadInt32() return TlsUtilities.ReadInt32(m_databuf, m_skipped); } + public int ReadUint16(int skip) + { + if (m_available < skip + 2) + throw new InvalidOperationException("Not enough data to read"); + + return TlsUtilities.ReadUint16(m_databuf, m_skipped + skip); + } + /// Remove some bytes from our data from the beginning. /// How many bytes to remove. public void RemoveData(int i) @@ -167,6 +228,14 @@ public void RemoveData(byte[] buf, int off, int len, int skip) RemoveData(skip + len); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void RemoveData(Span buffer, int skip) + { + Read(buffer, skip); + RemoveData(skip + buffer.Length); + } +#endif + public byte[] RemoveData(int len, int skip) { byte[] buf = new byte[len]; @@ -183,7 +252,7 @@ public void Shrink() } else { - int desiredSize = ByteQueue.NextTwoPow(m_available); + int desiredSize = GetAllocationSize(m_available); if (desiredSize < m_databuf.Length) { byte[] tmp = new byte[desiredSize]; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ByteQueueInputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ByteQueueInputStream.cs index f6246d8..a179272 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ByteQueueInputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ByteQueueInputStream.cs @@ -33,20 +33,31 @@ public int Peek(byte[] buf) return bytesToRead; } - public override int ReadByte() + public override int Read(byte[] buffer, int offset, int count) { - if (m_buffer.Available == 0) - return -1; + Streams.ValidateBufferArguments(buffer, offset, count); - return m_buffer.RemoveData(1, 0)[0]; + int bytesToRead = System.Math.Min(m_buffer.Available, count); + m_buffer.RemoveData(buffer, offset, bytesToRead, 0); + return bytesToRead; } - public override int Read(byte[] buf, int off, int len) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int Read(Span buffer) { - int bytesToRead = System.Math.Min(m_buffer.Available, len); - m_buffer.RemoveData(buf, off, bytesToRead, 0); + int bytesToRead = System.Math.Min(m_buffer.Available, buffer.Length); + m_buffer.RemoveData(buffer[..bytesToRead], 0); return bytesToRead; } +#endif + + public override int ReadByte() + { + if (m_buffer.Available == 0) + return -1; + + return m_buffer.RemoveData(1, 0)[0]; + } public long Skip(long n) { @@ -59,17 +70,6 @@ public int Available { get { return m_buffer.Available; } } - -#if PORTABLE || NETFX_CORE - //protected override void Dispose(bool disposing) - //{ - // base.Dispose(disposing); - //} -#else - public override void Close() - { - } -#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ByteQueueOutputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ByteQueueOutputStream.cs index 601fe24..138b435 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ByteQueueOutputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ByteQueueOutputStream.cs @@ -22,14 +22,23 @@ public ByteQueue Buffer get { return m_buffer; } } - public override void WriteByte(byte b) + public override void Write(byte[] buffer, int offset, int count) { - m_buffer.AddData(new byte[]{ b }, 0, 1); + Streams.ValidateBufferArguments(buffer, offset, count); + + m_buffer.AddData(buffer, offset, count); } - public override void Write(byte[] buf, int off, int len) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) + { + m_buffer.AddData(buffer); + } +#endif + + public override void WriteByte(byte value) { - m_buffer.AddData(buf, off, len); + m_buffer.AddData(new byte[]{ value }, 0, 1); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/Certificate.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/Certificate.cs index 5fc3511..23734be 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/Certificate.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/Certificate.cs @@ -1,11 +1,9 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; - using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls { @@ -28,18 +26,8 @@ public sealed class Certificate public sealed class ParseOptions { - private int m_maxChainLength = int.MaxValue; - - public int MaxChainLength - { - get { return m_maxChainLength; } - } - - public ParseOptions SetMaxChainLength(int maxChainLength) - { - this.m_maxChainLength = maxChainLength; - return this; - } + public short CertificateType { get; set; } = Tls.CertificateType.X509; + public int MaxChainLength { get; set; } = int.MaxValue; } private static CertificateEntry[] Convert(TlsCertificate[] certificateList) @@ -58,22 +46,29 @@ private static CertificateEntry[] Convert(TlsCertificate[] certificateList) private readonly byte[] m_certificateRequestContext; private readonly CertificateEntry[] m_certificateEntryList; + private readonly short m_certificateType; public Certificate(TlsCertificate[] certificateList) : this(null, Convert(certificateList)) { } - // TODO[tls13] Prefer to manage the certificateRequestContext internally only? public Certificate(byte[] certificateRequestContext, CertificateEntry[] certificateEntryList) + : this(Tls.CertificateType.X509, certificateRequestContext, certificateEntryList) + { + } + + // TODO[tls13] Prefer to manage the certificateRequestContext internally only? + public Certificate(short certificateType, byte[] certificateRequestContext, CertificateEntry[] certificateEntryList) { if (null != certificateRequestContext && !TlsUtilities.IsValidUint8(certificateRequestContext.Length)) throw new ArgumentException("cannot be longer than 255", "certificateRequestContext"); if (TlsUtilities.IsNullOrContainsNull(certificateEntryList)) throw new ArgumentException("cannot be null or contain any nulls", "certificateEntryList"); - this.m_certificateRequestContext = TlsUtilities.Clone(certificateRequestContext); - this.m_certificateEntryList = certificateEntryList; + m_certificateRequestContext = TlsUtilities.Clone(certificateRequestContext); + m_certificateEntryList = certificateEntryList; + m_certificateType = certificateType; } public byte[] GetCertificateRequestContext() @@ -102,22 +97,13 @@ public CertificateEntry[] GetCertificateEntryList() return CloneCertificateEntryList(); } - public short CertificateType - { - get { return Tls.CertificateType.X509; } - } + public short CertificateType => m_certificateType; - public int Length - { - get { return m_certificateEntryList.Length; } - } + public int Length => m_certificateEntryList.Length; /// true if this certificate chain contains no certificates, or false otherwise. /// - public bool IsEmpty - { - get { return m_certificateEntryList.Length == 0; } - } + public bool IsEmpty => m_certificateEntryList.Length == 0; /// Encode this to a , and optionally calculate the /// "end point hash" (per RFC 5929's tls-server-end-point binding). @@ -139,8 +125,8 @@ public void Encode(TlsContext context, Stream messageOutput, Stream endPointHash } int count = m_certificateEntryList.Length; - IList certEncodings = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(count); - IList extEncodings = isTlsV13 ? BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(count) : null; + var certEncodings = new List(count); + var extEncodings = isTlsV13 ? new List(count) : null; long totalLength = 0; for (int i = 0; i < count; ++i) @@ -160,7 +146,7 @@ public void Encode(TlsContext context, Stream messageOutput, Stream endPointHash if (isTlsV13) { - IDictionary extensions = entry.Extensions; + var extensions = entry.Extensions; byte[] extEncoding = (null == extensions) ? TlsUtilities.EmptyBytes : TlsProtocol.WriteExtensionsData(extensions); @@ -171,18 +157,21 @@ public void Encode(TlsContext context, Stream messageOutput, Stream endPointHash } } - TlsUtilities.CheckUint24(totalLength); - TlsUtilities.WriteUint24((int)totalLength, messageOutput); + // RFC 7250 indicates the raw key is not wrapped in a cert list like X509 is + // but RFC 8446 wraps it in a CertificateEntry, which is inside certificate_list + if (isTlsV13 || m_certificateType != Tls.CertificateType.RawPublicKey) + { + TlsUtilities.CheckUint24(totalLength); + TlsUtilities.WriteUint24((int)totalLength, messageOutput); + } for (int i = 0; i < count; ++i) { - byte[] certEncoding = (byte[])certEncodings[i]; - TlsUtilities.WriteOpaque24(certEncoding, messageOutput); + TlsUtilities.WriteOpaque24(certEncodings[i], messageOutput); if (isTlsV13) { - byte[] extEncoding = (byte[])extEncodings[i]; - TlsUtilities.WriteOpaque16(extEncoding, messageOutput); + TlsUtilities.WriteOpaque16(extEncodings[i], messageOutput); } } } @@ -200,6 +189,7 @@ public static Certificate Parse(ParseOptions options, TlsContext context, Stream { SecurityParameters securityParameters = context.SecurityParameters; bool isTlsV13 = TlsUtilities.IsTlsV13(securityParameters.NegotiatedVersion); + short certType = options.CertificateType; byte[] certificateRequestContext = null; if (isTlsV13) @@ -212,7 +202,7 @@ public static Certificate Parse(ParseOptions options, TlsContext context, Stream { return !isTlsV13 ? EmptyChain : certificateRequestContext.Length < 1 ? EmptyChainTls13 - : new Certificate(certificateRequestContext, EmptyCertEntries); + : new Certificate(certType, certificateRequestContext, EmptyCertEntries); } byte[] certListData = TlsUtilities.ReadFully(totalLength, messageInput); @@ -221,7 +211,7 @@ public static Certificate Parse(ParseOptions options, TlsContext context, Stream TlsCrypto crypto = context.Crypto; int maxChainLength = System.Math.Max(1, options.MaxChainLength); - IList certificate_list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var certificate_list = new List(); while (buf.Position < buf.Length) { if (certificate_list.Count >= maxChainLength) @@ -230,15 +220,27 @@ public static Certificate Parse(ParseOptions options, TlsContext context, Stream "Certificate chain longer than maximum (" + maxChainLength + ")"); } - byte[] derEncoding = TlsUtilities.ReadOpaque24(buf, 1); - TlsCertificate cert = crypto.CreateCertificate(derEncoding); + // RFC 7250 indicates the raw key is not wrapped in a cert list like X509 is + // but RFC 8446 wraps it in a CertificateEntry, which is inside certificate_list + byte[] derEncoding; + if (isTlsV13 || certType != Tls.CertificateType.RawPublicKey) + { + derEncoding = TlsUtilities.ReadOpaque24(buf, 1); + } + else + { + derEncoding = certListData; + buf.Seek(totalLength, SeekOrigin.Current); + } + + TlsCertificate cert = crypto.CreateCertificate(certType, derEncoding); if (certificate_list.Count < 1 && endPointHashOutput != null) { CalculateEndPointHash(context, cert, derEncoding, endPointHashOutput); } - IDictionary extensions = null; + IDictionary extensions = null; if (isTlsV13) { byte[] extEncoding = TlsUtilities.ReadOpaque16(buf); @@ -255,7 +257,7 @@ public static Certificate Parse(ParseOptions options, TlsContext context, Stream certificateList[i] = (CertificateEntry)certificate_list[i]; } - return new Certificate(certificateRequestContext, certificateList); + return new Certificate(certType, certificateRequestContext, certificateList); } private static void CalculateEndPointHash(TlsContext context, TlsCertificate cert, byte[] encoding, diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateCompressionAlgorithm.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateCompressionAlgorithm.cs new file mode 100644 index 0000000..5970bcd --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateCompressionAlgorithm.cs @@ -0,0 +1,51 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls +{ + /** + * RFC 8879 + */ + public abstract class CertificateCompressionAlgorithm + { + public const int zlib = 1; + public const int brotli = 2; + public const int zstd = 3; + + public static string GetName(int certificateCompressionAlgorithm) + { + switch (certificateCompressionAlgorithm) + { + case zlib: + return "zlib"; + case brotli: + return "brotli"; + case zstd: + return "zstd"; + default: + return "UNKNOWN"; + } + } + + public static string GetText(int certificateCompressionAlgorithm) + { + return GetName(certificateCompressionAlgorithm) + "(" + certificateCompressionAlgorithm + ")"; + } + + public static bool IsRecognized(int certificateCompressionAlgorithm) + { + switch (certificateCompressionAlgorithm) + { + case zlib: + case brotli: + case zstd: + return true; + default: + return false; + } + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateCompressionAlgorithm.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateCompressionAlgorithm.cs.meta new file mode 100644 index 0000000..35c114a --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateCompressionAlgorithm.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6e946795c64c7bf45be136ba500d866f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateEntry.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateEntry.cs index a2b17b0..bdf4951 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateEntry.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateEntry.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; @@ -10,9 +10,9 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls public sealed class CertificateEntry { private readonly TlsCertificate m_certificate; - private readonly IDictionary m_extensions; + private readonly IDictionary m_extensions; - public CertificateEntry(TlsCertificate certificate, IDictionary extensions) + public CertificateEntry(TlsCertificate certificate, IDictionary extensions) { if (null == certificate) throw new ArgumentNullException("certificate"); @@ -26,7 +26,7 @@ public TlsCertificate Certificate get { return m_certificate; } } - public IDictionary Extensions + public IDictionary Extensions { get { return m_extensions; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateRequest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateRequest.cs index af82e7c..0163940 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateRequest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateRequest.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; @@ -39,8 +39,8 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls public sealed class CertificateRequest { /// - private static IList CheckSupportedSignatureAlgorithms(IList supportedSignatureAlgorithms, - short alertDescription) + private static IList CheckSupportedSignatureAlgorithms( + IList supportedSignatureAlgorithms, short alertDescription) { if (null == supportedSignatureAlgorithms) throw new TlsFatalAlert(alertDescription, "'signature_algorithms' is required"); @@ -50,25 +50,26 @@ private static IList CheckSupportedSignatureAlgorithms(IList supportedSignatureA private readonly byte[] m_certificateRequestContext; private readonly short[] m_certificateTypes; - private readonly IList m_supportedSignatureAlgorithms; - private readonly IList m_supportedSignatureAlgorithmsCert; - private readonly IList m_certificateAuthorities; + private readonly IList m_supportedSignatureAlgorithms; + private readonly IList m_supportedSignatureAlgorithmsCert; + private readonly IList m_certificateAuthorities; /// see for valid constants. /// - /// an of . - public CertificateRequest(short[] certificateTypes, IList supportedSignatureAlgorithms, - IList certificateAuthorities) + /// an of . + public CertificateRequest(short[] certificateTypes, + IList supportedSignatureAlgorithms, IList certificateAuthorities) : this(null, certificateTypes, supportedSignatureAlgorithms, null, certificateAuthorities) { } // TODO[tls13] Prefer to manage the certificateRequestContext internally only? /// - public CertificateRequest(byte[] certificateRequestContext, IList supportedSignatureAlgorithms, - IList supportedSignatureAlgorithmsCert, IList certificateAuthorities) + public CertificateRequest(byte[] certificateRequestContext, + IList supportedSignatureAlgorithms, + IList supportedSignatureAlgorithmsCert, IList certificateAuthorities) : this(certificateRequestContext, null, - CheckSupportedSignatureAlgorithms(supportedSignatureAlgorithms, AlertDescription.internal_error), + CheckSupportedSignatureAlgorithms(supportedSignatureAlgorithms, AlertDescription.internal_error), supportedSignatureAlgorithmsCert, certificateAuthorities) { /* @@ -79,7 +80,8 @@ public CertificateRequest(byte[] certificateRequestContext, IList supportedSigna } private CertificateRequest(byte[] certificateRequestContext, short[] certificateTypes, - IList supportedSignatureAlgorithms, IList supportedSignatureAlgorithmsCert, IList certificateAuthorities) + IList supportedSignatureAlgorithms, + IList supportedSignatureAlgorithmsCert, IList certificateAuthorities) { if (null != certificateRequestContext && !TlsUtilities.IsValidUint8(certificateRequestContext.Length)) throw new ArgumentException("cannot be longer than 255", "certificateRequestContext"); @@ -108,22 +110,22 @@ public short[] CertificateTypes get { return m_certificateTypes; } } - /// an of (or null before TLS 1.2). + /// an of (or null before TLS 1.2). /// - public IList SupportedSignatureAlgorithms + public IList SupportedSignatureAlgorithms { get { return m_supportedSignatureAlgorithms; } } - /// an optional of . May be non-null from + /// an optional of . May be non-null from /// TLS 1.3 onwards. - public IList SupportedSignatureAlgorithmsCert + public IList SupportedSignatureAlgorithmsCert { get { return m_supportedSignatureAlgorithmsCert; } } - /// an of . - public IList CertificateAuthorities + /// an of . + public IList CertificateAuthorities { get { return m_certificateAuthorities; } } @@ -155,7 +157,7 @@ public void Encode(TlsContext context, Stream output) { TlsUtilities.WriteOpaque8(m_certificateRequestContext, output); - IDictionary extensions = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + var extensions = new Dictionary(); TlsExtensionsUtilities.AddSignatureAlgorithmsExtension(extensions, m_supportedSignatureAlgorithms); if (null != m_supportedSignatureAlgorithmsCert) @@ -189,7 +191,7 @@ public void Encode(TlsContext context, Stream output) } else { - IList derEncodings = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(m_certificateAuthorities.Count); + var derEncodings = new List(m_certificateAuthorities.Count); int totalLength = 0; foreach (X509Name certificateAuthority in m_certificateAuthorities) @@ -231,15 +233,14 @@ public static CertificateRequest Parse(TlsContext context, Stream input) byte[] extEncoding = TlsUtilities.ReadOpaque16(input); - IDictionary extensions = TlsProtocol.ReadExtensionsData13(HandshakeType.certificate_request, - extEncoding); + var extensions = TlsProtocol.ReadExtensionsData13(HandshakeType.certificate_request, extEncoding); - IList supportedSignatureAlgorithms13 = CheckSupportedSignatureAlgorithms( + var supportedSignatureAlgorithms13 = CheckSupportedSignatureAlgorithms( TlsExtensionsUtilities.GetSignatureAlgorithmsExtension(extensions), AlertDescription.missing_extension); - IList supportedSignatureAlgorithmsCert13 = TlsExtensionsUtilities + var supportedSignatureAlgorithmsCert13 = TlsExtensionsUtilities .GetSignatureAlgorithmsCertExtension(extensions); - IList certificateAuthorities13 = TlsExtensionsUtilities.GetCertificateAuthoritiesExtension(extensions); + var certificateAuthorities13 = TlsExtensionsUtilities.GetCertificateAuthoritiesExtension(extensions); return new CertificateRequest(certificateRequestContext, supportedSignatureAlgorithms13, supportedSignatureAlgorithmsCert13, certificateAuthorities13); @@ -249,24 +250,26 @@ public static CertificateRequest Parse(TlsContext context, Stream input) short[] certificateTypes = TlsUtilities.ReadUint8ArrayWithUint8Length(input, 1); - IList supportedSignatureAlgorithms = null; + IList supportedSignatureAlgorithms = null; if (isTLSv12) { supportedSignatureAlgorithms = TlsUtilities.ParseSupportedSignatureAlgorithms(input); } - IList certificateAuthorities = null; + IList certificateAuthorities = null; { byte[] certAuthData = TlsUtilities.ReadOpaque16(input); if (certAuthData.Length > 0) { - certificateAuthorities = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + certificateAuthorities = new List(); MemoryStream bis = new MemoryStream(certAuthData, false); do { byte[] derEncoding = TlsUtilities.ReadOpaque16(bis, 1); - Asn1Object asn1 = TlsUtilities.ReadDerObject(derEncoding); - certificateAuthorities.Add(X509Name.GetInstance(asn1)); + Asn1Object asn1 = TlsUtilities.ReadAsn1Object(derEncoding); + X509Name ca = X509Name.GetInstance(asn1); + TlsUtilities.RequireDerEncoding(ca, derEncoding); + certificateAuthorities.Add(ca); } while (bis.Position < bis.Length); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateStatus.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateStatus.cs index cdffc73..97b4a49 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateStatus.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateStatus.cs @@ -1,12 +1,11 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ocsp; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls { @@ -45,15 +44,15 @@ public OcspResponse OcspResponse } } - /// an of (possibly null) . - public IList OcspResponseList + /// an of (possibly null) . + public IList OcspResponseList { get { if (!IsCorrectType(CertificateStatusType.ocsp_multi, m_response)) throw new InvalidOperationException("'response' is not an OCSPResponseList"); - return (IList)m_response; + return (IList)m_response; } } @@ -75,10 +74,10 @@ public void Encode(Stream output) } case CertificateStatusType.ocsp_multi: { - IList ocspResponseList = (IList)m_response; + var ocspResponseList = (IList)m_response; int count = ocspResponseList.Count; - IList derEncodings = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(count); + var derEncodings = new List(count); long totalLength = 0; foreach (OcspResponse ocspResponse in ocspResponseList) { @@ -139,8 +138,7 @@ public static CertificateStatus Parse(TlsContext context, Stream input) RequireStatusRequestVersion(1, statusRequestVersion); byte[] derEncoding = TlsUtilities.ReadOpaque24(input, 1); - Asn1Object derObject = TlsUtilities.ReadDerObject(derEncoding); - response = OcspResponse.GetInstance(derObject); + response = ParseOcspResponse(derEncoding); break; } case CertificateStatusType.ocsp_multi: @@ -150,7 +148,7 @@ public static CertificateStatus Parse(TlsContext context, Stream input) byte[] ocsp_response_list = TlsUtilities.ReadOpaque24(input, 1); MemoryStream buf = new MemoryStream(ocsp_response_list, false); - IList ocspResponseList = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var ocspResponseList = new List(); while (buf.Position < buf.Length) { if (ocspResponseList.Count >= certificateCount) @@ -164,14 +162,11 @@ public static CertificateStatus Parse(TlsContext context, Stream input) else { byte[] derEncoding = TlsUtilities.ReadFully(length, buf); - Asn1Object derObject = TlsUtilities.ReadDerObject(derEncoding); - OcspResponse ocspResponse = OcspResponse.GetInstance(derObject); - ocspResponseList.Add(ocspResponse); + ocspResponseList.Add(ParseOcspResponse(derEncoding)); } } - // Match IList capacity to actual size - response = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(ocspResponseList); + response = ocspResponseList; break; } default: @@ -181,7 +176,7 @@ public static CertificateStatus Parse(TlsContext context, Stream input) return new CertificateStatus(status_type, response); } - private static bool IsCorrectType(short statusType, Object response) + private static bool IsCorrectType(short statusType, object response) { switch (statusType) { @@ -196,20 +191,16 @@ private static bool IsCorrectType(short statusType, Object response) private static bool IsOcspResponseList(object response) { - if (!(response is IList)) - return false; - - IList v = (IList)response; - int count = v.Count; - if (count < 1) - return false; + return response is IList v && v.Count > 0; + } - foreach (object e in v) - { - if (null != e && !(e is OcspResponse)) - return false; - } - return true; + /// + private static OcspResponse ParseOcspResponse(byte[] derEncoding) + { + Asn1Object asn1 = TlsUtilities.ReadAsn1Object(derEncoding); + OcspResponse ocspResponse = OcspResponse.GetInstance(asn1); + TlsUtilities.RequireDerEncoding(ocspResponse, derEncoding); + return ocspResponse; } /// diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateUrl.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateUrl.cs index f3f4a9c..72fed8c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateUrl.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateUrl.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -13,11 +13,11 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls public sealed class CertificateUrl { private readonly short m_type; - private readonly IList m_urlAndHashList; + private readonly IList m_urlAndHashList; /// see for valid constants. - /// an of . - public CertificateUrl(short type, IList urlAndHashList) + /// an of . + public CertificateUrl(short type, IList urlAndHashList) { if (!CertChainType.IsValid(type)) throw new ArgumentException("not a valid CertChainType value", "type"); @@ -37,8 +37,8 @@ public short Type get { return m_type; } } - /// an of . - public IList UrlAndHashList + /// an of . + public IList UrlAndHashList { get { return m_urlAndHashList; } } @@ -77,7 +77,7 @@ public static CertificateUrl Parse(TlsContext context, Stream input) MemoryStream buf = new MemoryStream(urlAndHashListData, false); - IList url_and_hash_list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var url_and_hash_list = new List(); while (buf.Position < buf.Length) { UrlAndHash url_and_hash = UrlAndHash.Parse(context, buf); @@ -103,15 +103,15 @@ internal ListBuffer16() internal void EncodeTo(Stream output) { // Patch actual length back in - int length = (int)Length - 2; + int length = Convert.ToInt32(Length) - 2; TlsUtilities.CheckUint16(length); Seek(0L, SeekOrigin.Begin); TlsUtilities.WriteUint16(length, this); - Streams.WriteBufTo(this, output); + WriteTo(output); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(this); + Dispose(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateVerify.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateVerify.cs new file mode 100644 index 0000000..fabc013 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateVerify.cs @@ -0,0 +1,61 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.IO; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls +{ + public sealed class CertificateVerify + { + private readonly int m_algorithm; + private readonly byte[] m_signature; + + public CertificateVerify(int algorithm, byte[] signature) + { + if (!TlsUtilities.IsValidUint16(algorithm)) + throw new ArgumentException("algorithm"); + if (signature == null) + throw new ArgumentNullException("signature"); + + this.m_algorithm = algorithm; + this.m_signature = signature; + } + + /// a value. + public int Algorithm + { + get { return m_algorithm; } + } + + public byte[] Signature + { + get { return m_signature; } + } + + /// Encode this to a . + /// the to encode to. + /// + public void Encode(Stream output) + { + TlsUtilities.WriteUint16(m_algorithm, output); + TlsUtilities.WriteOpaque16(m_signature, output); + } + + /// Parse a from a . + /// the of the current connection. + /// the to parse from. + /// a object. + /// + public static CertificateVerify Parse(TlsContext context, Stream input) + { + if (!TlsUtilities.IsTlsV13(context)) + throw new InvalidOperationException(); + + int algorithm = TlsUtilities.ReadUint16(input); + byte[] signature = TlsUtilities.ReadOpaque16(input); + return new CertificateVerify(algorithm, signature); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateVerify.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateVerify.cs.meta new file mode 100644 index 0000000..c873418 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CertificateVerify.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e72d5eef8356da2429d50ff32b574022 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ChannelBinding.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ChannelBinding.cs index 1d89078..aa1acab 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ChannelBinding.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ChannelBinding.cs @@ -17,6 +17,11 @@ public abstract class ChannelBinding public const int tls_server_end_point = 0; public const int tls_unique = 1; public const int tls_unique_for_telnet = 2; + + /* + * RFC 9266 + */ + public const int tls_exporter = 3; } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ClientHello.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ClientHello.cs index 7bf3225..af56934 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ClientHello.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ClientHello.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -16,11 +16,11 @@ public sealed class ClientHello private readonly byte[] m_sessionID; private readonly byte[] m_cookie; private readonly int[] m_cipherSuites; - private readonly IDictionary m_extensions; + private readonly IDictionary m_extensions; private readonly int m_bindersSize; public ClientHello(ProtocolVersion version, byte[] random, byte[] sessionID, byte[] cookie, - int[] cipherSuites, IDictionary extensions, int bindersSize) + int[] cipherSuites, IDictionary extensions, int bindersSize) { this.m_version = version; this.m_random = random; @@ -46,7 +46,7 @@ public byte[] Cookie get { return m_cookie; } } - public IDictionary Extensions + public IDictionary Extensions { get { return m_extensions; } } @@ -144,7 +144,7 @@ private static ClientHello ImplParse(MemoryStream messageInput, Stream dtlsOutpu int cipher_suites_length = TlsUtilities.ReadUint16(input); if (cipher_suites_length < 2 || (cipher_suites_length & 1) != 0 - || (int)(messageInput.Length - messageInput.Position) < cipher_suites_length) + || Convert.ToInt32(messageInput.Length - messageInput.Position) < cipher_suites_length) { throw new TlsFatalAlert(AlertDescription.decode_error); } @@ -163,7 +163,7 @@ private static ClientHello ImplParse(MemoryStream messageInput, Stream dtlsOutpu * NOTE: Can't use TlsProtocol.ReadExtensions directly because TeeInputStream a) won't have * 'Length' or 'Position' properties in the FIPS provider, b) isn't a MemoryStream. */ - IDictionary extensions = null; + IDictionary extensions = null; if (messageInput.Position < messageInput.Length) { byte[] extBytes = TlsUtilities.ReadOpaque16(input); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CombinedHash.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CombinedHash.cs index 41f394d..51d59a2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CombinedHash.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/CombinedHash.cs @@ -45,6 +45,14 @@ public virtual void Update(byte[] input, int inOff, int len) m_sha1.Update(input, inOff, len); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Update(ReadOnlySpan input) + { + m_md5.Update(input); + m_sha1.Update(input); + } +#endif + public virtual byte[] CalculateHash() { if (null != m_context && TlsUtilities.IsSsl(m_context)) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DatagramReceiver.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DatagramReceiver.cs index 87035fd..d0cb25a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DatagramReceiver.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DatagramReceiver.cs @@ -12,6 +12,11 @@ public interface DatagramReceiver /// int Receive(byte[] buf, int off, int len, int waitMillis); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// + int Receive(Span buffer, int waitMillis); +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DatagramSender.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DatagramSender.cs index ca127fd..7580cc2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DatagramSender.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DatagramSender.cs @@ -12,6 +12,11 @@ public interface DatagramSender /// void Send(byte[] buf, int off, int len); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// + void Send(ReadOnlySpan buffer); +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DefaultTlsClient.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DefaultTlsClient.cs index 839c06a..5586533 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DefaultTlsClient.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DefaultTlsClient.cs @@ -12,10 +12,10 @@ public abstract class DefaultTlsClient private static readonly int[] DefaultCipherSuites = new int[] { /* - * TODO[tls13] TLS 1.3 + * TLS 1.3 */ - //CipherSuite.TLS_CHACHA20_POLY1305_SHA256, - //CipherSuite.TLS_AES_128_GCM_SHA256, + CipherSuite.TLS_CHACHA20_POLY1305_SHA256, + CipherSuite.TLS_AES_128_GCM_SHA256, /* * pre-TLS 1.3 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DefaultTlsDHGroupVerifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DefaultTlsDHGroupVerifier.cs index 78948a3..1fa1ea5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DefaultTlsDHGroupVerifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DefaultTlsDHGroupVerifier.cs @@ -1,11 +1,10 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls { @@ -14,7 +13,7 @@ public class DefaultTlsDHGroupVerifier { public static readonly int DefaultMinimumPrimeBits = 2048; - private static readonly IList DefaultGroups = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + private static readonly List DefaultGroups = new List(); private static void AddDefaultGroup(DHGroup dhGroup) { @@ -43,7 +42,7 @@ static DefaultTlsDHGroupVerifier() } // IList is (DHGroup) - protected readonly IList m_groups; + protected readonly IList m_groups; protected readonly int m_minimumPrimeBits; /// Accept named groups and various standard DH groups with 'P' at least @@ -63,11 +62,11 @@ public DefaultTlsDHGroupVerifier(int minimumPrimeBits) /// Accept named groups and a custom set of group parameters, subject to a minimum bitlength for 'P'. /// - /// a list of acceptable s. + /// a list of acceptable s. /// the minimum bitlength of 'P'. - public DefaultTlsDHGroupVerifier(IList groups, int minimumPrimeBits) + public DefaultTlsDHGroupVerifier(IList groups, int minimumPrimeBits) { - this.m_groups = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(groups); + this.m_groups = new List(groups); this.m_minimumPrimeBits = minimumPrimeBits; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DefaultTlsServer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DefaultTlsServer.cs index f895482..8189a59 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DefaultTlsServer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DefaultTlsServer.cs @@ -13,11 +13,11 @@ public abstract class DefaultTlsServer private static readonly int[] DefaultCipherSuites = new int[] { /* - * TODO[tls13] TLS 1.3 + * TLS 1.3 */ - //CipherSuite.TLS_CHACHA20_POLY1305_SHA256, - //CipherSuite.TLS_AES_256_GCM_SHA384, - //CipherSuite.TLS_AES_128_GCM_SHA256, + CipherSuite.TLS_CHACHA20_POLY1305_SHA256, + CipherSuite.TLS_AES_256_GCM_SHA384, + CipherSuite.TLS_AES_128_GCM_SHA256, /* * pre-TLS 1.3 @@ -87,10 +87,6 @@ public override TlsCredentials GetCredentials() case KeyExchangeAlgorithm.DHE_DSS: return GetDsaSignerCredentials(); - case KeyExchangeAlgorithm.DH_anon: - case KeyExchangeAlgorithm.ECDH_anon: - return null; - case KeyExchangeAlgorithm.ECDHE_ECDSA: return GetECDsaSignerCredentials(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DefaultTlsSrpConfigVerifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DefaultTlsSrpConfigVerifier.cs index c51fa09..060b665 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DefaultTlsSrpConfigVerifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DefaultTlsSrpConfigVerifier.cs @@ -1,18 +1,17 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls { public class DefaultTlsSrpConfigVerifier : TlsSrpConfigVerifier { - private static readonly IList DefaultGroups = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + private static readonly List DefaultGroups = new List(); static DefaultTlsSrpConfigVerifier() { @@ -26,7 +25,7 @@ static DefaultTlsSrpConfigVerifier() } // IList is (SRP6Group) - protected readonly IList m_groups; + protected readonly IList m_groups; /// Accept only the group parameters specified in RFC 5054 Appendix A. public DefaultTlsSrpConfigVerifier() @@ -35,10 +34,10 @@ public DefaultTlsSrpConfigVerifier() } /// Specify a custom set of acceptable group parameters. - /// an of acceptable . - public DefaultTlsSrpConfigVerifier(IList groups) + /// an of acceptable . + public DefaultTlsSrpConfigVerifier(IList groups) { - this.m_groups = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(groups); + this.m_groups = new List(groups); } public virtual bool Accept(TlsSrpConfig srpConfig) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DeferredHash.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DeferredHash.cs index 9ba2d13..f51c0fa 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DeferredHash.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DeferredHash.cs @@ -1,11 +1,10 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls { @@ -18,7 +17,7 @@ internal sealed class DeferredHash private readonly TlsContext m_context; private DigestInputBuffer m_buf; - private readonly IDictionary m_hashes; + private IDictionary m_hashes; private bool m_forceBuffering; private bool m_sealed; @@ -26,30 +25,21 @@ internal DeferredHash(TlsContext context) { this.m_context = context; this.m_buf = new DigestInputBuffer(); - this.m_hashes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + this.m_hashes = new Dictionary(); this.m_forceBuffering = false; this.m_sealed = false; } - private DeferredHash(TlsContext context, IDictionary hashes) - { - this.m_context = context; - this.m_buf = null; - this.m_hashes = hashes; - this.m_forceBuffering = false; - this.m_sealed = true; - } - /// public void CopyBufferTo(Stream output) { if (m_buf == null) { - // If you see this, you need to call forceBuffering() before SealHashAlgorithms() + // If you see this, you need to call ForceBuffering() before SealHashAlgorithms() throw new InvalidOperationException("Not buffering"); } - m_buf.CopyTo(output); + m_buf.CopyInputTo(output); } public void ForceBuffering() @@ -98,18 +88,18 @@ public void SealHashAlgorithms() CheckStopBuffering(); } - public TlsHandshakeHash StopTracking() + public void StopTracking() { SecurityParameters securityParameters = m_context.SecurityParameters; - IDictionary newHashes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + IDictionary newHashes = new Dictionary(); switch (securityParameters.PrfAlgorithm) { case PrfAlgorithm.ssl_prf_legacy: case PrfAlgorithm.tls_prf_legacy: { - CloneHash(newHashes, HashAlgorithm.md5); - CloneHash(newHashes, HashAlgorithm.sha1); + CloneHash(newHashes, CryptoHashAlgorithm.md5); + CloneHash(newHashes, CryptoHashAlgorithm.sha1); break; } default: @@ -118,7 +108,11 @@ public TlsHandshakeHash StopTracking() break; } } - return new DeferredHash(m_context, newHashes); + + this.m_buf = null; + this.m_hashes = newHashes; + this.m_forceBuffering = false; + this.m_sealed = true; } public TlsHash ForkPrfHash() @@ -133,7 +127,9 @@ public TlsHash ForkPrfHash() case PrfAlgorithm.ssl_prf_legacy: case PrfAlgorithm.tls_prf_legacy: { - prfHash = new CombinedHash(m_context, CloneHash(HashAlgorithm.md5), CloneHash(HashAlgorithm.sha1)); + TlsHash md5Hash = CloneHash(CryptoHashAlgorithm.md5); + TlsHash sha1Hash = CloneHash(CryptoHashAlgorithm.sha1); + prfHash = new CombinedHash(m_context, md5Hash, sha1Hash); break; } default: @@ -153,20 +149,19 @@ public TlsHash ForkPrfHash() public byte[] GetFinalHash(int cryptoHashAlgorithm) { - TlsHash d = (TlsHash)m_hashes[cryptoHashAlgorithm]; - if (d == null) + if (!m_hashes.TryGetValue(cryptoHashAlgorithm, out var hash)) throw new InvalidOperationException("CryptoHashAlgorithm." + cryptoHashAlgorithm + " is not being tracked"); CheckStopBuffering(); - d = d.CloneHash(); + hash = hash.CloneHash(); if (m_buf != null) { - m_buf.UpdateDigest(d); + m_buf.UpdateDigest(hash); } - return d.CalculateHash(); + return hash.CalculateHash(); } public void Update(byte[] input, int inOff, int len) @@ -183,6 +178,22 @@ public void Update(byte[] input, int inOff, int len) } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Update(ReadOnlySpan input) + { + if (m_buf != null) + { + m_buf.Write(input); + return; + } + + foreach (TlsHash hash in m_hashes.Values) + { + hash.Update(input); + } + } +#endif + public byte[] CalculateHash() { throw new InvalidOperationException("Use 'ForkPrfHash' to get a definite hash"); @@ -222,7 +233,7 @@ private void CheckStopBuffering() private void CheckTrackingHash(int cryptoHashAlgorithm) { - if (!m_hashes.Contains(cryptoHashAlgorithm)) + if (!m_hashes.ContainsKey(cryptoHashAlgorithm)) { TlsHash hash = m_context.Crypto.CreateHash(cryptoHashAlgorithm); m_hashes[cryptoHashAlgorithm] = hash; @@ -231,10 +242,10 @@ private void CheckTrackingHash(int cryptoHashAlgorithm) private TlsHash CloneHash(int cryptoHashAlgorithm) { - return ((TlsHash)m_hashes[cryptoHashAlgorithm]).CloneHash(); + return m_hashes[cryptoHashAlgorithm].CloneHash(); } - private void CloneHash(IDictionary newHashes, int cryptoHashAlgorithm) + private void CloneHash(IDictionary newHashes, int cryptoHashAlgorithm) { TlsHash hash = CloneHash(cryptoHashAlgorithm); if (m_buf != null) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DigestInputBuffer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DigestInputBuffer.cs index 1d116d2..9de3e79 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DigestInputBuffer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DigestInputBuffer.cs @@ -4,7 +4,6 @@ using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls { @@ -13,16 +12,14 @@ internal class DigestInputBuffer { internal void UpdateDigest(TlsHash hash) { - Streams.WriteBufTo(this, new TlsHashSink(hash)); + WriteTo(new TlsHashSink(hash)); } /// - internal void CopyTo(Stream output) + internal void CopyInputTo(Stream output) { - // TODO[tls-port] - // NOTE: Copy data since the output here may be under control of external code. - //Streams.PipeAll(new MemoryStream(buf, 0, count), output); - Streams.WriteBufTo(this, output); + // TODO[tls] Consider defensive copy if 'output' might be external code + WriteTo(output); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DigitallySigned.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DigitallySigned.cs index 082f6cb..bfe8d9d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DigitallySigned.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DigitallySigned.cs @@ -7,27 +7,27 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls { public sealed class DigitallySigned { - private readonly SignatureAndHashAlgorithm algorithm; - private readonly byte[] signature; + private readonly SignatureAndHashAlgorithm m_algorithm; + private readonly byte[] m_signature; public DigitallySigned(SignatureAndHashAlgorithm algorithm, byte[] signature) { if (signature == null) throw new ArgumentNullException("signature"); - this.algorithm = algorithm; - this.signature = signature; + this.m_algorithm = algorithm; + this.m_signature = signature; } /// a (or null before TLS 1.2). public SignatureAndHashAlgorithm Algorithm { - get { return algorithm; } + get { return m_algorithm; } } public byte[] Signature { - get { return signature; } + get { return m_signature; } } /// Encode this to a . @@ -35,11 +35,11 @@ public byte[] Signature /// public void Encode(Stream output) { - if (algorithm != null) + if (m_algorithm != null) { - algorithm.Encode(output); + m_algorithm.Encode(output); } - TlsUtilities.WriteOpaque16(signature, output); + TlsUtilities.WriteOpaque16(m_signature, output); } /// Parse a from a . diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsClientProtocol.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsClientProtocol.cs index 08dc56f..751886d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsClientProtocol.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsClientProtocol.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; @@ -175,7 +175,7 @@ internal virtual DtlsTransport ClientHandshake(ClientHandshakeState state, DtlsR recordLayer.InitHeartbeat(state.heartbeat, HeartbeatMode.peer_allowed_to_send == state.heartbeatPolicy); - return new DtlsTransport(recordLayer); + return new DtlsTransport(recordLayer, state.client.IgnoreCorruptDtlsRecords); } InvalidateSession(state); @@ -239,12 +239,6 @@ internal virtual DtlsTransport ClientHandshake(ClientHandshakeState state, DtlsR TlsUtilities.EstablishServerSigAlgs(securityParameters, state.certificateRequest); - /* - * TODO Give the client a chance to immediately select the CertificateVerify hash - * algorithm here to avoid tracking the other hash algorithms unnecessarily? - */ - TlsUtilities.TrackHashAlgorithms(handshake.HandshakeHash, securityParameters.ServerSigAlgs); - serverMessage = handshake.ReceiveMessage(); } else @@ -264,54 +258,68 @@ internal virtual DtlsTransport ClientHandshake(ClientHandshakeState state, DtlsR throw new TlsFatalAlert(AlertDescription.unexpected_message); } - IList clientSupplementalData = state.client.GetClientSupplementalData(); - if (clientSupplementalData != null) - { - byte[] supplementalDataBody = GenerateSupplementalData(clientSupplementalData); - handshake.SendMessage(HandshakeType.supplemental_data, supplementalDataBody); - } + TlsCredentials clientAuthCredentials = null; + TlsCredentialedSigner clientAuthSigner = null; + Certificate clientAuthCertificate = null; + SignatureAndHashAlgorithm clientAuthAlgorithm = null; + TlsStreamSigner clientAuthStreamSigner = null; - if (null != state.certificateRequest) + if (state.certificateRequest != null) { - state.clientCredentials = TlsUtilities.EstablishClientCredentials(state.authentication, + clientAuthCredentials = TlsUtilities.EstablishClientCredentials(state.authentication, state.certificateRequest); + if (clientAuthCredentials != null) + { + clientAuthCertificate = clientAuthCredentials.Certificate; - /* - * RFC 5246 If no suitable certificate is available, the client MUST send a certificate - * message containing no certificates. - * - * NOTE: In previous RFCs, this was SHOULD instead of MUST. - */ + if (clientAuthCredentials is TlsCredentialedSigner) + { + clientAuthSigner = (TlsCredentialedSigner)clientAuthCredentials; + clientAuthAlgorithm = TlsUtilities.GetSignatureAndHashAlgorithm( + securityParameters.NegotiatedVersion, clientAuthSigner); + clientAuthStreamSigner = clientAuthSigner.GetStreamSigner(); - Certificate clientCertificate = null; - if (null != state.clientCredentials) + if (ProtocolVersion.DTLSv12.Equals(securityParameters.NegotiatedVersion)) { - clientCertificate = state.clientCredentials.Certificate; - } + TlsUtilities.VerifySupportedSignatureAlgorithm(securityParameters.ServerSigAlgs, + clientAuthAlgorithm, AlertDescription.internal_error); - SendCertificateMessage(state.clientContext, handshake, clientCertificate, null); + if (clientAuthStreamSigner == null) + { + TlsUtilities.TrackHashAlgorithmClient(handshake.HandshakeHash, clientAuthAlgorithm); + } } - TlsCredentialedSigner credentialedSigner = null; - TlsStreamSigner streamSigner = null; - - if (null != state.clientCredentials) + if (clientAuthStreamSigner != null) { - state.keyExchange.ProcessClientCredentials(state.clientCredentials); + handshake.HandshakeHash.ForceBuffering(); + } + } + } + } - if (state.clientCredentials is TlsCredentialedSigner) + handshake.HandshakeHash.SealHashAlgorithms(); + + if (clientAuthCredentials == null) { - credentialedSigner = (TlsCredentialedSigner)state.clientCredentials; - streamSigner = credentialedSigner.GetStreamSigner(); - } + state.keyExchange.SkipClientCredentials(); } else { - state.keyExchange.SkipClientCredentials(); + state.keyExchange.ProcessClientCredentials(clientAuthCredentials); } - bool forceBuffering = streamSigner != null; - TlsUtilities.SealHandshakeHash(state.clientContext, handshake.HandshakeHash, forceBuffering); + var clientSupplementalData = state.client.GetClientSupplementalData(); + if (clientSupplementalData != null) + { + byte[] supplementalDataBody = GenerateSupplementalData(clientSupplementalData); + handshake.SendMessage(HandshakeType.supplemental_data, supplementalDataBody); + } + + if (null != state.certificateRequest) + { + SendCertificateMessage(state.clientContext, handshake, clientAuthCertificate, null); + } byte[] clientKeyExchangeBody = GenerateClientKeyExchange(state); handshake.SendMessage(HandshakeType.client_key_exchange, clientKeyExchangeBody); @@ -321,17 +329,15 @@ internal virtual DtlsTransport ClientHandshake(ClientHandshakeState state, DtlsR TlsProtocol.EstablishMasterSecret(state.clientContext, state.keyExchange); recordLayer.InitPendingEpoch(TlsUtilities.InitCipher(state.clientContext)); + if (clientAuthSigner != null) { - if (credentialedSigner != null) - { - DigitallySigned certificateVerify = TlsUtilities.GenerateCertificateVerifyClient( - state.clientContext, credentialedSigner, streamSigner, handshake.HandshakeHash); + DigitallySigned certificateVerify = TlsUtilities.GenerateCertificateVerifyClient(state.clientContext, + clientAuthSigner, clientAuthAlgorithm, clientAuthStreamSigner, handshake.HandshakeHash); byte[] certificateVerifyBody = GenerateCertificateVerify(state, certificateVerify); handshake.SendMessage(HandshakeType.certificate_verify, certificateVerifyBody); } handshake.PrepareToFinish(); - } securityParameters.m_localVerifyData = TlsUtilities.CalculateVerifyData(state.clientContext, handshake.HandshakeHash, false); @@ -388,7 +394,7 @@ internal virtual DtlsTransport ClientHandshake(ClientHandshakeState state, DtlsR recordLayer.InitHeartbeat(state.heartbeat, HeartbeatMode.peer_allowed_to_send == state.heartbeatPolicy); - return new DtlsTransport(recordLayer); + return new DtlsTransport(recordLayer, state.client.IgnoreCorruptDtlsRecords); } /// @@ -414,6 +420,13 @@ protected virtual byte[] GenerateClientHello(ClientHandshakeState state) context.SetClientVersion(client_version); + { + bool useGmtUnixTime = ProtocolVersion.DTLSv12.IsEqualOrLaterVersionOf(client_version) + && state.client.ShouldUseGmtUnixTime(); + + securityParameters.m_clientRandom = TlsProtocol.CreateRandomBlock(useGmtUnixTime, state.clientContext); + } + byte[] session_id = TlsUtilities.GetSessionID(state.tlsSession); bool fallback = state.client.IsFallback(); @@ -467,13 +480,6 @@ protected virtual byte[] GenerateClientHello(ClientHandshakeState state) throw new TlsFatalAlert(AlertDescription.internal_error); } - { - bool useGmtUnixTime = ProtocolVersion.DTLSv12.IsEqualOrLaterVersionOf(client_version) - && state.client.ShouldUseGmtUnixTime(); - - securityParameters.m_clientRandom = TlsProtocol.CreateRandomBlock(useGmtUnixTime, state.clientContext); - } - // Cipher Suites (and SCSV) { /* @@ -575,6 +581,10 @@ protected virtual void ProcessCertificateRequest(ClientHandshakeState state, byt TlsProtocol.AssertEmpty(buf); state.certificateRequest = TlsUtilities.ValidateCertificateRequest(certificateRequest, state.keyExchange); + + state.clientContext.SecurityParameters.m_clientCertificateType = + TlsExtensionsUtilities.GetClientCertificateTypeExtensionServer(state.serverExtensions, + CertificateType.X509); } /// @@ -629,7 +639,7 @@ protected virtual void ProcessNewSessionTicket(ClientHandshakeState state, byte[ protected virtual void ProcessServerCertificate(ClientHandshakeState state, byte[] body) { state.authentication = TlsUtilities.ReceiveServerCertificate(state.clientContext, state.client, - new MemoryStream(body, false)); + new MemoryStream(body, false), state.serverExtensions); } /// @@ -834,8 +844,8 @@ protected virtual void ProcessServerHello(ClientHandshakeState state, byte[] bod - IDictionary sessionClientExtensions = state.clientExtensions, - sessionServerExtensions = state.serverExtensions; + var sessionClientExtensions = state.clientExtensions; + var sessionServerExtensions = state.serverExtensions; if (state.resumedSession) { @@ -910,7 +920,7 @@ protected virtual void ProcessServerKeyExchange(ClientHandshakeState state, byte protected virtual void ProcessServerSupplementalData(ClientHandshakeState state, byte[] body) { MemoryStream buf = new MemoryStream(body, false); - IList serverSupplementalData = TlsProtocol.ReadSupplementalDataMessage(buf); + var serverSupplementalData = TlsProtocol.ReadSupplementalDataMessage(buf); state.client.ProcessServerSupplementalData(serverSupplementalData); } @@ -966,16 +976,15 @@ protected internal class ClientHandshakeState internal TlsSecret sessionMasterSecret = null; internal SessionParameters.Builder sessionParametersBuilder = null; internal int[] offeredCipherSuites = null; - internal IDictionary clientExtensions = null; - internal IDictionary serverExtensions = null; + internal IDictionary clientExtensions = null; + internal IDictionary serverExtensions = null; internal bool resumedSession = false; internal bool expectSessionTicket = false; - internal IDictionary clientAgreements = null; + internal IDictionary clientAgreements = null; internal TlsKeyExchange keyExchange = null; internal TlsAuthentication authentication = null; internal CertificateStatus certificateStatus = null; internal CertificateRequest certificateRequest = null; - internal TlsCredentials clientCredentials = null; internal TlsHeartbeat heartbeat = null; internal short heartbeatPolicy = HeartbeatMode.peer_not_allowed_to_send; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsProtocol.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsProtocol.cs index 9a5a2e6..6b69a61 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsProtocol.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsProtocol.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -41,8 +41,9 @@ internal static void ApplyMaxFragmentLengthExtension(DtlsRecordLayer recordLayer } /// - internal static short EvaluateMaxFragmentLengthExtension(bool resumedSession, IDictionary clientExtensions, - IDictionary serverExtensions, short alertDescription) + internal static short EvaluateMaxFragmentLengthExtension(bool resumedSession, + IDictionary clientExtensions, IDictionary serverExtensions, + short alertDescription) { short maxFragmentLength = TlsExtensionsUtilities.GetMaxFragmentLengthExtension(serverExtensions); if (maxFragmentLength >= 0) @@ -66,7 +67,7 @@ internal static byte[] GenerateCertificate(TlsContext context, Certificate certi } /// - internal static byte[] GenerateSupplementalData(IList supplementalData) + internal static byte[] GenerateSupplementalData(IList supplementalData) { MemoryStream buf = new MemoryStream(); TlsProtocol.WriteSupplementalData(buf, supplementalData); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsReassembler.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsReassembler.cs index e45b308..065a687 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsReassembler.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsReassembler.cs @@ -1,9 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; - -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; +using System.Collections.Generic; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls { @@ -12,7 +10,7 @@ internal sealed class DtlsReassembler private readonly short m_msg_type; private readonly byte[] m_body; - private readonly IList m_missing = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + private readonly List m_missing = new List(); internal DtlsReassembler(short msg_type, int length) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsRecordLayer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsRecordLayer.cs index e9785ef..3a8d5c8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsRecordLayer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsRecordLayer.cs @@ -2,9 +2,7 @@ #pragma warning disable using System; using System.IO; -#if !PORTABLE || NETFX_CORE || DOTNET using System.Net.Sockets; -#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -246,6 +244,9 @@ public virtual int GetSendLimit() /// public virtual int Receive(byte[] buf, int off, int len, int waitMillis) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return Receive(buf.AsSpan(off, len), waitMillis); +#else long currentTimeMillis = DateTimeUtilities.CurrentUnixMs(); Timeout timeout = Timeout.ForWaitMillis(waitMillis, currentTimeMillis); @@ -309,11 +310,85 @@ public virtual int Receive(byte[] buf, int off, int len, int waitMillis) } return -1; +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// + public virtual int Receive(Span buffer, int waitMillis) + { + long currentTimeMillis = DateTimeUtilities.CurrentUnixMs(); + + Timeout timeout = Timeout.ForWaitMillis(waitMillis, currentTimeMillis); + byte[] record = null; + + while (waitMillis >= 0) + { + if (null != m_retransmitTimeout && m_retransmitTimeout.RemainingMillis(currentTimeMillis) < 1) + { + m_retransmit = null; + m_retransmitEpoch = null; + m_retransmitTimeout = null; + } + + if (Timeout.HasExpired(m_heartbeatTimeout, currentTimeMillis)) + { + if (null != m_heartbeatInFlight) + throw new TlsTimeoutException("Heartbeat timed out"); + + this.m_heartbeatInFlight = HeartbeatMessage.Create(m_context, + HeartbeatMessageType.heartbeat_request, m_heartbeat.GeneratePayload()); + this.m_heartbeatTimeout = new Timeout(m_heartbeat.TimeoutMillis, currentTimeMillis); + + this.m_heartbeatResendMillis = DtlsReliableHandshake.INITIAL_RESEND_MILLIS; + this.m_heartbeatResendTimeout = new Timeout(m_heartbeatResendMillis, currentTimeMillis); + + SendHeartbeatMessage(m_heartbeatInFlight); + } + else if (Timeout.HasExpired(m_heartbeatResendTimeout, currentTimeMillis)) + { + this.m_heartbeatResendMillis = DtlsReliableHandshake.BackOff(m_heartbeatResendMillis); + this.m_heartbeatResendTimeout = new Timeout(m_heartbeatResendMillis, currentTimeMillis); + + SendHeartbeatMessage(m_heartbeatInFlight); + } + + waitMillis = Timeout.ConstrainWaitMillis(waitMillis, m_heartbeatTimeout, currentTimeMillis); + waitMillis = Timeout.ConstrainWaitMillis(waitMillis, m_heartbeatResendTimeout, currentTimeMillis); + + // NOTE: Guard against bad logic giving a negative value + if (waitMillis < 0) + { + waitMillis = 1; + } + + int receiveLimit = System.Math.Min(buffer.Length, GetReceiveLimit()) + RECORD_HEADER_LENGTH; + if (null == record || record.Length < receiveLimit) + { + record = new byte[receiveLimit]; + } + + int received = ReceiveRecord(record, 0, receiveLimit, waitMillis); + int processed = ProcessRecord(received, record, buffer); + if (processed >= 0) + { + return processed; + } + + currentTimeMillis = DateTimeUtilities.CurrentUnixMs(); + waitMillis = Timeout.GetWaitMillis(timeout, currentTimeMillis); + } + + return -1; + } +#endif + /// public virtual void Send(byte[] buf, int off, int len) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Send(buf.AsSpan(off, len)); +#else short contentType = ContentType.application_data; if (m_inHandshake || m_writeEpoch == m_retransmitEpoch) @@ -342,7 +417,7 @@ public virtual void Send(byte[] buf, int off, int len) // Implicitly send change_cipher_spec and change to pending cipher state // TODO Send change_cipher_spec and finished records in single datagram? - byte[] data = new byte[]{ 1 }; + byte[] data = new byte[1]{ 1 }; SendRecord(ContentType.change_cipher_spec, data, 0, data.Length); this.m_writeEpoch = nextEpoch; @@ -350,7 +425,51 @@ public virtual void Send(byte[] buf, int off, int len) } SendRecord(contentType, buf, off, len); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// + public virtual void Send(ReadOnlySpan buffer) + { + short contentType = ContentType.application_data; + + if (m_inHandshake || m_writeEpoch == m_retransmitEpoch) + { + contentType = ContentType.handshake; + + short handshakeType = TlsUtilities.ReadUint8(buffer); + if (handshakeType == HandshakeType.finished) + { + DtlsEpoch nextEpoch = null; + if (m_inHandshake) + { + nextEpoch = m_pendingEpoch; + } + else if (m_writeEpoch == m_retransmitEpoch) + { + nextEpoch = m_currentEpoch; + } + + if (nextEpoch == null) + { + // TODO + throw new InvalidOperationException(); + } + + // Implicitly send change_cipher_spec and change to pending cipher state + + // TODO Send change_cipher_spec and finished records in single datagram? + ReadOnlySpan data = stackalloc byte[1]{ 1 }; + SendRecord(ContentType.change_cipher_spec, data); + + this.m_writeEpoch = nextEpoch; + } + } + + SendRecord(contentType, buffer); } +#endif /// public virtual void Close() @@ -398,7 +517,7 @@ internal virtual void Failed() } /// - internal virtual void Warn(short alertDescription, String message) + internal virtual void Warn(short alertDescription, string message) { RaiseAlert(AlertLevel.warning, alertDescription, message, null); } @@ -436,11 +555,13 @@ private void RaiseAlert(short alertLevel, short alertDescription, string message { m_peer.NotifyAlertRaised(alertLevel, alertDescription, message, cause); - byte[] error = new byte[2]; - error[0] = (byte)alertLevel; - error[1] = (byte)alertDescription; - +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + ReadOnlySpan error = stackalloc byte[2]{ (byte)alertLevel, (byte)alertDescription }; + SendRecord(ContentType.alert, error); +#else + byte[] error = new byte[2]{ (byte)alertLevel, (byte)alertDescription }; SendRecord(ContentType.alert, error, 0, 2); +#endif } /// @@ -454,7 +575,6 @@ private int ReceiveDatagram(byte[] buf, int off, int len, int waitMillis) { return -1; } -#if !PORTABLE || NETFX_CORE || DOTNET catch (SocketException e) { if (TlsUtilities.IsTimeout(e)) @@ -462,7 +582,6 @@ private int ReceiveDatagram(byte[] buf, int off, int len, int waitMillis) throw e; } -#endif // TODO[tls-port] Can we support interrupted IO on .NET? //catch (InterruptedIOException e) //{ @@ -473,7 +592,11 @@ private int ReceiveDatagram(byte[] buf, int off, int len, int waitMillis) // TODO Include 'currentTimeMillis' as an argument, use with Timeout, resetHeartbeat /// +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int ProcessRecord(int received, byte[] record, Span buffer) +#else private int ProcessRecord(int received, byte[] record, byte[] buf, int off) +#endif { // NOTE: received < 0 (timeout) is covered by this first case if (received < RECORD_HEADER_LENGTH) @@ -706,7 +829,11 @@ private int ProcessRecord(int received, byte[] record, byte[] buf, int off) this.m_retransmitTimeout = null; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + decoded.buf.AsSpan(decoded.off, decoded.len).CopyTo(buffer); +#else Array.Copy(decoded.buf, decoded.off, buf, off, decoded.len); +#endif return decoded.len; } @@ -718,9 +845,7 @@ private int ReceiveRecord(byte[] buf, int off, int len, int waitMillis) int length = 0; if (m_recordQueue.Available >= RECORD_HEADER_LENGTH) { - byte[] lengthBytes = new byte[2]; - m_recordQueue.Read(lengthBytes, 0, 2, 11); - length = TlsUtilities.ReadUint16(lengthBytes, 0); + length = m_recordQueue.ReadUint16(11); } int received = System.Math.Min(m_recordQueue.Available, RECORD_HEADER_LENGTH + length); @@ -760,9 +885,16 @@ private void SendHeartbeatMessage(HeartbeatMessage heartbeatMessage) { MemoryStream output = new MemoryStream(); heartbeatMessage.Encode(output); - byte[] buf = output.ToArray(); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + if (!output.TryGetBuffer(out var buffer)) + throw new InvalidOperationException(); + + SendRecord(ContentType.heartbeat, buffer); +#else + byte[] buf = output.ToArray(); SendRecord(ContentType.heartbeat, buf, 0, buf.Length); +#endif } /* @@ -772,12 +904,20 @@ private void SendHeartbeatMessage(HeartbeatMessage heartbeatMessage) * be possible reordering of records (which might surprise a reliable transport implementation). */ /// +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private void SendRecord(short contentType, ReadOnlySpan buffer) +#else private void SendRecord(short contentType, byte[] buf, int off, int len) +#endif { // Never send anything until a valid ClientHello has been received if (m_writeVersion == null) return; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int len = buffer.Length; +#endif + if (len > m_plaintextLimit) throw new TlsFatalAlert(AlertDescription.internal_error); @@ -795,8 +935,13 @@ private void SendRecord(short contentType, byte[] buf, int off, int len) long macSequenceNumber = GetMacSequenceNumber(recordEpoch, recordSequenceNumber); ProtocolVersion recordVersion = m_writeVersion; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + TlsEncodeResult encoded = m_writeEpoch.Cipher.EncodePlaintext(macSequenceNumber, contentType, + recordVersion, RECORD_HEADER_LENGTH, buffer); +#else TlsEncodeResult encoded = m_writeEpoch.Cipher.EncodePlaintext(macSequenceNumber, contentType, recordVersion, RECORD_HEADER_LENGTH, buf, off, len); +#endif int ciphertextLength = encoded.len - RECORD_HEADER_LENGTH; TlsUtilities.CheckUint16(ciphertextLength); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsReliableHandshake.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsReliableHandshake.cs index e76c39d..dacfd40 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsReliableHandshake.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsReliableHandshake.cs @@ -1,10 +1,9 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls @@ -84,9 +83,9 @@ internal static void SendHelloVerifyRequest(DatagramSender sender, long recordSe private TlsHandshakeHash m_handshakeHash; - private IDictionary m_currentInboundFlight = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private IDictionary m_previousInboundFlight = null; - private IList m_outboundFlight = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + private IDictionary m_currentInboundFlight = new Dictionary(); + private IDictionary m_previousInboundFlight = null; + private IList m_outboundFlight = new List(); private int m_resendMillis = -1; private Timeout m_resendTimeout = null; @@ -126,9 +125,9 @@ internal DtlsReliableHandshake(TlsContext context, DtlsRecordLayer transport, in internal void ResetAfterHelloVerifyRequestClient() { - this.m_currentInboundFlight = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + this.m_currentInboundFlight = new Dictionary(); this.m_previousInboundFlight = null; - this.m_outboundFlight = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + this.m_outboundFlight = new List(); this.m_resendMillis = -1; this.m_resendTimeout = null; @@ -144,11 +143,9 @@ internal TlsHandshakeHash HandshakeHash get { return m_handshakeHash; } } - internal TlsHandshakeHash PrepareToFinish() + internal void PrepareToFinish() { - TlsHandshakeHash result = m_handshakeHash; - this.m_handshakeHash = m_handshakeHash.StopTracking(); - return result; + m_handshakeHash.StopTracking(); } /// @@ -174,69 +171,61 @@ internal void SendMessage(short msg_type, byte[] body) UpdateHandshakeMessagesDigest(message); } + /// + internal Message ReceiveMessage() + { + Message message = ImplReceiveMessage(); + UpdateHandshakeMessagesDigest(message); + return message; + } + /// internal byte[] ReceiveMessageBody(short msg_type) { - Message message = ReceiveMessage(); + Message message = ImplReceiveMessage(); if (message.Type != msg_type) throw new TlsFatalAlert(AlertDescription.unexpected_message); + UpdateHandshakeMessagesDigest(message); return message.Body; } /// - internal Message ReceiveMessage() + internal Message ReceiveMessageDelayedDigest(short msg_type) { - long currentTimeMillis = DateTimeUtilities.CurrentUnixMs(); - - if (null == m_resendTimeout) - { - m_resendMillis = INITIAL_RESEND_MILLIS; - m_resendTimeout = new Timeout(m_resendMillis, currentTimeMillis); - - PrepareInboundFlight(BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable()); - } + Message message = ImplReceiveMessage(); + if (message.Type != msg_type) + throw new TlsFatalAlert(AlertDescription.unexpected_message); - byte[] buf = null; + return message; + } - for (;;) + /// + internal void UpdateHandshakeMessagesDigest(Message message) + { + short msg_type = message.Type; + switch (msg_type) { - if (m_recordLayer.IsClosed) - throw new TlsFatalAlert(AlertDescription.user_canceled); - - Message pending = GetPendingMessage(); - if (pending != null) - return pending; - - if (Timeout.HasExpired(m_handshakeTimeout, currentTimeMillis)) - throw new TlsTimeoutException("Handshake timed out"); - - int waitMillis = Timeout.GetWaitMillis(m_handshakeTimeout, currentTimeMillis); - waitMillis = Timeout.ConstrainWaitMillis(waitMillis, m_resendTimeout, currentTimeMillis); - - // NOTE: Ensure a finite wait, of at least 1ms - if (waitMillis < 1) - { - waitMillis = 1; - } - - int receiveLimit = m_recordLayer.GetReceiveLimit(); - if (buf == null || buf.Length < receiveLimit) - { - buf = new byte[receiveLimit]; - } - - int received = m_recordLayer.Receive(buf, 0, receiveLimit, waitMillis); - if (received < 0) - { - ResendOutboundFlight(); - } - else - { - ProcessRecord(MAX_RECEIVE_AHEAD, m_recordLayer.ReadEpoch, buf, 0, received); - } + case HandshakeType.hello_request: + case HandshakeType.hello_verify_request: + case HandshakeType.key_update: + break; - currentTimeMillis = DateTimeUtilities.CurrentUnixMs(); + // TODO[dtls13] Not included in the transcript for (D)TLS 1.3+ + case HandshakeType.new_session_ticket: + default: + { + byte[] body = message.Body; + byte[] buf = new byte[MESSAGE_HEADER_LENGTH]; + TlsUtilities.WriteUint8(msg_type, buf, 0); + TlsUtilities.WriteUint24(body.Length, buf, 1); + TlsUtilities.WriteUint16(message.Seq, buf, 4); + TlsUtilities.WriteUint24(0, buf, 6); + TlsUtilities.WriteUint24(body.Length, buf, 9); + m_handshakeHash.Update(buf, 0, buf.Length); + m_handshakeHash.Update(body, 0, body.Length); + break; + } } } @@ -292,20 +281,75 @@ private void CheckInboundFlight() /// private Message GetPendingMessage() { - DtlsReassembler next = (DtlsReassembler)m_currentInboundFlight[m_next_receive_seq]; - if (next != null) + if (m_currentInboundFlight.TryGetValue(m_next_receive_seq, out var next)) { byte[] body = next.GetBodyIfComplete(); if (body != null) { m_previousInboundFlight = null; - return UpdateHandshakeMessagesDigest(new Message(m_next_receive_seq++, next.MsgType, body)); + return new Message(m_next_receive_seq++, next.MsgType, body); } } return null; } - private void PrepareInboundFlight(IDictionary nextFlight) + /// + private Message ImplReceiveMessage() + { + long currentTimeMillis = DateTimeUtilities.CurrentUnixMs(); + + if (null == m_resendTimeout) + { + m_resendMillis = INITIAL_RESEND_MILLIS; + m_resendTimeout = new Timeout(m_resendMillis, currentTimeMillis); + + PrepareInboundFlight(new Dictionary()); + } + + byte[] buf = null; + + for (;;) + { + if (m_recordLayer.IsClosed) + throw new TlsFatalAlert(AlertDescription.user_canceled); + + Message pending = GetPendingMessage(); + if (pending != null) + return pending; + + if (Timeout.HasExpired(m_handshakeTimeout, currentTimeMillis)) + throw new TlsTimeoutException("Handshake timed out"); + + int waitMillis = Timeout.GetWaitMillis(m_handshakeTimeout, currentTimeMillis); + waitMillis = Timeout.ConstrainWaitMillis(waitMillis, m_resendTimeout, currentTimeMillis); + + // NOTE: Ensure a finite wait, of at least 1ms + if (waitMillis < 1) + { + waitMillis = 1; + } + + int receiveLimit = m_recordLayer.GetReceiveLimit(); + if (buf == null || buf.Length < receiveLimit) + { + buf = new byte[receiveLimit]; + } + + int received = m_recordLayer.Receive(buf, 0, receiveLimit, waitMillis); + if (received < 0) + { + ResendOutboundFlight(); + } + else + { + ProcessRecord(MAX_RECEIVE_AHEAD, m_recordLayer.ReadEpoch, buf, 0, received); + } + + currentTimeMillis = DateTimeUtilities.CurrentUnixMs(); + } + } + + private void PrepareInboundFlight(IDictionary nextFlight) { ResetAll(m_currentInboundFlight); m_previousInboundFlight = m_currentInboundFlight; @@ -351,8 +395,7 @@ private void ProcessRecord(int windowSize, int epoch, byte[] buf, int off, int l } else if (message_seq >= m_next_receive_seq) { - DtlsReassembler reassembler = (DtlsReassembler)m_currentInboundFlight[message_seq]; - if (reassembler == null) + if (!m_currentInboundFlight.TryGetValue(message_seq, out var reassembler)) { reassembler = new DtlsReassembler(msg_type, length); m_currentInboundFlight[message_seq] = reassembler; @@ -368,8 +411,7 @@ private void ProcessRecord(int windowSize, int epoch, byte[] buf, int off, int l * retransmit our last flight */ - DtlsReassembler reassembler = (DtlsReassembler)m_previousInboundFlight[message_seq]; - if (reassembler != null) + if (m_previousInboundFlight.TryGetValue(message_seq, out var reassembler)) { reassembler.ContributeFragment(msg_type, length, buf, off + MESSAGE_HEADER_LENGTH, fragment_offset, fragment_length); @@ -401,37 +443,6 @@ private void ResendOutboundFlight() m_resendTimeout = new Timeout(m_resendMillis); } - /// - private Message UpdateHandshakeMessagesDigest(Message message) - { - short msg_type = message.Type; - switch (msg_type) - { - case HandshakeType.hello_request: - case HandshakeType.hello_verify_request: - case HandshakeType.key_update: - break; - - // TODO[dtls13] Not included in the transcript for (D)TLS 1.3+ - case HandshakeType.new_session_ticket: - default: - { - byte[] body = message.Body; - byte[] buf = new byte[MESSAGE_HEADER_LENGTH]; - TlsUtilities.WriteUint8(msg_type, buf, 0); - TlsUtilities.WriteUint24(body.Length, buf, 1); - TlsUtilities.WriteUint16(message.Seq, buf, 4); - TlsUtilities.WriteUint24(0, buf, 6); - TlsUtilities.WriteUint24(body.Length, buf, 9); - m_handshakeHash.Update(buf, 0, buf.Length); - m_handshakeHash.Update(body, 0, body.Length); - break; - } - } - - return message; - } - /// private void WriteMessage(Message message) { @@ -472,7 +483,7 @@ private void WriteHandshakeFragment(Message message, int fragment_offset, int fr fragment.SendToRecordLayer(m_recordLayer); } - private static bool CheckAll(IDictionary inboundFlight) + private static bool CheckAll(IDictionary inboundFlight) { foreach (DtlsReassembler r in inboundFlight.Values) { @@ -482,7 +493,7 @@ private static bool CheckAll(IDictionary inboundFlight) return true; } - private static void ResetAll(IDictionary inboundFlight) + private static void ResetAll(IDictionary inboundFlight) { foreach (DtlsReassembler r in inboundFlight.Values) { @@ -529,16 +540,11 @@ internal RecordLayerBuffer(int size) internal void SendToRecordLayer(DtlsRecordLayer recordLayer) { -#if PORTABLE || NETFX_CORE - byte[] buf = ToArray(); - int bufLen = buf.Length; -#else byte[] buf = GetBuffer(); - int bufLen = (int)Length; -#endif + int bufLen = Convert.ToInt32(Length); recordLayer.Send(buf, 0, bufLen); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(this); + Dispose(); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsServerProtocol.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsServerProtocol.cs index 57c3fba..db7451d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsServerProtocol.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsServerProtocol.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; @@ -149,7 +149,7 @@ internal virtual DtlsTransport ServerHandshake(ServerHandshakeState state, DtlsR handshake.HandshakeHash.NotifyPrfDetermined(); - IList serverSupplementalData = state.server.GetServerSupplementalData(); + var serverSupplementalData = state.server.GetServerSupplementalData(); if (serverSupplementalData != null) { byte[] supplementalDataBody = GenerateSupplementalData(serverSupplementalData); @@ -157,7 +157,13 @@ internal virtual DtlsTransport ServerHandshake(ServerHandshakeState state, DtlsR } state.keyExchange = TlsUtilities.InitKeyExchangeServer(state.serverContext, state.server); - state.serverCredentials = TlsUtilities.EstablishServerCredentials(state.server); + + state.serverCredentials = null; + + if (!KeyExchangeAlgorithm.IsAnonymous(securityParameters.KeyExchangeAlgorithm)) + { + state.serverCredentials = TlsUtilities.EstablishServerCredentials(state.server); + } // Server certificate { @@ -227,17 +233,34 @@ internal virtual DtlsTransport ServerHandshake(ServerHandshakeState state, DtlsR TlsUtilities.EstablishServerSigAlgs(securityParameters, state.certificateRequest); - TlsUtilities.TrackHashAlgorithms(handshake.HandshakeHash, securityParameters.ServerSigAlgs); + if (ProtocolVersion.DTLSv12.Equals(securityParameters.NegotiatedVersion)) + { + TlsUtilities.TrackHashAlgorithms(handshake.HandshakeHash, securityParameters.ServerSigAlgs); - byte[] certificateRequestBody = GenerateCertificateRequest(state, state.certificateRequest); - handshake.SendMessage(HandshakeType.certificate_request, certificateRequestBody); + if (state.serverContext.Crypto.HasAnyStreamVerifiers(securityParameters.ServerSigAlgs)) + { + handshake.HandshakeHash.ForceBuffering(); + } + } + else + { + if (state.serverContext.Crypto.HasAnyStreamVerifiersLegacy(state.certificateRequest.CertificateTypes)) + { + handshake.HandshakeHash.ForceBuffering(); + } + } } } - handshake.SendMessage(HandshakeType.server_hello_done, TlsUtilities.EmptyBytes); + handshake.HandshakeHash.SealHashAlgorithms(); + + if (null != state.certificateRequest) + { + byte[] certificateRequestBody = GenerateCertificateRequest(state, state.certificateRequest); + handshake.SendMessage(HandshakeType.certificate_request, certificateRequestBody); + } - bool forceBuffering = false; - TlsUtilities.SealHandshakeHash(state.serverContext, handshake.HandshakeHash, forceBuffering); + handshake.SendMessage(HandshakeType.server_hello_done, TlsUtilities.EmptyBytes); clientMessage = handshake.ReceiveMessage(); @@ -299,12 +322,17 @@ internal virtual DtlsTransport ServerHandshake(ServerHandshakeState state, DtlsR * parameters). */ { - TlsHandshakeHash certificateVerifyHash = handshake.PrepareToFinish(); - if (ExpectCertificateVerifyMessage(state)) { - byte[] certificateVerifyBody = handshake.ReceiveMessageBody(HandshakeType.certificate_verify); - ProcessCertificateVerify(state, certificateVerifyBody, certificateVerifyHash); + clientMessage = handshake.ReceiveMessageDelayedDigest(HandshakeType.certificate_verify); + byte[] certificateVerifyBody = clientMessage.Body; + ProcessCertificateVerify(state, certificateVerifyBody, handshake.HandshakeHash); + handshake.PrepareToFinish(); + handshake.UpdateHandshakeMessagesDigest(clientMessage); + } + else + { + handshake.PrepareToFinish(); } } @@ -355,7 +383,7 @@ internal virtual DtlsTransport ServerHandshake(ServerHandshakeState state, DtlsR recordLayer.InitHeartbeat(state.heartbeat, HeartbeatMode.peer_allowed_to_send == state.heartbeatPolicy); - return new DtlsTransport(recordLayer); + return new DtlsTransport(recordLayer, state.server.IgnoreCorruptDtlsRecords); } /// @@ -611,7 +639,11 @@ protected virtual void ProcessClientCertificate(ServerHandshakeState state, byte MemoryStream buf = new MemoryStream(body, false); Certificate.ParseOptions options = new Certificate.ParseOptions() - .SetMaxChainLength(state.server.GetMaxCertificateChainLength()); + { + CertificateType = TlsExtensionsUtilities.GetClientCertificateTypeExtensionServer( + state.clientExtensions, CertificateType.X509), + MaxChainLength = state.server.GetMaxCertificateChainLength(), + }; Certificate clientCertificate = Certificate.Parse(options, state.serverContext, buf, null); @@ -641,7 +673,7 @@ protected virtual void ProcessCertificateVerify(ServerHandshakeState state, byte protected virtual void ProcessClientHello(ServerHandshakeState state, byte[] body) { MemoryStream buf = new MemoryStream(body, false); - ClientHello clientHello = ClientHello.Parse(buf, new NullOutputStream()); + ClientHello clientHello = ClientHello.Parse(buf, Stream.Null); ProcessClientHello(state, clientHello); } @@ -803,7 +835,7 @@ protected virtual void ProcessClientKeyExchange(ServerHandshakeState state, byte protected virtual void ProcessClientSupplementalData(ServerHandshakeState state, byte[] body) { MemoryStream buf = new MemoryStream(body, false); - IList clientSupplementalData = TlsProtocol.ReadSupplementalDataMessage(buf); + var clientSupplementalData = TlsProtocol.ReadSupplementalDataMessage(buf); state.server.ProcessClientSupplementalData(clientSupplementalData); } @@ -827,8 +859,8 @@ protected internal class ServerHandshakeState internal TlsSecret sessionMasterSecret = null; internal SessionParameters.Builder sessionParametersBuilder = null; internal int[] offeredCipherSuites = null; - internal IDictionary clientExtensions = null; - internal IDictionary serverExtensions = null; + internal IDictionary clientExtensions = null; + internal IDictionary serverExtensions = null; internal bool offeredExtendedMasterSecret = false; internal bool resumedSession = false; internal bool expectSessionTicket = false; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsTransport.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsTransport.cs index 0779d80..d4a4652 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsTransport.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/DtlsTransport.cs @@ -2,9 +2,7 @@ #pragma warning disable using System; using System.IO; -#if !PORTABLE || NETFX_CORE || DOTNET using System.Net.Sockets; -#endif namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls { @@ -12,10 +10,12 @@ public class DtlsTransport : DatagramTransport { private readonly DtlsRecordLayer m_recordLayer; + private readonly bool m_ignoreCorruptRecords; - internal DtlsTransport(DtlsRecordLayer recordLayer) + internal DtlsTransport(DtlsRecordLayer recordLayer, bool ignoreCorruptRecords) { - this.m_recordLayer = recordLayer; + m_recordLayer = recordLayer; + m_ignoreCorruptRecords = ignoreCorruptRecords; } /// @@ -39,6 +39,10 @@ public virtual int Receive(byte[] buf, int off, int len, int waitMillis) throw new ArgumentException("invalid offset: " + off, "off"); if (len < 0 || len > buf.Length - off) throw new ArgumentException("invalid length: " + len, "len"); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return Receive(buf.AsSpan(off, len), waitMillis); +#else if (waitMillis < 0) throw new ArgumentException("cannot be negative", "waitMillis"); @@ -48,6 +52,9 @@ public virtual int Receive(byte[] buf, int off, int len, int waitMillis) } catch (TlsFatalAlert fatalAlert) { + if (m_ignoreCorruptRecords && AlertDescription.bad_record_mac == fatalAlert.AlertDescription) + return -1; + m_recordLayer.Fail(fatalAlert.AlertDescription); throw fatalAlert; } @@ -55,7 +62,6 @@ public virtual int Receive(byte[] buf, int off, int len, int waitMillis) { throw e; } -#if !PORTABLE || NETFX_CORE || DOTNET catch (SocketException e) { if (TlsUtilities.IsTimeout(e)) @@ -64,7 +70,55 @@ public virtual int Receive(byte[] buf, int off, int len, int waitMillis) m_recordLayer.Fail(AlertDescription.internal_error); throw new TlsFatalAlert(AlertDescription.internal_error, e); } + // TODO[tls-port] Can we support interrupted IO on .NET? + //catch (InterruptedIOException e) + //{ + // throw e; + //} + catch (IOException e) + { + m_recordLayer.Fail(AlertDescription.internal_error); + throw e; + } + catch (Exception e) + { + m_recordLayer.Fail(AlertDescription.internal_error); + throw new TlsFatalAlert(AlertDescription.internal_error, e); + } #endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// + public virtual int Receive(Span buffer, int waitMillis) + { + if (waitMillis < 0) + throw new ArgumentException("cannot be negative", nameof(waitMillis)); + + try + { + return m_recordLayer.Receive(buffer, waitMillis); + } + catch (TlsFatalAlert fatalAlert) + { + if (m_ignoreCorruptRecords && AlertDescription.bad_record_mac == fatalAlert.AlertDescription) + return -1; + + m_recordLayer.Fail(fatalAlert.AlertDescription); + throw fatalAlert; + } + catch (TlsTimeoutException e) + { + throw e; + } + catch (SocketException e) + { + if (TlsUtilities.IsTimeout(e)) + throw e; + + m_recordLayer.Fail(AlertDescription.internal_error); + throw new TlsFatalAlert(AlertDescription.internal_error, e); + } // TODO[tls-port] Can we support interrupted IO on .NET? //catch (InterruptedIOException e) //{ @@ -81,6 +135,7 @@ public virtual int Receive(byte[] buf, int off, int len, int waitMillis) throw new TlsFatalAlert(AlertDescription.internal_error, e); } } +#endif /// public virtual void Send(byte[] buf, int off, int len) @@ -92,6 +147,9 @@ public virtual void Send(byte[] buf, int off, int len) if (len < 0 || len > buf.Length - off) throw new ArgumentException("invalid length: " + len, "len"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Send(buf.AsSpan(off, len)); +#else try { m_recordLayer.Send(buf, off, len); @@ -105,7 +163,6 @@ public virtual void Send(byte[] buf, int off, int len) { throw e; } -#if !PORTABLE || NETFX_CORE || DOTNET catch (SocketException e) { if (TlsUtilities.IsTimeout(e)) @@ -114,7 +171,48 @@ public virtual void Send(byte[] buf, int off, int len) m_recordLayer.Fail(AlertDescription.internal_error); throw new TlsFatalAlert(AlertDescription.internal_error, e); } + // TODO[tls-port] Can we support interrupted IO on .NET? + //catch (InterruptedIOException e) + //{ + // throw e; + //} + catch (IOException e) + { + m_recordLayer.Fail(AlertDescription.internal_error); + throw e; + } + catch (Exception e) + { + m_recordLayer.Fail(AlertDescription.internal_error); + throw new TlsFatalAlert(AlertDescription.internal_error, e); + } #endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void Send(ReadOnlySpan buffer) + { + try + { + m_recordLayer.Send(buffer); + } + catch (TlsFatalAlert fatalAlert) + { + m_recordLayer.Fail(fatalAlert.AlertDescription); + throw fatalAlert; + } + catch (TlsTimeoutException e) + { + throw e; + } + catch (SocketException e) + { + if (TlsUtilities.IsTimeout(e)) + throw e; + + m_recordLayer.Fail(AlertDescription.internal_error); + throw new TlsFatalAlert(AlertDescription.internal_error, e); + } // TODO[tls-port] Can we support interrupted IO on .NET? //catch (InterruptedIOException e) //{ @@ -131,6 +229,7 @@ public virtual void Send(byte[] buf, int off, int len) throw new TlsFatalAlert(AlertDescription.internal_error, e); } } +#endif /// public virtual void Close() diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ExtensionType.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ExtensionType.cs index 910959e..53c17ee 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ExtensionType.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ExtensionType.cs @@ -108,6 +108,11 @@ public abstract class ExtensionType */ public const int cached_info = 25; + /* + * RFC 8879 + */ + public const int compress_certificate = 27; + /* * RFC 8449 */ @@ -193,6 +198,8 @@ public static string GetName(int extensionType) return "token_binding"; case cached_info: return "cached_info"; + case compress_certificate: + return "compress_certificate"; case record_size_limit: return "record_size_limit"; case session_ticket: @@ -259,6 +266,7 @@ public static bool IsRecognized(int extensionType) case extended_master_secret: case token_binding: case cached_info: + case compress_certificate: case record_size_limit: case session_ticket: case pre_shared_key: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/HandshakeMessageInput.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/HandshakeMessageInput.cs index b88c27c..6f7be41 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/HandshakeMessageInput.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/HandshakeMessageInput.cs @@ -4,7 +4,6 @@ using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls { @@ -15,46 +14,28 @@ public sealed class HandshakeMessageInput private readonly int m_offset; internal HandshakeMessageInput(byte[] buf, int offset, int length) -#if PORTABLE || NETFX_CORE - : base(buf, offset, length, false) -#else : base(buf, offset, length, false, true) -#endif { -#if PORTABLE || NETFX_CORE - this.m_offset = 0; -#else - this.m_offset = offset; -#endif + m_offset = offset; } public void UpdateHash(TlsHash hash) { - Streams.WriteBufTo(this, new TlsHashSink(hash)); + WriteTo(new TlsHashSink(hash)); } internal void UpdateHashPrefix(TlsHash hash, int bindersSize) { -#if PORTABLE || NETFX_CORE - byte[] buf = ToArray(); - int count = buf.Length; -#else byte[] buf = GetBuffer(); - int count = (int)Length; -#endif + int count = Convert.ToInt32(Length); hash.Update(buf, m_offset, count - bindersSize); } internal void UpdateHashSuffix(TlsHash hash, int bindersSize) { -#if PORTABLE || NETFX_CORE - byte[] buf = ToArray(); - int count = buf.Length; -#else byte[] buf = GetBuffer(); - int count = (int)Length; -#endif + int count = Convert.ToInt32(Length); hash.Update(buf, m_offset + count - bindersSize, bindersSize); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/HandshakeMessageOutput.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/HandshakeMessageOutput.cs index 44bb6c6..086739d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/HandshakeMessageOutput.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/HandshakeMessageOutput.cs @@ -43,40 +43,31 @@ internal HandshakeMessageOutput(short handshakeType, int bodyLength) internal void Send(TlsProtocol protocol) { // Patch actual length back in - int bodyLength = (int)Length - 4; + int bodyLength = Convert.ToInt32(Length) - 4; TlsUtilities.CheckUint24(bodyLength); Seek(1L, SeekOrigin.Begin); TlsUtilities.WriteUint24(bodyLength, this); -#if PORTABLE || NETFX_CORE - byte[] buf = ToArray(); - int count = buf.Length; -#else byte[] buf = GetBuffer(); - int count = (int)Length; -#endif + int count = Convert.ToInt32(Length); + protocol.WriteHandshakeMessage(buf, 0, count); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(this); + Dispose(); } internal void PrepareClientHello(TlsHandshakeHash handshakeHash, int bindersSize) { // Patch actual length back in - int bodyLength = (int)Length - 4 + bindersSize; + int bodyLength = Convert.ToInt32(Length) - 4 + bindersSize; TlsUtilities.CheckUint24(bodyLength); Seek(1L, SeekOrigin.Begin); TlsUtilities.WriteUint24(bodyLength, this); -#if PORTABLE || NETFX_CORE - byte[] buf = ToArray(); - int count = buf.Length; -#else byte[] buf = GetBuffer(); - int count = (int)Length; -#endif + int count = Convert.ToInt32(Length); handshakeHash.Update(buf, 0, count); @@ -85,13 +76,8 @@ internal void PrepareClientHello(TlsHandshakeHash handshakeHash, int bindersSize internal void SendClientHello(TlsClientProtocol clientProtocol, TlsHandshakeHash handshakeHash, int bindersSize) { -#if PORTABLE || NETFX_CORE - byte[] buf = ToArray(); - int count = buf.Length; -#else byte[] buf = GetBuffer(); - int count = (int)Length; -#endif + int count = Convert.ToInt32(Length); if (bindersSize > 0) { @@ -100,7 +86,7 @@ internal void SendClientHello(TlsClientProtocol clientProtocol, TlsHandshakeHash clientProtocol.WriteHandshakeMessage(buf, 0, count); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(this); + Dispose(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/HandshakeType.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/HandshakeType.cs index d76489d..b052780 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/HandshakeType.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/HandshakeType.cs @@ -46,6 +46,11 @@ public abstract class HandshakeType public const short key_update = 24; public const short message_hash = 254; + /* + * RFC 8879 + */ + public const short compressed_certificate = 25; + public static string GetName(short handshakeType) { switch (handshakeType) @@ -90,6 +95,8 @@ public static string GetName(short handshakeType) return "key_update"; case message_hash: return "message_hash"; + case compressed_certificate: + return "compressed_certificate"; default: return "UNKNOWN"; } @@ -124,6 +131,7 @@ public static bool IsRecognized(short handshakeType) case encrypted_extensions: case key_update: case message_hash: + case compressed_certificate: return true; default: return false; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/KeyExchangeAlgorithm.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/KeyExchangeAlgorithm.cs index b686148..e17047c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/KeyExchangeAlgorithm.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/KeyExchangeAlgorithm.cs @@ -61,6 +61,19 @@ public abstract class KeyExchangeAlgorithm * GMT 0024-2014 */ public const int SM2 = 25; + + public static bool IsAnonymous(int keyExchangeAlgorithm) + { + switch (keyExchangeAlgorithm) + { + case DH_anon: + case DH_anon_EXPORT: + case ECDH_anon: + return true; + default: + return false; + } + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/OcspStatusRequest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/OcspStatusRequest.cs index 65050e7..1a21808 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/OcspStatusRequest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/OcspStatusRequest.cs @@ -1,13 +1,12 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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.Utilities; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls @@ -15,22 +14,22 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls /// RFC 3546 3.6 public sealed class OcspStatusRequest { - private readonly IList m_responderIDList; + private readonly IList m_responderIDList; private readonly X509Extensions m_requestExtensions; - /// an of , specifying the list of + /// an of , specifying the list of /// trusted OCSP responders. An empty list has the special meaning that the responders are implicitly known to /// the server - e.g., by prior arrangement. /// OCSP request extensions. A null value means that there are no extensions. /// - public OcspStatusRequest(IList responderIDList, X509Extensions requestExtensions) + public OcspStatusRequest(IList responderIDList, X509Extensions requestExtensions) { this.m_responderIDList = responderIDList; this.m_requestExtensions = requestExtensions; } - /// an of . - public IList ResponderIDList + /// an of . + public IList ResponderIDList { get { return m_responderIDList; } } @@ -59,8 +58,8 @@ public void Encode(Stream output) TlsUtilities.WriteOpaque16(derEncoding, buf); } TlsUtilities.CheckUint16(buf.Length); - TlsUtilities.WriteUint16((int)buf.Length, output); - Streams.WriteBufTo(buf, output); + TlsUtilities.WriteUint16(Convert.ToInt32(buf.Length), output); + buf.WriteTo(output); } if (m_requestExtensions == null) @@ -82,7 +81,7 @@ public void Encode(Stream output) /// public static OcspStatusRequest Parse(Stream input) { - IList responderIDList = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var responderIDList = new List(); { byte[] data = TlsUtilities.ReadOpaque16(input); if (data.Length > 0) @@ -91,7 +90,9 @@ public static OcspStatusRequest Parse(Stream input) do { byte[] derEncoding = TlsUtilities.ReadOpaque16(buf, 1); - ResponderID responderID = ResponderID.GetInstance(TlsUtilities.ReadDerObject(derEncoding)); + Asn1Object asn1 = TlsUtilities.ReadAsn1Object(derEncoding); + ResponderID responderID = ResponderID.GetInstance(asn1); + TlsUtilities.RequireDerEncoding(responderID, derEncoding); responderIDList.Add(responderID); } while (buf.Position < buf.Length); @@ -103,7 +104,10 @@ public static OcspStatusRequest Parse(Stream input) byte[] derEncoding = TlsUtilities.ReadOpaque16(input); if (derEncoding.Length > 0) { - requestExtensions = X509Extensions.GetInstance(TlsUtilities.ReadDerObject(derEncoding)); + Asn1Object asn1 = TlsUtilities.ReadAsn1Object(derEncoding); + X509Extensions extensions = X509Extensions.GetInstance(asn1); + TlsUtilities.RequireDerEncoding(extensions, derEncoding); + requestExtensions = extensions; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/OfferedPsks.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/OfferedPsks.cs index d42c3be..a6e1e28 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/OfferedPsks.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/OfferedPsks.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; @@ -44,16 +44,16 @@ internal SelectedConfig(int index, TlsPsk psk, short[] pskKeyExchangeModes, TlsS } } - private readonly IList m_identities; - private readonly IList m_binders; + private readonly IList m_identities; + private readonly IList m_binders; private readonly int m_bindersSize; - public OfferedPsks(IList identities) + public OfferedPsks(IList identities) : this(identities, null, -1) { } - private OfferedPsks(IList identities, IList binders, int bindersSize) + private OfferedPsks(IList identities, IList binders, int bindersSize) { if (null == identities || identities.Count < 1) throw new ArgumentException("cannot be null or empty", "identities"); @@ -67,7 +67,7 @@ private OfferedPsks(IList identities, IList binders, int bindersSize) this.m_bindersSize = bindersSize; } - public IList Binders + public IList Binders { get { return m_binders; } } @@ -77,7 +77,7 @@ public int BindersSize get { return m_bindersSize; } } - public IList Identities + public IList Identities { get { return m_identities; } } @@ -188,7 +188,7 @@ internal static int GetBindersSize(TlsPsk[] psks) /// public static OfferedPsks Parse(Stream input) { - IList identities = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var identities = new List(); { int totalLengthIdentities = TlsUtilities.ReadUint16(input); if (totalLengthIdentities < 7) @@ -204,7 +204,7 @@ public static OfferedPsks Parse(Stream input) while (buf.Position < buf.Length); } - IList binders = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var binders = new List(); int totalLengthBinders = TlsUtilities.ReadUint16(input); { if (totalLengthBinders < 33) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ProtocolName.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ProtocolName.cs index 921801a..388dba5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ProtocolName.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ProtocolName.cs @@ -15,7 +15,7 @@ public static ProtocolName AsRawBytes(byte[] bytes) return new ProtocolName(Arrays.Clone(bytes)); } - public static ProtocolName AsUtf8Encoding(String name) + public static ProtocolName AsUtf8Encoding(string name) { return new ProtocolName(Strings.ToUtf8ByteArray(name)); } @@ -37,6 +37,17 @@ public static ProtocolName AsUtf8Encoding(String name) public static readonly ProtocolName Coap = AsUtf8Encoding("coap"); public static readonly ProtocolName Xmpp_Client = AsUtf8Encoding("xmpp-client"); public static readonly ProtocolName Xmpp_Server = AsUtf8Encoding("xmpp-server"); + public static readonly ProtocolName Acme_Tls_1 = AsUtf8Encoding("acme-tls/1"); + public static readonly ProtocolName Oasis_Mqtt = AsUtf8Encoding("mqtt"); + public static readonly ProtocolName Dns_Over_Tls = AsUtf8Encoding("dot"); + public static readonly ProtocolName Ntske_1 = AsUtf8Encoding("ntske/1"); + public static readonly ProtocolName Sun_Rpc = AsUtf8Encoding("sunrpc"); + public static readonly ProtocolName Http_3 = AsUtf8Encoding("h3"); + public static readonly ProtocolName Smb_2 = AsUtf8Encoding("smb"); + public static readonly ProtocolName Irc = AsUtf8Encoding("irc"); + public static readonly ProtocolName Nntp_Reading = AsUtf8Encoding("nntp"); + public static readonly ProtocolName Nntp_Transit = AsUtf8Encoding("nnsp"); + public static readonly ProtocolName Dns_Over_Quic = AsUtf8Encoding("doq"); private readonly byte[] m_bytes; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ProtocolVersion.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ProtocolVersion.cs index 404b09b..21c1710 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ProtocolVersion.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ProtocolVersion.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -16,6 +16,7 @@ public sealed class ProtocolVersion public static readonly ProtocolVersion TLSv13 = new ProtocolVersion(0x0304, "TLS 1.3"); public static readonly ProtocolVersion DTLSv10 = new ProtocolVersion(0xFEFF, "DTLS 1.0"); public static readonly ProtocolVersion DTLSv12 = new ProtocolVersion(0xFEFD, "DTLS 1.2"); + public static readonly ProtocolVersion DTLSv13 = new ProtocolVersion(0xFEFC, "DTLS 1.3"); internal static readonly ProtocolVersion CLIENT_EARLIEST_SUPPORTED_DTLS = DTLSv10; internal static readonly ProtocolVersion CLIENT_EARLIEST_SUPPORTED_TLS = SSLv3; @@ -170,7 +171,7 @@ public ProtocolVersion[] DownTo(ProtocolVersion min) if (!IsEqualOrLaterVersionOf(min)) throw new ArgumentException("must be an equal or earlier version of this one", "min"); - IList result = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var result = new List(); result.Add(this); ProtocolVersion current = this; @@ -180,12 +181,7 @@ public ProtocolVersion[] DownTo(ProtocolVersion min) result.Add(current); } - ProtocolVersion[] versions = new ProtocolVersion[result.Count]; - for (int i = 0; i < result.Count; ++i) - { - versions[i] = (ProtocolVersion)result[i]; - } - return versions; + return result.ToArray(); } public int FullVersion @@ -227,17 +223,22 @@ public ProtocolVersion GetEquivalentTlsVersion() { switch (MajorVersion) { - case 0x03: - return this; - case 0xFE: - switch (MinorVersion) - { - case 0xFF: return TLSv11; - case 0xFD: return TLSv12; - default: return null; - } + case 0x03: + return this; + case 0xFE: + switch (MinorVersion) + { + case 0xFF: + return TLSv11; + case 0xFD: + return TLSv12; + case 0xFC: + return TLSv13; default: return null; + } + default: + return null; } } @@ -249,15 +250,20 @@ public ProtocolVersion GetNextVersion() case 0x03: switch (minor) { - case 0xFF: return null; - default: return Get(major, minor + 1); + case 0xFF: + return null; + default: + return Get(major, minor + 1); } case 0xFE: switch (minor) { - case 0x00: return null; - case 0xFF: return DTLSv12; - default: return Get(major, minor - 1); + case 0x00: + return null; + case 0xFF: + return DTLSv12; + default: + return Get(major, minor - 1); } default: return null; @@ -269,21 +275,26 @@ public ProtocolVersion GetPreviousVersion() int major = MajorVersion, minor = MinorVersion; switch (major) { - case 0x03: - switch (minor) - { - case 0x00: return null; - default: return Get(major, minor - 1); - } - case 0xFE: - switch (minor) - { - case 0xFF: return null; - case 0xFD: return DTLSv10; - default: return Get(major, minor + 1); - } + case 0x03: + switch (minor) + { + case 0x00: + return null; default: + return Get(major, minor - 1); + } + case 0xFE: + switch (minor) + { + case 0xFF: return null; + case 0xFD: + return DTLSv10; + default: + return Get(major, minor + 1); + } + default: + return null; } } @@ -369,6 +380,8 @@ public static ProtocolVersion Get(int major, int minor) throw new ArgumentException("{0xFE, 0xFE} is a reserved protocol version"); case 0xFD: return DTLSv12; + case 0xFC: + return DTLSv13; } return GetUnknownVersion(major, minor, "DTLS"); } @@ -401,7 +414,7 @@ private static ProtocolVersion GetUnknownVersion(int major, int minor, string pr CheckUint8(minor); int v = (major << 8) | minor; - string hex = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(Convert.ToString(0x10000 | v, 16).Substring(1)); + string hex = Convert.ToString(0x10000 | v, 16).Substring(1).ToUpperInvariant(); return new ProtocolVersion(v, prefix + " 0x" + hex); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/PskTlsClient.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/PskTlsClient.cs index b8c85f4..1724b74 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/PskTlsClient.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/PskTlsClient.cs @@ -36,7 +36,7 @@ public PskTlsClient(TlsCrypto crypto, TlsPskIdentity pskIdentity) protected override ProtocolVersion[] GetSupportedVersions() { - return ProtocolVersion.TLSv12.DownTo(ProtocolVersion.TLSv10); + return ProtocolVersion.TLSv12.Only(); } protected override int[] GetSupportedCipherSuites() diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/PskTlsServer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/PskTlsServer.cs index a96d276..d2d2700 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/PskTlsServer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/PskTlsServer.cs @@ -42,7 +42,7 @@ protected virtual TlsCredentialedDecryptor GetRsaEncryptionCredentials() protected override ProtocolVersion[] GetSupportedVersions() { - return ProtocolVersion.TLSv12.DownTo(ProtocolVersion.TLSv10); + return ProtocolVersion.TLSv12.Only(); } protected override int[] GetSupportedCipherSuites() diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/RecordStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/RecordStream.cs index 4f1feff..c1a10e6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/RecordStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/RecordStream.cs @@ -266,6 +266,9 @@ internal TlsDecodeResult DecodeAndVerify(short recordType, ProtocolVersion recor /// internal void WriteRecord(short contentType, byte[] plaintext, int plaintextOffset, int plaintextLength) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + WriteRecord(contentType, plaintext.AsSpan(plaintextOffset, plaintextLength)); +#else // Never send anything until a valid ClientHello has been received if (m_writeVersion == null) return; @@ -295,6 +298,58 @@ internal void WriteRecord(short contentType, byte[] plaintext, int plaintextOffs TlsUtilities.WriteVersion(recordVersion, encoded.buf, encoded.off + RecordFormat.VersionOffset); TlsUtilities.WriteUint16(ciphertextLength, encoded.buf, encoded.off + RecordFormat.LengthOffset); + // TODO[tls-port] Can we support interrupted IO on .NET? + try + { + m_output.Write(encoded.buf, encoded.off, encoded.len); + } + //catch (InterruptedIOException e) + //{ + // throw new TlsFatalAlert(AlertDescription.internal_error, e); + //} + finally + { + if (encoded.fromBufferPool) + BufferPool.Release(encoded.buf); + } + + m_output.Flush(); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// + internal void WriteRecord(short contentType, ReadOnlySpan plaintext) + { + // Never send anything until a valid ClientHello has been received + if (m_writeVersion == null) + return; + + /* + * RFC 5246 6.2.1 The length should not exceed 2^14. + */ + CheckLength(plaintext.Length, m_plaintextLimit, AlertDescription.internal_error); + + /* + * RFC 5246 6.2.1 Implementations MUST NOT send zero-length fragments of Handshake, Alert, + * or ChangeCipherSpec content types. + */ + if (plaintext.Length < 1 && contentType != ContentType.application_data) + throw new TlsFatalAlert(AlertDescription.internal_error); + + long seqNo=m_writeSeqNo.NextValue(AlertDescription.internal_error); + ProtocolVersion recordVersion = m_writeVersion; + + TlsEncodeResult encoded = m_writeCipher.EncodePlaintext(seqNo, contentType, recordVersion, + RecordFormat.FragmentOffset, plaintext); + + int ciphertextLength = encoded.len - RecordFormat.FragmentOffset; + TlsUtilities.CheckUint16(ciphertextLength); + + TlsUtilities.WriteUint8(encoded.recordType, encoded.buf, encoded.off + RecordFormat.TypeOffset); + TlsUtilities.WriteVersion(recordVersion, encoded.buf, encoded.off + RecordFormat.VersionOffset); + TlsUtilities.WriteUint16(ciphertextLength, encoded.buf, encoded.off + RecordFormat.LengthOffset); + // TODO[tls-port] Can we support interrupted IO on .NET? //try //{ @@ -307,6 +362,7 @@ internal void WriteRecord(short contentType, byte[] plaintext, int plaintextOffs m_output.Flush(); } +#endif /// internal void Close() @@ -316,7 +372,7 @@ internal void Close() IOException io = null; try { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(m_input); + m_input.Dispose(); } catch (IOException e) { @@ -325,7 +381,7 @@ internal void Close() try { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(m_output); + m_output.Dispose(); } catch (IOException e) { @@ -486,12 +542,12 @@ internal bool ReadHeader(Stream input) internal void Reset() { - if (m_buf != m_header) - BufferPool.Release(m_buf); + if (m_buf != m_header) + BufferPool.Release(m_buf); - m_buf = m_header; - m_pos = 0; - } + m_buf = m_header; + m_pos = 0; + } private void Resize(int length) { @@ -503,6 +559,9 @@ private void Resize(int length) byte[] tmp = BufferPool.Get(length, true); Array.Copy(m_buf, 0, tmp, 0, m_pos); + + if (m_buf != m_header) + BufferPool.Release(m_buf); m_buf = tmp; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SecurityParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SecurityParameters.cs index dc31625..6bdee51 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SecurityParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SecurityParameters.cs @@ -1,7 +1,6 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; @@ -10,6 +9,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls public sealed class SecurityParameters { internal int m_entity = -1; + internal bool m_resumedSession = false; internal bool m_secureRenegotiation = false; internal int m_cipherSuite = Tls.CipherSuite.TLS_NULL_WITH_NULL_NULL; internal short m_maxFragmentLength = -1; @@ -41,18 +41,19 @@ public sealed class SecurityParameters internal ProtocolName m_applicationProtocol = null; internal bool m_applicationProtocolSet = false; internal short[] m_clientCertTypes = null; - internal IList m_clientServerNames = null; - internal IList m_clientSigAlgs = null; - internal IList m_clientSigAlgsCert = null; + internal IList m_clientServerNames = null; + internal IList m_clientSigAlgs = null; + internal IList m_clientSigAlgsCert = null; internal int[] m_clientSupportedGroups = null; - internal IList m_serverSigAlgs = null; - internal IList m_serverSigAlgsCert = null; + internal IList m_serverSigAlgs = null; + internal IList m_serverSigAlgsCert = null; internal int[] m_serverSupportedGroups = null; internal int m_keyExchangeAlgorithm = -1; internal Certificate m_localCertificate = null; internal Certificate m_peerCertificate = null; internal ProtocolVersion m_negotiatedVersion = null; internal int m_statusRequestVersion = 0; + internal short m_clientCertificateType = -1; // TODO[tls-ops] Investigate whether we can handle verify data using TlsSecret internal byte[] m_localVerifyData = null; @@ -101,6 +102,11 @@ public int CipherSuite get { return m_cipherSuite; } } + public short ClientCertificateType + { + get { return m_clientCertificateType; } + } + public short[] ClientCertTypes { get { return m_clientCertTypes; } @@ -111,17 +117,17 @@ public byte[] ClientRandom get { return m_clientRandom; } } - public IList ClientServerNames + public IList ClientServerNames { get { return m_clientServerNames; } } - public IList ClientSigAlgs + public IList ClientSigAlgs { get { return m_clientSigAlgs; } } - public IList ClientSigAlgsCert + public IList ClientSigAlgsCert { get { return m_clientSigAlgsCert; } } @@ -176,6 +182,11 @@ public bool IsExtendedPadding get { return m_extendedPadding; } } + public bool IsResumedSession + { + get { return m_resumedSession; } + } + public bool IsSecureRenegotiation { get { return m_secureRenegotiation; } @@ -251,12 +262,12 @@ public byte[] ServerRandom get { return m_serverRandom; } } - public IList ServerSigAlgs + public IList ServerSigAlgs { get { return m_serverSigAlgs; } } - public IList ServerSigAlgsCert + public IList ServerSigAlgsCert { get { return m_serverSigAlgsCert; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ServerHello.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ServerHello.cs index d78fc9d..02ba7fd 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ServerHello.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ServerHello.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -18,15 +18,15 @@ public sealed class ServerHello private readonly byte[] m_random; private readonly byte[] m_sessionID; private readonly int m_cipherSuite; - private readonly IDictionary m_extensions; + private readonly IDictionary m_extensions; - public ServerHello(byte[] sessionID, int cipherSuite, IDictionary extensions) + public ServerHello(byte[] sessionID, int cipherSuite, IDictionary extensions) : this(ProtocolVersion.TLSv12, Arrays.Clone(HelloRetryRequestMagic), sessionID, cipherSuite, extensions) { } public ServerHello(ProtocolVersion version, byte[] random, byte[] sessionID, int cipherSuite, - IDictionary extensions) + IDictionary extensions) { this.m_version = version; this.m_random = random; @@ -40,7 +40,7 @@ public int CipherSuite get { return m_cipherSuite; } } - public IDictionary Extensions + public IDictionary Extensions { get { return m_extensions; } } @@ -102,7 +102,7 @@ public static ServerHello Parse(MemoryStream input) if (CompressionMethod.cls_null != compressionMethod) throw new TlsFatalAlert(AlertDescription.illegal_parameter); - IDictionary extensions = TlsProtocol.ReadExtensions(input); + var extensions = TlsProtocol.ReadExtensions(input); return new ServerHello(version, random, sessionID, cipherSuite, extensions); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ServerNameList.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ServerNameList.cs index e232fd4..405c7e5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ServerNameList.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/ServerNameList.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; @@ -11,10 +11,10 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls { public sealed class ServerNameList { - private readonly IList m_serverNameList; + private readonly IList m_serverNameList; - /// an of . - public ServerNameList(IList serverNameList) + /// an of . + public ServerNameList(IList serverNameList) { if (null == serverNameList) throw new ArgumentNullException("serverNameList"); @@ -22,8 +22,8 @@ public ServerNameList(IList serverNameList) this.m_serverNameList = serverNameList; } - /// an of . - public IList ServerNames + /// an of . + public IList ServerNames { get { return m_serverNameList; } } @@ -45,10 +45,10 @@ public void Encode(Stream output) entry.Encode(buf); } - int length = (int)buf.Length; + int length = Convert.ToInt32(buf.Length); TlsUtilities.CheckUint16(length); TlsUtilities.WriteUint16(length, output); - Streams.WriteBufTo(buf, output); + buf.WriteTo(output); } /// Parse a from a . @@ -62,7 +62,7 @@ public static ServerNameList Parse(Stream input) MemoryStream buf = new MemoryStream(data, false); short[] nameTypesSeen = TlsUtilities.EmptyShorts; - IList server_name_list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var server_name_list = new List(); while (buf.Position < buf.Length) { ServerName entry = ServerName.Parse(buf); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SessionParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SessionParameters.cs index f0cb170..79beac2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SessionParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SessionParameters.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; @@ -84,7 +84,7 @@ public Builder SetSrpIdentity(byte[] srpIdentity) } /// - public Builder SetServerExtensions(IDictionary serverExtensions) + public Builder SetServerExtensions(IDictionary serverExtensions) { if (serverExtensions == null || serverExtensions.Count < 1) { @@ -181,7 +181,7 @@ public byte[] PskIdentity } /// - public IDictionary ReadServerExtensions() + public IDictionary ReadServerExtensions() { if (m_encodedServerExtensions == null) return null; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SignatureAlgorithm.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SignatureAlgorithm.cs index 99c0832..275f651 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SignatureAlgorithm.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SignatureAlgorithm.cs @@ -88,20 +88,16 @@ public static string GetName(short signatureAlgorithm) return "dsa"; case ecdsa: return "ecdsa"; - case ed25519: - return "ed25519"; - case ed448: - return "ed448"; - case gostr34102012_256: - return "gostr34102012_256"; - case gostr34102012_512: - return "gostr34102012_512"; case rsa_pss_rsae_sha256: return "rsa_pss_rsae_sha256"; case rsa_pss_rsae_sha384: return "rsa_pss_rsae_sha384"; case rsa_pss_rsae_sha512: return "rsa_pss_rsae_sha512"; + case ed25519: + return "ed25519"; + case ed448: + return "ed448"; case rsa_pss_pss_sha256: return "rsa_pss_pss_sha256"; case rsa_pss_pss_sha384: @@ -114,6 +110,10 @@ public static string GetName(short signatureAlgorithm) return "ecdsa_brainpoolP384r1tls13_sha384"; case ecdsa_brainpoolP512r1tls13_sha512: return "ecdsa_brainpoolP512r1tls13_sha512"; + case gostr34102012_256: + return "gostr34102012_256"; + case gostr34102012_512: + return "gostr34102012_512"; default: return "UNKNOWN"; } @@ -123,6 +123,33 @@ public static string GetText(short signatureAlgorithm) { return GetName(signatureAlgorithm) + "(" + signatureAlgorithm + ")"; } + + public static bool IsRecognized(short signatureAlgorithm) + { + switch (signatureAlgorithm) + { + case anonymous: + case rsa: + case dsa: + case ecdsa: + case rsa_pss_rsae_sha256: + case rsa_pss_rsae_sha384: + case rsa_pss_rsae_sha512: + case ed25519: + case ed448: + case rsa_pss_pss_sha256: + case rsa_pss_pss_sha384: + case rsa_pss_pss_sha512: + case ecdsa_brainpoolP256r1tls13_sha256: + case ecdsa_brainpoolP384r1tls13_sha384: + case ecdsa_brainpoolP512r1tls13_sha512: + case gostr34102012_256: + case gostr34102012_512: + return true; + default: + return false; + } + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SignatureScheme.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SignatureScheme.cs index 6b388b6..4d3f9ba 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SignatureScheme.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SignatureScheme.cs @@ -94,11 +94,16 @@ public static int GetCryptoHashAlgorithm(int signatureScheme) if (HashAlgorithm.Intrinsic == hashAlgorithm || !HashAlgorithm.IsRecognized(hashAlgorithm)) return -1; - return TlsCryptoUtilities.GetHash(GetHashAlgorithm(signatureScheme)); + return TlsCryptoUtilities.GetHash(hashAlgorithm); } } } + public static int GetCryptoHashAlgorithm(SignatureAndHashAlgorithm signatureAndHashAlgorithm) + { + return GetCryptoHashAlgorithm(From(signatureAndHashAlgorithm)); + } + public static string GetName(int signatureScheme) { switch (signatureScheme) @@ -196,7 +201,7 @@ public static SignatureAndHashAlgorithm GetSignatureAndHashAlgorithm(int signatu public static string GetText(int signatureScheme) { - string hex = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(Convert.ToString(signatureScheme, 16)); + string hex = Convert.ToString(signatureScheme, 16).ToUpperInvariant(); return GetName(signatureScheme) + "(0x" + hex + ")"; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SrpTlsClient.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SrpTlsClient.cs index 8b41cf3..d484c67 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SrpTlsClient.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SrpTlsClient.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; @@ -36,7 +36,7 @@ protected override int[] GetSupportedCipherSuites() protected override ProtocolVersion[] GetSupportedVersions() { - return ProtocolVersion.TLSv12.DownTo(ProtocolVersion.TLSv10); + return ProtocolVersion.TLSv12.Only(); } protected virtual bool RequireSrpServerExtension @@ -46,16 +46,16 @@ protected virtual bool RequireSrpServerExtension } /// - public override IDictionary GetClientExtensions() + public override IDictionary GetClientExtensions() { - IDictionary clientExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised( + var clientExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised( base.GetClientExtensions()); TlsSrpUtilities.AddSrpExtension(clientExtensions, m_srpIdentity.GetSrpIdentity()); return clientExtensions; } /// - public override void ProcessServerExtensions(IDictionary serverExtensions) + public override void ProcessServerExtensions(IDictionary serverExtensions) { if (!TlsUtilities.HasExpectedEmptyExtensionData(serverExtensions, ExtensionType.srp, AlertDescription.illegal_parameter)) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SrpTlsServer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SrpTlsServer.cs index 621063a..f77f70c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SrpTlsServer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/SrpTlsServer.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; @@ -46,7 +46,7 @@ protected virtual TlsCredentialedSigner GetRsaSignerCredentials() protected override ProtocolVersion[] GetSupportedVersions() { - return ProtocolVersion.TLSv12.DownTo(ProtocolVersion.TLSv10); + return ProtocolVersion.TLSv12.Only(); } protected override int[] GetSupportedCipherSuites() @@ -54,7 +54,7 @@ protected override int[] GetSupportedCipherSuites() return TlsUtilities.GetSupportedCipherSuites(Crypto, DefaultCipherSuites); } - public override void ProcessClientExtensions(IDictionary clientExtensions) + public override void ProcessClientExtensions(IDictionary clientExtensions) { base.ProcessClientExtensions(clientExtensions); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsClient.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsClient.cs index 2f2f4de..dd59924 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsClient.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsClient.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls @@ -22,15 +22,15 @@ public interface TlsClient /// Return the external PSKs to offer in the ClientHello. /// This will only be called when TLS 1.3 or higher is amongst the offered protocol versions. - /// an of instances, or null if none should be + /// an of instances, or null if none should be /// offered. - IList GetExternalPsks(); + IList GetExternalPsks(); bool IsFallback(); /// (Int32 -> byte[]) /// - IDictionary GetClientExtensions(); + IDictionary GetClientExtensions(); /// If this client is offering TLS 1.3 or higher, this method may be called to determine for which /// groups a key share should be included in the initial ClientHello. @@ -38,9 +38,10 @@ public interface TlsClient /// Groups that were not included in the supported_groups extension (by will /// be ignored. The protocol will then add a suitable key_share extension to the ClientHello extensions. /// - /// an of named group values, possibly empty or null. + /// an of named group values, possibly empty or + /// null. /// - IList GetEarlyKeyShareGroups(); + IList GetEarlyKeyShareGroups(); /// void NotifyServerVersion(ProtocolVersion selectedVersion); @@ -74,11 +75,11 @@ public interface TlsClient /// /// (Int32 -> byte[]) /// - void ProcessServerExtensions(IDictionary serverExtensions); + void ProcessServerExtensions(IDictionary serverExtensions); /// (SupplementalDataEntry) /// - void ProcessServerSupplementalData(IList serverSupplementalData); + void ProcessServerSupplementalData(IList serverSupplementalData); /// TlsPskIdentity GetPskIdentity(); @@ -97,7 +98,7 @@ public interface TlsClient /// (SupplementalDataEntry) /// - IList GetClientSupplementalData(); + IList GetClientSupplementalData(); /// RFC 5077 3.3. NewSessionTicket Handshake Message /// diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsClientProtocol.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsClientProtocol.cs index 4b2bea3..cb48fb9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsClientProtocol.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsClientProtocol.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; @@ -15,7 +15,7 @@ public class TlsClientProtocol protected TlsClient m_tlsClient = null; internal TlsClientContextImpl m_tlsClientContext = null; - protected IDictionary m_clientAgreements = null; + protected IDictionary m_clientAgreements = null; internal OfferedPsks.BindersConfig m_clientBinders = null; protected ClientHello m_clientHello = null; protected TlsKeyExchange m_keyExchange = null; @@ -120,7 +120,7 @@ protected override TlsPeer Peer /// protected virtual void Handle13HandshakeMessage(short type, HandshakeMessageInput buf) { - if (!IsTlsV13ConnectionState() || m_resumedSession) + if (!IsTlsV13ConnectionState()) throw new TlsFatalAlert(AlertDescription.internal_error); switch (type) @@ -317,6 +317,7 @@ protected virtual void Handle13HandshakeMessage(short type, HandshakeMessageInpu case HandshakeType.certificate_url: case HandshakeType.client_hello: case HandshakeType.client_key_exchange: + case HandshakeType.compressed_certificate: case HandshakeType.end_of_early_data: case HandshakeType.hello_request: case HandshakeType.hello_verify_request: @@ -336,6 +337,9 @@ protected override void HandleHandshakeMessage(short type, HandshakeMessageInput if (m_connectionState > CS_CLIENT_HELLO && TlsUtilities.IsTlsV13(securityParameters.NegotiatedVersion)) { + if (securityParameters.IsResumedSession) + throw new TlsFatalAlert(AlertDescription.internal_error); + Handle13HandshakeMessage(type, buf); return; } @@ -343,7 +347,7 @@ protected override void HandleHandshakeMessage(short type, HandshakeMessageInput if (!IsLegacyConnectionState()) throw new TlsFatalAlert(AlertDescription.internal_error); - if (m_resumedSession) + if (securityParameters.IsResumedSession) { if (type != HandshakeType.finished || m_connectionState != CS_SERVER_HELLO) throw new TlsFatalAlert(AlertDescription.unexpected_message); @@ -378,8 +382,8 @@ protected override void HandleHandshakeMessage(short type, HandshakeMessageInput * NOTE: Certificate processing (including authentication) is delayed to allow for a * possible CertificateStatus message. */ - this.m_authentication = TlsUtilities.ReceiveServerCertificate(m_tlsClientContext, m_tlsClient, - buf); + m_authentication = TlsUtilities.ReceiveServerCertificate(m_tlsClientContext, m_tlsClient, buf, + m_serverExtensions); break; } default: @@ -451,24 +455,27 @@ protected override void HandleHandshakeMessage(short type, HandshakeMessageInput { Process13HelloRetryRequest(serverHello); m_handshakeHash.NotifyPrfDetermined(); + m_handshakeHash.SealHashAlgorithms(); TlsUtilities.AdjustTranscriptForRetry(m_handshakeHash); buf.UpdateHash(m_handshakeHash); this.m_connectionState = CS_SERVER_HELLO_RETRY_REQUEST; Send13ClientHelloRetry(); - m_handshakeHash.SealHashAlgorithms(); this.m_connectionState = CS_CLIENT_HELLO_RETRY; } else { ProcessServerHello(serverHello); m_handshakeHash.NotifyPrfDetermined(); + if (TlsUtilities.IsTlsV13(securityParameters.NegotiatedVersion)) + { + m_handshakeHash.SealHashAlgorithms(); + } buf.UpdateHash(m_handshakeHash); this.m_connectionState = CS_SERVER_HELLO; if (TlsUtilities.IsTlsV13(securityParameters.NegotiatedVersion)) { - m_handshakeHash.SealHashAlgorithms(); Process13ServerHelloCoda(serverHello, false); } } @@ -527,61 +534,70 @@ protected override void HandleHandshakeMessage(short type, HandshakeMessageInput this.m_connectionState = CS_SERVER_HELLO_DONE; - IList clientSupplementalData = m_tlsClient.GetClientSupplementalData(); - if (clientSupplementalData != null) + TlsCredentials clientAuthCredentials = null; + TlsCredentialedSigner clientAuthSigner = null; + Certificate clientAuthCertificate = null; + SignatureAndHashAlgorithm clientAuthAlgorithm = null; + TlsStreamSigner clientAuthStreamSigner = null; + + if (m_certificateRequest != null) { - SendSupplementalDataMessage(clientSupplementalData); - this.m_connectionState = CS_CLIENT_SUPPLEMENTAL_DATA; - } + clientAuthCredentials = TlsUtilities.EstablishClientCredentials(m_authentication, + m_certificateRequest); + if (clientAuthCredentials != null) + { + clientAuthCertificate = clientAuthCredentials.Certificate; - TlsCredentialedSigner credentialedSigner = null; - TlsStreamSigner streamSigner = null; + if (clientAuthCredentials is TlsCredentialedSigner) + { + clientAuthSigner = (TlsCredentialedSigner)clientAuthCredentials; + clientAuthAlgorithm = TlsUtilities.GetSignatureAndHashAlgorithm( + securityParameters.NegotiatedVersion, clientAuthSigner); + clientAuthStreamSigner = clientAuthSigner.GetStreamSigner(); - if (m_certificateRequest == null) + if (ProtocolVersion.TLSv12.Equals(securityParameters.NegotiatedVersion)) { - m_keyExchange.SkipClientCredentials(); + TlsUtilities.VerifySupportedSignatureAlgorithm(securityParameters.ServerSigAlgs, + clientAuthAlgorithm, AlertDescription.internal_error); + + if (clientAuthStreamSigner == null) + { + TlsUtilities.TrackHashAlgorithmClient(m_handshakeHash, clientAuthAlgorithm); } - else + } + + if (clientAuthStreamSigner != null) { - Certificate clientCertificate = null; + m_handshakeHash.ForceBuffering(); + } + } + } + } - TlsCredentials clientCredentials = TlsUtilities.EstablishClientCredentials(m_authentication, - m_certificateRequest); - if (null == clientCredentials) + m_handshakeHash.SealHashAlgorithms(); + + if (clientAuthCredentials == null) { m_keyExchange.SkipClientCredentials(); - - /* - * RFC 5246 If no suitable certificate is available, the client MUST send a - * certificate message containing no certificates. - * - * NOTE: In previous RFCs, this was SHOULD instead of MUST. - */ } else { - m_keyExchange.ProcessClientCredentials(clientCredentials); - - clientCertificate = clientCredentials.Certificate; + m_keyExchange.ProcessClientCredentials(clientAuthCredentials); + } - if (clientCredentials is TlsCredentialedSigner) + var clientSupplementalData = m_tlsClient.GetClientSupplementalData(); + if (clientSupplementalData != null) { - credentialedSigner = (TlsCredentialedSigner)clientCredentials; - streamSigner = credentialedSigner.GetStreamSigner(); - } + SendSupplementalDataMessage(clientSupplementalData); + this.m_connectionState = CS_CLIENT_SUPPLEMENTAL_DATA; } - SendCertificateMessage(clientCertificate, null); + if (m_certificateRequest != null) + { + SendCertificateMessage(clientAuthCertificate, null); this.m_connectionState = CS_CLIENT_CERTIFICATE; } - bool forceBuffering = streamSigner != null; - TlsUtilities.SealHandshakeHash(m_tlsClientContext, m_handshakeHash, forceBuffering); - - /* - * Send the client key exchange message, depending on the key exchange we are using - * in our CipherSuite. - */ SendClientKeyExchange(); this.m_connectionState = CS_CLIENT_KEY_EXCHANGE; @@ -602,15 +618,16 @@ protected override void HandleHandshakeMessage(short type, HandshakeMessageInput m_recordStream.SetPendingCipher(TlsUtilities.InitCipher(m_tlsClientContext)); - if (credentialedSigner != null) + if (clientAuthSigner != null) { DigitallySigned certificateVerify = TlsUtilities.GenerateCertificateVerifyClient( - m_tlsClientContext, credentialedSigner, streamSigner, m_handshakeHash); + m_tlsClientContext, clientAuthSigner, clientAuthAlgorithm, clientAuthStreamSigner, + m_handshakeHash); SendCertificateVerifyMessage(certificateVerify); this.m_connectionState = CS_CLIENT_CERTIFICATE_VERIFY; } - this.m_handshakeHash = m_handshakeHash.StopTracking(); + m_handshakeHash.StopTracking(); SendChangeCipherSpec(); SendFinishedMessage(); @@ -675,13 +692,6 @@ protected override void HandleHandshakeMessage(short type, HandshakeMessageInput ReceiveCertificateRequest(buf); TlsUtilities.EstablishServerSigAlgs(securityParameters, m_certificateRequest); - - /* - * TODO Give the client a chance to immediately select the CertificateVerify hash - * algorithm here to avoid tracking the other hash algorithms unnecessarily? - */ - TlsUtilities.TrackHashAlgorithms(m_handshakeHash, securityParameters.ServerSigAlgs); - break; } default: @@ -746,6 +756,7 @@ protected override void HandleHandshakeMessage(short type, HandshakeMessageInput case HandshakeType.certificate_verify: case HandshakeType.client_hello: case HandshakeType.client_key_exchange: + case HandshakeType.compressed_certificate: case HandshakeType.encrypted_extensions: case HandshakeType.end_of_early_data: case HandshakeType.hello_verify_request: @@ -764,7 +775,7 @@ protected virtual void HandleServerCertificate() } /// - protected virtual void HandleSupplementalData(IList serverSupplementalData) + protected virtual void HandleSupplementalData(IList serverSupplementalData) { m_tlsClient.ProcessServerSupplementalData(serverSupplementalData); this.m_connectionState = CS_SERVER_SUPPLEMENTAL_DATA; @@ -802,7 +813,7 @@ protected virtual void Process13HelloRetryRequest(ServerHello helloRetryRequest) throw new TlsFatalAlert(AlertDescription.illegal_parameter); } - IDictionary extensions = helloRetryRequest.Extensions; + var extensions = helloRetryRequest.Extensions; if (null == extensions) throw new TlsFatalAlert(AlertDescription.illegal_parameter); @@ -870,7 +881,7 @@ protected virtual void Process13HelloRetryRequest(ServerHello helloRetryRequest) securityParameters.m_negotiatedVersion = server_version; TlsUtilities.NegotiatedVersionTlsClient(m_tlsClientContext, m_tlsClient); - this.m_resumedSession = false; + securityParameters.m_resumedSession = false; securityParameters.m_sessionID = TlsUtilities.EmptyBytes; m_tlsClient.NotifySessionID(TlsUtilities.EmptyBytes); @@ -898,7 +909,7 @@ protected virtual void Process13ServerHello(ServerHello serverHello, bool afterH throw new TlsFatalAlert(AlertDescription.illegal_parameter); } - IDictionary extensions = serverHello.Extensions; + var extensions = serverHello.Extensions; if (null == extensions) throw new TlsFatalAlert(AlertDescription.illegal_parameter); @@ -925,7 +936,7 @@ protected virtual void Process13ServerHello(ServerHello serverHello, bool afterH throw new TlsFatalAlert(AlertDescription.illegal_parameter); } - this.m_resumedSession = false; + securityParameters.m_resumedSession = false; securityParameters.m_sessionID = TlsUtilities.EmptyBytes; m_tlsClient.NotifySessionID(TlsUtilities.EmptyBytes); @@ -952,7 +963,8 @@ protected virtual void Process13ServerHello(ServerHello serverHello, bool afterH * * OCSP information is carried in an extension for a CertificateEntry. */ - securityParameters.m_statusRequestVersion = m_clientExtensions.Contains(ExtensionType.status_request) ? 1 : 0; + securityParameters.m_statusRequestVersion = + m_clientExtensions.ContainsKey(ExtensionType.status_request) ? 1 : 0; TlsSecret pskEarlySecret = null; { @@ -1044,7 +1056,7 @@ protected virtual void Process13ServerHelloCoda(ServerHello serverHello, bool af /// protected virtual void ProcessServerHello(ServerHello serverHello) { - IDictionary serverHelloExtensions = serverHello.Extensions; + var serverHelloExtensions = serverHello.Extensions; ProtocolVersion legacy_version = serverHello.Version; ProtocolVersion supported_version = TlsExtensionsUtilities.GetSupportedVersionsExtensionServer( @@ -1114,7 +1126,7 @@ protected virtual void ProcessServerHello(ServerHello serverHello) byte[] selectedSessionID = serverHello.SessionID; securityParameters.m_sessionID = selectedSessionID; m_tlsClient.NotifySessionID(selectedSessionID); - this.m_resumedSession = selectedSessionID.Length > 0 && m_tlsSession != null + securityParameters.m_resumedSession = selectedSessionID.Length > 0 && m_tlsSession != null && Arrays.AreEqual(selectedSessionID, m_tlsSession.SessionID); } @@ -1172,7 +1184,7 @@ protected virtual void ProcessServerHello(ServerHello serverHello) * extensions appearing in the client hello, and send a server hello containing no * extensions[.] */ - if (m_resumedSession) + if (securityParameters.IsResumedSession) { // TODO[compat-gnutls] GnuTLS test server sends server extensions e.g. ec_point_formats // TODO[compat-openssl] OpenSSL test server sends server extensions e.g. ec_point_formats @@ -1268,11 +1280,12 @@ protected virtual void ProcessServerHello(ServerHello serverHello) { bool acceptedExtendedMasterSecret = TlsExtensionsUtilities.HasExtendedMasterSecretExtension( m_serverExtensions); + bool resumedSession = securityParameters.IsResumedSession; if (acceptedExtendedMasterSecret) { if (server_version.IsSsl - || (!m_resumedSession && !m_tlsClient.ShouldUseExtendedMasterSecret())) + || (!resumedSession && !m_tlsClient.ShouldUseExtendedMasterSecret())) { throw new TlsFatalAlert(AlertDescription.handshake_failure); } @@ -1280,7 +1293,7 @@ protected virtual void ProcessServerHello(ServerHello serverHello) else { if (m_tlsClient.RequiresExtendedMasterSecret() - || (m_resumedSession && !m_tlsClient.AllowLegacyResumption())) + || (resumedSession && !m_tlsClient.AllowLegacyResumption())) { throw new TlsFatalAlert(AlertDescription.handshake_failure); } @@ -1298,8 +1311,9 @@ protected virtual void ProcessServerHello(ServerHello serverHello) m_serverExtensions); securityParameters.m_applicationProtocolSet = true; - IDictionary sessionClientExtensions = m_clientExtensions, sessionServerExtensions = m_serverExtensions; - if (m_resumedSession) + var sessionClientExtensions = m_clientExtensions; + var sessionServerExtensions = m_serverExtensions; + if (securityParameters.IsResumedSession) { if (securityParameters.CipherSuite != m_sessionParameters.CipherSuite || !server_version.Equals(m_sessionParameters.NegotiatedVersion)) @@ -1338,7 +1352,7 @@ protected virtual void ProcessServerHello(ServerHello serverHello) * TODO It's surprising that there's no provision to allow a 'fresh' CertificateStatus to be sent in * a session resumption handshake. */ - if (!m_resumedSession) + if (!securityParameters.IsResumedSession) { // TODO[tls13] See RFC 8446 4.4.2.1 if (TlsUtilities.HasExpectedEmptyExtensionData(sessionServerExtensions, @@ -1364,7 +1378,7 @@ protected virtual void ProcessServerHello(ServerHello serverHello) ApplyMaxFragmentLengthExtension(securityParameters.MaxFragmentLength); - if (m_resumedSession) + if (securityParameters.IsResumedSession) { securityParameters.m_masterSecret = m_sessionMasterSecret; m_recordStream.SetPendingCipher(TlsUtilities.InitCipher(m_tlsClientContext)); @@ -1400,9 +1414,22 @@ protected virtual void Receive13CertificateRequest(MemoryStream buf, bool postHa this.m_certificateRequest = certificateRequest; + m_tlsClientContext.SecurityParameters.m_clientCertificateType = + TlsExtensionsUtilities.GetClientCertificateTypeExtensionServer(m_serverExtensions, + CertificateType.X509); + TlsUtilities.EstablishServerSigAlgs(m_tlsClientContext.SecurityParameters, certificateRequest); } + protected override void Send13CertificateMessage(Certificate certificate) + { + // Create a new certificate with the current context. + certificate = new Certificate(this.m_certificateRequest.GetCertificateRequestContext(), certificate.GetCertificateEntryList()); + + // call base's implementation with the new certificate + base.Send13CertificateMessage(certificate); + } + /// protected virtual void Receive13EncryptedExtensions(MemoryStream buf) { @@ -1435,8 +1462,9 @@ protected virtual void Receive13EncryptedExtensions(MemoryStream buf) m_serverExtensions); securityParameters.m_applicationProtocolSet = true; - IDictionary sessionClientExtensions = m_clientExtensions, sessionServerExtensions = m_serverExtensions; - if (m_resumedSession) + var sessionClientExtensions = m_clientExtensions; + var sessionServerExtensions = m_serverExtensions; + if (securityParameters.IsResumedSession) { if (securityParameters.CipherSuite != m_sessionParameters.CipherSuite || !negotiatedVersion.Equals(m_sessionParameters.NegotiatedVersion)) @@ -1459,8 +1487,8 @@ protected virtual void Receive13EncryptedExtensions(MemoryStream buf) * * OCSP information is carried in an extension for a CertificateEntry. */ - securityParameters.m_statusRequestVersion = m_clientExtensions.Contains(ExtensionType.status_request) - ? 1 : 0; + securityParameters.m_statusRequestVersion = + m_clientExtensions.ContainsKey(ExtensionType.status_request) ? 1 : 0; this.m_expectSessionTicket = false; @@ -1502,7 +1530,8 @@ protected virtual void Receive13ServerCertificate(MemoryStream buf) if (m_selectedPsk13) throw new TlsFatalAlert(AlertDescription.unexpected_message); - this.m_authentication = TlsUtilities.Receive13ServerCertificate(m_tlsClientContext, m_tlsClient, buf); + m_authentication = TlsUtilities.Receive13ServerCertificate(m_tlsClientContext, m_tlsClient, buf, + m_serverExtensions); // NOTE: In TLS 1.3 we don't have to wait for a possible CertificateStatus message. HandleServerCertificate(); @@ -1515,12 +1544,11 @@ protected virtual void Receive13ServerCertificateVerify(MemoryStream buf) if (null == serverCertificate || serverCertificate.IsEmpty) throw new TlsFatalAlert(AlertDescription.internal_error); - // TODO[tls13] Actual structure is 'CertificateVerify' in RFC 8446, consider adding for clarity - DigitallySigned certificateVerify = DigitallySigned.Parse(m_tlsClientContext, buf); + CertificateVerify certificateVerify = CertificateVerify.Parse(m_tlsClientContext, buf); AssertEmpty(buf); - TlsUtilities.Verify13CertificateVerifyServer(m_tlsClientContext, certificateVerify, m_handshakeHash); + TlsUtilities.Verify13CertificateVerifyServer(m_tlsClientContext, m_handshakeHash, certificateVerify); } /// @@ -1545,7 +1573,11 @@ protected virtual void ReceiveCertificateRequest(MemoryStream buf) AssertEmpty(buf); - this.m_certificateRequest = TlsUtilities.ValidateCertificateRequest(certificateRequest, m_keyExchange); + m_certificateRequest = TlsUtilities.ValidateCertificateRequest(certificateRequest, m_keyExchange); + + m_tlsClientContext.SecurityParameters.m_clientCertificateType = + TlsExtensionsUtilities.GetClientCertificateTypeExtensionServer(m_serverExtensions, + CertificateType.X509); } /// @@ -1567,7 +1599,7 @@ protected virtual ServerHello ReceiveServerHelloMessage(MemoryStream buf) /// protected virtual void Send13ClientHelloRetry() { - IDictionary clientHelloExtensions = m_clientHello.Extensions; + var clientHelloExtensions = m_clientHello.Extensions; clientHelloExtensions.Remove(ExtensionType.cookie); clientHelloExtensions.Remove(ExtensionType.early_data); @@ -1651,8 +1683,8 @@ protected virtual void SendClientHello() SecurityParameters securityParameters = m_tlsClientContext.SecurityParameters; ProtocolVersion[] supportedVersions = m_tlsClient.GetProtocolVersions(); - ProtocolVersion earliestVersion = ProtocolVersion.GetEarliestTls(supportedVersions), - latestVersion = ProtocolVersion.GetLatestTls(supportedVersions); + ProtocolVersion earliestVersion = ProtocolVersion.GetEarliestTls(supportedVersions); + ProtocolVersion latestVersion = ProtocolVersion.GetLatestTls(supportedVersions); if (securityParameters.IsRenegotiating) { @@ -1684,6 +1716,12 @@ protected virtual void SendClientHello() bool offeringTlsV12Minus = ProtocolVersion.TLSv12.IsEqualOrLaterVersionOf(earliestVersion); bool offeringTlsV13Plus = ProtocolVersion.TLSv13.IsEqualOrEarlierVersionOf(latestVersion); + { + bool useGmtUnixTime = !offeringTlsV13Plus && m_tlsClient.ShouldUseGmtUnixTime(); + + securityParameters.m_clientRandom = CreateRandomBlock(useGmtUnixTime, m_tlsClientContext); + } + EstablishSession(offeringTlsV12Minus ? m_tlsClient.GetSessionToResume() : null); m_tlsClient.NotifySessionToResume(m_tlsSession); @@ -1756,11 +1794,11 @@ protected virtual void SendClientHello() throw new TlsFatalAlert(AlertDescription.internal_error); } - { - bool useGmtUnixTime = !offeringTlsV13Plus && m_tlsClient.ShouldUseGmtUnixTime(); - - securityParameters.m_clientRandom = CreateRandomBlock(useGmtUnixTime, m_tlsClientContext); - } +// { +// bool useGmtUnixTime = !offeringTlsV13Plus && m_tlsClient.ShouldUseGmtUnixTime(); +// +// securityParameters.m_clientRandom = CreateRandomBlock(useGmtUnixTime, m_tlsClientContext); +// } if (securityParameters.IsRenegotiating) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsException.cs index 76e51a9..5e10076 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsException.cs @@ -2,27 +2,34 @@ #pragma warning disable using System; using System.IO; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls { - public class TlsException + [Serializable] + public class TlsException : IOException { - public TlsException() - : base() - { - } + public TlsException() + : base() + { + } - public TlsException(string message) - : base(message) - { - } + public TlsException(string message) + : base(message) + { + } - public TlsException(string message, Exception cause) - : base(message, cause) - { - } - } + public TlsException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected TlsException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsExtensionsUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsExtensionsUtilities.cs index 7ecaa1e..3e0180d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsExtensionsUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsExtensionsUtilities.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; @@ -10,511 +10,553 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls { - public abstract class TlsExtensionsUtilities + public static class TlsExtensionsUtilities { - public static IDictionary EnsureExtensionsInitialised(IDictionary extensions) + public static IDictionary EnsureExtensionsInitialised(IDictionary extensions) { - return extensions == null ? BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable() : extensions; + return extensions == null ? new Dictionary() : extensions; } /// (Int32 -> byte[]) - /// an of . + /// an of . /// - public static void AddAlpnExtensionClient(IDictionary extensions, IList protocolNameList) + public static void AddAlpnExtensionClient(IDictionary extensions, + IList protocolNameList) { - extensions[ExtensionType.application_layer_protocol_negotiation] = CreateAlpnExtensionClient(protocolNameList); + extensions[ExtensionType.application_layer_protocol_negotiation] = + CreateAlpnExtensionClient(protocolNameList); } /// - public static void AddAlpnExtensionServer(IDictionary extensions, ProtocolName protocolName) + public static void AddAlpnExtensionServer(IDictionary extensions, ProtocolName protocolName) { extensions[ExtensionType.application_layer_protocol_negotiation] = CreateAlpnExtensionServer(protocolName); } /// - public static void AddCertificateAuthoritiesExtension(IDictionary extensions, IList authorities) + public static void AddCertificateAuthoritiesExtension(IDictionary extensions, + IList authorities) { extensions[ExtensionType.certificate_authorities] = CreateCertificateAuthoritiesExtension(authorities); } /// - public static void AddClientCertificateTypeExtensionClient(IDictionary extensions, short[] certificateTypes) + public static void AddClientCertificateTypeExtensionClient(IDictionary extensions, + short[] certificateTypes) { extensions[ExtensionType.client_certificate_type] = CreateCertificateTypeExtensionClient(certificateTypes); } /// - public static void AddClientCertificateTypeExtensionServer(IDictionary extensions, short certificateType) + public static void AddClientCertificateTypeExtensionServer(IDictionary extensions, + short certificateType) { extensions[ExtensionType.client_certificate_type] = CreateCertificateTypeExtensionServer(certificateType); } - public static void AddClientCertificateUrlExtension(IDictionary extensions) + public static void AddClientCertificateUrlExtension(IDictionary extensions) { extensions[ExtensionType.client_certificate_url] = CreateClientCertificateUrlExtension(); } /// - public static void AddCookieExtension(IDictionary extensions, byte[] cookie) + public static void AddCompressCertificateExtension(IDictionary extensions, int[] algorithms) + { + extensions[ExtensionType.compress_certificate] = CreateCompressCertificateExtension(algorithms); + } + + /// + public static void AddCookieExtension(IDictionary extensions, byte[] cookie) { extensions[ExtensionType.cookie] = CreateCookieExtension(cookie); } - public static void AddEarlyDataIndication(IDictionary extensions) + public static void AddEarlyDataIndication(IDictionary extensions) { extensions[ExtensionType.early_data] = CreateEarlyDataIndication(); } /// - public static void AddEarlyDataMaxSize(IDictionary extensions, long maxSize) + public static void AddEarlyDataMaxSize(IDictionary extensions, long maxSize) { extensions[ExtensionType.early_data] = CreateEarlyDataMaxSize(maxSize); } - public static void AddEmptyExtensionData(IDictionary extensions, Int32 extType) + public static void AddEmptyExtensionData(IDictionary extensions, int extType) { extensions[extType] = CreateEmptyExtensionData(); } - public static void AddEncryptThenMacExtension(IDictionary extensions) + public static void AddEncryptThenMacExtension(IDictionary extensions) { extensions[ExtensionType.encrypt_then_mac] = CreateEncryptThenMacExtension(); } - public static void AddExtendedMasterSecretExtension(IDictionary extensions) + public static void AddExtendedMasterSecretExtension(IDictionary extensions) { extensions[ExtensionType.extended_master_secret] = CreateExtendedMasterSecretExtension(); } /// - public static void AddHeartbeatExtension(IDictionary extensions, HeartbeatExtension heartbeatExtension) + public static void AddHeartbeatExtension(IDictionary extensions, + HeartbeatExtension heartbeatExtension) { extensions[ExtensionType.heartbeat] = CreateHeartbeatExtension(heartbeatExtension); } /// - public static void AddKeyShareClientHello(IDictionary extensions, IList clientShares) + public static void AddKeyShareClientHello(IDictionary extensions, + IList clientShares) { extensions[ExtensionType.key_share] = CreateKeyShareClientHello(clientShares); } /// - public static void AddKeyShareHelloRetryRequest(IDictionary extensions, int namedGroup) + public static void AddKeyShareHelloRetryRequest(IDictionary extensions, int namedGroup) { extensions[ExtensionType.key_share] = CreateKeyShareHelloRetryRequest(namedGroup); } /// - public static void AddKeyShareServerHello(IDictionary extensions, KeyShareEntry serverShare) + public static void AddKeyShareServerHello(IDictionary extensions, KeyShareEntry serverShare) { extensions[ExtensionType.key_share] = CreateKeyShareServerHello(serverShare); } /// - public static void AddMaxFragmentLengthExtension(IDictionary extensions, short maxFragmentLength) + public static void AddMaxFragmentLengthExtension(IDictionary extensions, short maxFragmentLength) { extensions[ExtensionType.max_fragment_length] = CreateMaxFragmentLengthExtension(maxFragmentLength); } /// - public static void AddOidFiltersExtension(IDictionary extensions, IDictionary filters) + public static void AddOidFiltersExtension(IDictionary extensions, + IDictionary filters) { extensions[ExtensionType.oid_filters] = CreateOidFiltersExtension(filters); } /// - public static void AddPaddingExtension(IDictionary extensions, int dataLength) + public static void AddPaddingExtension(IDictionary extensions, int dataLength) { extensions[ExtensionType.padding] = CreatePaddingExtension(dataLength); } - public static void AddPostHandshakeAuthExtension(IDictionary extensions) + public static void AddPostHandshakeAuthExtension(IDictionary extensions) { extensions[ExtensionType.post_handshake_auth] = CreatePostHandshakeAuthExtension(); } /// - public static void AddPreSharedKeyClientHello(IDictionary extensions, OfferedPsks offeredPsks) + public static void AddPreSharedKeyClientHello(IDictionary extensions, OfferedPsks offeredPsks) { extensions[ExtensionType.pre_shared_key] = CreatePreSharedKeyClientHello(offeredPsks); } /// - public static void AddPreSharedKeyServerHello(IDictionary extensions, int selectedIdentity) + public static void AddPreSharedKeyServerHello(IDictionary extensions, int selectedIdentity) { extensions[ExtensionType.pre_shared_key] = CreatePreSharedKeyServerHello(selectedIdentity); } /// - public static void AddPskKeyExchangeModesExtension(IDictionary extensions, short[] modes) + public static void AddPskKeyExchangeModesExtension(IDictionary extensions, short[] modes) { extensions[ExtensionType.psk_key_exchange_modes] = CreatePskKeyExchangeModesExtension(modes); } /// - public static void AddRecordSizeLimitExtension(IDictionary extensions, int recordSizeLimit) + public static void AddRecordSizeLimitExtension(IDictionary extensions, int recordSizeLimit) { extensions[ExtensionType.record_size_limit] = CreateRecordSizeLimitExtension(recordSizeLimit); } /// - public static void AddServerCertificateTypeExtensionClient(IDictionary extensions, short[] certificateTypes) + public static void AddServerCertificateTypeExtensionClient(IDictionary extensions, + short[] certificateTypes) { extensions[ExtensionType.server_certificate_type] = CreateCertificateTypeExtensionClient(certificateTypes); } /// - public static void AddServerCertificateTypeExtensionServer(IDictionary extensions, short certificateType) + public static void AddServerCertificateTypeExtensionServer(IDictionary extensions, + short certificateType) { extensions[ExtensionType.server_certificate_type] = CreateCertificateTypeExtensionServer(certificateType); } /// - public static void AddServerNameExtensionClient(IDictionary extensions, IList serverNameList) + public static void AddServerNameExtensionClient(IDictionary extensions, + IList serverNameList) { extensions[ExtensionType.server_name] = CreateServerNameExtensionClient(serverNameList); } /// - public static void AddServerNameExtensionServer(IDictionary extensions) + public static void AddServerNameExtensionServer(IDictionary extensions) { extensions[ExtensionType.server_name] = CreateServerNameExtensionServer(); } /// - public static void AddSignatureAlgorithmsExtension(IDictionary extensions, IList supportedSignatureAlgorithms) + public static void AddSignatureAlgorithmsExtension(IDictionary extensions, + IList supportedSignatureAlgorithms) { - extensions[ExtensionType.signature_algorithms] = CreateSignatureAlgorithmsExtension(supportedSignatureAlgorithms); + extensions[ExtensionType.signature_algorithms] = + CreateSignatureAlgorithmsExtension(supportedSignatureAlgorithms); } /// - public static void AddSignatureAlgorithmsCertExtension(IDictionary extensions, IList supportedSignatureAlgorithms) + public static void AddSignatureAlgorithmsCertExtension(IDictionary extensions, + IList supportedSignatureAlgorithms) { - extensions[ExtensionType.signature_algorithms_cert] = CreateSignatureAlgorithmsCertExtension(supportedSignatureAlgorithms); + extensions[ExtensionType.signature_algorithms_cert] = + CreateSignatureAlgorithmsCertExtension(supportedSignatureAlgorithms); } /// - public static void AddStatusRequestExtension(IDictionary extensions, CertificateStatusRequest statusRequest) + public static void AddStatusRequestExtension(IDictionary extensions, + CertificateStatusRequest statusRequest) { extensions[ExtensionType.status_request] = CreateStatusRequestExtension(statusRequest); } /// - public static void AddStatusRequestV2Extension(IDictionary extensions, IList statusRequestV2) + public static void AddStatusRequestV2Extension(IDictionary extensions, + IList statusRequestV2) { extensions[ExtensionType.status_request_v2] = CreateStatusRequestV2Extension(statusRequestV2); } /// - public static void AddSupportedGroupsExtension(IDictionary extensions, IList namedGroups) + public static void AddSupportedGroupsExtension(IDictionary extensions, IList namedGroups) { extensions[ExtensionType.supported_groups] = CreateSupportedGroupsExtension(namedGroups); } /// - public static void AddSupportedPointFormatsExtension(IDictionary extensions, short[] ecPointFormats) + public static void AddSupportedPointFormatsExtension(IDictionary extensions, + short[] ecPointFormats) { extensions[ExtensionType.ec_point_formats] = CreateSupportedPointFormatsExtension(ecPointFormats); } /// - public static void AddSupportedVersionsExtensionClient(IDictionary extensions, ProtocolVersion[] versions) + public static void AddSupportedVersionsExtensionClient(IDictionary extensions, + ProtocolVersion[] versions) { extensions[ExtensionType.supported_versions] = CreateSupportedVersionsExtensionClient(versions); } /// - public static void AddSupportedVersionsExtensionServer(IDictionary extensions, ProtocolVersion selectedVersion) + public static void AddSupportedVersionsExtensionServer(IDictionary extensions, + ProtocolVersion selectedVersion) { extensions[ExtensionType.supported_versions] = CreateSupportedVersionsExtensionServer(selectedVersion); } - public static void AddTruncatedHmacExtension(IDictionary extensions) + public static void AddTruncatedHmacExtension(IDictionary extensions) { extensions[ExtensionType.truncated_hmac] = CreateTruncatedHmacExtension(); } /// - public static void AddTrustedCAKeysExtensionClient(IDictionary extensions, IList trustedAuthoritiesList) + public static void AddTrustedCAKeysExtensionClient(IDictionary extensions, + IList trustedAuthoritiesList) { extensions[ExtensionType.trusted_ca_keys] = CreateTrustedCAKeysExtensionClient(trustedAuthoritiesList); } - public static void AddTrustedCAKeysExtensionServer(IDictionary extensions) + public static void AddTrustedCAKeysExtensionServer(IDictionary extensions) { extensions[ExtensionType.trusted_ca_keys] = CreateTrustedCAKeysExtensionServer(); } - /// an of . + /// an of . /// - public static IList GetAlpnExtensionClient(IDictionary extensions) + public static IList GetAlpnExtensionClient(IDictionary extensions) { - byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.application_layer_protocol_negotiation); + byte[] extensionData = TlsUtilities.GetExtensionData(extensions, + ExtensionType.application_layer_protocol_negotiation); return extensionData == null ? null : ReadAlpnExtensionClient(extensionData); } /// - public static ProtocolName GetAlpnExtensionServer(IDictionary extensions) + public static ProtocolName GetAlpnExtensionServer(IDictionary extensions) { - byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.application_layer_protocol_negotiation); + byte[] extensionData = TlsUtilities.GetExtensionData(extensions, + ExtensionType.application_layer_protocol_negotiation); return extensionData == null ? null : ReadAlpnExtensionServer(extensionData); } /// - public static IList GetCertificateAuthoritiesExtension(IDictionary extensions) + public static IList GetCertificateAuthoritiesExtension(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.certificate_authorities); return extensionData == null ? null : ReadCertificateAuthoritiesExtension(extensionData); } /// - public static short[] GetClientCertificateTypeExtensionClient(IDictionary extensions) + public static short[] GetClientCertificateTypeExtensionClient(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.client_certificate_type); return extensionData == null ? null : ReadCertificateTypeExtensionClient(extensionData); } /// - public static short GetClientCertificateTypeExtensionServer(IDictionary extensions) + public static short GetClientCertificateTypeExtensionServer(IDictionary extensions, + short defaultValue) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.client_certificate_type); - return extensionData == null ? (short)-1 : ReadCertificateTypeExtensionServer(extensionData); + return extensionData == null ? defaultValue : ReadCertificateTypeExtensionServer(extensionData); + } + + /// + public static int[] GetCompressCertificateExtension(IDictionary extensions) + { + byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.compress_certificate); + return extensionData == null ? null : ReadCompressCertificateExtension(extensionData); } /// - public static byte[] GetCookieExtension(IDictionary extensions) + public static byte[] GetCookieExtension(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.cookie); return extensionData == null ? null : ReadCookieExtension(extensionData); } /// - public static long GetEarlyDataMaxSize(IDictionary extensions) + public static long GetEarlyDataMaxSize(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.early_data); return extensionData == null ? -1L : ReadEarlyDataMaxSize(extensionData); } /// - public static HeartbeatExtension GetHeartbeatExtension(IDictionary extensions) + public static HeartbeatExtension GetHeartbeatExtension(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.heartbeat); return extensionData == null ? null : ReadHeartbeatExtension(extensionData); } /// - public static IList GetKeyShareClientHello(IDictionary extensions) + public static IList GetKeyShareClientHello(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.key_share); return extensionData == null ? null : ReadKeyShareClientHello(extensionData); } /// - public static int GetKeyShareHelloRetryRequest(IDictionary extensions) + public static int GetKeyShareHelloRetryRequest(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.key_share); return extensionData == null ? -1 : ReadKeyShareHelloRetryRequest(extensionData); } /// - public static KeyShareEntry GetKeyShareServerHello(IDictionary extensions) + public static KeyShareEntry GetKeyShareServerHello(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.key_share); return extensionData == null ? null : ReadKeyShareServerHello(extensionData); } /// - public static short GetMaxFragmentLengthExtension(IDictionary extensions) + public static short GetMaxFragmentLengthExtension(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.max_fragment_length); return extensionData == null ? (short)-1 : ReadMaxFragmentLengthExtension(extensionData); } /// - public static IDictionary GetOidFiltersExtension(IDictionary extensions) + public static IDictionary GetOidFiltersExtension( + IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.oid_filters); return extensionData == null ? null : ReadOidFiltersExtension(extensionData); } /// - public static int GetPaddingExtension(IDictionary extensions) + public static int GetPaddingExtension(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.padding); return extensionData == null ? -1 : ReadPaddingExtension(extensionData); } /// - public static OfferedPsks GetPreSharedKeyClientHello(IDictionary extensions) + public static OfferedPsks GetPreSharedKeyClientHello(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.pre_shared_key); return extensionData == null ? null : ReadPreSharedKeyClientHello(extensionData); } /// - public static int GetPreSharedKeyServerHello(IDictionary extensions) + public static int GetPreSharedKeyServerHello(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.pre_shared_key); return extensionData == null ? -1 : ReadPreSharedKeyServerHello(extensionData); } /// - public static short[] GetPskKeyExchangeModesExtension(IDictionary extensions) + public static short[] GetPskKeyExchangeModesExtension(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.psk_key_exchange_modes); return extensionData == null ? null : ReadPskKeyExchangeModesExtension(extensionData); } /// - public static int GetRecordSizeLimitExtension(IDictionary extensions) + public static int GetRecordSizeLimitExtension(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.record_size_limit); return extensionData == null ? -1 : ReadRecordSizeLimitExtension(extensionData); } /// - public static short[] GetServerCertificateTypeExtensionClient(IDictionary extensions) + public static short[] GetServerCertificateTypeExtensionClient(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.server_certificate_type); return extensionData == null ? null : ReadCertificateTypeExtensionClient(extensionData); } /// - public static short GetServerCertificateTypeExtensionServer(IDictionary extensions) + public static short GetServerCertificateTypeExtensionServer(IDictionary extensions, + short defaultValue) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.server_certificate_type); - return extensionData == null ? (short)-1 : ReadCertificateTypeExtensionServer(extensionData); + return extensionData == null ? defaultValue : ReadCertificateTypeExtensionServer(extensionData); } /// - public static IList GetServerNameExtensionClient(IDictionary extensions) + public static IList GetServerNameExtensionClient(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.server_name); return extensionData == null ? null : ReadServerNameExtensionClient(extensionData); } /// - public static IList GetSignatureAlgorithmsExtension(IDictionary extensions) + public static IList GetSignatureAlgorithmsExtension( + IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.signature_algorithms); return extensionData == null ? null : ReadSignatureAlgorithmsExtension(extensionData); } /// - public static IList GetSignatureAlgorithmsCertExtension(IDictionary extensions) + public static IList GetSignatureAlgorithmsCertExtension( + IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.signature_algorithms_cert); return extensionData == null ? null : ReadSignatureAlgorithmsCertExtension(extensionData); } /// - public static CertificateStatusRequest GetStatusRequestExtension(IDictionary extensions) + public static CertificateStatusRequest GetStatusRequestExtension(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.status_request); return extensionData == null ? null : ReadStatusRequestExtension(extensionData); } /// - public static IList GetStatusRequestV2Extension(IDictionary extensions) + public static IList GetStatusRequestV2Extension( + IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.status_request_v2); return extensionData == null ? null : ReadStatusRequestV2Extension(extensionData); } /// - public static int[] GetSupportedGroupsExtension(IDictionary extensions) + public static int[] GetSupportedGroupsExtension(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.supported_groups); return extensionData == null ? null : ReadSupportedGroupsExtension(extensionData); } /// - public static short[] GetSupportedPointFormatsExtension(IDictionary extensions) + public static short[] GetSupportedPointFormatsExtension(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.ec_point_formats); return extensionData == null ? null : ReadSupportedPointFormatsExtension(extensionData); } /// - public static ProtocolVersion[] GetSupportedVersionsExtensionClient(IDictionary extensions) + public static ProtocolVersion[] GetSupportedVersionsExtensionClient(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.supported_versions); return extensionData == null ? null : ReadSupportedVersionsExtensionClient(extensionData); } /// - public static ProtocolVersion GetSupportedVersionsExtensionServer(IDictionary extensions) + public static ProtocolVersion GetSupportedVersionsExtensionServer(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.supported_versions); return extensionData == null ? null : ReadSupportedVersionsExtensionServer(extensionData); } /// - public static IList GetTrustedCAKeysExtensionClient(IDictionary extensions) + public static IList GetTrustedCAKeysExtensionClient(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.trusted_ca_keys); return extensionData == null ? null : ReadTrustedCAKeysExtensionClient(extensionData); } /// - public static bool HasClientCertificateUrlExtension(IDictionary extensions) + public static bool HasClientCertificateUrlExtension(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.client_certificate_url); return extensionData == null ? false : ReadClientCertificateUrlExtension(extensionData); } /// - public static bool HasEarlyDataIndication(IDictionary extensions) + public static bool HasEarlyDataIndication(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.early_data); return extensionData == null ? false : ReadEarlyDataIndication(extensionData); } /// - public static bool HasEncryptThenMacExtension(IDictionary extensions) + public static bool HasEncryptThenMacExtension(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.encrypt_then_mac); return extensionData == null ? false : ReadEncryptThenMacExtension(extensionData); } /// - public static bool HasExtendedMasterSecretExtension(IDictionary extensions) + public static bool HasExtendedMasterSecretExtension(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.extended_master_secret); return extensionData == null ? false : ReadExtendedMasterSecretExtension(extensionData); } /// - public static bool HasServerNameExtensionServer(IDictionary extensions) + public static bool HasServerNameExtensionServer(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.server_name); return extensionData == null ? false : ReadServerNameExtensionServer(extensionData); } /// - public static bool HasPostHandshakeAuthExtension(IDictionary extensions) + public static bool HasPostHandshakeAuthExtension(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.post_handshake_auth); return extensionData == null ? false : ReadPostHandshakeAuthExtension(extensionData); } /// - public static bool HasTruncatedHmacExtension(IDictionary extensions) + public static bool HasTruncatedHmacExtension(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.truncated_hmac); return extensionData == null ? false : ReadTruncatedHmacExtension(extensionData); } /// - public static bool HasTrustedCAKeysExtensionServer(IDictionary extensions) + public static bool HasTrustedCAKeysExtensionServer(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.trusted_ca_keys); return extensionData == null ? false : ReadTrustedCAKeysExtensionServer(extensionData); } - /// an of . + /// an of . /// - public static byte[] CreateAlpnExtensionClient(IList protocolNameList) + public static byte[] CreateAlpnExtensionClient(IList protocolNameList) { if (protocolNameList == null || protocolNameList.Count < 1) throw new TlsFatalAlert(AlertDescription.internal_error); @@ -535,14 +577,14 @@ public static byte[] CreateAlpnExtensionClient(IList protocolNameList) /// public static byte[] CreateAlpnExtensionServer(ProtocolName protocolName) { - IList protocol_name_list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var protocol_name_list = new List(); protocol_name_list.Add(protocolName); return CreateAlpnExtensionClient(protocol_name_list); } /// - public static byte[] CreateCertificateAuthoritiesExtension(IList authorities) + public static byte[] CreateCertificateAuthoritiesExtension(IList authorities) { if (null == authorities || authorities.Count < 1) throw new TlsFatalAlert(AlertDescription.internal_error); @@ -581,6 +623,15 @@ public static byte[] CreateClientCertificateUrlExtension() return CreateEmptyExtensionData(); } + /// + public static byte[] CreateCompressCertificateExtension(int[] algorithms) + { + if (TlsUtilities.IsNullOrEmpty(algorithms) || algorithms.Length > 127) + throw new TlsFatalAlert(AlertDescription.internal_error); + + return TlsUtilities.EncodeUint16ArrayWithUint8Length(algorithms); + } + /// public static byte[] CreateCookieExtension(byte[] cookie) { @@ -632,7 +683,7 @@ public static byte[] CreateHeartbeatExtension(HeartbeatExtension heartbeatExtens } /// - public static byte[] CreateKeyShareClientHello(IList clientShares) + public static byte[] CreateKeyShareClientHello(IList clientShares) { if (clientShares == null || clientShares.Count < 1) return TlsUtilities.EncodeUint16(0); @@ -678,7 +729,7 @@ public static byte[] CreateMaxFragmentLengthExtension(short maxFragmentLength) } /// - public static byte[] CreateOidFiltersExtension(IDictionary filters) + public static byte[] CreateOidFiltersExtension(IDictionary filters) { MemoryStream buf = new MemoryStream(); @@ -687,9 +738,11 @@ public static byte[] CreateOidFiltersExtension(IDictionary filters) if (null != filters) { - foreach (DerObjectIdentifier certificateExtensionOid in filters.Keys) + //foreach (DerObjectIdentifier certificateExtensionOid in filters.Keys) + foreach (var filter in filters) { - byte[] certificateExtensionValues = (byte[])filters[certificateExtensionOid]; + var certificateExtensionOid = filter.Key; + var certificateExtensionValues = filter.Value; if (null == certificateExtensionOid || null == certificateExtensionValues) throw new TlsFatalAlert(AlertDescription.internal_error); @@ -754,7 +807,7 @@ public static byte[] CreateRecordSizeLimitExtension(int recordSizeLimit) } /// - public static byte[] CreateServerNameExtensionClient(IList serverNameList) + public static byte[] CreateServerNameExtensionClient(IList serverNameList) { if (serverNameList == null) throw new TlsFatalAlert(AlertDescription.internal_error); @@ -772,7 +825,8 @@ public static byte[] CreateServerNameExtensionServer() } /// - public static byte[] CreateSignatureAlgorithmsExtension(IList supportedSignatureAlgorithms) + public static byte[] CreateSignatureAlgorithmsExtension( + IList supportedSignatureAlgorithms) { MemoryStream buf = new MemoryStream(); @@ -782,7 +836,8 @@ public static byte[] CreateSignatureAlgorithmsExtension(IList supportedSignature } /// - public static byte[] CreateSignatureAlgorithmsCertExtension(IList supportedSignatureAlgorithms) + public static byte[] CreateSignatureAlgorithmsCertExtension( + IList supportedSignatureAlgorithms) { return CreateSignatureAlgorithmsExtension(supportedSignatureAlgorithms); } @@ -801,7 +856,7 @@ public static byte[] CreateStatusRequestExtension(CertificateStatusRequest statu } /// - public static byte[] CreateStatusRequestV2Extension(IList statusRequestV2) + public static byte[] CreateStatusRequestV2Extension(IList statusRequestV2) { if (statusRequestV2 == null || statusRequestV2.Count < 1) throw new TlsFatalAlert(AlertDescription.internal_error); @@ -820,7 +875,7 @@ public static byte[] CreateStatusRequestV2Extension(IList statusRequestV2) } /// - public static byte[] CreateSupportedGroupsExtension(IList namedGroups) + public static byte[] CreateSupportedGroupsExtension(IList namedGroups) { if (namedGroups == null || namedGroups.Count < 1) throw new TlsFatalAlert(AlertDescription.internal_error); @@ -829,7 +884,7 @@ public static byte[] CreateSupportedGroupsExtension(IList namedGroups) int[] values = new int[count]; for (int i = 0; i < count; ++i) { - values[i] = (Int32)namedGroups[i]; + values[i] = namedGroups[i]; } return TlsUtilities.EncodeUint16ArrayWithUint16Length(values); @@ -863,7 +918,7 @@ public static byte[] CreateSupportedVersionsExtensionClient(ProtocolVersion[] ve TlsUtilities.WriteUint8(count * 2, data, 0); for (int i = 0; i < count; ++i) { - TlsUtilities.WriteVersion((ProtocolVersion)versions[i], data, 1 + i * 2); + TlsUtilities.WriteVersion(versions[i], data, 1 + i * 2); } return data; } @@ -880,7 +935,7 @@ public static byte[] CreateTruncatedHmacExtension() } /// - public static byte[] CreateTrustedCAKeysExtensionClient(IList trustedAuthoritiesList) + public static byte[] CreateTrustedCAKeysExtensionClient(IList trustedAuthoritiesList) { MemoryStream buf = new MemoryStream(); @@ -915,9 +970,9 @@ private static bool ReadEmptyExtensionData(byte[] extensionData) return true; } - /// an of . + /// an of . /// - public static IList ReadAlpnExtensionClient(byte[] extensionData) + public static IList ReadAlpnExtensionClient(byte[] extensionData) { if (extensionData == null) throw new ArgumentNullException("extensionData"); @@ -928,7 +983,7 @@ public static IList ReadAlpnExtensionClient(byte[] extensionData) if (length != (extensionData.Length - 2)) throw new TlsFatalAlert(AlertDescription.decode_error); - IList protocol_name_list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var protocol_name_list = new List(); while (buf.Position < buf.Length) { ProtocolName protocolName = ProtocolName.Parse(buf); @@ -941,15 +996,15 @@ public static IList ReadAlpnExtensionClient(byte[] extensionData) /// public static ProtocolName ReadAlpnExtensionServer(byte[] extensionData) { - IList protocol_name_list = ReadAlpnExtensionClient(extensionData); + var protocol_name_list = ReadAlpnExtensionClient(extensionData); if (protocol_name_list.Count != 1) throw new TlsFatalAlert(AlertDescription.decode_error); - return (ProtocolName)protocol_name_list[0]; + return protocol_name_list[0]; } /// - public static IList ReadCertificateAuthoritiesExtension(byte[] extensionData) + public static IList ReadCertificateAuthoritiesExtension(byte[] extensionData) { if (extensionData == null) throw new ArgumentNullException("extensionData"); @@ -962,12 +1017,14 @@ public static IList ReadCertificateAuthoritiesExtension(byte[] extensionData) if (length != (extensionData.Length - 2)) throw new TlsFatalAlert(AlertDescription.decode_error); - IList authorities = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var authorities = new List(); while (buf.Position < buf.Length) { byte[] derEncoding = TlsUtilities.ReadOpaque16(buf, 1); - Asn1Object asn1 = TlsUtilities.ReadDerObject(derEncoding); - authorities.Add(X509Name.GetInstance(asn1)); + Asn1Object asn1 = TlsUtilities.ReadAsn1Object(derEncoding); + X509Name ca = X509Name.GetInstance(asn1); + TlsUtilities.RequireDerEncoding(ca, derEncoding); + authorities.Add(ca); } return authorities; } @@ -994,6 +1051,16 @@ public static bool ReadClientCertificateUrlExtension(byte[] extensionData) return ReadEmptyExtensionData(extensionData); } + /// + public static int[] ReadCompressCertificateExtension(byte[] extensionData) + { + int[] algorithms = TlsUtilities.DecodeUint16ArrayWithUint8Length(extensionData); + if (algorithms.Length < 1) + throw new TlsFatalAlert(AlertDescription.decode_error); + + return algorithms; + } + /// public static byte[] ReadCookieExtension(byte[] extensionData) { @@ -1040,7 +1107,7 @@ public static HeartbeatExtension ReadHeartbeatExtension(byte[] extensionData) } /// - public static IList ReadKeyShareClientHello(byte[] extensionData) + public static IList ReadKeyShareClientHello(byte[] extensionData) { if (extensionData == null) throw new ArgumentNullException("extensionData"); @@ -1058,7 +1125,7 @@ public static IList ReadKeyShareClientHello(byte[] extensionData) if (length != (extensionData.Length - 2)) throw new TlsFatalAlert(AlertDescription.decode_error); - IList clientShares = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var clientShares = new List(); while (buf.Position < buf.Length) { KeyShareEntry clientShare = KeyShareEntry.Parse(buf); @@ -1096,7 +1163,7 @@ public static short ReadMaxFragmentLengthExtension(byte[] extensionData) } /// - public static IDictionary ReadOidFiltersExtension(byte[] extensionData) + public static IDictionary ReadOidFiltersExtension(byte[] extensionData) { if (extensionData == null) throw new ArgumentNullException("extensionData"); @@ -1109,14 +1176,15 @@ public static IDictionary ReadOidFiltersExtension(byte[] extensionData) if (length != (extensionData.Length - 2)) throw new TlsFatalAlert(AlertDescription.decode_error); - IDictionary filters = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + var filters = new Dictionary(); while (buf.Position < buf.Length) { byte[] derEncoding = TlsUtilities.ReadOpaque8(buf, 1); - Asn1Object asn1 = TlsUtilities.ReadDerObject(derEncoding); + Asn1Object asn1 = TlsUtilities.ReadAsn1Object(derEncoding); DerObjectIdentifier certificateExtensionOid = DerObjectIdentifier.GetInstance(asn1); + TlsUtilities.RequireDerEncoding(certificateExtensionOid, derEncoding); - if (filters.Contains(certificateExtensionOid)) + if (filters.ContainsKey(certificateExtensionOid)) throw new TlsFatalAlert(AlertDescription.illegal_parameter); byte[] certificateExtensionValues = TlsUtilities.ReadOpaque16(buf); @@ -1186,7 +1254,7 @@ public static int ReadRecordSizeLimitExtension(byte[] extensionData) } /// - public static IList ReadServerNameExtensionClient(byte[] extensionData) + public static IList ReadServerNameExtensionClient(byte[] extensionData) { if (extensionData == null) throw new ArgumentNullException("extensionData"); @@ -1207,14 +1275,14 @@ public static bool ReadServerNameExtensionServer(byte[] extensionData) } /// - public static IList ReadSignatureAlgorithmsExtension(byte[] extensionData) + public static IList ReadSignatureAlgorithmsExtension(byte[] extensionData) { if (extensionData == null) throw new ArgumentNullException("extensionData"); MemoryStream buf = new MemoryStream(extensionData, false); - IList supported_signature_algorithms = TlsUtilities.ParseSupportedSignatureAlgorithms(buf); + var supported_signature_algorithms = TlsUtilities.ParseSupportedSignatureAlgorithms(buf); TlsProtocol.AssertEmpty(buf); @@ -1222,7 +1290,7 @@ public static IList ReadSignatureAlgorithmsExtension(byte[] extensionData) } /// - public static IList ReadSignatureAlgorithmsCertExtension(byte[] extensionData) + public static IList ReadSignatureAlgorithmsCertExtension(byte[] extensionData) { return ReadSignatureAlgorithmsExtension(extensionData); } @@ -1243,7 +1311,7 @@ public static CertificateStatusRequest ReadStatusRequestExtension(byte[] extensi } /// - public static IList ReadStatusRequestV2Extension(byte[] extensionData) + public static IList ReadStatusRequestV2Extension(byte[] extensionData) { if (extensionData == null) throw new ArgumentNullException("extensionData"); @@ -1256,7 +1324,7 @@ public static IList ReadStatusRequestV2Extension(byte[] extensionData) if (length != (extensionData.Length - 2)) throw new TlsFatalAlert(AlertDescription.decode_error); - IList statusRequestV2 = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var statusRequestV2 = new List(); while (buf.Position < buf.Length) { CertificateStatusRequestItemV2 entry = CertificateStatusRequestItemV2.Parse(buf); @@ -1338,7 +1406,7 @@ public static bool ReadTruncatedHmacExtension(byte[] extensionData) } /// - public static IList ReadTrustedCAKeysExtensionClient(byte[] extensionData) + public static IList ReadTrustedCAKeysExtensionClient(byte[] extensionData) { if (extensionData == null) throw new ArgumentNullException("extensionData"); @@ -1351,7 +1419,7 @@ public static IList ReadTrustedCAKeysExtensionClient(byte[] extensionData) if (length != (extensionData.Length - 2)) throw new TlsFatalAlert(AlertDescription.decode_error); - IList trusted_authorities_list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var trusted_authorities_list = new List(); while (buf.Position < buf.Length) { TrustedAuthority entry = TrustedAuthority.Parse(buf); @@ -1369,7 +1437,7 @@ public static bool ReadTrustedCAKeysExtensionServer(byte[] extensionData) /// private static byte[] PatchOpaque16(MemoryStream buf) { - int length = (int)buf.Length - 2; + int length = Convert.ToInt32(buf.Length) - 2; TlsUtilities.CheckUint16(length); byte[] extensionData = buf.ToArray(); TlsUtilities.WriteUint16(length, extensionData, 0); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsFatalAlert.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsFatalAlert.cs index 5badcab..877b2d8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsFatalAlert.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsFatalAlert.cs @@ -1,9 +1,11 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls { + [Serializable] public class TlsFatalAlert : TlsException { @@ -17,10 +19,10 @@ private static string GetMessage(short alertDescription, string detailMessage) return msg; } - protected readonly short m_alertDescription; + protected readonly byte m_alertDescription; public TlsFatalAlert(short alertDescription) - : this(alertDescription, (string)null) + : this(alertDescription, null, null) { } @@ -37,7 +39,22 @@ public TlsFatalAlert(short alertDescription, Exception alertCause) public TlsFatalAlert(short alertDescription, string detailMessage, Exception alertCause) : base(GetMessage(alertDescription, detailMessage), alertCause) { - this.m_alertDescription = alertDescription; + if (!TlsUtilities.IsValidUint8(alertDescription)) + throw new ArgumentOutOfRangeException(nameof(alertDescription)); + + m_alertDescription = (byte)alertDescription; + } + + protected TlsFatalAlert(SerializationInfo info, StreamingContext context) + : base(info, context) + { + m_alertDescription = info.GetByte("alertDescription"); + } + + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddValue("alertDescription", m_alertDescription); } public virtual short AlertDescription diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsFatalAlertReceived.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsFatalAlertReceived.cs index 3cdc24e..54ae305 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsFatalAlertReceived.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsFatalAlertReceived.cs @@ -1,18 +1,35 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls { + [Serializable] public class TlsFatalAlertReceived : TlsException { - protected readonly short m_alertDescription; + protected readonly byte m_alertDescription; public TlsFatalAlertReceived(short alertDescription) : base(Tls.AlertDescription.GetText(alertDescription)) { - this.m_alertDescription = alertDescription; + if (!TlsUtilities.IsValidUint8(alertDescription)) + throw new ArgumentOutOfRangeException(nameof(alertDescription)); + + m_alertDescription = (byte)alertDescription; + } + + protected TlsFatalAlertReceived(SerializationInfo info, StreamingContext context) + : base(info, context) + { + m_alertDescription = info.GetByte("alertDescription"); + } + + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddValue("alertDescription", m_alertDescription); } public virtual short AlertDescription diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsHandshakeHash.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsHandshakeHash.cs index e018f74..b9e6f43 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsHandshakeHash.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsHandshakeHash.cs @@ -22,7 +22,7 @@ public interface TlsHandshakeHash void SealHashAlgorithms(); - TlsHandshakeHash StopTracking(); + void StopTracking(); TlsHash ForkPrfHash(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsNoCloseNotifyException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsNoCloseNotifyException.cs index 670f466..f10a55b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsNoCloseNotifyException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsNoCloseNotifyException.cs @@ -2,6 +2,7 @@ #pragma warning disable using System; using System.IO; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls { @@ -12,6 +13,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls /// malicious). It may be possible to check for truncation via some property of a higher level protocol /// built upon TLS, e.g.the Content-Length header for HTTPS. /// + [Serializable] public class TlsNoCloseNotifyException : EndOfStreamException { @@ -19,7 +21,12 @@ public TlsNoCloseNotifyException() : base("No close_notify alert received before connection closed") { } - } + + protected TlsNoCloseNotifyException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsPeer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsPeer.cs index 089cf8c..6518c87 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsPeer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsPeer.cs @@ -121,6 +121,13 @@ public interface TlsPeer /// /// the value. short GetHeartbeatPolicy(); + + /// Indicates whether a DTLS connection should ignore corrupt records (bad_record_mac) instead of + /// failing the connection. + /// Called only once at the start of a connection and applies throughout. + /// The value true to ignore corrupt DTLS records, or false to fail the connection. + /// + bool IgnoreCorruptDtlsRecords { get; } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsProtocol.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsProtocol.cs index 6ec2f3e..df22a57 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsProtocol.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsProtocol.cs @@ -1,12 +1,14 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.Connections.TLS; +using BestHTTP.PlatformSupport.Threading; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls { @@ -124,7 +126,7 @@ protected bool IsTlsV13ConnectionState() //private readonly ByteQueue m_heartbeatQueue = new ByteQueue(0); internal readonly RecordStream m_recordStream; - internal readonly object m_recordWriteLock = new object(); + //internal readonly object m_recordWriteLock = new object(); private int m_maxHandshakeMessageSize = -1; @@ -148,11 +150,10 @@ protected bool IsTlsV13ConnectionState() protected byte[] m_retryCookie = null; protected int m_retryGroup = -1; - protected IDictionary m_clientExtensions = null; - protected IDictionary m_serverExtensions = null; + protected IDictionary m_clientExtensions = null; + protected IDictionary m_serverExtensions = null; protected short m_connectionState = CS_START; - protected bool m_resumedSession = false; protected bool m_selectedPsk13 = false; protected bool m_receivedChangeCipherSpec = false; protected bool m_expectSessionTicket = false; @@ -349,7 +350,8 @@ protected virtual void BlockForHandshake() throw new TlsFatalAlert(AlertDescription.internal_error); } - SafeReadRecord(); + using (new WriteLock(this.applicationDataLock)) + SafeReadRecord(); } } @@ -369,7 +371,6 @@ protected virtual void BeginHandshake(bool renegotiation) this.m_handshakeHash = new DeferredHash(context); this.m_connectionState = CS_START; - this.m_resumedSession = false; this.m_selectedPsk13 = false; context.HandshakeBeginning(peer); @@ -405,7 +406,6 @@ protected virtual void CleanupHandshake() this.m_clientExtensions = null; this.m_serverExtensions = null; - this.m_resumedSession = false; this.m_selectedPsk13 = false; this.m_receivedChangeCipherSpec = false; this.m_expectSessionTicket = false; @@ -714,53 +714,104 @@ public virtual int ApplicationDataAvailable /// The method will return immediately, if there is still some data left in the buffer, or block until some /// application data has been read from the network. /// - /// The buffer where the data will be copied to. - /// The position where the data will be placed in the buffer. - /// The maximum number of bytes to read. + /// The buffer where the data will be copied to. + /// The position where the data will be placed in the buffer. + /// The maximum number of bytes to read. /// The number of bytes read. /// If something goes wrong during reading data. - public virtual int ReadApplicationData(byte[] buf, int off, int len) + public virtual int ReadApplicationData(byte[] buffer, int offset, int count) { - if (len < 1) - return 0; + Streams.ValidateBufferArguments(buffer, offset, count); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return ReadApplicationData(buffer.AsSpan(offset, count)); +#else + if (!m_appDataReady) + throw new InvalidOperationException("Cannot read application data until initial handshake completed."); - while (m_applicationDataQueue.Available == 0) + using (new WriteLock(this.applicationDataLock)) { - if (this.m_closed) + while (m_applicationDataQueue.Available < 1) { - if (this.m_failedWithError) - throw new IOException("Cannot read application data on failed TLS connection"); + if (this.m_closed) + { + if (this.m_failedWithError) + throw new IOException("Cannot read application data on failed TLS connection"); - return -1; + return 0; + } + + /* + * NOTE: Only called more than once when empty records are received, so no special + * InterruptedIOException handling is necessary. + */ + SafeReadRecord(); } - if (!m_appDataReady) - throw new InvalidOperationException("Cannot read application data until initial handshake completed."); - /* - * NOTE: Only called more than once when empty records are received, so no special - * InterruptedIOException handling is necessary. - */ - SafeReadRecord(); + if (count > 0) + { + count = System.Math.Min(count, m_applicationDataQueue.Available); + m_applicationDataQueue.RemoveData(buffer, offset, count, 0); } + return count; + } +#endif + } - len = System.Math.Min(len, m_applicationDataQueue.Available); - m_applicationDataQueue.RemoveData(buf, off, len, 0); - return len; + System.Threading.ReaderWriterLockSlim applicationDataLock = new System.Threading.ReaderWriterLockSlim(); + + public bool TryEnterApplicationDataLock(int millisecondsTimeout) + { + return this.applicationDataLock.TryEnterWriteLock(millisecondsTimeout); + } + + public void ExitApplicationDataLock() + { + this.applicationDataLock.ExitWriteLock(); } public int TestApplicationData() { - while (m_applicationDataQueue.Available == 0) + using (new WriteLock(this.applicationDataLock)) + { + while (m_applicationDataQueue.Available == 0) + { + if (this.m_closed) + { + if (this.m_failedWithError) + throw new IOException("Cannot read application data on failed TLS connection"); + + return -1; + } + if (!m_appDataReady) + throw new InvalidOperationException("Cannot read application data until initial handshake completed."); + + /* + * NOTE: Only called more than once when empty records are received, so no special + * InterruptedIOException handling is necessary. + */ + SafeReadRecord(); + } + + return m_applicationDataQueue.Available; + } + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual int ReadApplicationData(Span buffer) + { + if (!m_appDataReady) + throw new InvalidOperationException("Cannot read application data until initial handshake completed."); + + while (m_applicationDataQueue.Available < 1) { if (this.m_closed) { if (this.m_failedWithError) throw new IOException("Cannot read application data on failed TLS connection"); - return -1; + return 0; } - if (!m_appDataReady) - throw new InvalidOperationException("Cannot read application data until initial handshake completed."); /* * NOTE: Only called more than once when empty records are received, so no special @@ -769,8 +820,15 @@ public int TestApplicationData() SafeReadRecord(); } - return m_applicationDataQueue.Available; + int count = buffer.Length; + if (count > 0) + { + count = System.Math.Min(count, m_applicationDataQueue.Available); + m_applicationDataQueue.RemoveData(buffer[..count], 0); + } + return count; } +#endif /// protected virtual RecordPreview SafePreviewRecordHeader(byte[] recordHeader) @@ -816,17 +874,17 @@ protected virtual void SafeReadRecord() catch (TlsFatalAlertReceived e) { // Connection failure already handled at source - throw e; + throw; } catch (TlsFatalAlert e) { HandleException(e.AlertDescription, "Failed to read record", e); - throw e; + throw; } catch (IOException e) { HandleException(AlertDescription.internal_error, "Failed to read record", e); - throw e; + throw; } catch (Exception e) { @@ -887,6 +945,32 @@ protected virtual void SafeWriteRecord(short type, byte[] buf, int offset, int l } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// + protected virtual void SafeWriteRecord(short type, ReadOnlySpan buffer) + { + try + { + m_recordStream.WriteRecord(type, buffer); + } + catch (TlsFatalAlert e) + { + HandleException(e.AlertDescription, "Failed to write record", e); + throw e; + } + catch (IOException e) + { + HandleException(AlertDescription.internal_error, "Failed to write record", e); + throw e; + } + catch (Exception e) + { + HandleException(AlertDescription.internal_error, "Failed to write record", e); + throw new TlsFatalAlert(AlertDescription.internal_error, e); + } + } +#endif + /// Write some application data. /// /// Fragmentation is handled internally. Usable in both blocking/non-blocking modes.

@@ -895,22 +979,103 @@ protected virtual void SafeWriteRecord(short type, byte[] buf, int offset, int l /// This method must not be called until after the initial handshake is complete. Attempting to call it earlier /// will result in an . ///
- /// The buffer containing application data to send. - /// The offset at which the application data begins - /// The number of bytes of application data. + /// The buffer containing application data to send. + /// The offset at which the application data begins + /// The number of bytes of application data. /// If called before the initial handshake has completed. /// /// If connection is already closed, or for encryption or transport errors. /// - public virtual void WriteApplicationData(byte[] buf, int off, int len) + public virtual void WriteApplicationData(byte[] buffer, int offset, int count) + { + Streams.ValidateBufferArguments(buffer, offset, count); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + WriteApplicationData(buffer.AsSpan(offset, count)); +#else + if (!m_appDataReady) + throw new InvalidOperationException( + "Cannot write application data until initial handshake completed."); + + //lock (m_recordWriteLock) + { + while (count > 0) + { + if (m_closed) + throw new IOException("Cannot write application data on closed/failed TLS connection"); + + /* + * RFC 5246 6.2.1. Zero-length fragments of Application data MAY be sent as they are + * potentially useful as a traffic analysis countermeasure. + * + * NOTE: Actually, implementations appear to have settled on 1/n-1 record splitting. + */ + if (m_appDataSplitEnabled) + { + /* + * Protect against known IV attack! + * + * DO NOT REMOVE THIS CODE, EXCEPT YOU KNOW EXACTLY WHAT YOU ARE DOING HERE. + */ + switch (m_appDataSplitMode) + { + case ADS_MODE_0_N_FIRSTONLY: + { + this.m_appDataSplitEnabled = false; + SafeWriteRecord(ContentType.application_data, TlsUtilities.EmptyBytes, 0, 0); + break; + } + case ADS_MODE_0_N: + { + SafeWriteRecord(ContentType.application_data, TlsUtilities.EmptyBytes, 0, 0); + break; + } + case ADS_MODE_1_Nsub1: + default: + { + if (count > 1) + { + SafeWriteRecord(ContentType.application_data, buffer, offset, 1); + ++offset; + --count; + } + break; + } + } + } + else if (m_keyUpdateEnabled) + { + if (m_keyUpdatePendingSend) + { + Send13KeyUpdate(false); + } + else if (m_recordStream.NeedsKeyUpdate()) + { + Send13KeyUpdate(true); + } + } + + // Fragment data according to the current fragment limit. + int toWrite = System.Math.Min(count, m_recordStream.PlaintextLimit); + SafeWriteRecord(ContentType.application_data, buffer, offset, toWrite); + offset += toWrite; + count -= toWrite; + } + } +#endif + } + + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void WriteApplicationData(ReadOnlySpan buffer) { if (!m_appDataReady) throw new InvalidOperationException( "Cannot write application data until initial handshake completed."); - lock (m_recordWriteLock) + //lock (m_recordWriteLock) { - while (len > 0) + while (!buffer.IsEmpty) { if (m_closed) throw new IOException("Cannot write application data on closed/failed TLS connection"); @@ -944,11 +1109,10 @@ public virtual void WriteApplicationData(byte[] buf, int off, int len) case ADS_MODE_1_Nsub1: default: { - if (len > 1) + if (buffer.Length > 1) { - SafeWriteRecord(ContentType.application_data, buf, off, 1); - ++off; - --len; + SafeWriteRecord(ContentType.application_data, buffer[..1]); + buffer = buffer[1..]; } break; } @@ -967,13 +1131,13 @@ public virtual void WriteApplicationData(byte[] buf, int off, int len) } // Fragment data according to the current fragment limit. - int toWrite = System.Math.Min(len, m_recordStream.PlaintextLimit); - SafeWriteRecord(ContentType.application_data, buf, off, toWrite); - off += toWrite; - len -= toWrite; + int toWrite = System.Math.Min(buffer.Length, m_recordStream.PlaintextLimit); + SafeWriteRecord(ContentType.application_data, buffer[..toWrite]); + buffer = buffer[toWrite..]; } } } +#endif public virtual int AppDataSplitMode { @@ -1104,6 +1268,28 @@ public virtual RecordPreview PreviewInputRecord(byte[] recordHeader) return SafePreviewRecordHeader(recordHeader); } + public virtual int PreviewOutputRecord() + { + if (m_blocking) + throw new InvalidOperationException("Cannot use PreviewOutputRecord() in blocking mode!"); + + ByteQueue buffer = m_outputBuffer.Buffer; + int available = buffer.Available; + if (available < 1) + return 0; + + if (available >= RecordFormat.FragmentOffset) + { + int length = buffer.ReadUint16(RecordFormat.LengthOffset); + int recordSize = RecordFormat.FragmentOffset + length; + + if (available >= recordSize) + return recordSize; + } + + throw new InvalidOperationException("Can only use PreviewOutputRecord() for record-aligned output."); + } + /// public virtual RecordPreview PreviewOutputRecord(int applicationDataSize) { @@ -1237,7 +1423,7 @@ public virtual int ApplicationDataLimit } /// Gets the amount of received application data. - /// A call to is guaranteed to be able to return at least + /// A call to is guaranteed to be able to return at least /// this much data.

/// Only allowed in non-blocking mode. ///
@@ -1330,9 +1516,8 @@ protected virtual bool EstablishSession(TlsSession sessionToResume) return false; /* - * NOTE: For session resumption without extended_master_secret, renegotiation MUST be - * disabled (see RFC 7627 5.4). We currently do not implement renegotiation and it is - * unlikely we ever would since it was removed in TLS 1.3. + * NOTE: For session resumption without extended_master_secret, renegotiation MUST be disabled + * (see RFC 7627 5.4). */ } @@ -1376,7 +1561,12 @@ protected virtual void ProcessFinishedMessage(MemoryStream buf) SecurityParameters securityParameters = context.SecurityParameters; bool isServerContext = context.IsServer; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span verify_data = stackalloc byte[securityParameters.VerifyDataLength]; + TlsUtilities.ReadFully(verify_data, buf); +#else byte[] verify_data = TlsUtilities.ReadFully(securityParameters.VerifyDataLength, buf); +#endif AssertEmpty(buf); @@ -1395,7 +1585,7 @@ protected virtual void ProcessFinishedMessage(MemoryStream buf) securityParameters.m_peerVerifyData = expected_verify_data; - if (!m_resumedSession || securityParameters.IsExtendedMasterSecret) + if (!securityParameters.IsResumedSession || securityParameters.IsExtendedMasterSecret) { if (null == securityParameters.LocalVerifyData) { @@ -1411,7 +1601,12 @@ protected virtual void Process13FinishedMessage(MemoryStream buf) SecurityParameters securityParameters = context.SecurityParameters; bool isServerContext = context.IsServer; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span verify_data = stackalloc byte[securityParameters.VerifyDataLength]; + TlsUtilities.ReadFully(verify_data, buf); +#else byte[] verify_data = TlsUtilities.ReadFully(securityParameters.VerifyDataLength, buf); +#endif AssertEmpty(buf); @@ -1563,7 +1758,7 @@ protected virtual void SendFinishedMessage() securityParameters.m_localVerifyData = verify_data; - if (!m_resumedSession || securityParameters.IsExtendedMasterSecret) + if (!securityParameters.IsResumedSession || securityParameters.IsExtendedMasterSecret) { if (null == securityParameters.PeerVerifyData) { @@ -1611,7 +1806,7 @@ protected virtual void Send13KeyUpdate(bool updateRequested) } /// - protected virtual void SendSupplementalDataMessage(IList supplementalData) + protected virtual void SendSupplementalDataMessage(IList supplementalData) { HandshakeMessageOutput message = new HandshakeMessageOutput(HandshakeType.supplemental_data); WriteSupplementalData(message, supplementalData); @@ -1620,6 +1815,8 @@ protected virtual void SendSupplementalDataMessage(IList supplementalData) public virtual void Close() { + applicationDataLock?.Dispose(); + applicationDataLock = null; HandleClose(true); } @@ -1664,14 +1861,14 @@ public virtual bool IsHandshaking } /// - protected virtual short ProcessMaxFragmentLengthExtension(IDictionary clientExtensions, - IDictionary serverExtensions, short alertDescription) + protected virtual short ProcessMaxFragmentLengthExtension(IDictionary clientExtensions, + IDictionary serverExtensions, short alertDescription) { short maxFragmentLength = TlsExtensionsUtilities.GetMaxFragmentLengthExtension(serverExtensions); if (maxFragmentLength >= 0) { - if (!MaxFragmentLength.IsValid(maxFragmentLength) - || (!m_resumedSession && + if (!MaxFragmentLength.IsValid(maxFragmentLength) || + (clientExtensions != null && maxFragmentLength != TlsExtensionsUtilities.GetMaxFragmentLengthExtension(clientExtensions))) { throw new TlsFatalAlert(alertDescription); @@ -1745,7 +1942,7 @@ internal static void EstablishMasterSecret(TlsContext context, TlsKeyExchange ke } /// - internal static IDictionary ReadExtensions(MemoryStream input) + internal static IDictionary ReadExtensions(MemoryStream input) { if (input.Position >= input.Length) return null; @@ -1758,10 +1955,10 @@ internal static IDictionary ReadExtensions(MemoryStream input) } /// - internal static IDictionary ReadExtensionsData(byte[] extBytes) + internal static IDictionary ReadExtensionsData(byte[] extBytes) { // Int32 -> byte[] - IDictionary extensions = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + var extensions = new Dictionary(); if (extBytes.Length > 0) { @@ -1775,12 +1972,11 @@ internal static IDictionary ReadExtensionsData(byte[] extBytes) /* * RFC 3546 2.3 There MUST NOT be more than one extension of the same type. */ - Int32 key = extension_type; - if (extensions.Contains(key)) + if (extensions.ContainsKey(extension_type)) throw new TlsFatalAlert(AlertDescription.illegal_parameter, "Repeated extension: " + ExtensionType.GetText(extension_type)); - extensions.Add(key, extension_data); + extensions.Add(extension_type, extension_data); } while (buf.Position < buf.Length); } @@ -1789,10 +1985,10 @@ internal static IDictionary ReadExtensionsData(byte[] extBytes) } /// - internal static IDictionary ReadExtensionsData13(int handshakeType, byte[] extBytes) + internal static IDictionary ReadExtensionsData13(int handshakeType, byte[] extBytes) { // Int32 -> byte[] - IDictionary extensions = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + var extensions = new Dictionary(); if (extBytes.Length > 0) { @@ -1813,12 +2009,11 @@ internal static IDictionary ReadExtensionsData13(int handshakeType, byte[] extBy /* * RFC 3546 2.3 There MUST NOT be more than one extension of the same type. */ - Int32 key = extension_type; - if (extensions.Contains(key)) + if (extensions.ContainsKey(extension_type)) throw new TlsFatalAlert(AlertDescription.illegal_parameter, "Repeated extension: " + ExtensionType.GetText(extension_type)); - extensions.Add(key, extension_data); + extensions.Add(extension_type, extension_data); } while (buf.Position < buf.Length); } @@ -1827,7 +2022,7 @@ internal static IDictionary ReadExtensionsData13(int handshakeType, byte[] extBy } /// - internal static IDictionary ReadExtensionsDataClientHello(byte[] extBytes) + internal static IDictionary ReadExtensionsDataClientHello(byte[] extBytes) { /* * TODO[tls13] We are currently allowing any extensions to appear in ClientHello. It is @@ -1837,7 +2032,7 @@ internal static IDictionary ReadExtensionsDataClientHello(byte[] extBytes) */ // Int32 -> byte[] - IDictionary extensions = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + var extensions = new Dictionary(); if (extBytes.Length > 0) { @@ -1854,12 +2049,11 @@ internal static IDictionary ReadExtensionsDataClientHello(byte[] extBytes) /* * RFC 3546 2.3 There MUST NOT be more than one extension of the same type. */ - Int32 key = extension_type; - if (extensions.Contains(key)) + if (extensions.ContainsKey(extension_type)) throw new TlsFatalAlert(AlertDescription.illegal_parameter, "Repeated extension: " + ExtensionType.GetText(extension_type)); - extensions.Add(key, extension_data); + extensions.Add(extension_type, extension_data); pre_shared_key_found |= (ExtensionType.pre_shared_key == extension_type); } @@ -1874,7 +2068,7 @@ internal static IDictionary ReadExtensionsDataClientHello(byte[] extBytes) } /// - internal static IList ReadSupplementalDataMessage(MemoryStream input) + internal static IList ReadSupplementalDataMessage(MemoryStream input) { byte[] supp_data = TlsUtilities.ReadOpaque24(input, 1); @@ -1882,7 +2076,7 @@ internal static IList ReadSupplementalDataMessage(MemoryStream input) MemoryStream buf = new MemoryStream(supp_data, false); - IList supplementalData = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var supplementalData = new List(); while (buf.Position < buf.Length) { @@ -1896,13 +2090,13 @@ internal static IList ReadSupplementalDataMessage(MemoryStream input) } /// - internal static void WriteExtensions(Stream output, IDictionary extensions) + internal static void WriteExtensions(Stream output, IDictionary extensions) { WriteExtensions(output, extensions, 0); } /// - internal static void WriteExtensions(Stream output, IDictionary extensions, int bindersSize) + internal static void WriteExtensions(Stream output, IDictionary extensions, int bindersSize) { if (null == extensions || extensions.Count < 1) return; @@ -1916,13 +2110,13 @@ internal static void WriteExtensions(Stream output, IDictionary extensions, int } /// - internal static byte[] WriteExtensionsData(IDictionary extensions) + internal static byte[] WriteExtensionsData(IDictionary extensions) { return WriteExtensionsData(extensions, 0); } /// - internal static byte[] WriteExtensionsData(IDictionary extensions, int bindersSize) + internal static byte[] WriteExtensionsData(IDictionary extensions, int bindersSize) { MemoryStream buf = new MemoryStream(); WriteExtensionsData(extensions, buf, bindersSize); @@ -1930,13 +2124,13 @@ internal static byte[] WriteExtensionsData(IDictionary extensions, int bindersSi } /// - internal static void WriteExtensionsData(IDictionary extensions, MemoryStream buf) + internal static void WriteExtensionsData(IDictionary extensions, MemoryStream buf) { WriteExtensionsData(extensions, buf, 0); } /// - internal static void WriteExtensionsData(IDictionary extensions, MemoryStream buf, int bindersSize) + internal static void WriteExtensionsData(IDictionary extensions, MemoryStream buf, int bindersSize) { /* * NOTE: There are reports of servers that don't accept a zero-length extension as the last @@ -1948,10 +2142,10 @@ internal static void WriteExtensionsData(IDictionary extensions, MemoryStream bu } /// - internal static void WritePreSharedKeyExtension(MemoryStream buf, IDictionary extensions, int bindersSize) + internal static void WritePreSharedKeyExtension(MemoryStream buf, IDictionary extensions, + int bindersSize) { - byte[] extension_data = (byte[])extensions[ExtensionType.pre_shared_key]; - if (null != extension_data) + if (extensions.TryGetValue(ExtensionType.pre_shared_key, out var extension_data)) { TlsUtilities.CheckUint16(ExtensionType.pre_shared_key); TlsUtilities.WriteUint16(ExtensionType.pre_shared_key, buf); @@ -1964,17 +2158,18 @@ internal static void WritePreSharedKeyExtension(MemoryStream buf, IDictionary ex } /// - internal static void WriteSelectedExtensions(Stream output, IDictionary extensions, bool selectEmpty) + internal static void WriteSelectedExtensions(Stream output, IDictionary extensions, + bool selectEmpty) { - foreach (Int32 key in extensions.Keys) + foreach (var extension in extensions) { - int extension_type = key; + int extension_type = extension.Key; // NOTE: Must be last; handled by 'WritePreSharedKeyExtension' if (ExtensionType.pre_shared_key == extension_type) continue; - byte[] extension_data = (byte[])extensions[key]; + byte[] extension_data = extension.Value; if (selectEmpty == (extension_data.Length == 0)) { @@ -1986,7 +2181,7 @@ internal static void WriteSelectedExtensions(Stream output, IDictionary extensio } /// - internal static void WriteSupplementalData(Stream output, IList supplementalData) + internal static void WriteSupplementalData(Stream output, IList supplementalData) { MemoryStream buf = new MemoryStream(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsServer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsServer.cs index b06ae2c..8f1ae05 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsServer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsServer.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; @@ -31,10 +31,10 @@ public interface TlsServer /// Note that this will only be called when TLS 1.3 or higher is amongst the offered protocol versions, and one /// or more PSKs are actually offered. ///
- /// an of instances. + /// an of instances. /// The corresponding to the selected identity, or null to not select /// any. - TlsPskExternal GetExternalPsk(IList identities); + TlsPskExternal GetExternalPsk(IList identities); void NotifySession(TlsSession session); @@ -49,7 +49,7 @@ public interface TlsServer /// (Int32 -> byte[]) /// - void ProcessClientExtensions(IDictionary clientExtensions); + void ProcessClientExtensions(IDictionary clientExtensions); /// ProtocolVersion GetServerVersion(); @@ -62,15 +62,15 @@ public interface TlsServer /// (Int32 -> byte[]) /// - IDictionary GetServerExtensions(); + IDictionary GetServerExtensions(); /// (Int32 -> byte[]) /// - void GetServerExtensionsForConnection(IDictionary serverExtensions); + void GetServerExtensionsForConnection(IDictionary serverExtensions); /// (SupplementalDataEntry) /// - IList GetServerSupplementalData(); + IList GetServerSupplementalData(); /// Return server credentials to use. /// @@ -109,7 +109,7 @@ public interface TlsServer /// (SupplementalDataEntry) /// - void ProcessClientSupplementalData(IList clientSupplementalData); + void ProcessClientSupplementalData(IList clientSupplementalData); /// Called by the protocol handler to report the client certificate, only if /// returned non-null. diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsServerProtocol.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsServerProtocol.cs index bf57134..9c368c5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsServerProtocol.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsServerProtocol.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; @@ -105,7 +105,7 @@ protected virtual ServerHello Generate13HelloRetryRequest(ClientHello clientHell SecurityParameters securityParameters = m_tlsServerContext.SecurityParameters; ProtocolVersion serverVersion = securityParameters.NegotiatedVersion; - IDictionary serverHelloExtensions = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + var serverHelloExtensions = new Dictionary(); TlsExtensionsUtilities.AddSupportedVersionsExtensionServer(serverHelloExtensions, serverVersion); if (m_retryGroup >= 0) { @@ -131,7 +131,7 @@ protected virtual ServerHello Generate13ServerHello(ClientHello clientHello, byte[] legacy_session_id = clientHello.SessionID; - IDictionary clientHelloExtensions = clientHello.Extensions; + var clientHelloExtensions = clientHello.Extensions; if (null == clientHelloExtensions) throw new TlsFatalAlert(AlertDescription.missing_extension); @@ -143,7 +143,7 @@ protected virtual ServerHello Generate13ServerHello(ClientHello clientHello, OfferedPsks.SelectedConfig selectedPsk = TlsUtilities.SelectPreSharedKey(m_tlsServerContext, m_tlsServer, clientHelloExtensions, clientHelloMessage, m_handshakeHash, afterHelloRetryRequest); - IList clientShares = TlsExtensionsUtilities.GetKeyShareClientHello(clientHelloExtensions); + var clientShares = TlsExtensionsUtilities.GetKeyShareClientHello(clientHelloExtensions); KeyShareEntry clientShare = null; if (afterHelloRetryRequest) @@ -189,6 +189,15 @@ protected virtual ServerHello Generate13ServerHello(ClientHello clientHello, } else { + { + securityParameters.m_serverRandom = CreateRandomBlock(false, m_tlsServerContext); + + if (!serverVersion.Equals(ProtocolVersion.GetLatestTls(m_tlsServer.GetProtocolVersions()))) + { + TlsUtilities.WriteDowngradeMarker(serverVersion, securityParameters.ServerRandom); + } + } + this.m_clientExtensions = clientHelloExtensions; securityParameters.m_secureRenegotiation = false; @@ -219,6 +228,7 @@ protected virtual ServerHello Generate13ServerHello(ClientHello clientHello, */ { // TODO[tls13] Resumption/PSK + securityParameters.m_resumedSession = false; this.m_tlsSession = TlsUtilities.ImportSession(TlsUtilities.EmptyBytes, null); this.m_sessionParameters = null; @@ -231,15 +241,6 @@ protected virtual ServerHello Generate13ServerHello(ClientHello clientHello, TlsUtilities.NegotiatedVersionTlsServer(m_tlsServerContext); - { - securityParameters.m_serverRandom = CreateRandomBlock(false, m_tlsServerContext); - - if (!serverVersion.Equals(ProtocolVersion.GetLatestTls(m_tlsServer.GetProtocolVersions()))) - { - TlsUtilities.WriteDowngradeMarker(serverVersion, securityParameters.ServerRandom); - } - } - { // TODO[tls13] Constrain selection when PSK selected int cipherSuite = m_tlsServer.GetSelectedCipherSuite(); @@ -289,8 +290,8 @@ protected virtual ServerHello Generate13ServerHello(ClientHello clientHello, } - IDictionary serverHelloExtensions = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - IDictionary serverEncryptedExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised( + var serverHelloExtensions = new Dictionary(); + var serverEncryptedExtensions = TlsExtensionsUtilities.EnsureExtensionsInitialised( m_tlsServer.GetServerExtensions()); m_tlsServer.GetServerExtensionsForConnection(serverEncryptedExtensions); @@ -316,8 +317,9 @@ protected virtual ServerHello Generate13ServerHello(ClientHello clientHello, if (serverEncryptedExtensions.Count > 0) { - securityParameters.m_maxFragmentLength = ProcessMaxFragmentLengthExtension(clientHelloExtensions, - serverEncryptedExtensions, AlertDescription.internal_error); + securityParameters.m_maxFragmentLength = ProcessMaxFragmentLengthExtension( + securityParameters.IsResumedSession ? null : clientHelloExtensions, serverEncryptedExtensions, + AlertDescription.internal_error); } securityParameters.m_encryptThenMac = false; @@ -328,8 +330,8 @@ protected virtual ServerHello Generate13ServerHello(ClientHello clientHello, * * OCSP information is carried in an extension for a CertificateEntry. */ - securityParameters.m_statusRequestVersion = clientHelloExtensions.Contains(ExtensionType.status_request) - ? 1 : 0; + securityParameters.m_statusRequestVersion = + clientHelloExtensions.ContainsKey(ExtensionType.status_request) ? 1 : 0; this.m_expectSessionTicket = false; @@ -462,6 +464,17 @@ protected virtual ServerHello GenerateServerHello(ClientHello clientHello, m_recordStream.SetWriteVersion(serverVersion); + { + bool useGmtUnixTime = m_tlsServer.ShouldUseGmtUnixTime(); + + securityParameters.m_serverRandom = CreateRandomBlock(useGmtUnixTime, m_tlsServerContext); + + if (!serverVersion.Equals(ProtocolVersion.GetLatestTls(m_tlsServer.GetProtocolVersions()))) + { + TlsUtilities.WriteDowngradeMarker(serverVersion, securityParameters.ServerRandom); + } + } + this.m_clientExtensions = clientHello.Extensions; byte[] clientRenegExtData = TlsUtilities.GetExtensionData(m_clientExtensions, ExtensionType.renegotiation_info); @@ -537,9 +550,10 @@ protected virtual ServerHello GenerateServerHello(ClientHello clientHello, m_tlsServer.ProcessClientExtensions(m_clientExtensions); } - this.m_resumedSession = EstablishSession(m_tlsServer.GetSessionToResume(clientHello.SessionID)); + bool resumedSession = EstablishSession(m_tlsServer.GetSessionToResume(clientHello.SessionID)); + securityParameters.m_resumedSession = resumedSession; - if (!m_resumedSession) + if (!resumedSession) { byte[] newSessionID = m_tlsServer.GetNewSessionID(); if (null == newSessionID) @@ -559,18 +573,7 @@ protected virtual ServerHello GenerateServerHello(ClientHello clientHello, TlsUtilities.NegotiatedVersionTlsServer(m_tlsServerContext); { - bool useGmtUnixTime = m_tlsServer.ShouldUseGmtUnixTime(); - - securityParameters.m_serverRandom = CreateRandomBlock(useGmtUnixTime, m_tlsServerContext); - - if (!serverVersion.Equals(ProtocolVersion.GetLatestTls(m_tlsServer.GetProtocolVersions()))) - { - TlsUtilities.WriteDowngradeMarker(serverVersion, securityParameters.ServerRandom); - } - } - - { - int cipherSuite = m_resumedSession + int cipherSuite = resumedSession ? m_sessionParameters.CipherSuite : m_tlsServer.GetSelectedCipherSuite(); @@ -586,7 +589,7 @@ protected virtual ServerHello GenerateServerHello(ClientHello clientHello, m_tlsServerContext.SetRsaPreMasterSecretVersion(clientLegacyVersion); { - IDictionary sessionServerExtensions = m_resumedSession + var sessionServerExtensions = resumedSession ? m_sessionParameters.ReadServerExtensions() : m_tlsServer.GetServerExtensions(); @@ -630,7 +633,7 @@ protected virtual ServerHello GenerateServerHello(ClientHello clientHello, * RFC 7627 4. Clients and servers SHOULD NOT accept handshakes that do not use the extended * master secret [..]. (and see 5.2, 5.3) */ - if (m_resumedSession) + if (resumedSession) { if (!m_sessionParameters.IsExtendedMasterSecret) { @@ -671,13 +674,13 @@ protected virtual ServerHello GenerateServerHello(ClientHello clientHello, securityParameters.m_encryptThenMac = TlsExtensionsUtilities.HasEncryptThenMacExtension( m_serverExtensions); - securityParameters.m_maxFragmentLength = ProcessMaxFragmentLengthExtension(m_clientExtensions, - m_serverExtensions, AlertDescription.internal_error); + securityParameters.m_maxFragmentLength = ProcessMaxFragmentLengthExtension( + resumedSession ? null : m_clientExtensions, m_serverExtensions, AlertDescription.internal_error); securityParameters.m_truncatedHmac = TlsExtensionsUtilities.HasTruncatedHmacExtension( m_serverExtensions); - if (!m_resumedSession) + if (!resumedSession) { if (TlsUtilities.HasExpectedEmptyExtensionData(m_serverExtensions, ExtensionType.status_request_v2, AlertDescription.internal_error)) @@ -722,16 +725,12 @@ protected virtual void Handle13HandshakeMessage(short type, HandshakeMessageInpu if (!IsTlsV13ConnectionState()) throw new TlsFatalAlert(AlertDescription.internal_error); - if (m_resumedSession) - { - /* - * TODO[tls13] Abbreviated handshakes (PSK resumption) - * - * NOTE: No CertificateRequest, Certificate, CertificateVerify messages, but client - * might now send EndOfEarlyData after receiving server Finished message. - */ - throw new TlsFatalAlert(AlertDescription.internal_error); - } + /* + * TODO[tls13] Abbreviated handshakes (PSK resumption) + * + * NOTE: No CertificateRequest, Certificate, CertificateVerify messages, but client + * might now send EndOfEarlyData after receiving server Finished message. + */ switch (type) { @@ -836,6 +835,7 @@ protected virtual void Handle13HandshakeMessage(short type, HandshakeMessageInpu case HandshakeType.certificate_status: case HandshakeType.certificate_url: case HandshakeType.client_key_exchange: + case HandshakeType.compressed_certificate: case HandshakeType.encrypted_extensions: case HandshakeType.end_of_early_data: case HandshakeType.hello_request: @@ -858,6 +858,9 @@ protected override void HandleHandshakeMessage(short type, HandshakeMessageInput if (m_connectionState > CS_CLIENT_HELLO && TlsUtilities.IsTlsV13(securityParameters.NegotiatedVersion)) { + if (securityParameters.IsResumedSession) + throw new TlsFatalAlert(AlertDescription.internal_error); + Handle13HandshakeMessage(type, buf); return; } @@ -865,7 +868,7 @@ protected override void HandleHandshakeMessage(short type, HandshakeMessageInput if (!IsLegacyConnectionState()) throw new TlsFatalAlert(AlertDescription.internal_error); - if (m_resumedSession) + if (securityParameters.IsResumedSession) { if (type != HandshakeType.finished || m_connectionState != CS_SERVER_FINISHED) throw new TlsFatalAlert(AlertDescription.unexpected_message); @@ -908,6 +911,7 @@ protected override void HandleHandshakeMessage(short type, HandshakeMessageInput if (serverHello.IsHelloRetryRequest()) { TlsUtilities.AdjustTranscriptForRetry(m_handshakeHash); + SendServerHelloMessage(serverHello); this.m_connectionState = CS_SERVER_HELLO_RETRY_REQUEST; @@ -933,7 +937,7 @@ protected override void HandleHandshakeMessage(short type, HandshakeMessageInput SendServerHelloMessage(serverHello); this.m_connectionState = CS_SERVER_HELLO; - if (m_resumedSession) + if (securityParameters.IsResumedSession) { securityParameters.m_masterSecret = m_sessionMasterSecret; m_recordStream.SetPendingCipher(TlsUtilities.InitCipher(m_tlsServerContext)); @@ -944,7 +948,7 @@ protected override void HandleHandshakeMessage(short type, HandshakeMessageInput break; } - IList serverSupplementalData = m_tlsServer.GetServerSupplementalData(); + var serverSupplementalData = m_tlsServer.GetServerSupplementalData(); if (serverSupplementalData != null) { SendSupplementalDataMessage(serverSupplementalData); @@ -953,7 +957,12 @@ protected override void HandleHandshakeMessage(short type, HandshakeMessageInput this.m_keyExchange = TlsUtilities.InitKeyExchangeServer(m_tlsServerContext, m_tlsServer); - TlsCredentials serverCredentials = TlsUtilities.EstablishServerCredentials(m_tlsServer); + TlsCredentials serverCredentials = null; + + if (!KeyExchangeAlgorithm.IsAnonymous(securityParameters.KeyExchangeAlgorithm)) + { + serverCredentials = TlsUtilities.EstablishServerCredentials(m_tlsServer); + } // Server certificate { @@ -1027,19 +1036,36 @@ protected override void HandleHandshakeMessage(short type, HandshakeMessageInput TlsUtilities.EstablishServerSigAlgs(securityParameters, m_certificateRequest); - TlsUtilities.TrackHashAlgorithms(m_handshakeHash, securityParameters.ServerSigAlgs); + if (ProtocolVersion.TLSv12.Equals(securityParameters.NegotiatedVersion)) + { + TlsUtilities.TrackHashAlgorithms(m_handshakeHash, securityParameters.ServerSigAlgs); - SendCertificateRequestMessage(m_certificateRequest); - this.m_connectionState = CS_SERVER_CERTIFICATE_REQUEST; + if (m_tlsServerContext.Crypto.HasAnyStreamVerifiers(securityParameters.ServerSigAlgs)) + { + m_handshakeHash.ForceBuffering(); + } + } + else + { + if (m_tlsServerContext.Crypto.HasAnyStreamVerifiersLegacy(m_certificateRequest.CertificateTypes)) + { + m_handshakeHash.ForceBuffering(); + } + } } } + m_handshakeHash.SealHashAlgorithms(); + + if (null != m_certificateRequest) + { + SendCertificateRequestMessage(m_certificateRequest); + this.m_connectionState = CS_SERVER_CERTIFICATE_REQUEST; + } + SendServerHelloDoneMessage(); this.m_connectionState = CS_SERVER_HELLO_DONE; - bool forceBuffering = false; - TlsUtilities.SealHandshakeHash(m_tlsServerContext, m_handshakeHash, forceBuffering); - break; } default: @@ -1203,6 +1229,7 @@ protected override void HandleHandshakeMessage(short type, HandshakeMessageInput case HandshakeType.certificate_request: case HandshakeType.certificate_status: case HandshakeType.certificate_url: + case HandshakeType.compressed_certificate: case HandshakeType.encrypted_extensions: case HandshakeType.end_of_early_data: case HandshakeType.hello_request: @@ -1265,7 +1292,11 @@ protected virtual void Receive13ClientCertificate(MemoryStream buf) throw new TlsFatalAlert(AlertDescription.unexpected_message); Certificate.ParseOptions options = new Certificate.ParseOptions() - .SetMaxChainLength(m_tlsServer.GetMaxCertificateChainLength()); + { + CertificateType = TlsExtensionsUtilities.GetClientCertificateTypeExtensionServer(m_serverExtensions, + CertificateType.X509), + MaxChainLength = m_tlsServer.GetMaxCertificateChainLength(), + }; Certificate clientCertificate = Certificate.Parse(options, m_tlsServerContext, buf, null); @@ -1281,13 +1312,11 @@ protected void Receive13ClientCertificateVerify(MemoryStream buf) if (null == clientCertificate || clientCertificate.IsEmpty) throw new TlsFatalAlert(AlertDescription.internal_error); - // TODO[tls13] Actual structure is 'CertificateVerify' in RFC 8446, consider adding for clarity - DigitallySigned certificateVerify = DigitallySigned.Parse(m_tlsServerContext, buf); + CertificateVerify certificateVerify = CertificateVerify.Parse(m_tlsServerContext, buf); AssertEmpty(buf); - TlsUtilities.Verify13CertificateVerifyClient(m_tlsServerContext, m_certificateRequest, certificateVerify, - m_handshakeHash); + TlsUtilities.Verify13CertificateVerifyClient(m_tlsServerContext, m_handshakeHash, certificateVerify); } /// @@ -1303,7 +1332,11 @@ protected virtual void ReceiveCertificateMessage(MemoryStream buf) throw new TlsFatalAlert(AlertDescription.unexpected_message); Certificate.ParseOptions options = new Certificate.ParseOptions() - .SetMaxChainLength(m_tlsServer.GetMaxCertificateChainLength()); + { + CertificateType = TlsExtensionsUtilities.GetClientCertificateTypeExtensionServer(m_serverExtensions, + CertificateType.X509), + MaxChainLength = m_tlsServer.GetMaxCertificateChainLength(), + }; Certificate clientCertificate = Certificate.Parse(options, m_tlsServerContext, buf, null); @@ -1322,7 +1355,7 @@ protected virtual void ReceiveCertificateVerifyMessage(MemoryStream buf) TlsUtilities.VerifyCertificateVerifyClient(m_tlsServerContext, m_certificateRequest, certificateVerify, m_handshakeHash); - this.m_handshakeHash = m_handshakeHash.StopTracking(); + m_handshakeHash.StopTracking(); } /// @@ -1357,12 +1390,12 @@ protected virtual void ReceiveClientKeyExchangeMessage(MemoryStream buf) if (!ExpectCertificateVerifyMessage()) { - this.m_handshakeHash = m_handshakeHash.StopTracking(); + m_handshakeHash.StopTracking(); } } /// - protected virtual void Send13EncryptedExtensionsMessage(IDictionary serverExtensions) + protected virtual void Send13EncryptedExtensionsMessage(IDictionary serverExtensions) { // TODO[tls13] Avoid extra copy; use placeholder to write opaque-16 data directly to message buffer diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsSrpUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsSrpUtilities.cs index ec5c3b2..33c9678 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsSrpUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsSrpUtilities.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; @@ -12,13 +12,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls public abstract class TlsSrpUtilities { /// - public static void AddSrpExtension(IDictionary extensions, byte[] identity) + public static void AddSrpExtension(IDictionary extensions, byte[] identity) { extensions[ExtensionType.srp] = CreateSrpExtension(identity); } /// - public static byte[] GetSrpExtension(IDictionary extensions) + public static byte[] GetSrpExtension(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.srp); return extensionData == null ? null : ReadSrpExtension(extensionData); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsSrtpUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsSrtpUtilities.cs index 668193c..1c9952f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsSrtpUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsSrtpUtilities.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls @@ -10,13 +10,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls public abstract class TlsSrtpUtilities { /// - public static void AddUseSrtpExtension(IDictionary extensions, UseSrtpData useSrtpData) + public static void AddUseSrtpExtension(IDictionary extensions, UseSrtpData useSrtpData) { extensions[ExtensionType.use_srtp] = CreateUseSrtpExtension(useSrtpData); } /// - public static UseSrtpData GetUseSrtpExtension(IDictionary extensions) + public static UseSrtpData GetUseSrtpExtension(IDictionary extensions) { byte[] extensionData = TlsUtilities.GetExtensionData(extensions, ExtensionType.use_srtp); return extensionData == null ? null : ReadUseSrtpExtension(extensionData); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsStream.cs index a4e9cd0..933acd7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsStream.cs @@ -12,14 +12,16 @@ internal class TlsStream public TlsProtocol Protocol { get => this.m_handler; } + byte[] oneByteBuf = new byte[1]; + internal TlsStream(TlsProtocol handler) { - this.m_handler = handler; + m_handler = handler; } public override bool CanRead { - get { return !m_handler.IsClosed; } + get { return true; } } public override bool CanSeek @@ -29,10 +31,9 @@ public override bool CanSeek public override bool CanWrite { - get { return !m_handler.IsClosed; } + get { return true; } } -#if PORTABLE || NETFX_CORE protected override void Dispose(bool disposing) { if (disposing) @@ -41,13 +42,6 @@ protected override void Dispose(bool disposing) } base.Dispose(disposing); } -#else - public override void Close() - { - m_handler.Close(); - base.Close(); - } -#endif public override void Flush() { @@ -65,16 +59,22 @@ public override long Position set { throw new NotSupportedException(); } } - public override int Read(byte[] buf, int off, int len) + public override int Read(byte[] buffer, int offset, int count) + { + return m_handler.ReadApplicationData(buffer, offset, count); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int Read(Span buffer) { - return m_handler.ReadApplicationData(buf, off, len); + return m_handler.ReadApplicationData(buffer); } +#endif public override int ReadByte() { - byte[] buf = new byte[1]; - int ret = Read(buf, 0, 1); - return ret <= 0 ? -1 : buf[0]; + int ret = m_handler.ReadApplicationData(oneByteBuf, 0, 1); + return ret <= 0 ? -1 : oneByteBuf[0]; } public override long Seek(long offset, SeekOrigin origin) @@ -87,14 +87,22 @@ public override void SetLength(long value) throw new NotSupportedException(); } - public override void Write(byte[] buf, int off, int len) + public override void Write(byte[] buffer, int offset, int count) + { + m_handler.WriteApplicationData(buffer, offset, count); + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) { - m_handler.WriteApplicationData(buf, off, len); + m_handler.WriteApplicationData(buffer); } +#endif - public override void WriteByte(byte b) + public override void WriteByte(byte value) { - Write(new byte[]{ b }, 0, 1); + oneByteBuf[0] = value; + Write(oneByteBuf, 0, 1); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsTimeoutException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsTimeoutException.cs index d085d00..2861e2b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsTimeoutException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsTimeoutException.cs @@ -2,27 +2,34 @@ #pragma warning disable using System; using System.IO; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls { - public class TlsTimeoutException + [Serializable] + public class TlsTimeoutException : IOException { - public TlsTimeoutException() - : base() - { - } + public TlsTimeoutException() + : base() + { + } - public TlsTimeoutException(string message) - : base(message) - { - } + public TlsTimeoutException(string message) + : base(message) + { + } - public TlsTimeoutException(string message, Exception cause) - : base(message, cause) - { - } - } + public TlsTimeoutException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected TlsTimeoutException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsUtilities.cs index 10ee2cf..900f1b6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TlsUtilities.cs @@ -1,14 +1,10 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; -#if !PORTABLE || NETFX_CORE || DOTNET using System.Net.Sockets; -using BestHTTP.Connections.TLS; -#endif - using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Bsi; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Eac; @@ -19,8 +15,10 @@ using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Rosstandart; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X509; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.X9; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; using BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto; 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.Utilities.IO; @@ -32,24 +30,24 @@ public abstract class TlsUtilities private static readonly byte[] DowngradeTlsV11 = Hex.DecodeStrict("444F574E47524400"); private static readonly byte[] DowngradeTlsV12 = Hex.DecodeStrict("444F574E47524401"); - private static readonly IDictionary CertSigAlgOids = CreateCertSigAlgOids(); - private static readonly IList DefaultSupportedSigAlgs = CreateDefaultSupportedSigAlgs(); + private static readonly IDictionary CertSigAlgOids = CreateCertSigAlgOids(); + private static readonly IList DefaultSupportedSigAlgs = CreateDefaultSupportedSigAlgs(); - private static void AddCertSigAlgOid(IDictionary d, DerObjectIdentifier oid, + private static void AddCertSigAlgOid(IDictionary d, DerObjectIdentifier oid, SignatureAndHashAlgorithm sigAndHash) { d[oid.Id] = sigAndHash; } - private static void AddCertSigAlgOid(IDictionary d, DerObjectIdentifier oid, short hashAlgorithm, - short signatureAlgorithm) + private static void AddCertSigAlgOid(IDictionary d, DerObjectIdentifier oid, + short hashAlgorithm, short signatureAlgorithm) { AddCertSigAlgOid(d, oid, SignatureAndHashAlgorithm.GetInstance(hashAlgorithm, signatureAlgorithm)); } - private static IDictionary CreateCertSigAlgOids() + private static IDictionary CreateCertSigAlgOids() { - IDictionary d = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + var d = new Dictionary(); AddCertSigAlgOid(d, NistObjectIdentifiers.DsaWithSha224, HashAlgorithm.sha224, SignatureAlgorithm.dsa); AddCertSigAlgOid(d, NistObjectIdentifiers.DsaWithSha256, HashAlgorithm.sha256, SignatureAlgorithm.dsa); @@ -100,9 +98,9 @@ private static IDictionary CreateCertSigAlgOids() return d; } - private static IList CreateDefaultSupportedSigAlgs() + private static IList CreateDefaultSupportedSigAlgs() { - IList result = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var result = new List(); result.Add(SignatureAndHashAlgorithm.ed25519); result.Add(SignatureAndHashAlgorithm.ed448); result.Add(SignatureAndHashAlgorithm.GetInstance(HashAlgorithm.sha256, SignatureAlgorithm.ecdsa)); @@ -313,6 +311,13 @@ public static void WriteUint8(int i, byte[] buf, int offset) buf[offset] = (byte)i; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void WriteUint8(int i, Span buf) + { + buf[0] = (byte)i; + } +#endif + public static void WriteUint16(int i, Stream output) { output.WriteByte((byte)(i >> 8)); @@ -325,6 +330,14 @@ public static void WriteUint16(int i, byte[] buf, int offset) buf[offset + 1] = (byte)i; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void WriteUint16(int i, Span buf) + { + buf[0] = (byte)(i >> 8); + buf[1] = (byte)i; + } +#endif + public static void WriteUint24(int i, Stream output) { output.WriteByte((byte)(i >> 16)); @@ -413,6 +426,15 @@ public static void WriteOpaque8(byte[] data, byte[] buf, int off) Array.Copy(data, 0, buf, off + 1, data.Length); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void WriteOpaque8(ReadOnlySpan data, Span buf) + { + CheckUint8(data.Length); + WriteUint8(data.Length, buf); + data.CopyTo(buf[1..]); + } +#endif + public static void WriteOpaque16(byte[] buf, Stream output) { CheckUint16(buf.Length); @@ -489,6 +511,14 @@ public static void WriteUint16Array(int[] u16s, byte[] buf, int offset) } } + public static void WriteUint16ArrayWithUint8Length(int[] u16s, byte[] buf, int offset) + { + int length = 2 * u16s.Length; + CheckUint8(length); + WriteUint8(length, buf, offset); + WriteUint16Array(u16s, buf, offset + 1); + } + public static void WriteUint16ArrayWithUint16Length(int[] u16s, Stream output) { int length = 2 * u16s.Length; @@ -580,6 +610,25 @@ public static int DecodeUint16(byte[] buf) return ReadUint16(buf, 0); } + public static int[] DecodeUint16ArrayWithUint8Length(byte[] buf) + { + if (buf == null) + throw new ArgumentNullException("buf"); + + int length = ReadUint8(buf, 0); + if (buf.Length != (length + 1) || (length & 1) != 0) + throw new TlsFatalAlert(AlertDescription.decode_error); + + int count = length / 2, pos = 1; + int[] u16s = new int[count]; + for (int i = 0; i < count; ++i) + { + u16s[i] = ReadUint16(buf, pos); + pos += 2; + } + return u16s; + } + public static long DecodeUint32(byte[] buf) { if (buf == null) @@ -639,6 +688,14 @@ public static byte[] EncodeUint16(int u16) return encoding; } + public static byte[] EncodeUint16ArrayWithUint8Length(int[] u16s) + { + int length = 2 * u16s.Length; + byte[] result = new byte[1 + length]; + WriteUint16ArrayWithUint8Length(u16s, result, 0); + return result; + } + public static byte[] EncodeUint16ArrayWithUint16Length(int[] u16s) { int length = 2 * u16s.Length; @@ -692,8 +749,15 @@ public static short ReadUint8(Stream input) public static short ReadUint8(byte[] buf, int offset) { - return (short)(buf[offset] & 0xff); + return (short)buf[offset]; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static short ReadUint8(ReadOnlySpan buffer) + { + return (short)buffer[0]; } +#endif public static int ReadUint16(Stream input) { @@ -795,6 +859,15 @@ public static void ReadFully(byte[] buf, Stream input) throw new EndOfStreamException(); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void ReadFully(Span buf, Stream input) + { + int length = buf.Length; + if (length > 0 && length != Streams.ReadFully(input, buf)) + throw new EndOfStreamException(); + } +#endif + public static byte[] ReadOpaque8(Stream input) { short length = ReadUint8(input); @@ -905,18 +978,16 @@ public static Asn1Object ReadAsn1Object(byte[] encoding) return result; } - public static Asn1Object ReadDerObject(byte[] encoding) + /// + public static void RequireDerEncoding(Asn1Encodable asn1, byte[] encoding) { /* * NOTE: The current ASN.1 parsing code can't enforce DER-only parsing, but since DER is * canonical, we can check it by re-encoding the result and comparing to the original. */ - Asn1Object result = ReadAsn1Object(encoding); - byte[] check = result.GetEncoded(Asn1Encodable.Der); + byte[] check = asn1.GetEncoded(Asn1Encodable.Der); if (!Arrays.AreEqual(check, encoding)) throw new TlsFatalAlert(AlertDescription.decode_error); - - return result; } public static void WriteGmtUnixTime(byte[] buf, int offset) @@ -940,7 +1011,8 @@ public static void WriteVersion(ProtocolVersion version, byte[] buf, int offset) buf[offset + 1] = (byte)version.MinorVersion; } - public static void AddIfSupported(IList supportedAlgs, TlsCrypto crypto, SignatureAndHashAlgorithm alg) + public static void AddIfSupported(IList supportedAlgs, TlsCrypto crypto, + SignatureAndHashAlgorithm alg) { if (crypto.HasSignatureAndHashAlgorithm(alg)) { @@ -948,7 +1020,7 @@ public static void AddIfSupported(IList supportedAlgs, TlsCrypto crypto, Signatu } } - public static void AddIfSupported(IList supportedGroups, TlsCrypto crypto, int namedGroup) + public static void AddIfSupported(IList supportedGroups, TlsCrypto crypto, int namedGroup) { if (crypto.HasNamedGroup(namedGroup)) { @@ -956,7 +1028,7 @@ public static void AddIfSupported(IList supportedGroups, TlsCrypto crypto, int n } } - public static void AddIfSupported(IList supportedGroups, TlsCrypto crypto, int[] namedGroups) + public static void AddIfSupported(IList supportedGroups, TlsCrypto crypto, int[] namedGroups) { for (int i = 0; i < namedGroups.Length; ++i) { @@ -964,7 +1036,7 @@ public static void AddIfSupported(IList supportedGroups, TlsCrypto crypto, int[] } } - public static bool AddToSet(IList s, int i) + public static bool AddToSet(IList s, T i) { bool result = !s.Contains(i); if (result) @@ -974,17 +1046,17 @@ public static bool AddToSet(IList s, int i) return result; } - public static IList GetDefaultDssSignatureAlgorithms() + public static IList GetDefaultDssSignatureAlgorithms() { return GetDefaultSignatureAlgorithms(SignatureAlgorithm.dsa); } - public static IList GetDefaultECDsaSignatureAlgorithms() + public static IList GetDefaultECDsaSignatureAlgorithms() { return GetDefaultSignatureAlgorithms(SignatureAlgorithm.ecdsa); } - public static IList GetDefaultRsaSignatureAlgorithms() + public static IList GetDefaultRsaSignatureAlgorithms() { return GetDefaultSignatureAlgorithms(SignatureAlgorithm.rsa); } @@ -1016,52 +1088,58 @@ public static SignatureAndHashAlgorithm GetDefaultSignatureAlgorithm(short signa } } - public static IList GetDefaultSignatureAlgorithms(short signatureAlgorithm) + public static IList GetDefaultSignatureAlgorithms(short signatureAlgorithm) { SignatureAndHashAlgorithm sigAndHashAlg = GetDefaultSignatureAlgorithm(signatureAlgorithm); - return null == sigAndHashAlg ? BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList() : VectorOfOne(sigAndHashAlg); + return null == sigAndHashAlg ? new List() : VectorOfOne(sigAndHashAlg); } - public static IList GetDefaultSupportedSignatureAlgorithms(TlsContext context) + public static IList GetDefaultSupportedSignatureAlgorithms(TlsContext context) + { + return GetSupportedSignatureAlgorithms(context, DefaultSupportedSigAlgs); + } + + public static IList GetSupportedSignatureAlgorithms(TlsContext context, + IList candidates) { TlsCrypto crypto = context.Crypto; - IList result = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(DefaultSupportedSigAlgs.Count); - foreach (SignatureAndHashAlgorithm sigAndHashAlg in DefaultSupportedSigAlgs) + var result = new List(candidates.Count); + foreach (SignatureAndHashAlgorithm sigAndHashAlg in candidates) { AddIfSupported(result, crypto, sigAndHashAlg); } return result; } - public static SignatureAndHashAlgorithm GetSignatureAndHashAlgorithm(TlsContext context, - TlsCredentialedSigner signerCredentials) - { - return GetSignatureAndHashAlgorithm(context.ServerVersion, signerCredentials); - } - internal static SignatureAndHashAlgorithm GetSignatureAndHashAlgorithm(ProtocolVersion negotiatedVersion, - TlsCredentialedSigner signerCredentials) + TlsCredentialedSigner credentialedSigner) { SignatureAndHashAlgorithm signatureAndHashAlgorithm = null; - if (IsTlsV12(negotiatedVersion)) + if (IsSignatureAlgorithmsExtensionAllowed(negotiatedVersion)) { - signatureAndHashAlgorithm = signerCredentials.SignatureAndHashAlgorithm; + signatureAndHashAlgorithm = credentialedSigner.SignatureAndHashAlgorithm; if (signatureAndHashAlgorithm == null) + { + /* + * RFC 5246 4.7. digitally-signed element needs SignatureAndHashAlgorithm from TLS 1.2 + */ throw new TlsFatalAlert(AlertDescription.internal_error); + } } return signatureAndHashAlgorithm; } - public static byte[] GetExtensionData(IDictionary extensions, int extensionType) + public static byte[] GetExtensionData(IDictionary extensions, int extensionType) { - return extensions == null || !extensions.Contains(extensionType) - ? null - : (byte[])extensions[extensionType]; + if (extensions == null || !extensions.TryGetValue(extensionType, out var extensionData)) + return null; + + return extensionData; } - public static bool HasExpectedEmptyExtensionData(IDictionary extensions, int extensionType, + public static bool HasExpectedEmptyExtensionData(IDictionary extensions, int extensionType, short alertDescription) { byte[] extension_data = GetExtensionData(extensions, extensionType); @@ -1106,22 +1184,7 @@ public static bool IsNullOrContainsNull(object[] array) return false; } - public static bool IsNullOrEmpty(byte[] array) - { - return null == array || array.Length < 1; - } - - public static bool IsNullOrEmpty(short[] array) - { - return null == array || array.Length < 1; - } - - public static bool IsNullOrEmpty(int[] array) - { - return null == array || array.Length < 1; - } - - public static bool IsNullOrEmpty(object[] array) + public static bool IsNullOrEmpty(T[] array) { return null == array || array.Length < 1; } @@ -1131,7 +1194,7 @@ public static bool IsNullOrEmpty(string s) return null == s || s.Length < 1; } - public static bool IsNullOrEmpty(IList v) + public static bool IsNullOrEmpty(IList v) { return null == v || v.Count < 1; } @@ -1241,9 +1304,9 @@ public static short GetLegacySignatureAlgorithmServerCert(int keyExchangeAlgorit } } - public static IList GetLegacySupportedSignatureAlgorithms() + public static IList GetLegacySupportedSignatureAlgorithms() { - IList result = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(3); + var result = new List(3); result.Add(SignatureAndHashAlgorithm.GetInstance(HashAlgorithm.sha1, SignatureAlgorithm.dsa)); result.Add(SignatureAndHashAlgorithm.GetInstance(HashAlgorithm.sha1, SignatureAlgorithm.ecdsa)); result.Add(SignatureAndHashAlgorithm.GetInstance(HashAlgorithm.sha1, SignatureAlgorithm.rsa)); @@ -1251,10 +1314,12 @@ public static IList GetLegacySupportedSignatureAlgorithms() } /// - public static void EncodeSupportedSignatureAlgorithms(IList supportedSignatureAlgorithms, Stream output) + public static void EncodeSupportedSignatureAlgorithms( + IList supportedSignatureAlgorithms, Stream output) { - if (supportedSignatureAlgorithms == null || supportedSignatureAlgorithms.Count < 1 - || supportedSignatureAlgorithms.Count >= (1 << 15)) + if (supportedSignatureAlgorithms == null || + supportedSignatureAlgorithms.Count < 1 || + supportedSignatureAlgorithms.Count >= (1 << 15)) { throw new ArgumentException("must have length from 1 to (2^15 - 1)", "supportedSignatureAlgorithms"); } @@ -1279,7 +1344,7 @@ public static void EncodeSupportedSignatureAlgorithms(IList supportedSignatureAl } /// - public static IList ParseSupportedSignatureAlgorithms(Stream input) + public static IList ParseSupportedSignatureAlgorithms(Stream input) { // supported_signature_algorithms int length = ReadUint16(input); @@ -1287,7 +1352,7 @@ public static IList ParseSupportedSignatureAlgorithms(Stream input) throw new TlsFatalAlert(AlertDescription.decode_error); int count = length / 2; - IList supportedSignatureAlgorithms = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(count); + var supportedSignatureAlgorithms = new List(count); for (int i = 0; i < count; ++i) { SignatureAndHashAlgorithm sigAndHashAlg = SignatureAndHashAlgorithm.Parse(input); @@ -1301,8 +1366,17 @@ public static IList ParseSupportedSignatureAlgorithms(Stream input) } /// - public static void VerifySupportedSignatureAlgorithm(IList supportedSignatureAlgorithms, - SignatureAndHashAlgorithm signatureAlgorithm) + public static void VerifySupportedSignatureAlgorithm( + IList supportedSignatureAlgorithms, SignatureAndHashAlgorithm signatureAlgorithm) + { + VerifySupportedSignatureAlgorithm(supportedSignatureAlgorithms, signatureAlgorithm, + AlertDescription.illegal_parameter); + } + + /// + internal static void VerifySupportedSignatureAlgorithm( + IList supportedSignatureAlgorithms, SignatureAndHashAlgorithm signatureAlgorithm, + short alertDescription) { if (supportedSignatureAlgorithms == null || supportedSignatureAlgorithms.Count < 1 || supportedSignatureAlgorithms.Count >= (1 << 15)) @@ -1315,12 +1389,12 @@ public static void VerifySupportedSignatureAlgorithm(IList supportedSignatureAlg if (signatureAlgorithm.Signature == SignatureAlgorithm.anonymous || !ContainsSignatureAlgorithm(supportedSignatureAlgorithms, signatureAlgorithm)) { - throw new TlsFatalAlert(AlertDescription.illegal_parameter); + throw new TlsFatalAlert(alertDescription); } } /// - public static bool ContainsSignatureAlgorithm(IList supportedSignatureAlgorithms, + public static bool ContainsSignatureAlgorithm(IList supportedSignatureAlgorithms, SignatureAndHashAlgorithm signatureAlgorithm) { foreach (SignatureAndHashAlgorithm entry in supportedSignatureAlgorithms) @@ -1332,7 +1406,8 @@ public static bool ContainsSignatureAlgorithm(IList supportedSignatureAlgorithms return false; } - public static bool ContainsAnySignatureAlgorithm(IList supportedSignatureAlgorithms, short signatureAlgorithm) + public static bool ContainsAnySignatureAlgorithm(IList supportedSignatureAlgorithms, + short signatureAlgorithm) { foreach (SignatureAndHashAlgorithm entry in supportedSignatureAlgorithms) { @@ -1349,6 +1424,14 @@ public static TlsSecret Prf(SecurityParameters securityParameters, TlsSecret sec return secret.DeriveUsingPrf(securityParameters.PrfAlgorithm, asciiLabel, seed, length); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static TlsSecret Prf(SecurityParameters securityParameters, TlsSecret secret, + ReadOnlySpan asciiLabel, ReadOnlySpan seed, int length) + { + return secret.DeriveUsingPrf(securityParameters.PrfAlgorithm, asciiLabel, seed, length); + } +#endif + public static byte[] Clone(byte[] data) { return null == data ? null : data.Length == 0 ? EmptyBytes : (byte[])data.Clone(); @@ -1369,6 +1452,18 @@ public static bool ConstantTimeAreEqual(int len, byte[] a, int aOff, byte[] b, i return 0 == d; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static bool ConstantTimeAreEqual(int len, Span a, int aOff, byte[] b, int bOff) + { + int d = 0; + for (int i = 0; i < len; ++i) + { + d |= a[aOff + i] ^ b[bOff + i]; + } + return 0 == d; + } +#endif + public static byte[] CopyOfRangeExact(byte[] original, int from, int to) { int newLength = to - from; @@ -1422,9 +1517,9 @@ internal static byte[] CalculateEndPointHash(TlsContext context, TlsCertificate } else { - if (CertSigAlgOids.Contains(sigAlgOid)) + if (CertSigAlgOids.TryGetValue(sigAlgOid, out var algorithm)) { - hashAlgorithm = ((SignatureAndHashAlgorithm)CertSigAlgOids[sigAlgOid]).Hash; + hashAlgorithm = algorithm.Hash; } } } @@ -1632,9 +1727,9 @@ internal static void Establish13PhaseApplication(TlsContext context, byte[] serv securityParameters.m_exporterMasterSecret = DeriveSecret(securityParameters, phaseSecret, "exp master", serverFinishedTranscriptHash); - KeyLogFileWriter.WriteLabel(Labels.CLIENT_TRAFFIC_SECRET_0, securityParameters); - KeyLogFileWriter.WriteLabel(Labels.SERVER_TRAFFIC_SECRET_0, securityParameters); - KeyLogFileWriter.WriteLabel(Labels.EXPORTER_SECRET, securityParameters); + Connections.TLS.KeyLogFileWriter.WriteLabel(Connections.TLS.Labels.CLIENT_TRAFFIC_SECRET_0, securityParameters); + Connections.TLS.KeyLogFileWriter.WriteLabel(Connections.TLS.Labels.SERVER_TRAFFIC_SECRET_0, securityParameters); + Connections.TLS.KeyLogFileWriter.WriteLabel(Connections.TLS.Labels.EXPORTER_SECRET, securityParameters); } internal static void Establish13PhaseEarly(TlsContext context, byte[] clientHelloTranscriptHash, @@ -1665,8 +1760,8 @@ internal static void Establish13PhaseHandshake(TlsContext context, byte[] server Establish13TrafficSecrets(context, serverHelloTranscriptHash, phaseSecret, "c hs traffic", "s hs traffic", recordStream); - KeyLogFileWriter.WriteLabel(Labels.CLIENT_HANDSHAKE_TRAFFIC_SECRET, securityParameters); - KeyLogFileWriter.WriteLabel(Labels.SERVER_HANDSHAKE_TRAFFIC_SECRET, securityParameters); + Connections.TLS.KeyLogFileWriter.WriteLabel(Connections.TLS.Labels.CLIENT_HANDSHAKE_TRAFFIC_SECRET, securityParameters); + Connections.TLS.KeyLogFileWriter.WriteLabel(Connections.TLS.Labels.SERVER_HANDSHAKE_TRAFFIC_SECRET, securityParameters); securityParameters.m_baseKeyClient = securityParameters.TrafficSecretClient; securityParameters.m_baseKeyServer = securityParameters.TrafficSecretServer; @@ -2052,7 +2147,7 @@ internal static byte[] CalculateSignatureHash(TlsContext context, SignatureAndHa TlsHash h = algorithm == null ? new CombinedHash(crypto) - : CreateHash(crypto, algorithm.Hash); + : CreateHash(crypto, algorithm); SecurityParameters sp = context.SecurityParameters; // NOTE: The implicit copy here is intended (and important) @@ -2082,54 +2177,44 @@ internal static void SendSignatureInput(TlsContext context, byte[] extraSignatur output.Write(extraSignatureInput, 0, extraSignatureInput.Length); } - buf.CopyTo(output); + buf.CopyInputTo(output); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(output); + output.Dispose(); } internal static DigitallySigned GenerateCertificateVerifyClient(TlsClientContext clientContext, - TlsCredentialedSigner credentialedSigner, TlsStreamSigner streamSigner, TlsHandshakeHash handshakeHash) + TlsCredentialedSigner clientAuthSigner, SignatureAndHashAlgorithm clientAuthAlgorithm, + TlsStreamSigner clientAuthStreamSigner, TlsHandshakeHash handshakeHash) { SecurityParameters securityParameters = clientContext.SecurityParameters; - ProtocolVersion negotiatedVersion = securityParameters.NegotiatedVersion; - - if (IsTlsV13(negotiatedVersion)) + if (IsTlsV13(securityParameters.NegotiatedVersion)) { - // Should be using GenerateCertificateVerify13 instead + // Should be using Generate13CertificateVerify instead throw new TlsFatalAlert(AlertDescription.internal_error); } - /* - * RFC 5246 4.7. digitally-signed element needs SignatureAndHashAlgorithm from TLS 1.2 - */ - SignatureAndHashAlgorithm signatureAndHashAlgorithm = GetSignatureAndHashAlgorithm(negotiatedVersion, - credentialedSigner); - byte[] signature; - if (streamSigner != null) + if (clientAuthStreamSigner != null) { - handshakeHash.CopyBufferTo(streamSigner.GetOutputStream()); - signature = streamSigner.GetSignature(); + handshakeHash.CopyBufferTo(clientAuthStreamSigner.Stream); + signature = clientAuthStreamSigner.GetSignature(); } else { byte[] hash; - if (signatureAndHashAlgorithm == null) + if (clientAuthAlgorithm == null) { hash = securityParameters.SessionHash; } else { - int signatureScheme = SignatureScheme.From(signatureAndHashAlgorithm); - int cryptoHashAlgorithm = SignatureScheme.GetCryptoHashAlgorithm(signatureScheme); - - hash = handshakeHash.GetFinalHash(cryptoHashAlgorithm); + hash = handshakeHash.GetFinalHash(SignatureScheme.GetCryptoHashAlgorithm(clientAuthAlgorithm)); } - signature = credentialedSigner.GenerateRawSignature(hash); + signature = clientAuthSigner.GenerateRawSignature(hash); } - return new DigitallySigned(signatureAndHashAlgorithm, signature); + return new DigitallySigned(clientAuthAlgorithm, signature); } internal static DigitallySigned Generate13CertificateVerify(TlsContext context, @@ -2159,16 +2244,13 @@ private static byte[] Generate13CertificateVerify(TlsCrypto crypto, TlsCredentia if (null != streamSigner) { - Stream output = streamSigner.GetOutputStream(); + Stream output = streamSigner.Stream; output.Write(header, 0, header.Length); output.Write(prfHash, 0, prfHash.Length); return streamSigner.GetSignature(); } - int signatureScheme = SignatureScheme.From(signatureAndHashAlgorithm); - int cryptoHashAlgorithm = SignatureScheme.GetCryptoHashAlgorithm(signatureScheme); - - TlsHash tlsHash = crypto.CreateHash(cryptoHashAlgorithm); + TlsHash tlsHash = CreateHash(crypto, signatureAndHashAlgorithm); tlsHash.Update(header, 0, header.Length); tlsHash.Update(prfHash, 0, prfHash.Length); byte[] hash = tlsHash.CalculateHash(); @@ -2188,22 +2270,17 @@ internal static void VerifyCertificateVerifyClient(TlsServerContext serverContex { signatureAlgorithm = verifyingCert.GetLegacySignatureAlgorithm(); - short clientCertType = GetLegacyClientCertType(signatureAlgorithm); - if (clientCertType < 0 || !Arrays.Contains(certificateRequest.CertificateTypes, clientCertType)) - throw new TlsFatalAlert(AlertDescription.unsupported_certificate); + CheckClientCertificateType(certificateRequest, GetLegacyClientCertType(signatureAlgorithm), + AlertDescription.unsupported_certificate); } else { - signatureAlgorithm = sigAndHashAlg.Signature; + VerifySupportedSignatureAlgorithm(securityParameters.ServerSigAlgs, sigAndHashAlg); - // TODO Is it possible (maybe only pre-1.2 to check this immediately when the Certificate arrives? - if (!IsValidSignatureAlgorithmForCertificateVerify(signatureAlgorithm, - certificateRequest.CertificateTypes)) - { - throw new TlsFatalAlert(AlertDescription.illegal_parameter); - } + signatureAlgorithm = sigAndHashAlg.Signature; - VerifySupportedSignatureAlgorithm(securityParameters.ServerSigAlgs, sigAndHashAlg); + CheckClientCertificateType(certificateRequest, + SignatureAlgorithm.GetClientCertificateType(signatureAlgorithm), AlertDescription.illegal_parameter); } // Verify the CertificateVerify message contains a correct signature. @@ -2215,7 +2292,7 @@ internal static void VerifyCertificateVerifyClient(TlsServerContext serverContex if (streamVerifier != null) { - handshakeHash.CopyBufferTo(streamVerifier.GetOutputStream()); + handshakeHash.CopyBufferTo(streamVerifier.Stream); verified = streamVerifier.IsVerified(); } else @@ -2223,10 +2300,7 @@ internal static void VerifyCertificateVerifyClient(TlsServerContext serverContex byte[] hash; if (IsTlsV12(serverContext)) { - int signatureScheme = SignatureScheme.From(sigAndHashAlg); - int cryptoHashAlgorithm = SignatureScheme.GetCryptoHashAlgorithm(signatureScheme); - - hash = handshakeHash.GetFinalHash(cryptoHashAlgorithm); + hash = handshakeHash.GetFinalHash(SignatureScheme.GetCryptoHashAlgorithm(sigAndHashAlg)); } else { @@ -2251,62 +2325,55 @@ internal static void VerifyCertificateVerifyClient(TlsServerContext serverContex } } + /// internal static void Verify13CertificateVerifyClient(TlsServerContext serverContext, - CertificateRequest certificateRequest, DigitallySigned certificateVerify, TlsHandshakeHash handshakeHash) + TlsHandshakeHash handshakeHash, CertificateVerify certificateVerify) { SecurityParameters securityParameters = serverContext.SecurityParameters; - Certificate clientCertificate = securityParameters.PeerCertificate; - TlsCertificate verifyingCert = clientCertificate.GetCertificateAt(0); - - SignatureAndHashAlgorithm sigAndHashAlg = certificateVerify.Algorithm; - VerifySupportedSignatureAlgorithm(securityParameters.ServerSigAlgs, sigAndHashAlg); - - int signatureScheme = SignatureScheme.From(sigAndHashAlg); - // Verify the CertificateVerify message contains a correct signature. - bool verified; - try - { - TlsVerifier verifier = verifyingCert.CreateVerifier(signatureScheme); + var supportedAlgorithms = securityParameters.ServerSigAlgs; + TlsCertificate certificate = securityParameters.PeerCertificate.GetCertificateAt(0); - verified = Verify13CertificateVerify(serverContext.Crypto, certificateVerify, verifier, - "TLS 1.3, client CertificateVerify", handshakeHash); - } - catch (TlsFatalAlert e) - { - throw e; - } - catch (Exception e) - { - throw new TlsFatalAlert(AlertDescription.decrypt_error, e); - } - - if (!verified) - { - throw new TlsFatalAlert(AlertDescription.decrypt_error); - } + Verify13CertificateVerify(supportedAlgorithms, "TLS 1.3, client CertificateVerify", handshakeHash, + certificate, certificateVerify); } + /// internal static void Verify13CertificateVerifyServer(TlsClientContext clientContext, - DigitallySigned certificateVerify, TlsHandshakeHash handshakeHash) + TlsHandshakeHash handshakeHash, CertificateVerify certificateVerify) { SecurityParameters securityParameters = clientContext.SecurityParameters; - Certificate serverCertificate = securityParameters.PeerCertificate; - TlsCertificate verifyingCert = serverCertificate.GetCertificateAt(0); - SignatureAndHashAlgorithm sigAndHashAlg = certificateVerify.Algorithm; - VerifySupportedSignatureAlgorithm(securityParameters.ClientSigAlgs, sigAndHashAlg); + var supportedAlgorithms = securityParameters.ClientSigAlgs; + TlsCertificate certificate = securityParameters.PeerCertificate.GetCertificateAt(0); - int signatureScheme = SignatureScheme.From(sigAndHashAlg); + Verify13CertificateVerify(supportedAlgorithms, "TLS 1.3, server CertificateVerify", handshakeHash, + certificate, certificateVerify); + } + /// + private static void Verify13CertificateVerify(IList supportedAlgorithms, + string contextString, TlsHandshakeHash handshakeHash, TlsCertificate certificate, + CertificateVerify certificateVerify) + { // Verify the CertificateVerify message contains a correct signature. bool verified; try { - TlsVerifier verifier = verifyingCert.CreateVerifier(signatureScheme); + int signatureScheme = certificateVerify.Algorithm; + + SignatureAndHashAlgorithm algorithm = SignatureScheme.GetSignatureAndHashAlgorithm(signatureScheme); + VerifySupportedSignatureAlgorithm(supportedAlgorithms, algorithm); - verified = Verify13CertificateVerify(clientContext.Crypto, certificateVerify, verifier, - "TLS 1.3, server CertificateVerify", handshakeHash); + Tls13Verifier verifier = certificate.CreateVerifier(signatureScheme); + + byte[] header = GetCertificateVerifyHeader(contextString); + byte[] prfHash = GetCurrentPrfHash(handshakeHash); + + Stream output = verifier.Stream; + output.Write(header, 0, header.Length); + output.Write(prfHash, 0, prfHash.Length); + verified = verifier.VerifySignature(certificateVerify.Signature); } catch (TlsFatalAlert e) { @@ -2323,32 +2390,6 @@ internal static void Verify13CertificateVerifyServer(TlsClientContext clientCont } } - private static bool Verify13CertificateVerify(TlsCrypto crypto, DigitallySigned certificateVerify, - TlsVerifier verifier, string contextString, TlsHandshakeHash handshakeHash) - { - TlsStreamVerifier streamVerifier = verifier.GetStreamVerifier(certificateVerify); - - byte[] header = GetCertificateVerifyHeader(contextString); - byte[] prfHash = GetCurrentPrfHash(handshakeHash); - - if (null != streamVerifier) - { - Stream output = streamVerifier.GetOutputStream(); - output.Write(header, 0, header.Length); - output.Write(prfHash, 0, prfHash.Length); - return streamVerifier.IsVerified(); - } - - int signatureScheme = SignatureScheme.From(certificateVerify.Algorithm); - int cryptoHashAlgorithm = SignatureScheme.GetCryptoHashAlgorithm(signatureScheme); - - TlsHash tlsHash = crypto.CreateHash(cryptoHashAlgorithm); - tlsHash.Update(header, 0, header.Length); - tlsHash.Update(prfHash, 0, prfHash.Length); - byte[] hash = tlsHash.CalculateHash(); - return verifier.VerifyRawSignature(certificateVerify, hash); - } - private static byte[] GetCertificateVerifyHeader(string contextString) { int count = contextString.Length; @@ -2373,13 +2414,13 @@ internal static void GenerateServerKeyExchangeSignature(TlsContext context, TlsC /* * RFC 5246 4.7. digitally-signed element needs SignatureAndHashAlgorithm from TLS 1.2 */ - SignatureAndHashAlgorithm algorithm = GetSignatureAndHashAlgorithm(context, credentials); + SignatureAndHashAlgorithm algorithm = GetSignatureAndHashAlgorithm(context.ServerVersion, credentials); TlsStreamSigner streamSigner = credentials.GetStreamSigner(); byte[] signature; if (streamSigner != null) { - SendSignatureInput(context, extraSignatureInput, digestBuffer, streamSigner.GetOutputStream()); + SendSignatureInput(context, extraSignatureInput, digestBuffer, streamSigner.Stream); signature = streamSigner.GetSignature(); } else @@ -2425,7 +2466,7 @@ internal static void VerifyServerKeyExchangeSignature(TlsContext context, Stream bool verified; if (streamVerifier != null) { - SendSignatureInput(context, null, digestBuffer, streamVerifier.GetOutputStream()); + SendSignatureInput(context, null, digestBuffer, streamVerifier.Stream); verified = streamVerifier.IsVerified(); } else @@ -2440,28 +2481,29 @@ internal static void VerifyServerKeyExchangeSignature(TlsContext context, Stream } } - internal static void TrackHashAlgorithms(TlsHandshakeHash handshakeHash, IList supportedSignatureAlgorithms) + internal static void TrackHashAlgorithmClient(TlsHandshakeHash handshakeHash, + SignatureAndHashAlgorithm signatureAndHashAlgorithm) { - if (supportedSignatureAlgorithms != null) + int cryptoHashAlgorithm = SignatureScheme.GetCryptoHashAlgorithm(signatureAndHashAlgorithm); + if (cryptoHashAlgorithm >= 0) { - foreach (SignatureAndHashAlgorithm signatureAndHashAlgorithm in supportedSignatureAlgorithms) - { - /* - * TODO We could validate the signature algorithm part. Currently the impact is - * that we might be tracking extra hashes pointlessly (but there are only a - * limited number of recognized hash algorithms). - */ - int signatureScheme = SignatureScheme.From(signatureAndHashAlgorithm); - int cryptoHashAlgorithm = SignatureScheme.GetCryptoHashAlgorithm(signatureScheme); + handshakeHash.TrackHashAlgorithm(cryptoHashAlgorithm); + } + } - if (cryptoHashAlgorithm >= 0) - { - handshakeHash.TrackHashAlgorithm(cryptoHashAlgorithm); - } - else if (HashAlgorithm.Intrinsic == signatureAndHashAlgorithm.Hash) - { - handshakeHash.ForceBuffering(); - } + internal static void TrackHashAlgorithms(TlsHandshakeHash handshakeHash, + IList supportedSignatureAlgorithms) + { + foreach (SignatureAndHashAlgorithm signatureAndHashAlgorithm in supportedSignatureAlgorithms) + { + int cryptoHashAlgorithm = SignatureScheme.GetCryptoHashAlgorithm(signatureAndHashAlgorithm); + if (cryptoHashAlgorithm >= 0) + { + handshakeHash.TrackHashAlgorithm(cryptoHashAlgorithm); + } + else if (HashAlgorithm.Intrinsic == signatureAndHashAlgorithm.Hash) + { + handshakeHash.ForceBuffering(); } } } @@ -2479,9 +2521,9 @@ public static bool HasSigningCapability(short clientCertificateType) } } - public static IList VectorOfOne(object obj) + public static IList VectorOfOne(T obj) { - IList v = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(1); + var v = new List(1); v.Add(obj); return v; } @@ -3223,9 +3265,9 @@ public static int GetKeyExchangeAlgorithm(int cipherSuite) } } - public static IList GetKeyExchangeAlgorithms(int[] cipherSuites) + public static IList GetKeyExchangeAlgorithms(int[] cipherSuites) { - IList result = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var result = new List(); if (null != cipherSuites) { for (int i = 0; i < cipherSuites.Length; ++i) @@ -3743,14 +3785,14 @@ public static ProtocolVersion GetMinimumVersion(int cipherSuite) } } - public static IList GetNamedGroupRoles(int[] cipherSuites) + public static IList GetNamedGroupRoles(int[] cipherSuites) { return GetNamedGroupRoles(GetKeyExchangeAlgorithms(cipherSuites)); } - public static IList GetNamedGroupRoles(IList keyExchangeAlgorithms) + public static IList GetNamedGroupRoles(IList keyExchangeAlgorithms) { - IList result = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var result = new List(); foreach (int keyExchangeAlgorithm in keyExchangeAlgorithms) { switch (keyExchangeAlgorithm) @@ -3815,7 +3857,7 @@ public static bool IsStreamCipherSuite(int cipherSuite) /// Whether a server can select the specified cipher suite given the available signature algorithms /// for ServerKeyExchange. - public static bool IsValidCipherSuiteForSignatureAlgorithms(int cipherSuite, IList sigAlgs) + public static bool IsValidCipherSuiteForSignatureAlgorithms(int cipherSuite, IList sigAlgs) { int keyExchangeAlgorithm = GetKeyExchangeAlgorithm(cipherSuite); @@ -3852,22 +3894,14 @@ internal static bool IsValidCipherSuiteSelection(int[] offeredCipherSuites, int } internal static bool IsValidKeyShareSelection(ProtocolVersion negotiatedVersion, int[] clientSupportedGroups, - IDictionary clientAgreements, int keyShareGroup) + IDictionary clientAgreements, int keyShareGroup) { return null != clientSupportedGroups && Arrays.Contains(clientSupportedGroups, keyShareGroup) - && !clientAgreements.Contains(keyShareGroup) + && !clientAgreements.ContainsKey(keyShareGroup) && NamedGroup.CanBeNegotiated(keyShareGroup, negotiatedVersion); } - internal static bool IsValidSignatureAlgorithmForCertificateVerify(short signatureAlgorithm, - short[] clientCertificateTypes) - { - short clientCertificateType = SignatureAlgorithm.GetClientCertificateType(signatureAlgorithm); - - return clientCertificateType >= 0 && Arrays.Contains(clientCertificateTypes, clientCertificateType); - } - internal static bool IsValidSignatureAlgorithmForServerKeyExchange(short signatureAlgorithm, int keyExchangeAlgorithm) { @@ -3938,20 +3972,19 @@ public static bool IsValidVersionForCipherSuite(int cipherSuite, ProtocolVersion } /// - public static SignatureAndHashAlgorithm ChooseSignatureAndHashAlgorithm(TlsContext context, IList sigHashAlgs, - short signatureAlgorithm) + public static SignatureAndHashAlgorithm ChooseSignatureAndHashAlgorithm(TlsContext context, + IList sigHashAlgs, short signatureAlgorithm) { return ChooseSignatureAndHashAlgorithm(context.ServerVersion, sigHashAlgs, signatureAlgorithm); } /// public static SignatureAndHashAlgorithm ChooseSignatureAndHashAlgorithm(ProtocolVersion negotiatedVersion, - IList sigHashAlgs, short signatureAlgorithm) + IList sigHashAlgs, short signatureAlgorithm) { if (!IsTlsV12(negotiatedVersion)) return null; - if (sigHashAlgs == null) { /* @@ -4000,33 +4033,25 @@ public static SignatureAndHashAlgorithm ChooseSignatureAndHashAlgorithm(Protocol return result; } - public static IList GetUsableSignatureAlgorithms(IList sigHashAlgs) + public static IList GetUsableSignatureAlgorithms(IList sigHashAlgs) { if (sigHashAlgs == null) + return new List(){ SignatureAlgorithm.rsa, SignatureAlgorithm.dsa, SignatureAlgorithm.ecdsa }; + + var v = new List(); + foreach (SignatureAndHashAlgorithm sigHashAlg in sigHashAlgs) { - IList v = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(3); - v.Add(SignatureAlgorithm.rsa); - v.Add(SignatureAlgorithm.dsa); - v.Add(SignatureAlgorithm.ecdsa); - return v; - } - else - { - IList v = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); - foreach (SignatureAndHashAlgorithm sigHashAlg in sigHashAlgs) + if (sigHashAlg.Hash >= MinimumHashStrict) { - if (sigHashAlg.Hash >= MinimumHashStrict) + short sigAlg = sigHashAlg.Signature; + if (!v.Contains(sigAlg)) { - short sigAlg = sigHashAlg.Signature; - if (!v.Contains(sigAlg)) - { - // TODO Check for crypto support before choosing (or pass in cached list?) - v.Add(sigAlg); - } + // TODO Check for crypto support before choosing (or pass in cached list?) + v.Add(sigAlg); } } - return v; } + return v; } public static int GetCommonCipherSuite13(ProtocolVersion negotiatedVersion, int[] peerCipherSuites, @@ -4110,9 +4135,22 @@ public static int[] GetSupportedCipherSuites(TlsCrypto crypto, int[] suites, int public static bool IsSupportedCipherSuite(TlsCrypto crypto, int cipherSuite) { - return IsSupportedKeyExchange(crypto, GetKeyExchangeAlgorithm(cipherSuite)) - && crypto.HasEncryptionAlgorithm(GetEncryptionAlgorithm(cipherSuite)) - && crypto.HasMacAlgorithm(GetMacAlgorithm(cipherSuite)); + int keyExchangeAlgorithm = GetKeyExchangeAlgorithm(cipherSuite); + if (!IsSupportedKeyExchange(crypto, keyExchangeAlgorithm)) + return false; + + int encryptionAlgorithm = GetEncryptionAlgorithm(cipherSuite); + if (encryptionAlgorithm < 0 || !crypto.HasEncryptionAlgorithm(encryptionAlgorithm)) + return false; + + int macAlgorithm = GetMacAlgorithm(cipherSuite); + if (macAlgorithm != MacAlgorithm.cls_null) + { + if (macAlgorithm < 0 || !crypto.HasMacAlgorithm(macAlgorithm)) + return false; + } + + return true; } public static bool IsSupportedKeyExchange(TlsCrypto crypto, int keyExchangeAlgorithm) @@ -4189,21 +4227,14 @@ internal static byte[] GetCurrentPrfHash(TlsHandshakeHash handshakeHash) return handshakeHash.ForkPrfHash().CalculateHash(); } - internal static void SealHandshakeHash(TlsContext context, TlsHandshakeHash handshakeHash, bool forceBuffering) + private static TlsHash CreateHash(TlsCrypto crypto, short hashAlgorithm) { - if (forceBuffering || !context.Crypto.HasAllRawSignatureAlgorithms()) - { - handshakeHash.ForceBuffering(); - } - - handshakeHash.SealHashAlgorithms(); + return crypto.CreateHash(TlsCryptoUtilities.GetHash(hashAlgorithm)); } - private static TlsHash CreateHash(TlsCrypto crypto, short hashAlgorithm) + private static TlsHash CreateHash(TlsCrypto crypto, SignatureAndHashAlgorithm signatureAndHashAlgorithm) { - int cryptoHashAlgorithm = TlsCryptoUtilities.GetHash(hashAlgorithm); - - return crypto.CreateHash(cryptoHashAlgorithm); + return crypto.CreateHash(SignatureScheme.GetCryptoHashAlgorithm(signatureAndHashAlgorithm)); } /// @@ -4377,7 +4408,7 @@ private static void CheckSigAlgOfClientCerts(TlsContext context, TlsCertificate[ { SecurityParameters securityParameters = context.SecurityParameters; short[] clientCertTypes = securityParameters.ClientCertTypes; - IList serverSigAlgsCert = securityParameters.ServerSigAlgsCert; + var serverSigAlgsCert = securityParameters.ServerSigAlgsCert; int trustAnchorPos = clientCertPath.Length - 1; for (int i = 0; i < trustAnchorPos; ++i) @@ -4427,8 +4458,8 @@ private static void CheckSigAlgOfClientCerts(TlsContext context, TlsCertificate[ private static void CheckSigAlgOfServerCerts(TlsContext context, TlsCertificate[] serverCertPath) { SecurityParameters securityParameters = context.SecurityParameters; - IList clientSigAlgsCert = securityParameters.ClientSigAlgsCert; - IList clientSigAlgs = securityParameters.ClientSigAlgs; + var clientSigAlgsCert = securityParameters.ClientSigAlgsCert; + var clientSigAlgs = securityParameters.ClientSigAlgs; /* * NOTE: For TLS 1.2, we'll check 'signature_algorithms' too (if it's distinct), since @@ -4479,8 +4510,8 @@ private static void CheckSigAlgOfServerCerts(TlsContext context, TlsCertificate[ } } - internal static void CheckTlsFeatures(Certificate serverCertificate, IDictionary clientExtensions, - IDictionary serverExtensions) + internal static void CheckTlsFeatures(Certificate serverCertificate, IDictionary clientExtensions, + IDictionary serverExtensions) { /* * RFC 7633 4.3.3. A client MUST treat a certificate with a TLS feature extension as an @@ -4490,13 +4521,26 @@ internal static void CheckTlsFeatures(Certificate serverCertificate, IDictionary byte[] tlsFeatures = serverCertificate.GetCertificateAt(0).GetExtension(TlsObjectIdentifiers.id_pe_tlsfeature); if (tlsFeatures != null) { - foreach (DerInteger tlsExtension in Asn1Sequence.GetInstance(ReadDerObject(tlsFeatures))) + // TODO[tls] Proper ASN.1 type class for this extension? + Asn1Sequence tlsFeaturesSeq = (Asn1Sequence)ReadAsn1Object(tlsFeatures); + for (int i = 0; i < tlsFeaturesSeq.Count; ++i) { - int extensionType = tlsExtension.IntValueExact; - CheckUint16(extensionType); + if (!(tlsFeaturesSeq[i] is DerInteger)) + throw new TlsFatalAlert(AlertDescription.bad_certificate); + } + + RequireDerEncoding(tlsFeaturesSeq, tlsFeatures); - if (clientExtensions.Contains(extensionType) && !serverExtensions.Contains(extensionType)) - throw new TlsFatalAlert(AlertDescription.certificate_unknown); + foreach (DerInteger tlsExtensionElement in tlsFeaturesSeq) + { + BigInteger tlsExtension = tlsExtensionElement.PositiveValue; + if (tlsExtension.BitLength <= 16) + { + int extensionType = tlsExtension.IntValueExact; + + if (clientExtensions.ContainsKey(extensionType) && !serverExtensions.ContainsKey(extensionType)) + throw new TlsFatalAlert(AlertDescription.certificate_unknown); + } } } } @@ -4542,7 +4586,8 @@ internal static void ProcessClientCertificate(TlsServerContext serverContext, Ce internal static void ProcessServerCertificate(TlsClientContext clientContext, CertificateStatus serverCertificateStatus, TlsKeyExchange keyExchange, - TlsAuthentication clientAuthentication, IDictionary clientExtensions, IDictionary serverExtensions) + TlsAuthentication clientAuthentication, IDictionary clientExtensions, + IDictionary serverExtensions) { SecurityParameters securityParameters = clientContext.SecurityParameters; bool isTlsV13 = IsTlsV13(securityParameters.NegotiatedVersion); @@ -4583,12 +4628,7 @@ internal static SignatureAndHashAlgorithm GetCertSigAndHashAlg(TlsCertificate su if (null != sigAlgOid) { if (!PkcsObjectIdentifiers.IdRsassaPss.Id.Equals(sigAlgOid)) - { - if (!CertSigAlgOids.Contains(sigAlgOid)) - return null; - - return (SignatureAndHashAlgorithm)CertSigAlgOids[sigAlgOid]; - } + return CollectionUtilities.GetValueOrNull(CertSigAlgOids, sigAlgOid); RsassaPssParameters pssParams = RsassaPssParameters.GetInstance(subjectCert.GetSigAlgParams()); if (null != pssParams) @@ -4736,6 +4776,17 @@ internal static TlsCredentialedSigner RequireSignerCredentials(TlsCredentials cr return (TlsCredentialedSigner)credentials; } + /// + private static void CheckClientCertificateType(CertificateRequest certificateRequest, + short clientCertificateType, short alertDescription) + { + if (clientCertificateType < 0 + || !Arrays.Contains(certificateRequest.CertificateTypes, clientCertificateType)) + { + throw new TlsFatalAlert(alertDescription); + } + } + private static void CheckDowngradeMarker(byte[] randomBlock, byte[] downgradeMarker) { int len = downgradeMarker.Length; @@ -4821,16 +4872,23 @@ private static bool isSafeRenegotiationServerCertificate(TlsClientContext client } internal static TlsAuthentication ReceiveServerCertificate(TlsClientContext clientContext, TlsClient client, - MemoryStream buf) + MemoryStream buf, IDictionary serverExtensions) { SecurityParameters securityParameters = clientContext.SecurityParameters; - if (null != securityParameters.PeerCertificate) + if (KeyExchangeAlgorithm.IsAnonymous(securityParameters.KeyExchangeAlgorithm) + || null != securityParameters.PeerCertificate) + { throw new TlsFatalAlert(AlertDescription.unexpected_message); + } MemoryStream endPointHash = new MemoryStream(); Certificate.ParseOptions options = new Certificate.ParseOptions() - .SetMaxChainLength(client.GetMaxCertificateChainLength()); + { + CertificateType = TlsExtensionsUtilities.GetServerCertificateTypeExtensionServer(serverExtensions, + CertificateType.X509), + MaxChainLength = client.GetMaxCertificateChainLength(), + }; Certificate serverCertificate = Certificate.Parse(options, clientContext, buf, endPointHash); @@ -4856,14 +4914,18 @@ internal static TlsAuthentication ReceiveServerCertificate(TlsClientContext clie } internal static TlsAuthentication Receive13ServerCertificate(TlsClientContext clientContext, TlsClient client, - MemoryStream buf) + MemoryStream buf, IDictionary serverExtensions) { SecurityParameters securityParameters = clientContext.SecurityParameters; if (null != securityParameters.PeerCertificate) throw new TlsFatalAlert(AlertDescription.unexpected_message); Certificate.ParseOptions options = new Certificate.ParseOptions() - .SetMaxChainLength(client.GetMaxCertificateChainLength()); + { + CertificateType = TlsExtensionsUtilities.GetServerCertificateTypeExtensionServer(serverExtensions, + CertificateType.X509), + MaxChainLength = client.GetMaxCertificateChainLength(), + }; Certificate serverCertificate = Certificate.Parse(options, clientContext, buf, null); @@ -4919,8 +4981,8 @@ public static bool ContainsNonAscii(string s) return false; } - internal static IDictionary AddKeyShareToClientHello(TlsClientContext clientContext, TlsClient client, - IDictionary clientExtensions) + internal static IDictionary AddKeyShareToClientHello(TlsClientContext clientContext, + TlsClient client, IDictionary clientExtensions) { /* * RFC 8446 9.2. If containing a "supported_groups" extension, it MUST also contain a @@ -4928,15 +4990,15 @@ internal static IDictionary AddKeyShareToClientHello(TlsClientContext clientCont * permitted. */ if (!IsTlsV13(clientContext.ClientVersion) - || !clientExtensions.Contains(ExtensionType.supported_groups)) + || !clientExtensions.ContainsKey(ExtensionType.supported_groups)) { return null; } - int[] supportedGroups = TlsExtensionsUtilities.GetSupportedGroupsExtension(clientExtensions); - IList keyShareGroups = client.GetEarlyKeyShareGroups(); - IDictionary clientAgreements = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(3); - IList clientShares = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(2); + var supportedGroups = TlsExtensionsUtilities.GetSupportedGroupsExtension(clientExtensions); + var keyShareGroups = client.GetEarlyKeyShareGroups(); + var clientAgreements = new Dictionary(3); + var clientShares = new List(2); CollectKeyShares(clientContext.Crypto, supportedGroups, keyShareGroups, clientAgreements, clientShares); @@ -4946,13 +5008,13 @@ internal static IDictionary AddKeyShareToClientHello(TlsClientContext clientCont return clientAgreements; } - internal static IDictionary AddKeyShareToClientHelloRetry(TlsClientContext clientContext, - IDictionary clientExtensions, int keyShareGroup) + internal static IDictionary AddKeyShareToClientHelloRetry(TlsClientContext clientContext, + IDictionary clientExtensions, int keyShareGroup) { int[] supportedGroups = new int[]{ keyShareGroup }; - IList keyShareGroups = VectorOfOne(keyShareGroup); - IDictionary clientAgreements = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(1); - IList clientShares = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(1); + var keyShareGroups = VectorOfOne(keyShareGroup); + var clientAgreements = new Dictionary(1); + var clientShares = new List(1); CollectKeyShares(clientContext.Crypto, supportedGroups, keyShareGroups, clientAgreements, clientShares); @@ -4967,8 +5029,8 @@ internal static IDictionary AddKeyShareToClientHelloRetry(TlsClientContext clien return clientAgreements; } - private static void CollectKeyShares(TlsCrypto crypto, int[] supportedGroups, IList keyShareGroups, - IDictionary clientAgreements, IList clientShares) + private static void CollectKeyShares(TlsCrypto crypto, int[] supportedGroups, IList keyShareGroups, + IDictionary clientAgreements, IList clientShares) { if (IsNullOrEmpty(supportedGroups)) return; @@ -4981,7 +5043,7 @@ private static void CollectKeyShares(TlsCrypto crypto, int[] supportedGroups, IL int supportedGroup = supportedGroups[i]; if (!keyShareGroups.Contains(supportedGroup) - || clientAgreements.Contains(supportedGroup) + || clientAgreements.ContainsKey(supportedGroup) || !crypto.HasNamedGroup(supportedGroup)) { continue; @@ -5014,7 +5076,7 @@ private static void CollectKeyShares(TlsCrypto crypto, int[] supportedGroups, IL } } - internal static KeyShareEntry SelectKeyShare(IList clientShares, int keyShareGroup) + internal static KeyShareEntry SelectKeyShare(IList clientShares, int keyShareGroup) { if (null != clientShares && 1 == clientShares.Count) { @@ -5028,7 +5090,7 @@ internal static KeyShareEntry SelectKeyShare(IList clientShares, int keyShareGro } internal static KeyShareEntry SelectKeyShare(TlsCrypto crypto, ProtocolVersion negotiatedVersion, - IList clientShares, int[] clientSupportedGroups, int[] serverSupportedGroups) + IList clientShares, int[] clientSupportedGroups, int[] serverSupportedGroups) { if (null != clientShares && !IsNullOrEmpty(clientSupportedGroups) && !IsNullOrEmpty(serverSupportedGroups)) { @@ -5152,7 +5214,7 @@ internal static TlsCredentialedSigner Establish13ClientCredentials(TlsAuthentica } internal static void EstablishClientSigAlgs(SecurityParameters securityParameters, - IDictionary clientExtensions) + IDictionary clientExtensions) { securityParameters.m_clientSigAlgs = TlsExtensionsUtilities.GetSignatureAlgorithmsExtension( clientExtensions); @@ -5387,6 +5449,7 @@ internal static bool IsPermittedExtensionType13(int handshakeType, int extension } } case ExtensionType.signature_algorithms: + case ExtensionType.compress_certificate: case ExtensionType.certificate_authorities: case ExtensionType.signature_algorithms_cert: { @@ -5476,7 +5539,8 @@ internal static bool IsPermittedExtensionType13(int handshakeType, int extension } /// - internal static void CheckExtensionData13(IDictionary extensions, int handshakeType, short alertDescription) + internal static void CheckExtensionData13(IDictionary extensions, int handshakeType, + short alertDescription) { foreach (int extensionType in extensions.Keys) { @@ -5498,21 +5562,15 @@ public static TlsSecret GenerateEncryptedPreMasterSecret(TlsContext context, Tls return preMasterSecret; } -#if !PORTABLE || NETFX_CORE || DOTNET public static bool IsTimeout(SocketException e) { -#if NET_1_1 - return 10060 == e.ErrorCode; -#else return SocketError.TimedOut == e.SocketErrorCode; -#endif } -#endif /// - internal static void AddPreSharedKeyToClientExtensions(TlsPsk[] psks, IDictionary clientExtensions) + internal static void AddPreSharedKeyToClientExtensions(TlsPsk[] psks, IDictionary clientExtensions) { - IList identities = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(psks.Length); + var identities = new List(psks.Length); for (int i = 0; i < psks.Length; ++i) { TlsPsk psk = psks[i]; @@ -5526,7 +5584,7 @@ internal static void AddPreSharedKeyToClientExtensions(TlsPsk[] psks, IDictionar /// internal static OfferedPsks.BindersConfig AddPreSharedKeyToClientHello(TlsClientContext clientContext, - TlsClient client, IDictionary clientExtensions, int[] offeredCipherSuites) + TlsClient client, IDictionary clientExtensions, int[] offeredCipherSuites) { if (!IsTlsV13(clientContext.ClientVersion)) return null; @@ -5552,13 +5610,13 @@ internal static OfferedPsks.BindersConfig AddPreSharedKeyToClientHello(TlsClient /// internal static OfferedPsks.BindersConfig AddPreSharedKeyToClientHelloRetry(TlsClientContext clientContext, - OfferedPsks.BindersConfig clientBinders, IDictionary clientExtensions) + OfferedPsks.BindersConfig clientBinders, IDictionary clientExtensions) { SecurityParameters securityParameters = clientContext.SecurityParameters; int prfAlgorithm = GetPrfAlgorithm13(securityParameters.CipherSuite); - IList pskIndices = GetPskIndices(clientBinders.m_psks, prfAlgorithm); + var pskIndices = GetPskIndices(clientBinders.m_psks, prfAlgorithm); if (pskIndices.Count < 1) return null; @@ -5591,8 +5649,8 @@ internal static OfferedPsks.BindersConfig AddPreSharedKeyToClientHelloRetry(TlsC } internal static OfferedPsks.SelectedConfig SelectPreSharedKey(TlsServerContext serverContext, TlsServer server, - IDictionary clientHelloExtensions, HandshakeMessageInput clientHelloMessage, TlsHandshakeHash handshakeHash, - bool afterHelloRetryRequest) + IDictionary clientHelloExtensions, HandshakeMessageInput clientHelloMessage, + TlsHandshakeHash handshakeHash, bool afterHelloRetryRequest) { bool handshakeHashUpdated = false; @@ -5684,7 +5742,7 @@ internal static TlsSecret[] GetPskEarlySecrets(TlsCrypto crypto, TlsPsk[] psks) /// internal static TlsPskExternal[] GetPskExternalsClient(TlsClient client, int[] offeredCipherSuites) { - IList externalPsks = client.GetExternalPsks(); + var externalPsks = client.GetExternalPsks(); if (IsNullOrEmpty(externalPsks)) return null; @@ -5710,9 +5768,9 @@ internal static TlsPskExternal[] GetPskExternalsClient(TlsClient client, int[] o return result; } - internal static IList GetPskIndices(TlsPsk[] psks, int prfAlgorithm) + internal static IList GetPskIndices(TlsPsk[] psks, int prfAlgorithm) { - IList v = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(psks.Length); + var v = new List(psks.Length); for (int i = 0; i < psks.Length; ++i) { if (psks[i].PrfAlgorithm == prfAlgorithm) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TrustedAuthority.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TrustedAuthority.cs index 1244cc8..4fdd0a4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TrustedAuthority.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/TrustedAuthority.cs @@ -109,8 +109,10 @@ public static TrustedAuthority Parse(Stream input) case Tls.IdentifierType.x509_name: { byte[] derEncoding = TlsUtilities.ReadOpaque16(input, 1); - Asn1Object asn1 = TlsUtilities.ReadDerObject(derEncoding); - identifier = X509Name.GetInstance(asn1); + Asn1Object asn1 = TlsUtilities.ReadAsn1Object(derEncoding); + X509Name x509Name = X509Name.GetInstance(asn1); + TlsUtilities.RequireDerEncoding(x509Name, derEncoding); + identifier = x509Name; break; } default: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/CryptoSignatureAlgorithm.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/CryptoSignatureAlgorithm.cs index 96fb866..ba3bd2a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/CryptoSignatureAlgorithm.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/CryptoSignatureAlgorithm.cs @@ -17,6 +17,9 @@ public abstract class CryptoSignatureAlgorithm public const int rsa_pss_pss_sha256 = 9; public const int rsa_pss_pss_sha384 = 10; public const int rsa_pss_pss_sha512 = 11; + public const int ecdsa_brainpoolP256r1tls13_sha256 = 26; + public const int ecdsa_brainpoolP384r1tls13_sha384 = 27; + public const int ecdsa_brainpoolP512r1tls13_sha512 = 28; public const int gostr34102012_256 = 64; public const int gostr34102012_512 = 65; public const int sm2 = 200; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/Tls13Verifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/Tls13Verifier.cs new file mode 100644 index 0000000..394ea47 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/Tls13Verifier.cs @@ -0,0 +1,18 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.IO; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto +{ + public interface Tls13Verifier + { + /// + Stream Stream { get; } + + /// + bool VerifySignature(byte[] signature); + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/Tls13Verifier.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/Tls13Verifier.cs.meta new file mode 100644 index 0000000..f33ef66 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/Tls13Verifier.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8d3d92b1fac74df4db2c07db7e134b0e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCertificate.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCertificate.cs index ed1def5..d009e2d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCertificate.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCertificate.cs @@ -23,7 +23,7 @@ public interface TlsCertificate /// /// - TlsVerifier CreateVerifier(int signatureScheme); + Tls13Verifier CreateVerifier(int signatureScheme); /// byte[] GetEncoded(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCipher.cs index e1c3a31..2dcc6ae 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCipher.cs @@ -40,6 +40,11 @@ public interface TlsCipher TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVersion recordVersion, int headerAllocation, byte[] plaintext, int offset, int len); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVersion recordVersion, + int headerAllocation, ReadOnlySpan plaintext); +#endif + /// Decode the passed in ciphertext using the current bulk cipher. /// sequence number of the message represented by ciphertext. /// content type used in the record for this message. diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCrypto.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCrypto.cs index 72da507..e52cd95 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCrypto.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCrypto.cs @@ -1,6 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; @@ -12,11 +13,33 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto /// cryptography in the API.
public interface TlsCrypto { - /// Return true if this TlsCrypto can perform raw signatures and verifications for all supported - /// algorithms. - /// true if this instance can perform raw signatures and verifications for all supported algorithms, - /// false otherwise. - bool HasAllRawSignatureAlgorithms(); + /// Return true if this TlsCrypto would use a stream verifier for any of the passed in algorithms. + /// + /// This method is only relevant to handshakes negotiating (D)TLS 1.2. + /// A list of + /// values. + /// true if this instance would use a stream verifier for any of the passed in algorithms, otherwise + /// false. + bool HasAnyStreamVerifiers(IList signatureAndHashAlgorithms); + + /// Return true if this TlsCrypto would use a stream verifier for any of the passed in algorithms. + /// + /// This method is only relevant to handshakes negotiating (D)TLS versions older than 1.2. + /// An array of values. + /// true if this instance would use a stream verifier for any of the passed in algorithms, otherwise + /// false. + bool HasAnyStreamVerifiersLegacy(short[] clientCertificateTypes); + + /// Return true if this TlsCrypto can support the passed in hash algorithm. + /// the algorithm of interest. + /// true if cryptoHashAlgorithm is supported, false otherwise. + bool HasCryptoHashAlgorithm(int cryptoHashAlgorithm); + + /// Return true if this TlsCrypto can support the passed in signature algorithm (not necessarily in + /// combination with EVERY hash algorithm). + /// the algorithm of interest. + /// true if cryptoSignatureAlgorithm is supported, false otherwise. + bool HasCryptoSignatureAlgorithm(int cryptoSignatureAlgorithm); /// Return true if this TlsCrypto can support DH key agreement. /// true if this instance can support DH key agreement, false otherwise. @@ -32,16 +55,10 @@ public interface TlsCrypto /// true if encryptionAlgorithm is supported, false otherwise. bool HasEncryptionAlgorithm(int encryptionAlgorithm); - /// Return true if this TlsCrypto can support the passed in hash algorithm. + /// Return true if this TlsCrypto can support HKDF with the passed in hash algorithm. /// the algorithm of interest. - /// true if cryptoHashAlgorithm is supported, false otherwise. - bool HasCryptoHashAlgorithm(int cryptoHashAlgorithm); - - /// Return true if this TlsCrypto can support the passed in signature algorithm (not necessarily in - /// combination with EVERY hash algorithm). - /// the algorithm of interest. - /// true if cryptoSignatureAlgorithm is supported, false otherwise. - bool HasCryptoSignatureAlgorithm(int cryptoSignatureAlgorithm); + /// true if HKDF is supported with cryptoHashAlgorithm, false otherwise. + bool HasHkdfAlgorithm(int cryptoHashAlgorithm); /// Return true if this TlsCrypto can support the passed in MAC algorithm. /// the algorithm of interest. @@ -97,6 +114,13 @@ public interface TlsCrypto /// if there is an issue on decoding or constructing the certificate. TlsCertificate CreateCertificate(byte[] encoding); + /// Create a TlsCertificate from an ASN.1 binary encoding of a certificate. + /// Certificate type as per IANA TLS Certificate Types registry. + /// DER/BER encoding of the certificate of interest. + /// a TlsCertificate. + /// if there is an issue on decoding or constructing the certificate. + TlsCertificate CreateCertificate(short type, byte[] encoding); + /// Create a cipher for the specified encryption and MAC algorithms. /// /// See enumeration classes , for appropriate @@ -158,6 +182,10 @@ public interface TlsCrypto /// a . TlsNonceGenerator CreateNonceGenerator(byte[] additionalSeedMaterial); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + TlsNonceGenerator CreateNonceGenerator(ReadOnlySpan additionalSeedMaterial); +#endif + /// Create an SRP-6 client. /// client config. /// an initialised SRP6 client object. diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCryptoException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCryptoException.cs index 8ed7c47..e915bc2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCryptoException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCryptoException.cs @@ -1,23 +1,35 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto { - /// Basic exception class for crypto services to pass back a cause. - public class TlsCryptoException + /// Basic exception class for crypto services to pass back a cause. + [Serializable] + public class TlsCryptoException : TlsException { - public TlsCryptoException(string msg) - : base(msg) - { - } + public TlsCryptoException() + : base() + { + } - public TlsCryptoException(string msg, Exception cause) - : base(msg, cause) - { - } - } + public TlsCryptoException(string message) + : base(message) + { + } + + public TlsCryptoException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected TlsCryptoException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCryptoUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCryptoUtilities.cs index 241e855..33895b2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCryptoUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsCryptoUtilities.cs @@ -3,6 +3,11 @@ 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; + namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto { public abstract class TlsCryptoUtilities @@ -70,6 +75,24 @@ public static int GetHashForPrf(int prfAlgorithm) } } + public static int GetHashInternalSize(int cryptoHashAlgorithm) + { + switch (cryptoHashAlgorithm) + { + case CryptoHashAlgorithm.md5: + case CryptoHashAlgorithm.sha1: + case CryptoHashAlgorithm.sha224: + case CryptoHashAlgorithm.sha256: + case CryptoHashAlgorithm.sm3: + return 64; + case CryptoHashAlgorithm.sha384: + case CryptoHashAlgorithm.sha512: + return 128; + default: + throw new ArgumentException(); + } + } + public static int GetHashOutputSize(int cryptoHashAlgorithm) { switch (cryptoHashAlgorithm) @@ -92,6 +115,30 @@ public static int GetHashOutputSize(int cryptoHashAlgorithm) } } + public static DerObjectIdentifier GetOidForHash(int cryptoHashAlgorithm) + { + switch (cryptoHashAlgorithm) + { + case CryptoHashAlgorithm.md5: + return PkcsObjectIdentifiers.MD5; + case CryptoHashAlgorithm.sha1: + return X509ObjectIdentifiers.IdSha1; + case CryptoHashAlgorithm.sha224: + return NistObjectIdentifiers.IdSha224; + case CryptoHashAlgorithm.sha256: + return NistObjectIdentifiers.IdSha256; + case CryptoHashAlgorithm.sha384: + return NistObjectIdentifiers.IdSha384; + case CryptoHashAlgorithm.sha512: + return NistObjectIdentifiers.IdSha512; + // TODO[RFC 8998] + //case CryptoHashAlgorithm.sm3: + // return GMObjectIdentifiers.sm3; + default: + throw new ArgumentException(); + } + } + public static int GetSignature(short signatureAlgorithm) { switch (signatureAlgorithm) @@ -118,6 +165,12 @@ public static int GetSignature(short signatureAlgorithm) return CryptoSignatureAlgorithm.rsa_pss_pss_sha384; case SignatureAlgorithm.rsa_pss_pss_sha512: return CryptoSignatureAlgorithm.rsa_pss_pss_sha512; + case SignatureAlgorithm.ecdsa_brainpoolP256r1tls13_sha256: + return CryptoSignatureAlgorithm.ecdsa_brainpoolP256r1tls13_sha256; + case SignatureAlgorithm.ecdsa_brainpoolP384r1tls13_sha384: + return CryptoSignatureAlgorithm.ecdsa_brainpoolP384r1tls13_sha384; + case SignatureAlgorithm.ecdsa_brainpoolP512r1tls13_sha512: + return CryptoSignatureAlgorithm.ecdsa_brainpoolP512r1tls13_sha512; case SignatureAlgorithm.gostr34102012_256: return CryptoSignatureAlgorithm.gostr34102012_256; case SignatureAlgorithm.gostr34102012_512: @@ -132,6 +185,9 @@ public static int GetSignature(short signatureAlgorithm) public static TlsSecret HkdfExpandLabel(TlsSecret secret, int cryptoHashAlgorithm, string label, byte[] context, int length) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return HkdfExpandLabel(secret, cryptoHashAlgorithm, label.AsSpan(), context.AsSpan(), length); +#else int labelLength = label.Length; if (labelLength < 1) throw new TlsFatalAlert(AlertDescription.internal_error); @@ -167,8 +223,55 @@ public static TlsSecret HkdfExpandLabel(TlsSecret secret, int cryptoHashAlgorith TlsUtilities.WriteOpaque8(context, hkdfLabel, 2 + (1 + expandedLabelLength)); } + return secret.HkdfExpand(cryptoHashAlgorithm, hkdfLabel, length); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + /// + public static TlsSecret HkdfExpandLabel(TlsSecret secret, int cryptoHashAlgorithm, ReadOnlySpan label, + ReadOnlySpan context, int length) + { + int labelLength = label.Length; + if (labelLength < 1) + throw new TlsFatalAlert(AlertDescription.internal_error); + + int contextLength = context.Length; + int expandedLabelLength = Tls13Prefix.Length + labelLength; + + int hkdfLabelLength = 2 + (1 + expandedLabelLength) + (1 + contextLength); + Span hkdfLabel = hkdfLabelLength <= 512 + ? stackalloc byte[hkdfLabelLength] + : new byte[hkdfLabelLength]; + + // uint16 length + { + TlsUtilities.CheckUint16(length); + TlsUtilities.WriteUint16(length, hkdfLabel); + } + + // opaque label<7..255> + { + TlsUtilities.CheckUint8(expandedLabelLength); + TlsUtilities.WriteUint8(expandedLabelLength, hkdfLabel[2..]); + + Tls13Prefix.CopyTo(hkdfLabel[3..]); + + int labelPos = 2 + (1 + Tls13Prefix.Length); + for (int i = 0; i < labelLength; ++i) + { + hkdfLabel[labelPos + i] = (byte)label[i]; + } + } + + // context + { + TlsUtilities.WriteOpaque8(context, hkdfLabel.Slice(2 + (1 + expandedLabelLength))); + } + return secret.HkdfExpand(cryptoHashAlgorithm, hkdfLabel, length); } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsEncodeResult.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsEncodeResult.cs index 3ca1ccf..3479aa9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsEncodeResult.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsEncodeResult.cs @@ -4,11 +4,12 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto { - public sealed class TlsEncodeResult + public readonly struct TlsEncodeResult { public readonly byte[] buf; public readonly int off, len; public readonly short recordType; + public readonly bool fromBufferPool; public TlsEncodeResult(byte[] buf, int off, int len, short recordType) { @@ -16,6 +17,16 @@ public TlsEncodeResult(byte[] buf, int off, int len, short recordType) this.off = off; this.len = len; this.recordType = recordType; + this.fromBufferPool = false; + } + + public TlsEncodeResult(byte[] buf, int off, int len, short recordType, bool fromPool) + { + this.buf = buf; + this.off = off; + this.len = len; + this.recordType = recordType; + this.fromBufferPool = fromPool; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsHash.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsHash.cs index c241b37..2af753b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsHash.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsHash.cs @@ -13,6 +13,10 @@ public interface TlsHash /// the length of the input data. void Update(byte[] input, int inOff, int length); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + void Update(ReadOnlySpan input); +#endif + /// Return calculated hash for any input passed in. /// the hash value. byte[] CalculateHash(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsHashSink.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsHashSink.cs index 000c9a8..0028c8a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsHashSink.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsHashSink.cs @@ -21,18 +21,30 @@ public virtual TlsHash Hash get { return m_hash; } } - public override void WriteByte(byte b) + public override void Write(byte[] buffer, int offset, int count) { - m_hash.Update(new byte[] { b }, 0, 1); + Streams.ValidateBufferArguments(buffer, offset, count); + + if (count > 0) + { + m_hash.Update(buffer, offset, count); + } } - public override void Write(byte[] buf, int off, int len) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) { - if (len > 0) + if (!buffer.IsEmpty) { - m_hash.Update(buf, off, len); + m_hash.Update(buffer); } } +#endif + + public override void WriteByte(byte value) + { + m_hash.Update(new byte[]{ value }, 0, 1); + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsMac.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsMac.cs index 6ad8b5b..8410983 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsMac.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsMac.cs @@ -13,12 +13,20 @@ public interface TlsMac /// length of the key in the array. void SetKey(byte[] key, int keyOff, int keyLen); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + void SetKey(ReadOnlySpan key); +#endif + /// Update the MAC with the passed in input. /// input array containing the data. /// offset into the input array the input starts at. /// the length of the input data. void Update(byte[] input, int inOff, int length); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + void Update(ReadOnlySpan input); +#endif + /// Return calculated MAC for any input passed in. /// the MAC value. byte[] CalculateMac(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsMacSink.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsMacSink.cs index 031bfd1..1ce8bc4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsMacSink.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsMacSink.cs @@ -21,18 +21,30 @@ public virtual TlsMac Mac get { return m_mac; } } - public override void WriteByte(byte b) + public override void Write(byte[] buffer, int offset, int count) { - m_mac.Update(new byte[]{ b }, 0, 1); + Streams.ValidateBufferArguments(buffer, offset, count); + + if (count > 0) + { + m_mac.Update(buffer, offset, count); + } } - public override void Write(byte[] buf, int off, int len) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) { - if (len > 0) + if (!buffer.IsEmpty) { - m_mac.Update(buf, off, len); + m_mac.Update(buffer); } } +#endif + + public override void WriteByte(byte value) + { + m_mac.Update(new byte[]{ value }, 0, 1); + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsNullNullCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsNullNullCipher.cs index 6c136f5..036e51e 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsNullNullCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsNullNullCipher.cs @@ -33,6 +33,16 @@ public TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVe return new TlsEncodeResult(result, 0, result.Length, contentType); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVersion recordVersion, + int headerAllocation, ReadOnlySpan plaintext) + { + byte[] result = new byte[headerAllocation + plaintext.Length]; + plaintext.CopyTo(result.AsSpan(headerAllocation)); + return new TlsEncodeResult(result, 0, result.Length, contentType); + } +#endif + public TlsDecodeResult DecodeCiphertext(long seqNo, short recordType, ProtocolVersion recordVersion, byte[] ciphertext, int offset, int len) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsSecret.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsSecret.cs index 5090676..5b123ea 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsSecret.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsSecret.cs @@ -25,6 +25,10 @@ public interface TlsSecret /// the new secret. TlsSecret DeriveUsingPrf(int prfAlgorithm, string label, byte[] seed, int length); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + TlsSecret DeriveUsingPrf(int prfAlgorithm, ReadOnlySpan label, ReadOnlySpan seed, int length); +#endif + /// Destroy the internal state of the secret. /// /// After this call, any attempt to use the will result in an @@ -46,6 +50,10 @@ public interface TlsSecret /// the secret's internal data. byte[] Extract(); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + void ExtractTo(Span output); +#endif + /// RFC 5869 HKDF-Expand function, with this secret's data as the pseudo-random key ('prk'). /// the hash algorithm to instantiate HMAC with. See /// for values. @@ -54,6 +62,10 @@ public interface TlsSecret /// output keying material (of 'length' octets). TlsSecret HkdfExpand(int cryptoHashAlgorithm, byte[] info, int length); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + TlsSecret HkdfExpand(int cryptoHashAlgorithm, ReadOnlySpan info, int length); +#endif + /// RFC 5869 HKDF-Extract function, with this secret's data as the 'salt'. /// /// The does not keep a copy of the data. After this call, any attempt to use @@ -66,6 +78,8 @@ public interface TlsSecret TlsSecret HkdfExtract(int cryptoHashAlgorithm, TlsSecret ikm); bool IsAlive(); + + int Length { get; } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsStreamSigner.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsStreamSigner.cs index 4093c15..a3a68ed 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsStreamSigner.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsStreamSigner.cs @@ -8,7 +8,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto public interface TlsStreamSigner { /// - Stream GetOutputStream(); + Stream Stream { get; } /// byte[] GetSignature(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsStreamVerifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsStreamVerifier.cs index 05ff0f2..7e77f88 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsStreamVerifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsStreamVerifier.cs @@ -8,7 +8,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto public interface TlsStreamVerifier { /// - Stream GetOutputStream(); + Stream Stream { get; } /// bool IsVerified(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsVerifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsVerifier.cs index 5a84ba2..8e573ba 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsVerifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/TlsVerifier.cs @@ -10,14 +10,14 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto public interface TlsVerifier { /// - TlsStreamVerifier GetStreamVerifier(DigitallySigned signature); + TlsStreamVerifier GetStreamVerifier(DigitallySigned digitallySigned); /// Return true if the passed in signature and hash represent a real signature. - /// the signature object containing the signature to be verified. + /// the signature object containing the signature to be verified. /// the hash calculated for the signature. /// true if signature verifies, false otherwise. /// in case of an exception verifying signature. - bool VerifyRawSignature(DigitallySigned signature, byte[] hash); + bool VerifyRawSignature(DigitallySigned digitallySigned, byte[] hash); } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/AbstractTlsCrypto.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/AbstractTlsCrypto.cs index 39bf9a6..273eaa3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/AbstractTlsCrypto.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/AbstractTlsCrypto.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.IO; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; @@ -14,7 +14,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto.Impl public abstract class AbstractTlsCrypto : TlsCrypto { - public abstract bool HasAllRawSignatureAlgorithms(); + public abstract bool HasAnyStreamVerifiers(IList signatureAndHashAlgorithms); + + public abstract bool HasAnyStreamVerifiersLegacy(short[] clientCertificateTypes); + + public abstract bool HasCryptoHashAlgorithm(int cryptoHashAlgorithm); + + public abstract bool HasCryptoSignatureAlgorithm(int cryptoSignatureAlgorithm); public abstract bool HasDHAgreement(); @@ -22,9 +28,7 @@ public abstract class AbstractTlsCrypto public abstract bool HasEncryptionAlgorithm(int encryptionAlgorithm); - public abstract bool HasCryptoHashAlgorithm(int cryptoHashAlgorithm); - - public abstract bool HasCryptoSignatureAlgorithm(int cryptoSignatureAlgorithm); + public abstract bool HasHkdfAlgorithm(int cryptoHashAlgorithm); public abstract bool HasMacAlgorithm(int macAlgorithm); @@ -46,7 +50,12 @@ public abstract class AbstractTlsCrypto public abstract SecureRandom SecureRandom { get; } - public abstract TlsCertificate CreateCertificate(byte[] encoding); + public virtual TlsCertificate CreateCertificate(byte[] encoding) + { + return CreateCertificate(CertificateType.X509, encoding); + } + + public abstract TlsCertificate CreateCertificate(short type, byte[] encoding); public abstract TlsCipher CreateCipher(TlsCryptoParameters cryptoParams, int encryptionAlgorithm, int macAlgorithm); @@ -64,7 +73,7 @@ public virtual TlsSecret AdoptSecret(TlsSecret secret) return CreateSecret(sec.CopyData()); } - throw new ArgumentException("unrecognized TlsSecret - cannot copy data: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(secret)); + throw new ArgumentException("unrecognized TlsSecret - cannot copy data: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(secret)); } public abstract TlsHash CreateHash(int cryptoHashAlgorithm); @@ -75,6 +84,10 @@ public virtual TlsSecret AdoptSecret(TlsSecret secret) public abstract TlsNonceGenerator CreateNonceGenerator(byte[] additionalSeedMaterial); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public abstract TlsNonceGenerator CreateNonceGenerator(ReadOnlySpan additionalSeedMaterial); +#endif + public abstract TlsSrp6Client CreateSrp6Client(TlsSrpConfig srpConfig); public abstract TlsSrp6Server CreateSrp6Server(TlsSrpConfig srpConfig, BigInteger srpVerifier); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/AbstractTlsSecret.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/AbstractTlsSecret.cs index 9f2f178..e7dd918 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/AbstractTlsSecret.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/AbstractTlsSecret.cs @@ -22,7 +22,7 @@ protected static byte[] CopyData(AbstractTlsSecret other) /// the byte[] making up the secret value. protected AbstractTlsSecret(byte[] data) { - this.m_data = data; + m_data = data; } protected virtual void CheckAlive() @@ -48,6 +48,11 @@ public virtual byte[] CalculateHmac(int cryptoHashAlgorithm, byte[] buf, int off public abstract TlsSecret DeriveUsingPrf(int prfAlgorithm, string label, byte[] seed, int length); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public abstract TlsSecret DeriveUsingPrf(int prfAlgorithm, ReadOnlySpan label, ReadOnlySpan seed, + int length); +#endif + public virtual void Destroy() { lock (this) @@ -56,7 +61,7 @@ public virtual void Destroy() { // TODO Is there a way to ensure the data is really overwritten? Array.Clear(m_data, 0, m_data.Length); - this.m_data = null; + m_data = null; } } } @@ -79,13 +84,30 @@ public virtual byte[] Extract() CheckAlive(); byte[] result = m_data; - this.m_data = null; + m_data = null; return result; } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual void ExtractTo(Span output) + { + lock (this) + { + CheckAlive(); + + m_data.CopyTo(output); + m_data = null; + } + } +#endif + public abstract TlsSecret HkdfExpand(int cryptoHashAlgorithm, byte[] info, int length); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public abstract TlsSecret HkdfExpand(int cryptoHashAlgorithm, ReadOnlySpan info, int length); +#endif + public abstract TlsSecret HkdfExtract(int cryptoHashAlgorithm, TlsSecret ikm); public virtual bool IsAlive() @@ -96,6 +118,19 @@ public virtual bool IsAlive() } } + public virtual int Length + { + get + { + lock (this) + { + CheckAlive(); + + return m_data.Length; + } + } + } + internal virtual byte[] CopyData() { lock (this) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/LegacyTls13Verifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/LegacyTls13Verifier.cs new file mode 100644 index 0000000..e096865 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/LegacyTls13Verifier.cs @@ -0,0 +1,64 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.IO; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto.Impl +{ + public sealed class LegacyTls13Verifier + : TlsVerifier + { + private readonly int m_signatureScheme; + private readonly Tls13Verifier m_tls13Verifier; + + public LegacyTls13Verifier(int signatureScheme, Tls13Verifier tls13Verifier) + { + if (!TlsUtilities.IsValidUint16(signatureScheme)) + throw new ArgumentException("signatureScheme"); + if (tls13Verifier == null) + throw new ArgumentNullException("tls13Verifier"); + + this.m_signatureScheme = signatureScheme; + this.m_tls13Verifier = tls13Verifier; + } + + public TlsStreamVerifier GetStreamVerifier(DigitallySigned digitallySigned) + { + SignatureAndHashAlgorithm algorithm = digitallySigned.Algorithm; + if (algorithm == null || SignatureScheme.From(algorithm) != m_signatureScheme) + throw new InvalidOperationException("Invalid algorithm: " + algorithm); + + return new TlsStreamVerifierImpl(m_tls13Verifier, digitallySigned.Signature); + } + + public bool VerifyRawSignature(DigitallySigned digitallySigned, byte[] hash) + { + throw new NotSupportedException(); + } + + private class TlsStreamVerifierImpl + : TlsStreamVerifier + { + private readonly Tls13Verifier m_tls13Verifier; + private readonly byte[] m_signature; + + internal TlsStreamVerifierImpl(Tls13Verifier tls13Verifier, byte[] signature) + { + this.m_tls13Verifier = tls13Verifier; + this.m_signature = signature; + } + + public Stream Stream + { + get { return m_tls13Verifier.Stream; } + } + + public bool IsVerified() + { + return m_tls13Verifier.VerifySignature(m_signature); + } + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/LegacyTls13Verifier.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/LegacyTls13Verifier.cs.meta new file mode 100644 index 0000000..9d9891c --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/LegacyTls13Verifier.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9382149a5067cb443bc964d772eb882c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsAeadCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsAeadCipher.cs index d08d909..6a276e7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsAeadCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsAeadCipher.cs @@ -74,6 +74,33 @@ public TlsAeadCipher(TlsCryptoParameters cryptoParams, TlsAeadCipherImpl encrypt } int keyBlockSize = (2 * keySize) + (2 * m_fixed_iv_length); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span keyBlock = keyBlockSize <= 512 + ? stackalloc byte[keyBlockSize] + : new byte[keyBlockSize]; + TlsImplUtilities.CalculateKeyBlock(cryptoParams, keyBlock); + + if (isServer) + { + decryptCipher.SetKey(keyBlock[..keySize]); keyBlock = keyBlock[keySize..]; + encryptCipher.SetKey(keyBlock[..keySize]); keyBlock = keyBlock[keySize..]; + + keyBlock[..m_fixed_iv_length].CopyTo(m_decryptNonce); keyBlock = keyBlock[m_fixed_iv_length..]; + keyBlock[..m_fixed_iv_length].CopyTo(m_encryptNonce); keyBlock = keyBlock[m_fixed_iv_length..]; + } + else + { + encryptCipher.SetKey(keyBlock[..keySize]); keyBlock = keyBlock[keySize..]; + decryptCipher.SetKey(keyBlock[..keySize]); keyBlock = keyBlock[keySize..]; + + keyBlock[..m_fixed_iv_length].CopyTo(m_encryptNonce); keyBlock = keyBlock[m_fixed_iv_length..]; + keyBlock[..m_fixed_iv_length].CopyTo(m_decryptNonce); keyBlock = keyBlock[m_fixed_iv_length..]; + } + + if (!keyBlock.IsEmpty) + throw new TlsFatalAlert(AlertDescription.internal_error); +#else byte[] keyBlock = TlsImplUtilities.CalculateKeyBlock(cryptoParams, keyBlockSize); int pos = 0; @@ -94,8 +121,9 @@ public TlsAeadCipher(TlsCryptoParameters cryptoParams, TlsAeadCipherImpl encrypt Array.Copy(keyBlock, pos, m_decryptNonce, 0, m_fixed_iv_length); pos += m_fixed_iv_length; } - if (keyBlockSize != pos) + if (pos != keyBlockSize) throw new TlsFatalAlert(AlertDescription.internal_error); +#endif int nonceLength = m_fixed_iv_length + m_record_iv_length; @@ -135,6 +163,10 @@ public virtual int GetPlaintextLimit(int ciphertextLimit) public virtual TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVersion recordVersion, int headerAllocation, byte[] plaintext, int plaintextOffset, int plaintextLength) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return EncodePlaintext(seqNo, contentType, recordVersion, headerAllocation, + plaintext.AsSpan(plaintextOffset, plaintextLength)); +#else byte[] nonce = new byte[m_encryptNonce.Length + m_record_iv_length]; switch (m_nonceMode) @@ -177,14 +209,13 @@ public virtual TlsEncodeResult EncodePlaintext(long seqNo, short contentType, Pr try { - m_encryptCipher.Init(nonce, m_macSize, additionalData); - Array.Copy(plaintext, plaintextOffset, output, outputPos, plaintextLength); if (m_isTlsV13) { output[outputPos + plaintextLength] = (byte)contentType; } + m_encryptCipher.Init(nonce, m_macSize, additionalData); outputPos += m_encryptCipher.DoFinal(output, outputPos, plaintextLength + extraLength, output, outputPos); } @@ -204,8 +235,84 @@ public virtual TlsEncodeResult EncodePlaintext(long seqNo, short contentType, Pr } return new TlsEncodeResult(output, 0, output.Length, recordType); +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVersion recordVersion, + int headerAllocation, ReadOnlySpan plaintext) + { + byte[] nonce = new byte[m_encryptNonce.Length + m_record_iv_length]; + + switch (m_nonceMode) + { + case NONCE_RFC5288: + Array.Copy(m_encryptNonce, 0, nonce, 0, m_encryptNonce.Length); + // RFC 5288/6655: The nonce_explicit MAY be the 64-bit sequence number. + TlsUtilities.WriteUint64(seqNo, nonce, m_encryptNonce.Length); + break; + case NONCE_RFC7905: + TlsUtilities.WriteUint64(seqNo, nonce, nonce.Length - 8); + for (int i = 0; i < m_encryptNonce.Length; ++i) + { + nonce[i] ^= m_encryptNonce[i]; + } + break; + default: + throw new TlsFatalAlert(AlertDescription.internal_error); + } + + int extraLength = m_isTlsV13 ? 1 : 0; + + // TODO[tls13] If we support adding padding to TLSInnerPlaintext, this will need review + int encryptionLength = m_encryptCipher.GetOutputSize(plaintext.Length + extraLength); + int ciphertextLength = m_record_iv_length + encryptionLength; + + byte[] output = new byte[headerAllocation + ciphertextLength]; + int outputPos = headerAllocation; + + if (m_record_iv_length != 0) + { + Array.Copy(nonce, nonce.Length - m_record_iv_length, output, outputPos, m_record_iv_length); + outputPos += m_record_iv_length; + } + + short recordType = m_isTlsV13 ? ContentType.application_data : contentType; + + byte[] additionalData = GetAdditionalData(seqNo, recordType, recordVersion, ciphertextLength, + plaintext.Length); + + try + { + plaintext.CopyTo(output.AsSpan(outputPos)); + if (m_isTlsV13) + { + output[outputPos + plaintext.Length] = (byte)contentType; + } + + m_encryptCipher.Init(nonce, m_macSize, additionalData); + outputPos += m_encryptCipher.DoFinal(output, outputPos, plaintext.Length + extraLength, output, + outputPos); + } + catch (IOException e) + { + throw e; + } + catch (Exception e) + { + throw new TlsFatalAlert(AlertDescription.internal_error, e); + } + + if (outputPos != output.Length) + { + // NOTE: The additional data mechanism for AEAD ciphers requires exact output size prediction. + throw new TlsFatalAlert(AlertDescription.internal_error); + } + + return new TlsEncodeResult(output, 0, output.Length, recordType); + } +#endif + public virtual TlsDecodeResult DecodeCiphertext(long seqNo, short recordType, ProtocolVersion recordVersion, byte[] ciphertext, int ciphertextOffset, int ciphertextLength) { @@ -246,12 +353,21 @@ public virtual TlsDecodeResult DecodeCiphertext(long seqNo, short recordType, Pr outputPos = m_decryptCipher.DoFinal(ciphertext, encryptionOffset, encryptionLength, ciphertext, encryptionOffset); } + catch (TlsFatalAlert fatalAlert) + { + if (AlertDescription.bad_record_mac == fatalAlert.AlertDescription) + { + m_decryptCipher.Reset(); + } + throw fatalAlert; + } catch (IOException e) { throw e; } catch (Exception e) { + m_decryptCipher.Reset(); throw new TlsFatalAlert(AlertDescription.bad_record_mac, e); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsAeadCipherImpl.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsAeadCipherImpl.cs index 0d72338..936af5f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsAeadCipherImpl.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsAeadCipherImpl.cs @@ -15,6 +15,10 @@ public interface TlsAeadCipherImpl /// void SetKey(byte[] key, int keyOff, int keyLen); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + void SetKey(ReadOnlySpan key); +#endif + /// Initialise the parameters for the AEAD operator. /// the nonce. /// MAC size in bytes. @@ -39,6 +43,8 @@ public interface TlsAeadCipherImpl /// the amount of data written to output. /// in case of failure. int DoFinal(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset); + + void Reset(); } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsBlockCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsBlockCipher.cs index d57921e..1f1feeb 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsBlockCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsBlockCipher.cs @@ -67,27 +67,55 @@ public TlsBlockCipher(TlsCryptoParameters cryptoParams, TlsBlockCipherImpl encry serverCipher = decryptCipher; } - int key_block_size = (2 * cipherKeySize) + clientMac.MacLength + serverMac.MacLength; + int keyBlockSize = (2 * cipherKeySize) + clientMac.MacLength + serverMac.MacLength; // From TLS 1.1 onwards, block ciphers don't need IVs from the key_block if (!m_useExplicitIV) { - key_block_size += clientCipher.GetBlockSize() + serverCipher.GetBlockSize(); + keyBlockSize += clientCipher.GetBlockSize() + serverCipher.GetBlockSize(); } - byte[] key_block = TlsImplUtilities.CalculateKeyBlock(cryptoParams, key_block_size); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span keyBlock = keyBlockSize <= 512 + ? stackalloc byte[keyBlockSize] + : new byte[keyBlockSize]; + TlsImplUtilities.CalculateKeyBlock(cryptoParams, keyBlock); - int offset = 0; + clientMac.SetKey(keyBlock[..clientMac.MacLength]); keyBlock = keyBlock[clientMac.MacLength..]; + serverMac.SetKey(keyBlock[..serverMac.MacLength]); keyBlock = keyBlock[serverMac.MacLength..]; - clientMac.SetKey(key_block, offset, clientMac.MacLength); - offset += clientMac.MacLength; - serverMac.SetKey(key_block, offset, serverMac.MacLength); - offset += serverMac.MacLength; + clientCipher.SetKey(keyBlock[..cipherKeySize]); keyBlock = keyBlock[cipherKeySize..]; + serverCipher.SetKey(keyBlock[..cipherKeySize]); keyBlock = keyBlock[cipherKeySize..]; - clientCipher.SetKey(key_block, offset, cipherKeySize); - offset += cipherKeySize; - serverCipher.SetKey(key_block, offset, cipherKeySize); - offset += cipherKeySize; + int clientIVLength = clientCipher.GetBlockSize(); + int serverIVLength = serverCipher.GetBlockSize(); + + if (m_useExplicitIV) + { + clientCipher.Init(clientIVLength <= 64 ? stackalloc byte[clientIVLength] : new byte[clientIVLength]); + serverCipher.Init(serverIVLength <= 64 ? stackalloc byte[serverIVLength] : new byte[serverIVLength]); + } + else + { + clientCipher.Init(keyBlock[..clientIVLength]); keyBlock = keyBlock[clientIVLength..]; + serverCipher.Init(keyBlock[..serverIVLength]); keyBlock = keyBlock[serverIVLength..]; + } + + if (!keyBlock.IsEmpty) + throw new TlsFatalAlert(AlertDescription.internal_error); +#else + byte[] keyBlock = TlsImplUtilities.CalculateKeyBlock(cryptoParams, keyBlockSize); + int pos = 0; + + clientMac.SetKey(keyBlock, pos, clientMac.MacLength); + pos += clientMac.MacLength; + serverMac.SetKey(keyBlock, pos, serverMac.MacLength); + pos += serverMac.MacLength; + + clientCipher.SetKey(keyBlock, pos, cipherKeySize); + pos += cipherKeySize; + serverCipher.SetKey(keyBlock, pos, cipherKeySize); + pos += cipherKeySize; int clientIVLength = clientCipher.GetBlockSize(); int serverIVLength = serverCipher.GetBlockSize(); @@ -99,14 +127,15 @@ public TlsBlockCipher(TlsCryptoParameters cryptoParams, TlsBlockCipherImpl encry } else { - clientCipher.Init(key_block, offset, clientIVLength); - offset += clientIVLength; - serverCipher.Init(key_block, offset, serverIVLength); - offset += serverIVLength; + clientCipher.Init(keyBlock, pos, clientIVLength); + pos += clientIVLength; + serverCipher.Init(keyBlock, pos, serverIVLength); + pos += serverIVLength; } - if (offset != key_block_size) + if (pos != keyBlockSize) throw new TlsFatalAlert(AlertDescription.internal_error); +#endif if (cryptoParams.IsServer) { @@ -172,6 +201,9 @@ public virtual int GetPlaintextLimit(int ciphertextLimit) public virtual TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVersion recordVersion, int headerAllocation, byte[] plaintext, int offset, int len) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return EncodePlaintext(seqNo, contentType, recordVersion, headerAllocation, plaintext.AsSpan(offset, len)); +#else int blockSize = m_encryptCipher.GetBlockSize(); int macSize = m_writeMac.Size; @@ -237,8 +269,81 @@ public virtual TlsEncodeResult EncodePlaintext(long seqNo, short contentType, Pr throw new TlsFatalAlert(AlertDescription.internal_error); return new TlsEncodeResult(outBuf, 0, outBuf.Length, contentType); +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVersion recordVersion, + int headerAllocation, ReadOnlySpan plaintext) + { + int blockSize = m_encryptCipher.GetBlockSize(); + int macSize = m_writeMac.Size; + + int enc_input_length = plaintext.Length; + if (!m_encryptThenMac) + { + enc_input_length += macSize; + } + + int padding_length = blockSize - (enc_input_length % blockSize); + if (m_useExtraPadding) + { + // Add a random number of extra blocks worth of padding + int maxExtraPadBlocks = (256 - padding_length) / blockSize; + int actualExtraPadBlocks = ChooseExtraPadBlocks(maxExtraPadBlocks); + padding_length += actualExtraPadBlocks * blockSize; + } + + int totalSize = plaintext.Length + macSize + padding_length; + if (m_useExplicitIV) + { + totalSize += blockSize; + } + + byte[] outBuf = new byte[headerAllocation + totalSize]; + int outOff = headerAllocation; + + if (m_useExplicitIV) + { + // Technically the explicit IV will be the encryption of this nonce + byte[] explicitIV = m_cryptoParams.NonceGenerator.GenerateNonce(blockSize); + Array.Copy(explicitIV, 0, outBuf, outOff, blockSize); + outOff += blockSize; + } + + plaintext.CopyTo(outBuf.AsSpan(outOff)); + outOff += plaintext.Length; + + if (!m_encryptThenMac) + { + byte[] mac = m_writeMac.CalculateMac(seqNo, contentType, plaintext); + mac.CopyTo(outBuf.AsSpan(outOff)); + outOff += mac.Length; + } + + byte padByte = (byte)(padding_length - 1); + for (int i = 0; i < padding_length; ++i) + { + outBuf[outOff++] = padByte; + } + + m_encryptCipher.DoFinal(outBuf, headerAllocation, outOff - headerAllocation, outBuf, headerAllocation); + + if (m_encryptThenMac) + { + byte[] mac = m_writeMac.CalculateMac(seqNo, contentType, outBuf, headerAllocation, + outOff - headerAllocation); + Array.Copy(mac, 0, outBuf, outOff, mac.Length); + outOff += mac.Length; + } + + if (outOff != outBuf.Length) + throw new TlsFatalAlert(AlertDescription.internal_error); + + return new TlsEncodeResult(outBuf, 0, outBuf.Length, contentType); + } +#endif + public virtual TlsDecodeResult DecodeCiphertext(long seqNo, short recordType, ProtocolVersion recordVersion, byte[] ciphertext, int offset, int len) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsBlockCipherImpl.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsBlockCipherImpl.cs index 7ef25a1..39a0d37 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsBlockCipherImpl.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsBlockCipherImpl.cs @@ -15,6 +15,10 @@ public interface TlsBlockCipherImpl /// void SetKey(byte[] key, int keyOff, int keyLen); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + void SetKey(ReadOnlySpan key); +#endif + /// Initialise the parameters for operator. /// array holding the initialization vector (IV). /// offset into the array the IV starts at. @@ -22,6 +26,10 @@ public interface TlsBlockCipherImpl /// if the parameters are inappropriate. void Init(byte[] iv, int ivOff, int ivLen); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + void Init(ReadOnlySpan iv); +#endif + /// Perform the cipher encryption/decryption returning the output in output. /// /// Note: we have to use DoFinal() here as it is the only way to guarantee output from the underlying cipher. diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsImplUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsImplUtilities.cs index d4324d9..8ae5012 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsImplUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsImplUtilities.cs @@ -58,21 +58,28 @@ public static byte[] CalculateKeyBlock(TlsCryptoParameters cryptoParams, int len { SecurityParameters securityParameters = cryptoParams.SecurityParameters; TlsSecret master_secret = securityParameters.MasterSecret; + int prfAlgorithm = securityParameters.PrfAlgorithm; byte[] seed = Arrays.Concatenate(securityParameters.ServerRandom, securityParameters.ClientRandom); - return Prf(securityParameters, master_secret, ExporterLabel.key_expansion, seed, length).Extract(); + return master_secret.DeriveUsingPrf(prfAlgorithm, ExporterLabel.key_expansion, seed, length).Extract(); } - public static TlsSecret Prf(SecurityParameters securityParameters, TlsSecret secret, string asciiLabel, - byte[] seed, int length) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void CalculateKeyBlock(TlsCryptoParameters cryptoParams, Span keyBlock) { - return secret.DeriveUsingPrf(securityParameters.PrfAlgorithm, asciiLabel, seed, length); - } + SecurityParameters securityParameters = cryptoParams.SecurityParameters; + TlsSecret master_secret = securityParameters.MasterSecret; + int prfAlgorithm = securityParameters.PrfAlgorithm; - public static TlsSecret Prf(TlsCryptoParameters cryptoParams, TlsSecret secret, string asciiLabel, byte[] seed, - int length) - { - return Prf(cryptoParams.SecurityParameters, secret, asciiLabel, seed, length); + Span cr = securityParameters.ClientRandom, sr = securityParameters.ServerRandom; + Span seed = stackalloc byte[sr.Length + cr.Length]; + sr.CopyTo(seed); + cr.CopyTo(seed[sr.Length..]); + + TlsSecret derived = master_secret.DeriveUsingPrf(prfAlgorithm, ExporterLabel.key_expansion, seed, + keyBlock.Length); + derived.ExtractTo(keyBlock); } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsNullCipher.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsNullCipher.cs index f16433b..229473b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsNullCipher.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsNullCipher.cs @@ -18,20 +18,33 @@ public TlsNullCipher(TlsCryptoParameters cryptoParams, TlsHmac clientMac, TlsHma if (TlsImplUtilities.IsTlsV13(cryptoParams)) throw new TlsFatalAlert(AlertDescription.internal_error); - this.m_cryptoParams = cryptoParams; + m_cryptoParams = cryptoParams; - int key_block_size = clientMac.MacLength + serverMac.MacLength; - byte[] key_block = TlsImplUtilities.CalculateKeyBlock(cryptoParams, key_block_size); + int keyBlockSize = clientMac.MacLength + serverMac.MacLength; - int offset = 0; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span keyBlock = keyBlockSize <= 512 + ? stackalloc byte[keyBlockSize] + : new byte[keyBlockSize]; + TlsImplUtilities.CalculateKeyBlock(cryptoParams, keyBlock); - clientMac.SetKey(key_block, offset, clientMac.MacLength); - offset += clientMac.MacLength; - serverMac.SetKey(key_block, offset, serverMac.MacLength); - offset += serverMac.MacLength; + clientMac.SetKey(keyBlock[..clientMac.MacLength]); keyBlock = keyBlock[clientMac.MacLength..]; + serverMac.SetKey(keyBlock[..serverMac.MacLength]); keyBlock = keyBlock[serverMac.MacLength..]; - if (offset != key_block_size) + if (!keyBlock.IsEmpty) throw new TlsFatalAlert(AlertDescription.internal_error); +#else + byte[] keyBlock = TlsImplUtilities.CalculateKeyBlock(cryptoParams, keyBlockSize); + int pos = 0; + + clientMac.SetKey(keyBlock, pos, clientMac.MacLength); + pos += clientMac.MacLength; + serverMac.SetKey(keyBlock, pos, serverMac.MacLength); + pos += serverMac.MacLength; + + if (pos != keyBlockSize) + throw new TlsFatalAlert(AlertDescription.internal_error); +#endif if (cryptoParams.IsServer) { @@ -70,6 +83,18 @@ public virtual TlsEncodeResult EncodePlaintext(long seqNo, short contentType, Pr return new TlsEncodeResult(ciphertext, 0, ciphertext.Length, contentType); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual TlsEncodeResult EncodePlaintext(long seqNo, short contentType, ProtocolVersion recordVersion, + int headerAllocation, ReadOnlySpan plaintext) + { + byte[] mac = m_writeMac.CalculateMac(seqNo, contentType, plaintext); + byte[] ciphertext = new byte[headerAllocation + plaintext.Length + mac.Length]; + plaintext.CopyTo(ciphertext.AsSpan(headerAllocation)); + mac.CopyTo(ciphertext.AsSpan(headerAllocation + plaintext.Length)); + return new TlsEncodeResult(ciphertext, 0, ciphertext.Length, contentType); + } +#endif + public virtual TlsDecodeResult DecodeCiphertext(long seqNo, short recordType, ProtocolVersion recordVersion, byte[] ciphertext, int offset, int len) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsSuiteHmac.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsSuiteHmac.cs index 8753c98..b791f54 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsSuiteHmac.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsSuiteHmac.cs @@ -57,6 +57,9 @@ public virtual int Size public virtual byte[] CalculateMac(long seqNo, short type, byte[] msg, int msgOff, int msgLen) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return CalculateMac(seqNo, type, msg.AsSpan(msgOff, msgLen)); +#else ProtocolVersion serverVersion = m_cryptoParams.ServerVersion; bool isSsl = serverVersion.IsSsl; @@ -72,8 +75,31 @@ public virtual byte[] CalculateMac(long seqNo, short type, byte[] msg, int msgOf m_mac.Update(macHeader, 0, macHeader.Length); m_mac.Update(msg, msgOff, msgLen); + return Truncate(m_mac.CalculateMac()); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public virtual byte[] CalculateMac(long seqNo, short type, ReadOnlySpan message) + { + ProtocolVersion serverVersion = m_cryptoParams.ServerVersion; + bool isSsl = serverVersion.IsSsl; + + byte[] macHeader = new byte[isSsl ? 11 : 13]; + TlsUtilities.WriteUint64(seqNo, macHeader, 0); + TlsUtilities.WriteUint8(type, macHeader, 8); + if (!isSsl) + { + TlsUtilities.WriteVersion(serverVersion, macHeader, 9); + } + TlsUtilities.WriteUint16(message.Length, macHeader, macHeader.Length - 2); + + m_mac.Update(macHeader); + m_mac.Update(message); + return Truncate(m_mac.CalculateMac()); } +#endif public virtual byte[] CalculateMacConstantTime(long seqNo, short type, byte[] msg, int msgOff, int msgLen, int fullLength, byte[] dummyData) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsSuiteMac.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsSuiteMac.cs index fc62f64..12516e0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsSuiteMac.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/TlsSuiteMac.cs @@ -20,6 +20,10 @@ public interface TlsSuiteMac /// A new byte array containing the MAC value. byte[] CalculateMac(long seqNo, short type, byte[] message, int offset, int length); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + byte[] CalculateMac(long seqNo, short type, ReadOnlySpan message); +#endif + /// Constant time calculation of the MAC for some given data with a given expected length. /// The sequence number of the record. /// The content type of the message. diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcChaCha20Poly1305.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcChaCha20Poly1305.cs index 1d4e288..e4177f8 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcChaCha20Poly1305.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcChaCha20Poly1305.cs @@ -32,7 +32,7 @@ public int DoFinal(byte[] input, int inputOffset, int inputLength, byte[] output { int ciphertextLength = inputLength; - m_cipher.ProcessBytes(input, inputOffset, inputLength, output, outputOffset); + m_cipher.DoFinal(input, inputOffset, inputLength, output, outputOffset); int outputLength = inputLength; if (ciphertextLength != outputLength) @@ -65,7 +65,7 @@ public int DoFinal(byte[] input, int inputOffset, int inputLength, byte[] output if (badMac) throw new TlsFatalAlert(AlertDescription.bad_record_mac); - m_cipher.ProcessBytes(input, inputOffset, ciphertextLength, output, outputOffset); + m_cipher.DoFinal(input, inputOffset, ciphertextLength, output, outputOffset); int outputLength = ciphertextLength; if (ciphertextLength != outputLength) @@ -98,18 +98,39 @@ public void Init(byte[] nonce, int macSize, byte[] additionalData) } } + public void Reset() + { + m_cipher.Reset(); + m_mac.Reset(); + } + public void SetKey(byte[] key, int keyOff, int keyLen) { KeyParameter cipherKey = new KeyParameter(key, keyOff, keyLen); m_cipher.Init(m_isEncrypting, new ParametersWithIV(cipherKey, Zeroes, 0, 12)); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void SetKey(ReadOnlySpan key) + { + KeyParameter cipherKey = new KeyParameter(key); + m_cipher.Init(m_isEncrypting, new ParametersWithIV(cipherKey, Zeroes.AsSpan(0, 12))); + } +#endif + private void InitMac() { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span firstBlock = stackalloc byte[64]; + m_cipher.ProcessBytes(firstBlock, firstBlock); + m_mac.Init(new KeyParameter(firstBlock[..32])); + firstBlock.Fill(0x00); +#else byte[] firstBlock = new byte[64]; m_cipher.ProcessBytes(firstBlock, 0, 64, firstBlock, 0); m_mac.Init(new KeyParameter(firstBlock, 0, 32)); Array.Clear(firstBlock, 0, firstBlock.Length); +#endif } private void UpdateMac(byte[] buf, int off, int len) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcDefaultTlsCredentialedAgreement.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcDefaultTlsCredentialedAgreement.cs index 56d6b9f..41ba0b5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcDefaultTlsCredentialedAgreement.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcDefaultTlsCredentialedAgreement.cs @@ -41,7 +41,7 @@ public BcDefaultTlsCredentialedAgreement(BcTlsCrypto crypto, Certificate certifi } else { - throw new ArgumentException("'privateKey' type not supported: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(privateKey)); + throw new ArgumentException("'privateKey' type not supported: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(privateKey)); } } @@ -102,7 +102,7 @@ public TlsSecret GenerateAgreement(TlsCertificate peerCertificate) { BcTlsCertificate bcCert = BcTlsCertificate.Convert(m_crypto, peerCertificate); ECPublicKeyParameters peerPublicKey = bcCert.GetPubKeyEC(); - return BcTlsECDomain.CalculateBasicAgreement(m_crypto, m_privateKey, peerPublicKey); + return BcTlsECDomain.CalculateECDHAgreement(m_crypto, m_privateKey, peerPublicKey); } public Certificate Certificate diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcDefaultTlsCredentialedDecryptor.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcDefaultTlsCredentialedDecryptor.cs index ffd6252..f9ce55d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcDefaultTlsCredentialedDecryptor.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcDefaultTlsCredentialedDecryptor.cs @@ -39,7 +39,7 @@ public BcDefaultTlsCredentialedDecryptor(BcTlsCrypto crypto, Certificate certifi } else { - throw new ArgumentException("'privateKey' type not supported: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(privateKey)); + throw new ArgumentException("'privateKey' type not supported: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(privateKey)); } this.m_crypto = crypto; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcDefaultTlsCredentialedSigner.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcDefaultTlsCredentialedSigner.cs index b4d70ed..a3089c0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcDefaultTlsCredentialedSigner.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcDefaultTlsCredentialedSigner.cs @@ -70,7 +70,7 @@ private static TlsSigner MakeSigner(BcTlsCrypto crypto, AsymmetricKeyParameter p } else { - throw new ArgumentException("'privateKey' type not supported: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(privateKey)); + throw new ArgumentException("'privateKey' type not supported: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(privateKey)); } return signer; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcSsl3Hmac.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcSsl3Hmac.cs index 4164f07..ee69066 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcSsl3Hmac.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcSsl3Hmac.cs @@ -3,6 +3,7 @@ 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.Tls.Crypto.Impl.BC @@ -53,11 +54,27 @@ public virtual void SetKey(byte[] key, int keyOff, int keyLen) Reset(); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void SetKey(ReadOnlySpan key) + { + this.m_secret = key.ToArray(); + + Reset(); + } +#endif + public virtual void Update(byte[] input, int inOff, int len) { m_digest.BlockUpdate(input, inOff, len); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Update(ReadOnlySpan input) + { + m_digest.BlockUpdate(input); + } +#endif + public virtual byte[] CalculateMac() { byte[] result = new byte[m_digest.GetDigestSize()]; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTls13Verifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTls13Verifier.cs new file mode 100644 index 0000000..141ed81 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTls13Verifier.cs @@ -0,0 +1,36 @@ +#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.IO; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto.Impl.BC +{ + internal sealed class BcTls13Verifier + : Tls13Verifier + { + private readonly SignerSink m_output; + + internal BcTls13Verifier(ISigner verifier) + { + if (verifier == null) + throw new ArgumentNullException("verifier"); + + this.m_output = new SignerSink(verifier); + } + + public Stream Stream + { + get { return m_output; } + } + + public bool VerifySignature(byte[] signature) + { + return m_output.Signer.VerifySignature(signature); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTls13Verifier.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTls13Verifier.cs.meta new file mode 100644 index 0000000..b83d4be --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTls13Verifier.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4243bb97339ecb84e889671b73a181af +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsAeadCipherImpl.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsAeadCipherImpl.cs index 069c9e6..f58f7ad 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsAeadCipherImpl.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsAeadCipherImpl.cs @@ -12,11 +12,11 @@ internal sealed class BcTlsAeadCipherImpl : TlsAeadCipherImpl { private readonly bool m_isEncrypting; - private readonly IAeadBlockCipher m_cipher; + private readonly IAeadCipher m_cipher; private KeyParameter key; - internal BcTlsAeadCipherImpl(IAeadBlockCipher cipher, bool isEncrypting) + internal BcTlsAeadCipherImpl(IAeadCipher cipher, bool isEncrypting) { this.m_cipher = cipher; this.m_isEncrypting = isEncrypting; @@ -27,6 +27,13 @@ public void SetKey(byte[] key, int keyOff, int keyLen) this.key = new KeyParameter(key, keyOff, keyLen); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void SetKey(ReadOnlySpan key) + { + this.key = new KeyParameter(key); + } +#endif + public void Init(byte[] nonce, int macSize, byte[] additionalData) { m_cipher.Init(m_isEncrypting, new AeadParameters(key, macSize * 8, nonce, additionalData)); @@ -52,6 +59,11 @@ public int DoFinal(byte[] input, int inputOffset, int inputLength, byte[] output return len; } + + public void Reset() + { + m_cipher.Reset(); + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsBlockCipherImpl.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsBlockCipherImpl.cs index 6a3bbb7..b0e47e9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsBlockCipherImpl.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsBlockCipherImpl.cs @@ -26,11 +26,25 @@ public void SetKey(byte[] key, int keyOff, int keyLen) this.key = new KeyParameter(key, keyOff, keyLen); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void SetKey(ReadOnlySpan key) + { + this.key = new KeyParameter(key); + } +#endif + public void Init(byte[] iv, int ivOff, int ivLen) { m_cipher.Init(m_isEncrypting, new ParametersWithIV(key, iv, ivOff, ivLen)); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Init(ReadOnlySpan iv) + { + m_cipher.Init(m_isEncrypting, new ParametersWithIV(key, iv)); + } +#endif + public int DoFinal(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) { int blockSize = m_cipher.GetBlockSize(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsCertificate.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsCertificate.cs index 1fe8529..92d5b4a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsCertificate.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsCertificate.cs @@ -5,17 +5,14 @@ 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.Math; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto.Impl.BC { /// Implementation class for a single X.509 certificate based on the BC light-weight API. public class BcTlsCertificate - : TlsCertificate + : BcTlsRawKeyCertificate { /// public static BcTlsCertificate Convert(BcTlsCrypto crypto, TlsCertificate certificate) @@ -31,7 +28,8 @@ public static X509CertificateStructure ParseCertificate(byte[] encoding) { try { - return X509CertificateStructure.GetInstance(encoding); + Asn1Object asn1 = TlsUtilities.ReadAsn1Object(encoding); + return X509CertificateStructure.GetInstance(asn1); } catch (Exception e) { @@ -39,15 +37,8 @@ public static X509CertificateStructure ParseCertificate(byte[] encoding) } } - protected readonly BcTlsCrypto m_crypto; protected readonly X509CertificateStructure m_certificate; - protected DHPublicKeyParameters m_pubKeyDH = null; - protected ECPublicKeyParameters m_pubKeyEC = null; - protected Ed25519PublicKeyParameters m_pubKeyEd25519 = null; - protected Ed448PublicKeyParameters m_pubKeyEd448 = null; - protected RsaKeyParameters m_pubKeyRsa = null; - /// public BcTlsCertificate(BcTlsCrypto crypto, byte[] encoding) : this(crypto, ParseCertificate(encoding)) @@ -55,133 +46,21 @@ public BcTlsCertificate(BcTlsCrypto crypto, byte[] encoding) } public BcTlsCertificate(BcTlsCrypto crypto, X509CertificateStructure certificate) + : base(crypto, certificate.SubjectPublicKeyInfo) { - this.m_crypto = crypto; - this.m_certificate = certificate; - } - - /// - public virtual TlsEncryptor CreateEncryptor(int tlsCertificateRole) - { - ValidateKeyUsage(KeyUsage.KeyEncipherment); - - switch (tlsCertificateRole) - { - case TlsCertificateRole.RsaEncryption: - { - this.m_pubKeyRsa = GetPubKeyRsa(); - return new BcTlsRsaEncryptor(m_crypto, m_pubKeyRsa); - } - // TODO[gmssl] - //case TlsCertificateRole.Sm2Encryption: - //{ - // this.m_pubKeyEC = GetPubKeyEC(); - // return new BcTlsSM2Encryptor(m_crypto, m_pubKeyEC); - //} - } - - throw new TlsFatalAlert(AlertDescription.certificate_unknown); - } - - /// - public virtual TlsVerifier CreateVerifier(short signatureAlgorithm) - { - switch (signatureAlgorithm) - { - case SignatureAlgorithm.rsa_pss_rsae_sha256: - case SignatureAlgorithm.rsa_pss_rsae_sha384: - case SignatureAlgorithm.rsa_pss_rsae_sha512: - case SignatureAlgorithm.ed25519: - case SignatureAlgorithm.ed448: - case SignatureAlgorithm.rsa_pss_pss_sha256: - case SignatureAlgorithm.rsa_pss_pss_sha384: - case SignatureAlgorithm.rsa_pss_pss_sha512: - return CreateVerifier(SignatureScheme.From(HashAlgorithm.Intrinsic, signatureAlgorithm)); - } - - ValidateKeyUsage(KeyUsage.DigitalSignature); - - switch (signatureAlgorithm) - { - case SignatureAlgorithm.rsa: - ValidateRsa_Pkcs1(); - return new BcTlsRsaVerifier(m_crypto, GetPubKeyRsa()); - - case SignatureAlgorithm.dsa: - return new BcTlsDsaVerifier(m_crypto, GetPubKeyDss()); - - case SignatureAlgorithm.ecdsa: - return new BcTlsECDsaVerifier(m_crypto, GetPubKeyEC()); - - default: - throw new TlsFatalAlert(AlertDescription.certificate_unknown); - } + m_certificate = certificate; } - /// - public virtual TlsVerifier CreateVerifier(int signatureScheme) - { - ValidateKeyUsage(KeyUsage.DigitalSignature); - - switch (signatureScheme) - { - case SignatureScheme.ecdsa_brainpoolP256r1tls13_sha256: - case SignatureScheme.ecdsa_brainpoolP384r1tls13_sha384: - case SignatureScheme.ecdsa_brainpoolP512r1tls13_sha512: - case SignatureScheme.ecdsa_secp256r1_sha256: - case SignatureScheme.ecdsa_secp384r1_sha384: - case SignatureScheme.ecdsa_secp521r1_sha512: - case SignatureScheme.ecdsa_sha1: - return new BcTlsECDsa13Verifier(m_crypto, GetPubKeyEC(), signatureScheme); - - case SignatureScheme.ed25519: - return new BcTlsEd25519Verifier(m_crypto, GetPubKeyEd25519()); - - case SignatureScheme.ed448: - return new BcTlsEd448Verifier(m_crypto, GetPubKeyEd448()); - - case SignatureScheme.rsa_pkcs1_sha1: - case SignatureScheme.rsa_pkcs1_sha256: - case SignatureScheme.rsa_pkcs1_sha384: - case SignatureScheme.rsa_pkcs1_sha512: - { - ValidateRsa_Pkcs1(); - return new BcTlsRsaVerifier(m_crypto, GetPubKeyRsa()); - } - - case SignatureScheme.rsa_pss_pss_sha256: - case SignatureScheme.rsa_pss_pss_sha384: - case SignatureScheme.rsa_pss_pss_sha512: - { - ValidateRsa_Pss_Pss(SignatureScheme.GetSignatureAlgorithm(signatureScheme)); - return new BcTlsRsaPssVerifier(m_crypto, GetPubKeyRsa(), signatureScheme); - } - - case SignatureScheme.rsa_pss_rsae_sha256: - case SignatureScheme.rsa_pss_rsae_sha384: - case SignatureScheme.rsa_pss_rsae_sha512: - { - ValidateRsa_Pss_Rsae(); - return new BcTlsRsaPssVerifier(m_crypto, GetPubKeyRsa(), signatureScheme); - } - - // TODO[RFC 8998] - //case SignatureScheme.sm2sig_sm3: - // return new BcTlsSM2Verifier(m_crypto, GetPubKeyEC(), Strings.ToByteArray("TLSv1.3+GM+Cipher+Suite")); - - default: - throw new TlsFatalAlert(AlertDescription.certificate_unknown); - } - } + public virtual X509CertificateStructure X509CertificateStructure => m_certificate; /// - public virtual byte[] GetEncoded() + public override byte[] GetEncoded() { return m_certificate.GetEncoded(Asn1Encodable.Der); } /// - public virtual byte[] GetExtension(DerObjectIdentifier extensionOid) + public override byte[] GetExtension(DerObjectIdentifier extensionOid) { X509Extensions extensions = m_certificate.TbsCertificate.Extensions; if (extensions != null) @@ -195,191 +74,13 @@ public virtual byte[] GetExtension(DerObjectIdentifier extensionOid) return null; } - public virtual BigInteger SerialNumber - { - get { return m_certificate.SerialNumber.Value; } - } - - public virtual string SigAlgOid - { - get { return m_certificate.SignatureAlgorithm.Algorithm.Id; } - } - - public virtual Asn1Encodable GetSigAlgParams() - { - return m_certificate.SignatureAlgorithm.Parameters; - } - - /// - public virtual short GetLegacySignatureAlgorithm() - { - AsymmetricKeyParameter publicKey = GetPublicKey(); - if (publicKey.IsPrivate) - throw new TlsFatalAlert(AlertDescription.internal_error); - - if (!SupportsKeyUsage(KeyUsage.DigitalSignature)) - return -1; - - /* - * RFC 5246 7.4.6. Client Certificate - */ - - /* - * RSA public key; the certificate MUST allow the key to be used for signing with the - * signature scheme and hash algorithm that will be employed in the certificate verify - * message. - */ - if (publicKey is RsaKeyParameters) - return SignatureAlgorithm.rsa; - - /* - * DSA public key; the certificate MUST allow the key to be used for signing with the - * hash algorithm that will be employed in the certificate verify message. - */ - if (publicKey is DsaPublicKeyParameters) - return SignatureAlgorithm.dsa; - - /* - * ECDSA-capable public key; the certificate MUST allow the key to be used for signing - * with the hash algorithm that will be employed in the certificate verify message; the - * public key MUST use a curve and point format supported by the server. - */ - if (publicKey is ECPublicKeyParameters) - { - // TODO Check the curve and point format - return SignatureAlgorithm.ecdsa; - } - - return -1; - } - - /// - public virtual DHPublicKeyParameters GetPubKeyDH() - { - try - { - return (DHPublicKeyParameters)GetPublicKey(); - } - catch (InvalidCastException e) - { - throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); - } - } - - /// - public virtual DsaPublicKeyParameters GetPubKeyDss() - { - try - { - return (DsaPublicKeyParameters)GetPublicKey(); - } - catch (InvalidCastException e) - { - throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); - } - } - - /// - public virtual ECPublicKeyParameters GetPubKeyEC() - { - try - { - return (ECPublicKeyParameters)GetPublicKey(); - } - catch (InvalidCastException e) - { - throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); - } - } - - /// - public virtual Ed25519PublicKeyParameters GetPubKeyEd25519() - { - try - { - return (Ed25519PublicKeyParameters)GetPublicKey(); - } - catch (InvalidCastException e) - { - throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); - } - } - - /// - public virtual Ed448PublicKeyParameters GetPubKeyEd448() - { - try - { - return (Ed448PublicKeyParameters)GetPublicKey(); - } - catch (InvalidCastException e) - { - throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); - } - } - - /// - public virtual RsaKeyParameters GetPubKeyRsa() - { - try - { - return (RsaKeyParameters)GetPublicKey(); - } - catch (InvalidCastException e) - { - throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); - } - } - - /// - public virtual bool SupportsSignatureAlgorithm(short signatureAlgorithm) - { - return SupportsSignatureAlgorithm(signatureAlgorithm, KeyUsage.DigitalSignature); - } + public override BigInteger SerialNumber => m_certificate.SerialNumber.Value; - /// - public virtual bool SupportsSignatureAlgorithmCA(short signatureAlgorithm) - { - return SupportsSignatureAlgorithm(signatureAlgorithm, KeyUsage.KeyCertSign); - } + public override string SigAlgOid => m_certificate.SignatureAlgorithm.Algorithm.Id; - /// - public virtual TlsCertificate CheckUsageInRole(int tlsCertificateRole) - { - switch (tlsCertificateRole) - { - case TlsCertificateRole.DH: - { - ValidateKeyUsage(KeyUsage.KeyAgreement); - this.m_pubKeyDH = GetPubKeyDH(); - return this; - } - case TlsCertificateRole.ECDH: - { - ValidateKeyUsage(KeyUsage.KeyAgreement); - this.m_pubKeyEC = GetPubKeyEC(); - return this; - } - } - - throw new TlsFatalAlert(AlertDescription.certificate_unknown); - } - - /// - protected virtual AsymmetricKeyParameter GetPublicKey() - { - SubjectPublicKeyInfo keyInfo = m_certificate.SubjectPublicKeyInfo; - try - { - return PublicKeyFactory.CreateKey(keyInfo); - } - catch (Exception e) - { - throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e); - } - } + public override Asn1Encodable GetSigAlgParams() => m_certificate.SignatureAlgorithm.Parameters; - protected virtual bool SupportsKeyUsage(int keyUsageBits) + protected override bool SupportsKeyUsage(int keyUsageBits) { X509Extensions exts = m_certificate.TbsCertificate.Extensions; if (exts != null) @@ -394,98 +95,6 @@ protected virtual bool SupportsKeyUsage(int keyUsageBits) } return true; } - - protected virtual bool SupportsRsa_Pkcs1() - { - AlgorithmIdentifier pubKeyAlgID = m_certificate.SubjectPublicKeyInfo.AlgorithmID; - return RsaUtilities.SupportsPkcs1(pubKeyAlgID); - } - - protected virtual bool SupportsRsa_Pss_Pss(short signatureAlgorithm) - { - AlgorithmIdentifier pubKeyAlgID = m_certificate.SubjectPublicKeyInfo.AlgorithmID; - return RsaUtilities.SupportsPss_Pss(signatureAlgorithm, pubKeyAlgID); - } - - protected virtual bool SupportsRsa_Pss_Rsae() - { - AlgorithmIdentifier pubKeyAlgID = m_certificate.SubjectPublicKeyInfo.AlgorithmID; - return RsaUtilities.SupportsPss_Rsae(pubKeyAlgID); - } - - /// - protected virtual bool SupportsSignatureAlgorithm(short signatureAlgorithm, int keyUsage) - { - if (!SupportsKeyUsage(keyUsage)) - return false; - - AsymmetricKeyParameter publicKey = GetPublicKey(); - - switch (signatureAlgorithm) - { - case SignatureAlgorithm.rsa: - return SupportsRsa_Pkcs1() - && publicKey is RsaKeyParameters; - - case SignatureAlgorithm.dsa: - return publicKey is DsaPublicKeyParameters; - - case SignatureAlgorithm.ecdsa: - case SignatureAlgorithm.ecdsa_brainpoolP256r1tls13_sha256: - case SignatureAlgorithm.ecdsa_brainpoolP384r1tls13_sha384: - case SignatureAlgorithm.ecdsa_brainpoolP512r1tls13_sha512: - return publicKey is ECPublicKeyParameters; - - case SignatureAlgorithm.ed25519: - return publicKey is Ed25519PublicKeyParameters; - - case SignatureAlgorithm.ed448: - return publicKey is Ed448PublicKeyParameters; - - case SignatureAlgorithm.rsa_pss_rsae_sha256: - case SignatureAlgorithm.rsa_pss_rsae_sha384: - case SignatureAlgorithm.rsa_pss_rsae_sha512: - return SupportsRsa_Pss_Rsae() - && publicKey is RsaKeyParameters; - - case SignatureAlgorithm.rsa_pss_pss_sha256: - case SignatureAlgorithm.rsa_pss_pss_sha384: - case SignatureAlgorithm.rsa_pss_pss_sha512: - return SupportsRsa_Pss_Pss(signatureAlgorithm) - && publicKey is RsaKeyParameters; - - default: - return false; - } - } - - /// - public virtual void ValidateKeyUsage(int keyUsageBits) - { - if (!SupportsKeyUsage(keyUsageBits)) - throw new TlsFatalAlert(AlertDescription.certificate_unknown); - } - - /// - protected virtual void ValidateRsa_Pkcs1() - { - if (!SupportsRsa_Pkcs1()) - throw new TlsFatalAlert(AlertDescription.certificate_unknown); - } - - /// - protected virtual void ValidateRsa_Pss_Pss(short signatureAlgorithm) - { - if (!SupportsRsa_Pss_Pss(signatureAlgorithm)) - throw new TlsFatalAlert(AlertDescription.certificate_unknown); - } - - /// - protected virtual void ValidateRsa_Pss_Rsae() - { - if (!SupportsRsa_Pss_Rsae()) - throw new TlsFatalAlert(AlertDescription.certificate_unknown); - } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsCrypto.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsCrypto.cs index 7beaf30..ec6ca60 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsCrypto.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsCrypto.cs @@ -1,6 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Agreement.Srp; @@ -28,8 +29,16 @@ public class BcTlsCrypto { private readonly SecureRandom m_entropySource; + public BcTlsCrypto() + : this(CryptoServicesRegistrar.GetSecureRandom()) + { + } + public BcTlsCrypto(SecureRandom entropySource) { + if (entropySource == null) + throw new ArgumentNullException(nameof(entropySource)); + this.m_entropySource = entropySource; } @@ -43,9 +52,17 @@ public override SecureRandom SecureRandom get { return m_entropySource; } } - public override TlsCertificate CreateCertificate(byte[] encoding) + public override TlsCertificate CreateCertificate(short type, byte[] encoding) { + switch (type) + { + case CertificateType.X509: return new BcTlsCertificate(this, encoding); + case CertificateType.RawPublicKey: + return new BcTlsRawKeyCertificate(this, encoding); + default: + throw new TlsFatalAlert(AlertDescription.internal_error); + } } public override TlsCipher CreateCipher(TlsCryptoParameters cryptoParams, int encryptionAlgorithm, @@ -141,9 +158,14 @@ public override TlsECDomain CreateECDomain(TlsECConfig ecConfig) public override TlsNonceGenerator CreateNonceGenerator(byte[] additionalSeedMaterial) { - IDigest digest = CreateDigest(CryptoHashAlgorithm.sha256); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return CreateNonceGenerator(Spans.FromNullableReadOnly(additionalSeedMaterial)); +#else + int cryptoHashAlgorithm = CryptoHashAlgorithm.sha256; + IDigest digest = CreateDigest(cryptoHashAlgorithm); - byte[] seed = new byte[digest.GetDigestSize()]; + int seedLength = TlsCryptoUtilities.GetHashOutputSize(cryptoHashAlgorithm); + byte[] seed = new byte[seedLength]; SecureRandom.NextBytes(seed); DigestRandomGenerator randomGenerator = new DigestRandomGenerator(digest); @@ -151,45 +173,64 @@ public override TlsNonceGenerator CreateNonceGenerator(byte[] additionalSeedMate randomGenerator.AddSeedMaterial(seed); return new BcTlsNonceGenerator(randomGenerator); +#endif } - public override bool HasAllRawSignatureAlgorithms() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override TlsNonceGenerator CreateNonceGenerator(ReadOnlySpan additionalSeedMaterial) { - // TODO[RFC 8422] Revisit the need to buffer the handshake for "Intrinsic" hash signatures - return !HasSignatureAlgorithm(SignatureAlgorithm.ed25519) - && !HasSignatureAlgorithm(SignatureAlgorithm.ed448); - } + int cryptoHashAlgorithm = CryptoHashAlgorithm.sha256; + IDigest digest = CreateDigest(cryptoHashAlgorithm); - public override bool HasDHAgreement() - { - return true; + int seedLength = TlsCryptoUtilities.GetHashOutputSize(cryptoHashAlgorithm); + Span seed = seedLength <= 128 + ? stackalloc byte[seedLength] + : new byte[seedLength]; + SecureRandom.NextBytes(seed); + + DigestRandomGenerator randomGenerator = new DigestRandomGenerator(digest); + randomGenerator.AddSeedMaterial(additionalSeedMaterial); + randomGenerator.AddSeedMaterial(seed); + + return new BcTlsNonceGenerator(randomGenerator); } +#endif - public override bool HasECDHAgreement() + public override bool HasAnyStreamVerifiers(IList signatureAndHashAlgorithms) + { + foreach (SignatureAndHashAlgorithm algorithm in signatureAndHashAlgorithms) { + switch (SignatureScheme.From(algorithm)) + { + case SignatureScheme.ed25519: + case SignatureScheme.ed448: return true; } + } + return false; + } - public override bool HasEncryptionAlgorithm(int encryptionAlgorithm) - { - switch (encryptionAlgorithm) + public override bool HasAnyStreamVerifiersLegacy(short[] clientCertificateTypes) { - case EncryptionAlgorithm.DES40_CBC: - case EncryptionAlgorithm.DES_CBC: - case EncryptionAlgorithm.IDEA_CBC: - case EncryptionAlgorithm.RC2_CBC_40: - case EncryptionAlgorithm.RC4_128: - case EncryptionAlgorithm.RC4_40: return false; - - default: - return true; - } } public override bool HasCryptoHashAlgorithm(int cryptoHashAlgorithm) { + switch (cryptoHashAlgorithm) + { + case CryptoHashAlgorithm.md5: + case CryptoHashAlgorithm.sha1: + case CryptoHashAlgorithm.sha224: + case CryptoHashAlgorithm.sha256: + case CryptoHashAlgorithm.sha384: + case CryptoHashAlgorithm.sha512: + case CryptoHashAlgorithm.sm3: return true; + + default: + return false; + } } public override bool HasCryptoSignatureAlgorithm(int cryptoSignatureAlgorithm) @@ -221,9 +262,85 @@ public override bool HasCryptoSignatureAlgorithm(int cryptoSignatureAlgorithm) } } + public override bool HasDHAgreement() + { + return true; + } + + public override bool HasECDHAgreement() + { + return true; + } + + public override bool HasEncryptionAlgorithm(int encryptionAlgorithm) + { + switch (encryptionAlgorithm) + { + case EncryptionAlgorithm.AES_128_CBC: + case EncryptionAlgorithm.AES_128_CCM: + case EncryptionAlgorithm.AES_128_CCM_8: + case EncryptionAlgorithm.AES_128_GCM: + case EncryptionAlgorithm.AES_256_CBC: + case EncryptionAlgorithm.AES_256_CCM: + case EncryptionAlgorithm.AES_256_CCM_8: + case EncryptionAlgorithm.AES_256_GCM: + case EncryptionAlgorithm.ARIA_128_CBC: + case EncryptionAlgorithm.ARIA_128_GCM: + case EncryptionAlgorithm.ARIA_256_CBC: + case EncryptionAlgorithm.ARIA_256_GCM: + case EncryptionAlgorithm.CAMELLIA_128_CBC: + case EncryptionAlgorithm.CAMELLIA_128_GCM: + case EncryptionAlgorithm.CAMELLIA_256_CBC: + case EncryptionAlgorithm.CAMELLIA_256_GCM: + case EncryptionAlgorithm.CHACHA20_POLY1305: + case EncryptionAlgorithm.cls_3DES_EDE_CBC: + case EncryptionAlgorithm.NULL: + case EncryptionAlgorithm.SEED_CBC: + case EncryptionAlgorithm.SM4_CBC: + case EncryptionAlgorithm.SM4_CCM: + case EncryptionAlgorithm.SM4_GCM: + return true; + + case EncryptionAlgorithm.DES_CBC: + case EncryptionAlgorithm.DES40_CBC: + case EncryptionAlgorithm.IDEA_CBC: + case EncryptionAlgorithm.RC2_CBC_40: + case EncryptionAlgorithm.RC4_128: + case EncryptionAlgorithm.RC4_40: + default: + return false; + } + } + + public override bool HasHkdfAlgorithm(int cryptoHashAlgorithm) + { + switch (cryptoHashAlgorithm) + { + case CryptoHashAlgorithm.sha256: + case CryptoHashAlgorithm.sha384: + case CryptoHashAlgorithm.sha512: + case CryptoHashAlgorithm.sm3: + return true; + + default: + return false; + } + } + public override bool HasMacAlgorithm(int macAlgorithm) { + switch (macAlgorithm) + { + case MacAlgorithm.hmac_md5: + case MacAlgorithm.hmac_sha1: + case MacAlgorithm.hmac_sha256: + case MacAlgorithm.hmac_sha384: + case MacAlgorithm.hmac_sha512: return true; + + default: + return false; + } } public override bool HasNamedGroup(int namedGroup) @@ -425,8 +542,8 @@ protected virtual TlsCipher CreateChaCha20Poly1305(TlsCryptoParameters cryptoPar protected virtual TlsAeadCipher CreateCipher_Aes_Ccm(TlsCryptoParameters cryptoParams, int cipherKeySize, int macSize) { - BcTlsAeadCipherImpl encrypt = new BcTlsAeadCipherImpl(CreateAeadBlockCipher_Aes_Ccm(), true); - BcTlsAeadCipherImpl decrypt = new BcTlsAeadCipherImpl(CreateAeadBlockCipher_Aes_Ccm(), false); + BcTlsAeadCipherImpl encrypt = new BcTlsAeadCipherImpl(CreateAeadCipher_Aes_Ccm(), true); + BcTlsAeadCipherImpl decrypt = new BcTlsAeadCipherImpl(CreateAeadCipher_Aes_Ccm(), false); return new TlsAeadCipher(cryptoParams, encrypt, decrypt, cipherKeySize, macSize, TlsAeadCipher.AEAD_CCM); } @@ -434,8 +551,8 @@ protected virtual TlsAeadCipher CreateCipher_Aes_Ccm(TlsCryptoParameters cryptoP protected virtual TlsAeadCipher CreateCipher_Aes_Gcm(TlsCryptoParameters cryptoParams, int cipherKeySize, int macSize) { - BcTlsAeadCipherImpl encrypt = new BcTlsAeadCipherImpl(CreateAeadBlockCipher_Aes_Gcm(), true); - BcTlsAeadCipherImpl decrypt = new BcTlsAeadCipherImpl(CreateAeadBlockCipher_Aes_Gcm(), false); + BcTlsAeadCipherImpl encrypt = new BcTlsAeadCipherImpl(CreateAeadCipher_Aes_Gcm(), true); + BcTlsAeadCipherImpl decrypt = new BcTlsAeadCipherImpl(CreateAeadCipher_Aes_Gcm(), false); return new TlsAeadCipher(cryptoParams, encrypt, decrypt, cipherKeySize, macSize, TlsAeadCipher.AEAD_GCM); } @@ -443,8 +560,8 @@ protected virtual TlsAeadCipher CreateCipher_Aes_Gcm(TlsCryptoParameters cryptoP protected virtual TlsAeadCipher CreateCipher_Aria_Gcm(TlsCryptoParameters cryptoParams, int cipherKeySize, int macSize) { - BcTlsAeadCipherImpl encrypt = new BcTlsAeadCipherImpl(CreateAeadBlockCipher_Aria_Gcm(), true); - BcTlsAeadCipherImpl decrypt = new BcTlsAeadCipherImpl(CreateAeadBlockCipher_Aria_Gcm(), false); + BcTlsAeadCipherImpl encrypt = new BcTlsAeadCipherImpl(CreateAeadCipher_Aria_Gcm(), true); + BcTlsAeadCipherImpl decrypt = new BcTlsAeadCipherImpl(CreateAeadCipher_Aria_Gcm(), false); return new TlsAeadCipher(cryptoParams, encrypt, decrypt, cipherKeySize, macSize, TlsAeadCipher.AEAD_GCM); } @@ -452,8 +569,8 @@ protected virtual TlsAeadCipher CreateCipher_Aria_Gcm(TlsCryptoParameters crypto protected virtual TlsAeadCipher CreateCipher_Camellia_Gcm(TlsCryptoParameters cryptoParams, int cipherKeySize, int macSize) { - BcTlsAeadCipherImpl encrypt = new BcTlsAeadCipherImpl(CreateAeadBlockCipher_Camellia_Gcm(), true); - BcTlsAeadCipherImpl decrypt = new BcTlsAeadCipherImpl(CreateAeadBlockCipher_Camellia_Gcm(), false); + BcTlsAeadCipherImpl encrypt = new BcTlsAeadCipherImpl(CreateAeadCipher_Camellia_Gcm(), true); + BcTlsAeadCipherImpl decrypt = new BcTlsAeadCipherImpl(CreateAeadCipher_Camellia_Gcm(), false); return new TlsAeadCipher(cryptoParams, encrypt, decrypt, cipherKeySize, macSize, TlsAeadCipher.AEAD_GCM); } @@ -472,16 +589,16 @@ protected virtual TlsCipher CreateCipher_Cbc(TlsCryptoParameters cryptoParams, i protected virtual TlsAeadCipher CreateCipher_SM4_Ccm(TlsCryptoParameters cryptoParams) { - BcTlsAeadCipherImpl encrypt = new BcTlsAeadCipherImpl(CreateAeadBlockCipher_SM4_Ccm(), true); - BcTlsAeadCipherImpl decrypt = new BcTlsAeadCipherImpl(CreateAeadBlockCipher_SM4_Ccm(), false); + BcTlsAeadCipherImpl encrypt = new BcTlsAeadCipherImpl(CreateAeadCipher_SM4_Ccm(), true); + BcTlsAeadCipherImpl decrypt = new BcTlsAeadCipherImpl(CreateAeadCipher_SM4_Ccm(), false); return new TlsAeadCipher(cryptoParams, encrypt, decrypt, 16, 16, TlsAeadCipher.AEAD_CCM); } protected virtual TlsAeadCipher CreateCipher_SM4_Gcm(TlsCryptoParameters cryptoParams) { - BcTlsAeadCipherImpl encrypt = new BcTlsAeadCipherImpl(CreateAeadBlockCipher_SM4_Gcm(), true); - BcTlsAeadCipherImpl decrypt = new BcTlsAeadCipherImpl(CreateAeadBlockCipher_SM4_Gcm(), false); + BcTlsAeadCipherImpl encrypt = new BcTlsAeadCipherImpl(CreateAeadCipher_SM4_Gcm(), true); + BcTlsAeadCipherImpl decrypt = new BcTlsAeadCipherImpl(CreateAeadCipher_SM4_Gcm(), false); return new TlsAeadCipher(cryptoParams, encrypt, decrypt, 16, 16, TlsAeadCipher.AEAD_GCM); } @@ -494,8 +611,7 @@ protected virtual TlsNullCipher CreateNullCipher(TlsCryptoParameters cryptoParam protected virtual IBlockCipher CreateAesEngine() { - //return new AesEngine(); - return new AesFastEngine(); + return AesUtilities.CreateEngine(); } protected virtual IBlockCipher CreateAriaEngine() @@ -523,50 +639,61 @@ protected virtual IBlockCipher CreateSM4Engine() return new SM4Engine(); } - protected virtual IAeadBlockCipher CreateCcmMode(IBlockCipher engine) + protected virtual IAeadCipher CreateCcmMode(IBlockCipher engine) { return new CcmBlockCipher(engine); } - protected virtual IAeadBlockCipher CreateGcmMode(IBlockCipher engine) + protected virtual IAeadCipher CreateGcmMode(IBlockCipher engine) { // TODO Consider allowing custom configuration of multiplier return new GcmBlockCipher(engine); } - protected virtual IAeadBlockCipher CreateAeadBlockCipher_Aes_Ccm() + protected virtual IAeadCipher CreateAeadCipher_Aes_Ccm() { return CreateCcmMode(CreateAesEngine()); } - protected virtual IAeadBlockCipher CreateAeadBlockCipher_Aes_Gcm() + protected virtual IAeadCipher CreateAeadCipher_Aes_Gcm() { return CreateGcmMode(CreateAesEngine()); } - protected virtual IAeadBlockCipher CreateAeadBlockCipher_Aria_Gcm() + protected virtual IAeadCipher CreateAeadCipher_Aria_Gcm() { return CreateGcmMode(CreateAriaEngine()); } - protected virtual IAeadBlockCipher CreateAeadBlockCipher_Camellia_Gcm() + protected virtual IAeadCipher CreateAeadCipher_Camellia_Gcm() { return CreateGcmMode(CreateCamelliaEngine()); } - protected virtual IAeadBlockCipher CreateAeadBlockCipher_SM4_Ccm() + protected virtual IAeadCipher CreateAeadCipher_SM4_Ccm() { return CreateCcmMode(CreateSM4Engine()); } - protected virtual IAeadBlockCipher CreateAeadBlockCipher_SM4_Gcm() + protected virtual IAeadCipher CreateAeadCipher_SM4_Gcm() { return CreateGcmMode(CreateSM4Engine()); } public override TlsHmac CreateHmac(int macAlgorithm) { + switch (macAlgorithm) + { + case MacAlgorithm.hmac_md5: + case MacAlgorithm.hmac_sha1: + case MacAlgorithm.hmac_sha256: + case MacAlgorithm.hmac_sha384: + case MacAlgorithm.hmac_sha512: return CreateHmacForHash(TlsCryptoUtilities.GetHashForHmac(macAlgorithm)); + + default: + throw new ArgumentException("invalid MacAlgorithm: " + macAlgorithm); + } } public override TlsHmac CreateHmacForHash(int cryptoHashAlgorithm) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsDH.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsDH.cs index 8009090..958d40b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsDH.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsDH.cs @@ -1,7 +1,6 @@ #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.Parameters; @@ -22,7 +21,6 @@ public BcTlsDH(BcTlsDHDomain domain) this.m_domain = domain; } - /// public virtual byte[] GenerateEphemeral() { this.m_localKeyPair = m_domain.GenerateKeyPair(); @@ -30,13 +28,11 @@ public virtual byte[] GenerateEphemeral() return m_domain.EncodePublicKey((DHPublicKeyParameters)m_localKeyPair.Public); } - /// public virtual void ReceivePeerValue(byte[] peerValue) { this.m_peerPublicKey = m_domain.DecodePublicKey(peerValue); } - /// public virtual TlsSecret CalculateSecret() { return m_domain.CalculateDHAgreement((DHPrivateKeyParameters)m_localKeyPair.Private, m_peerPublicKey); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsDHDomain.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsDHDomain.cs index 91d7b5e..3c5f5c5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsDHDomain.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsDHDomain.cs @@ -26,7 +26,7 @@ private static byte[] EncodeValue(DHParameters dh, bool padded, BigInteger x) private static int GetValueLength(DHParameters dh) { - return (dh.P.BitLength + 7) / 8; + return BigIntegers.GetUnsignedByteLength(dh.P); } public static BcTlsSecret CalculateDHAgreement(BcTlsCrypto crypto, DHPrivateKeyParameters privateKey, @@ -39,7 +39,7 @@ public static BcTlsSecret CalculateDHAgreement(BcTlsCrypto crypto, DHPrivateKeyP return crypto.AdoptLocalSecret(secret); } - public static DHParameters GetParameters(TlsDHConfig dhConfig) + public static DHParameters GetDomainParameters(TlsDHConfig dhConfig) { DHGroup dhGroup = TlsDHUtilities.GetDHGroup(dhConfig); if (dhGroup == null) @@ -48,21 +48,21 @@ public static DHParameters GetParameters(TlsDHConfig dhConfig) return new DHParameters(dhGroup.P, dhGroup.G, dhGroup.Q, dhGroup.L); } - protected readonly BcTlsCrypto crypto; - protected readonly TlsDHConfig dhConfig; - protected readonly DHParameters dhParameters; + protected readonly BcTlsCrypto m_crypto; + protected readonly TlsDHConfig m_config; + protected readonly DHParameters m_domainParameters; public BcTlsDHDomain(BcTlsCrypto crypto, TlsDHConfig dhConfig) { - this.crypto = crypto; - this.dhConfig = dhConfig; - this.dhParameters = GetParameters(dhConfig); + this.m_crypto = crypto; + this.m_config = dhConfig; + this.m_domainParameters = GetDomainParameters(dhConfig); } public virtual BcTlsSecret CalculateDHAgreement(DHPrivateKeyParameters privateKey, DHPublicKeyParameters publicKey) { - return CalculateDHAgreement(crypto, privateKey, publicKey, dhConfig.IsPadded); + return CalculateDHAgreement(m_crypto, privateKey, publicKey, m_config.IsPadded); } public virtual TlsAgreement CreateDH() @@ -73,7 +73,7 @@ public virtual TlsAgreement CreateDH() /// public virtual BigInteger DecodeParameter(byte[] encoding) { - if (dhConfig.IsPadded && GetValueLength(dhParameters) != encoding.Length) + if (m_config.IsPadded && GetValueLength(m_domainParameters) != encoding.Length) throw new TlsFatalAlert(AlertDescription.illegal_parameter); return new BigInteger(1, encoding); @@ -91,7 +91,7 @@ public virtual DHPublicKeyParameters DecodePublicKey(byte[] encoding) { BigInteger y = DecodeParameter(encoding); - return new DHPublicKeyParameters(y, dhParameters); + return new DHPublicKeyParameters(y, m_domainParameters); } catch (Exception e) { @@ -99,22 +99,20 @@ public virtual DHPublicKeyParameters DecodePublicKey(byte[] encoding) } } - /// public virtual byte[] EncodeParameter(BigInteger x) { - return EncodeValue(dhParameters, dhConfig.IsPadded, x); + return EncodeValue(m_domainParameters, m_config.IsPadded, x); } - /// public virtual byte[] EncodePublicKey(DHPublicKeyParameters publicKey) { - return EncodeValue(dhParameters, true, publicKey.Y); + return EncodeValue(m_domainParameters, true, publicKey.Y); } public virtual AsymmetricCipherKeyPair GenerateKeyPair() { DHBasicKeyPairGenerator keyPairGenerator = new DHBasicKeyPairGenerator(); - keyPairGenerator.Init(new DHKeyGenerationParameters(crypto.SecureRandom, dhParameters)); + keyPairGenerator.Init(new DHKeyGenerationParameters(m_crypto.SecureRandom, m_domainParameters)); return keyPairGenerator.GenerateKeyPair(); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsDsaVerifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsDsaVerifier.cs index a0e9521..b4d39c7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsDsaVerifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsDsaVerifier.cs @@ -18,9 +18,9 @@ public BcTlsDsaVerifier(BcTlsCrypto crypto, DsaPublicKeyParameters publicKey) { } - protected override IDsa CreateDsaImpl(int cryptoHashAlgorithm) + protected override IDsa CreateDsaImpl() { - return new DsaSigner(new HMacDsaKCalculator(m_crypto.CreateDigest(cryptoHashAlgorithm))); + return new DsaSigner(); } protected override short SignatureAlgorithm diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsDssVerifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsDssVerifier.cs index 53dc09b..cfc8a5c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsDssVerifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsDssVerifier.cs @@ -18,21 +18,17 @@ protected BcTlsDssVerifier(BcTlsCrypto crypto, AsymmetricKeyParameter publicKey) { } - protected abstract IDsa CreateDsaImpl(int cryptoHashAlgorithm); + protected abstract IDsa CreateDsaImpl(); protected abstract short SignatureAlgorithm { get; } - public override bool VerifyRawSignature(DigitallySigned signedParams, byte[] hash) + public override bool VerifyRawSignature(DigitallySigned digitallySigned, byte[] hash) { - SignatureAndHashAlgorithm algorithm = signedParams.Algorithm; + SignatureAndHashAlgorithm algorithm = digitallySigned.Algorithm; if (algorithm != null && algorithm.Signature != SignatureAlgorithm) throw new InvalidOperationException("Invalid algorithm: " + algorithm); - int cryptoHashAlgorithm = (null == algorithm) - ? CryptoHashAlgorithm.sha1 - : TlsCryptoUtilities.GetHash(algorithm.Hash); - - ISigner signer = new DsaDigestSigner(CreateDsaImpl(cryptoHashAlgorithm), new NullDigest()); + ISigner signer = new DsaDigestSigner(CreateDsaImpl(), new NullDigest()); signer.Init(false, m_publicKey); if (algorithm == null) { @@ -43,7 +39,7 @@ public override bool VerifyRawSignature(DigitallySigned signedParams, byte[] has { signer.BlockUpdate(hash, 0, hash.Length); } - return signer.VerifySignature(signedParams.Signature); + return signer.VerifySignature(digitallySigned.Signature); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsECDomain.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsECDomain.cs index eb882d3..6dbd234 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsECDomain.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsECDomain.cs @@ -6,7 +6,6 @@ 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.EC; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators; using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; @@ -21,7 +20,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto.Impl.BC public class BcTlsECDomain : TlsECDomain { - public static BcTlsSecret CalculateBasicAgreement(BcTlsCrypto crypto, ECPrivateKeyParameters privateKey, + public static BcTlsSecret CalculateECDHAgreement(BcTlsCrypto crypto, ECPrivateKeyParameters privateKey, ECPublicKeyParameters publicKey) { ECDHBasicAgreement basicAgreement = new ECDHBasicAgreement(); @@ -50,33 +49,29 @@ public static ECDomainParameters GetDomainParameters(int namedGroup) // Parameters are lazily created the first time a particular curve is accessed string curveName = NamedGroup.GetCurveName(namedGroup); - X9ECParameters ecP = CustomNamedCurves.GetByName(curveName); + X9ECParameters ecP = ECKeyPairGenerator.FindECCurveByName(curveName); if (ecP == null) - { - ecP = ECNamedCurveTable.GetByName(curveName); - if (ecP == null) - return null; - } + return null; // It's a bit inefficient to do this conversion every time return new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); } protected readonly BcTlsCrypto m_crypto; - protected readonly TlsECConfig m_ecConfig; - protected readonly ECDomainParameters m_ecDomainParameters; + protected readonly TlsECConfig m_config; + protected readonly ECDomainParameters m_domainParameters; public BcTlsECDomain(BcTlsCrypto crypto, TlsECConfig ecConfig) { this.m_crypto = crypto; - this.m_ecConfig = ecConfig; - this.m_ecDomainParameters = GetDomainParameters(ecConfig); + this.m_config = ecConfig; + this.m_domainParameters = GetDomainParameters(ecConfig); } public virtual BcTlsSecret CalculateECDHAgreement(ECPrivateKeyParameters privateKey, ECPublicKeyParameters publicKey) { - return CalculateBasicAgreement(m_crypto, privateKey, publicKey); + return CalculateECDHAgreement(m_crypto, privateKey, publicKey); } public virtual TlsAgreement CreateECDH() @@ -86,16 +81,17 @@ public virtual TlsAgreement CreateECDH() public virtual ECPoint DecodePoint(byte[] encoding) { - return m_ecDomainParameters.Curve.DecodePoint(encoding); + return m_domainParameters.Curve.DecodePoint(encoding); } + /// public virtual ECPublicKeyParameters DecodePublicKey(byte[] encoding) { try { ECPoint point = DecodePoint(encoding); - return new ECPublicKeyParameters(point, m_ecDomainParameters); + return new ECPublicKeyParameters(point, m_domainParameters); } catch (IOException e) { @@ -120,7 +116,7 @@ public virtual byte[] EncodePublicKey(ECPublicKeyParameters publicKey) public virtual AsymmetricCipherKeyPair GenerateKeyPair() { ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator(); - keyPairGenerator.Init(new ECKeyGenerationParameters(m_ecDomainParameters, m_crypto.SecureRandom)); + keyPairGenerator.Init(new ECKeyGenerationParameters(m_domainParameters, m_crypto.SecureRandom)); return keyPairGenerator.GenerateKeyPair(); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsECDsaVerifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsECDsaVerifier.cs index d41aa8a..1f612f1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsECDsaVerifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsECDsaVerifier.cs @@ -18,9 +18,9 @@ public BcTlsECDsaVerifier(BcTlsCrypto crypto, ECPublicKeyParameters publicKey) { } - protected override IDsa CreateDsaImpl(int cryptoHashAlgorithm) + protected override IDsa CreateDsaImpl() { - return new ECDsaSigner(new HMacDsaKCalculator(m_crypto.CreateDigest(cryptoHashAlgorithm))); + return new ECDsaSigner(); } protected override short SignatureAlgorithm diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsEd25519Signer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsEd25519Signer.cs index 6acd19b..dc40b92 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsEd25519Signer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsEd25519Signer.cs @@ -15,11 +15,6 @@ public BcTlsEd25519Signer(BcTlsCrypto crypto, Ed25519PrivateKeyParameters privat { } - public override byte[] GenerateRawSignature(SignatureAndHashAlgorithm algorithm, byte[] hash) - { - throw new NotSupportedException(); - } - public override TlsStreamSigner GetStreamSigner(SignatureAndHashAlgorithm algorithm) { if (algorithm == null || SignatureScheme.From(algorithm) != SignatureScheme.ed25519) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsEd448Signer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsEd448Signer.cs index 814cc26..2e7bb68 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsEd448Signer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsEd448Signer.cs @@ -15,11 +15,6 @@ public BcTlsEd448Signer(BcTlsCrypto crypto, Ed448PrivateKeyParameters privateKey { } - public override byte[] GenerateRawSignature(SignatureAndHashAlgorithm algorithm, byte[] hash) - { - throw new NotSupportedException(); - } - public override TlsStreamSigner GetStreamSigner(SignatureAndHashAlgorithm algorithm) { if (algorithm == null || SignatureScheme.From(algorithm) != SignatureScheme.ed448) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsHash.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsHash.cs index 7a45d44..84947a7 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsHash.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsHash.cs @@ -30,6 +30,13 @@ public void Update(byte[] data, int offSet, int length) m_digest.BlockUpdate(data, offSet, length); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Update(ReadOnlySpan input) + { + m_digest.BlockUpdate(input); + } +#endif + public byte[] CalculateHash() { byte[] rv = new byte[m_digest.GetDigestSize()]; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsHmac.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsHmac.cs index 51e4816..8666193 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsHmac.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsHmac.cs @@ -22,11 +22,25 @@ public void SetKey(byte[] key, int keyOff, int keyLen) m_hmac.Init(new KeyParameter(key, keyOff, keyLen)); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void SetKey(ReadOnlySpan key) + { + m_hmac.Init(new KeyParameter(key)); + } +#endif + public void Update(byte[] input, int inOff, int length) { m_hmac.BlockUpdate(input, inOff, length); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public void Update(ReadOnlySpan input) + { + m_hmac.BlockUpdate(input); + } +#endif + public byte[] CalculateMac() { byte[] rv = new byte[m_hmac.GetMacSize()]; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsRawKeyCertificate.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsRawKeyCertificate.cs new file mode 100644 index 0000000..1ecf2b7 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsRawKeyCertificate.cs @@ -0,0 +1,511 @@ +#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.Cmp; +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.Parameters; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Signers; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Security; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tls.Crypto.Impl.BC +{ + /// Implementation class for a single X.509 certificate based on the BC light-weight API. + public class BcTlsRawKeyCertificate + : TlsCertificate + { + protected readonly BcTlsCrypto m_crypto; + protected readonly SubjectPublicKeyInfo m_keyInfo; + + protected DHPublicKeyParameters m_pubKeyDH = null; + protected ECPublicKeyParameters m_pubKeyEC = null; + protected Ed25519PublicKeyParameters m_pubKeyEd25519 = null; + protected Ed448PublicKeyParameters m_pubKeyEd448 = null; + protected RsaKeyParameters m_pubKeyRsa = null; + + /// + public BcTlsRawKeyCertificate(BcTlsCrypto crypto, byte[] encoding) + : this(crypto, SubjectPublicKeyInfo.GetInstance(encoding)) + { + } + + public BcTlsRawKeyCertificate(BcTlsCrypto crypto, SubjectPublicKeyInfo keyInfo) + { + m_crypto = crypto; + m_keyInfo = keyInfo; + } + + public virtual SubjectPublicKeyInfo SubjectPublicKeyInfo => m_keyInfo; + + /// + public virtual TlsEncryptor CreateEncryptor(int tlsCertificateRole) + { + ValidateKeyUsage(KeyUsage.KeyEncipherment); + + switch (tlsCertificateRole) + { + case TlsCertificateRole.RsaEncryption: + { + this.m_pubKeyRsa = GetPubKeyRsa(); + return new BcTlsRsaEncryptor(m_crypto, m_pubKeyRsa); + } + // TODO[gmssl] + //case TlsCertificateRole.Sm2Encryption: + //{ + // this.m_pubKeyEC = GetPubKeyEC(); + // return new BcTlsSM2Encryptor(m_crypto, m_pubKeyEC); + //} + } + + throw new TlsFatalAlert(AlertDescription.certificate_unknown); + } + + /// + public virtual TlsVerifier CreateVerifier(short signatureAlgorithm) + { + switch (signatureAlgorithm) + { + case SignatureAlgorithm.ed25519: + case SignatureAlgorithm.ed448: + { + int signatureScheme = SignatureScheme.From(HashAlgorithm.Intrinsic, signatureAlgorithm); + Tls13Verifier tls13Verifier = CreateVerifier(signatureScheme); + return new LegacyTls13Verifier(signatureScheme, tls13Verifier); + } + } + + ValidateKeyUsage(KeyUsage.DigitalSignature); + + switch (signatureAlgorithm) + { + case SignatureAlgorithm.dsa: + return new BcTlsDsaVerifier(m_crypto, GetPubKeyDss()); + + case SignatureAlgorithm.ecdsa: + return new BcTlsECDsaVerifier(m_crypto, GetPubKeyEC()); + + case SignatureAlgorithm.rsa: + { + ValidateRsa_Pkcs1(); + return new BcTlsRsaVerifier(m_crypto, GetPubKeyRsa()); + } + + case SignatureAlgorithm.rsa_pss_pss_sha256: + case SignatureAlgorithm.rsa_pss_pss_sha384: + case SignatureAlgorithm.rsa_pss_pss_sha512: + { + ValidateRsa_Pss_Pss(signatureAlgorithm); + int signatureScheme = SignatureScheme.From(HashAlgorithm.Intrinsic, signatureAlgorithm); + return new BcTlsRsaPssVerifier(m_crypto, GetPubKeyRsa(), signatureScheme); + } + + case SignatureAlgorithm.rsa_pss_rsae_sha256: + case SignatureAlgorithm.rsa_pss_rsae_sha384: + case SignatureAlgorithm.rsa_pss_rsae_sha512: + { + ValidateRsa_Pss_Rsae(); + int signatureScheme = SignatureScheme.From(HashAlgorithm.Intrinsic, signatureAlgorithm); + return new BcTlsRsaPssVerifier(m_crypto, GetPubKeyRsa(), signatureScheme); + } + + default: + throw new TlsFatalAlert(AlertDescription.certificate_unknown); + } + } + + /// + public virtual Tls13Verifier CreateVerifier(int signatureScheme) + { + ValidateKeyUsage(KeyUsage.DigitalSignature); + + switch (signatureScheme) + { + case SignatureScheme.ecdsa_brainpoolP256r1tls13_sha256: + case SignatureScheme.ecdsa_brainpoolP384r1tls13_sha384: + case SignatureScheme.ecdsa_brainpoolP512r1tls13_sha512: + case SignatureScheme.ecdsa_secp256r1_sha256: + case SignatureScheme.ecdsa_secp384r1_sha384: + case SignatureScheme.ecdsa_secp521r1_sha512: + case SignatureScheme.ecdsa_sha1: + { + int cryptoHashAlgorithm = SignatureScheme.GetCryptoHashAlgorithm(signatureScheme); + IDigest digest = m_crypto.CreateDigest(cryptoHashAlgorithm); + + ISigner verifier = new DsaDigestSigner(new ECDsaSigner(), digest); + verifier.Init(false, GetPubKeyEC()); + + return new BcTls13Verifier(verifier); + } + + case SignatureScheme.ed25519: + { + Ed25519Signer verifier = new Ed25519Signer(); + verifier.Init(false, GetPubKeyEd25519()); + + return new BcTls13Verifier(verifier); + } + + case SignatureScheme.ed448: + { + Ed448Signer verifier = new Ed448Signer(TlsUtilities.EmptyBytes); + verifier.Init(false, GetPubKeyEd448()); + + return new BcTls13Verifier(verifier); + } + + case SignatureScheme.rsa_pkcs1_sha1: + case SignatureScheme.rsa_pkcs1_sha256: + case SignatureScheme.rsa_pkcs1_sha384: + case SignatureScheme.rsa_pkcs1_sha512: + { + ValidateRsa_Pkcs1(); + + int cryptoHashAlgorithm = SignatureScheme.GetCryptoHashAlgorithm(signatureScheme); + IDigest digest = m_crypto.CreateDigest(cryptoHashAlgorithm); + + RsaDigestSigner verifier = new RsaDigestSigner(digest, + TlsCryptoUtilities.GetOidForHash(cryptoHashAlgorithm)); + verifier.Init(false, GetPubKeyRsa()); + + return new BcTls13Verifier(verifier); + } + + case SignatureScheme.rsa_pss_pss_sha256: + case SignatureScheme.rsa_pss_pss_sha384: + case SignatureScheme.rsa_pss_pss_sha512: + { + ValidateRsa_Pss_Pss(SignatureScheme.GetSignatureAlgorithm(signatureScheme)); + + int cryptoHashAlgorithm = SignatureScheme.GetCryptoHashAlgorithm(signatureScheme); + IDigest digest = m_crypto.CreateDigest(cryptoHashAlgorithm); + + PssSigner verifier = new PssSigner(new RsaEngine(), digest, digest.GetDigestSize()); + verifier.Init(false, GetPubKeyRsa()); + + return new BcTls13Verifier(verifier); + } + + case SignatureScheme.rsa_pss_rsae_sha256: + case SignatureScheme.rsa_pss_rsae_sha384: + case SignatureScheme.rsa_pss_rsae_sha512: + { + ValidateRsa_Pss_Rsae(); + + int cryptoHashAlgorithm = SignatureScheme.GetCryptoHashAlgorithm(signatureScheme); + IDigest digest = m_crypto.CreateDigest(cryptoHashAlgorithm); + + PssSigner verifier = new PssSigner(new RsaEngine(), digest, digest.GetDigestSize()); + verifier.Init(false, GetPubKeyRsa()); + + return new BcTls13Verifier(verifier); + } + + // TODO[RFC 8998] + //case SignatureScheme.sm2sig_sm3: + //{ + // ParametersWithID parametersWithID = new ParametersWithID(GetPubKeyEC(), + // Strings.ToByteArray("TLSv1.3+GM+Cipher+Suite")); + + // SM2Signer verifier = new SM2Signer(); + // verifier.Init(false, parametersWithID); + + // return new BcTls13Verifier(verifier); + //} + + default: + throw new TlsFatalAlert(AlertDescription.certificate_unknown); + } + } + + /// + public virtual byte[] GetEncoded() + { + return m_keyInfo.GetEncoded(Asn1Encodable.Der); + } + + /// + public virtual byte[] GetExtension(DerObjectIdentifier extensionOid) + { + return null; + } + + public virtual BigInteger SerialNumber => null; + + public virtual string SigAlgOid => null; + + public virtual Asn1Encodable GetSigAlgParams() => null; + + /// + public virtual short GetLegacySignatureAlgorithm() + { + AsymmetricKeyParameter publicKey = GetPublicKey(); + if (publicKey.IsPrivate) + throw new TlsFatalAlert(AlertDescription.internal_error); + + if (!SupportsKeyUsage(KeyUsage.DigitalSignature)) + return -1; + + /* + * RFC 5246 7.4.6. Client Certificate + */ + + /* + * RSA public key; the certificate MUST allow the key to be used for signing with the + * signature scheme and hash algorithm that will be employed in the certificate verify + * message. + */ + if (publicKey is RsaKeyParameters) + return SignatureAlgorithm.rsa; + + /* + * DSA public key; the certificate MUST allow the key to be used for signing with the + * hash algorithm that will be employed in the certificate verify message. + */ + if (publicKey is DsaPublicKeyParameters) + return SignatureAlgorithm.dsa; + + /* + * ECDSA-capable public key; the certificate MUST allow the key to be used for signing + * with the hash algorithm that will be employed in the certificate verify message; the + * public key MUST use a curve and point format supported by the server. + */ + if (publicKey is ECPublicKeyParameters) + { + // TODO Check the curve and point format + return SignatureAlgorithm.ecdsa; + } + + return -1; + } + + /// + public virtual DHPublicKeyParameters GetPubKeyDH() + { + try + { + return (DHPublicKeyParameters)GetPublicKey(); + } + catch (InvalidCastException e) + { + throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); + } + } + + /// + public virtual DsaPublicKeyParameters GetPubKeyDss() + { + try + { + return (DsaPublicKeyParameters)GetPublicKey(); + } + catch (InvalidCastException e) + { + throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); + } + } + + /// + public virtual ECPublicKeyParameters GetPubKeyEC() + { + try + { + return (ECPublicKeyParameters)GetPublicKey(); + } + catch (InvalidCastException e) + { + throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); + } + } + + /// + public virtual Ed25519PublicKeyParameters GetPubKeyEd25519() + { + try + { + return (Ed25519PublicKeyParameters)GetPublicKey(); + } + catch (InvalidCastException e) + { + throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); + } + } + + /// + public virtual Ed448PublicKeyParameters GetPubKeyEd448() + { + try + { + return (Ed448PublicKeyParameters)GetPublicKey(); + } + catch (InvalidCastException e) + { + throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); + } + } + + /// + public virtual RsaKeyParameters GetPubKeyRsa() + { + try + { + return (RsaKeyParameters)GetPublicKey(); + } + catch (InvalidCastException e) + { + throw new TlsFatalAlert(AlertDescription.certificate_unknown, e); + } + } + + /// + public virtual bool SupportsSignatureAlgorithm(short signatureAlgorithm) + { + return SupportsSignatureAlgorithm(signatureAlgorithm, KeyUsage.DigitalSignature); + } + + /// + public virtual bool SupportsSignatureAlgorithmCA(short signatureAlgorithm) + { + return SupportsSignatureAlgorithm(signatureAlgorithm, KeyUsage.KeyCertSign); + } + + /// + public virtual TlsCertificate CheckUsageInRole(int tlsCertificateRole) + { + switch (tlsCertificateRole) + { + case TlsCertificateRole.DH: + { + ValidateKeyUsage(KeyUsage.KeyAgreement); + this.m_pubKeyDH = GetPubKeyDH(); + return this; + } + case TlsCertificateRole.ECDH: + { + ValidateKeyUsage(KeyUsage.KeyAgreement); + this.m_pubKeyEC = GetPubKeyEC(); + return this; + } + } + + throw new TlsFatalAlert(AlertDescription.certificate_unknown); + } + + /// + protected virtual AsymmetricKeyParameter GetPublicKey() + { + try + { + return PublicKeyFactory.CreateKey(m_keyInfo); + } + catch (Exception e) + { + throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e); + } + } + + protected virtual bool SupportsKeyUsage(int keyUsageBits) + { + return true; + } + + protected virtual bool SupportsRsa_Pkcs1() + { + AlgorithmIdentifier pubKeyAlgID = m_keyInfo.AlgorithmID; + return RsaUtilities.SupportsPkcs1(pubKeyAlgID); + } + + protected virtual bool SupportsRsa_Pss_Pss(short signatureAlgorithm) + { + AlgorithmIdentifier pubKeyAlgID = m_keyInfo.AlgorithmID; + return RsaUtilities.SupportsPss_Pss(signatureAlgorithm, pubKeyAlgID); + } + + protected virtual bool SupportsRsa_Pss_Rsae() + { + AlgorithmIdentifier pubKeyAlgID = m_keyInfo.AlgorithmID; + return RsaUtilities.SupportsPss_Rsae(pubKeyAlgID); + } + + /// + protected virtual bool SupportsSignatureAlgorithm(short signatureAlgorithm, int keyUsage) + { + if (!SupportsKeyUsage(keyUsage)) + return false; + + AsymmetricKeyParameter publicKey = GetPublicKey(); + + switch (signatureAlgorithm) + { + case SignatureAlgorithm.rsa: + return SupportsRsa_Pkcs1() + && publicKey is RsaKeyParameters; + + case SignatureAlgorithm.dsa: + return publicKey is DsaPublicKeyParameters; + + case SignatureAlgorithm.ecdsa: + case SignatureAlgorithm.ecdsa_brainpoolP256r1tls13_sha256: + case SignatureAlgorithm.ecdsa_brainpoolP384r1tls13_sha384: + case SignatureAlgorithm.ecdsa_brainpoolP512r1tls13_sha512: + return publicKey is ECPublicKeyParameters; + + case SignatureAlgorithm.ed25519: + return publicKey is Ed25519PublicKeyParameters; + + case SignatureAlgorithm.ed448: + return publicKey is Ed448PublicKeyParameters; + + case SignatureAlgorithm.rsa_pss_rsae_sha256: + case SignatureAlgorithm.rsa_pss_rsae_sha384: + case SignatureAlgorithm.rsa_pss_rsae_sha512: + return SupportsRsa_Pss_Rsae() + && publicKey is RsaKeyParameters; + + case SignatureAlgorithm.rsa_pss_pss_sha256: + case SignatureAlgorithm.rsa_pss_pss_sha384: + case SignatureAlgorithm.rsa_pss_pss_sha512: + return SupportsRsa_Pss_Pss(signatureAlgorithm) + && publicKey is RsaKeyParameters; + + default: + return false; + } + } + + /// + public virtual void ValidateKeyUsage(int keyUsageBits) + { + if (!SupportsKeyUsage(keyUsageBits)) + throw new TlsFatalAlert(AlertDescription.certificate_unknown); + } + + /// + protected virtual void ValidateRsa_Pkcs1() + { + if (!SupportsRsa_Pkcs1()) + throw new TlsFatalAlert(AlertDescription.certificate_unknown); + } + + /// + protected virtual void ValidateRsa_Pss_Pss(short signatureAlgorithm) + { + if (!SupportsRsa_Pss_Pss(signatureAlgorithm)) + throw new TlsFatalAlert(AlertDescription.certificate_unknown); + } + + /// + protected virtual void ValidateRsa_Pss_Rsae() + { + if (!SupportsRsa_Pss_Rsae()) + throw new TlsFatalAlert(AlertDescription.certificate_unknown); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsRawKeyCertificate.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsRawKeyCertificate.cs.meta new file mode 100644 index 0000000..a7d43f7 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsRawKeyCertificate.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: eb9ce5833c16ef344b2932731dc4fd48 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsRsaPssSigner.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsRsaPssSigner.cs index 381f55d..0c49638 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsRsaPssSigner.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsRsaPssSigner.cs @@ -25,11 +25,6 @@ public BcTlsRsaPssSigner(BcTlsCrypto crypto, RsaKeyParameters privateKey, int si } public override byte[] GenerateRawSignature(SignatureAndHashAlgorithm algorithm, byte[] hash) - { - throw new NotSupportedException(); - } - - public override TlsStreamSigner GetStreamSigner(SignatureAndHashAlgorithm algorithm) { if (algorithm == null || SignatureScheme.From(algorithm) != m_signatureScheme) throw new InvalidOperationException("Invalid algorithm: " + algorithm); @@ -37,10 +32,18 @@ public override TlsStreamSigner GetStreamSigner(SignatureAndHashAlgorithm algori int cryptoHashAlgorithm = SignatureScheme.GetCryptoHashAlgorithm(m_signatureScheme); IDigest digest = m_crypto.CreateDigest(cryptoHashAlgorithm); - PssSigner signer = new PssSigner(new RsaBlindedEngine(), digest, digest.GetDigestSize()); + PssSigner signer = PssSigner.CreateRawSigner(new RsaBlindedEngine(), digest, digest, digest.GetDigestSize(), + PssSigner.TrailerImplicit); signer.Init(true, new ParametersWithRandom(m_privateKey, m_crypto.SecureRandom)); - - return new BcTlsStreamSigner(signer); + signer.BlockUpdate(hash, 0, hash.Length); + try + { + return signer.GenerateSignature(); + } + catch (CryptoException e) + { + throw new TlsFatalAlert(AlertDescription.internal_error, e); + } } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsRsaPssVerifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsRsaPssVerifier.cs index 8356735..5af7fa2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsRsaPssVerifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsRsaPssVerifier.cs @@ -24,24 +24,20 @@ public BcTlsRsaPssVerifier(BcTlsCrypto crypto, RsaKeyParameters publicKey, int s this.m_signatureScheme = signatureScheme; } - public override bool VerifyRawSignature(DigitallySigned signature, byte[] hash) + public override bool VerifyRawSignature(DigitallySigned digitallySigned, byte[] hash) { - throw new NotSupportedException(); - } - - public override TlsStreamVerifier GetStreamVerifier(DigitallySigned signature) - { - SignatureAndHashAlgorithm algorithm = signature.Algorithm; + SignatureAndHashAlgorithm algorithm = digitallySigned.Algorithm; if (algorithm == null || SignatureScheme.From(algorithm) != m_signatureScheme) throw new InvalidOperationException("Invalid algorithm: " + algorithm); int cryptoHashAlgorithm = SignatureScheme.GetCryptoHashAlgorithm(m_signatureScheme); IDigest digest = m_crypto.CreateDigest(cryptoHashAlgorithm); - PssSigner verifier = new PssSigner(new RsaEngine(), digest, digest.GetDigestSize()); + PssSigner verifier = PssSigner.CreateRawSigner(new RsaEngine(), digest, digest, digest.GetDigestSize(), + PssSigner.TrailerImplicit); verifier.Init(false, m_publicKey); - - return new BcTlsStreamVerifier(verifier, signature.Signature); + verifier.BlockUpdate(hash, 0, hash.Length); + return verifier.VerifySignature(digitallySigned.Signature); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsRsaVerifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsRsaVerifier.cs index 67fae7f..109ff36 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsRsaVerifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsRsaVerifier.cs @@ -21,11 +21,11 @@ public BcTlsRsaVerifier(BcTlsCrypto crypto, RsaKeyParameters publicKey) { } - public override bool VerifyRawSignature(DigitallySigned signedParams, byte[] hash) + public override bool VerifyRawSignature(DigitallySigned digitallySigned, byte[] hash) { IDigest nullDigest = new NullDigest(); - SignatureAndHashAlgorithm algorithm = signedParams.Algorithm; + SignatureAndHashAlgorithm algorithm = digitallySigned.Algorithm; ISigner signer; if (algorithm != null) { @@ -48,7 +48,7 @@ public override bool VerifyRawSignature(DigitallySigned signedParams, byte[] has } signer.Init(false, m_publicKey); signer.BlockUpdate(hash, 0, hash.Length); - return signer.VerifySignature(signedParams.Signature); + return signer.VerifySignature(digitallySigned.Signature); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsSecret.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsSecret.cs index d5b0ae6..abdc609 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsSecret.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsSecret.cs @@ -26,7 +26,7 @@ public static BcTlsSecret Convert(BcTlsCrypto crypto, TlsSecret secret) return crypto.AdoptLocalSecret(CopyData(abstractTlsSecret)); } - throw new ArgumentException("unrecognized TlsSecret - cannot copy data: " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(secret)); + throw new ArgumentException("unrecognized TlsSecret - cannot copy data: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(secret)); } // SSL3 magic mix constants ("A", "BB", "CCC", ...) @@ -76,8 +76,34 @@ public override TlsSecret DeriveUsingPrf(int prfAlgorithm, string label, byte[] } } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override TlsSecret DeriveUsingPrf(int prfAlgorithm, ReadOnlySpan label, ReadOnlySpan seed, + int length) + { + lock (this) + { + CheckAlive(); + + switch (prfAlgorithm) + { + case PrfAlgorithm.tls13_hkdf_sha256: + return TlsCryptoUtilities.HkdfExpandLabel(this, CryptoHashAlgorithm.sha256, label, seed, length); + case PrfAlgorithm.tls13_hkdf_sha384: + return TlsCryptoUtilities.HkdfExpandLabel(this, CryptoHashAlgorithm.sha384, label, seed, length); + case PrfAlgorithm.tls13_hkdf_sm3: + return TlsCryptoUtilities.HkdfExpandLabel(this, CryptoHashAlgorithm.sm3, label, seed, length); + default: + return m_crypto.AdoptLocalSecret(Prf(prfAlgorithm, label, seed, length)); + } + } + } +#endif + public override TlsSecret HkdfExpand(int cryptoHashAlgorithm, byte[] info, int length) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return HkdfExpand(cryptoHashAlgorithm, info.AsSpan(), length); +#else lock (this) { if (length < 1) @@ -100,10 +126,10 @@ public override TlsSecret HkdfExpand(int cryptoHashAlgorithm, byte[] info, int l byte counter = 0x00; int pos = 0; - for (; ; ) + for (;;) { hmac.BlockUpdate(info, 0, info.Length); - hmac.Update((byte)++counter); + hmac.Update(++counter); hmac.DoFinal(t, 0); int remaining = length - pos; @@ -118,9 +144,60 @@ public override TlsSecret HkdfExpand(int cryptoHashAlgorithm, byte[] info, int l hmac.BlockUpdate(t, 0, t.Length); } + return m_crypto.AdoptLocalSecret(okm); + } +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override TlsSecret HkdfExpand(int cryptoHashAlgorithm, ReadOnlySpan info, int length) + { + lock (this) + { + if (length < 1) + return m_crypto.AdoptLocalSecret(TlsUtilities.EmptyBytes); + + int hashLen = TlsCryptoUtilities.GetHashOutputSize(cryptoHashAlgorithm); + if (length > (255 * hashLen)) + throw new ArgumentException("must be <= 255 * (output size of 'hashAlgorithm')", "length"); + + CheckAlive(); + + ReadOnlySpan prk = m_data; + + HMac hmac = new HMac(m_crypto.CreateDigest(cryptoHashAlgorithm)); + hmac.Init(new KeyParameter(prk)); + + byte[] okm = new byte[length]; + + Span t = hashLen <= 128 + ? stackalloc byte[hashLen] + : new byte[hashLen]; + byte counter = 0x00; + + int pos = 0; + for (;;) + { + hmac.BlockUpdate(info); + hmac.Update(++counter); + hmac.DoFinal(t); + + int remaining = length - pos; + if (remaining <= hashLen) + { + t[..remaining].CopyTo(okm.AsSpan(pos)); + break; + } + + t.CopyTo(okm.AsSpan(pos)); + pos += hashLen; + hmac.BlockUpdate(t); + } + return m_crypto.AdoptLocalSecret(okm); } } +#endif public override TlsSecret HkdfExtract(int cryptoHashAlgorithm, TlsSecret ikm) { @@ -148,15 +225,16 @@ protected override AbstractTlsCrypto Crypto get { return m_crypto; } } - protected virtual void HmacHash(IDigest digest, byte[] secret, int secretOff, int secretLen, byte[] seed, - byte[] output) + protected virtual void HmacHash(int cryptoHashAlgorithm, byte[] secret, int secretOff, int secretLen, + byte[] seed, byte[] output) { - HMac mac = new HMac(digest); - mac.Init(new KeyParameter(secret, secretOff, secretLen)); + IDigest digest = m_crypto.CreateDigest(cryptoHashAlgorithm); + HMac hmac = new HMac(digest); + hmac.Init(new KeyParameter(secret, secretOff, secretLen)); byte[] a = seed; - int macSize = mac.GetMacSize(); + int macSize = hmac.GetMacSize(); byte[] b1 = new byte[macSize]; byte[] b2 = new byte[macSize]; @@ -164,12 +242,12 @@ protected virtual void HmacHash(IDigest digest, byte[] secret, int secretOff, in int pos = 0; while (pos < output.Length) { - mac.BlockUpdate(a, 0, a.Length); - mac.DoFinal(b1, 0); + hmac.BlockUpdate(a, 0, a.Length); + hmac.DoFinal(b1, 0); a = b1; - mac.BlockUpdate(a, 0, a.Length); - mac.BlockUpdate(seed, 0, seed.Length); - mac.DoFinal(b2, 0); + hmac.BlockUpdate(a, 0, a.Length); + hmac.BlockUpdate(seed, 0, seed.Length); + hmac.DoFinal(b2, 0); Array.Copy(b2, 0, output, pos, System.Math.Min(macSize, output.Length - pos)); pos += macSize; } @@ -188,8 +266,33 @@ protected virtual byte[] Prf(int prfAlgorithm, string label, byte[] seed, int le return Prf_1_2(prfAlgorithm, labelSeed, length); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + protected virtual byte[] Prf(int prfAlgorithm, ReadOnlySpan label, ReadOnlySpan seed, int length) + { + if (PrfAlgorithm.ssl_prf_legacy == prfAlgorithm) + return Prf_Ssl(seed, length); + + byte[] labelSeed = new byte[label.Length + seed.Length]; + + for (int i = 0; i < label.Length; ++i) + { + labelSeed[i] = (byte)label[i]; + } + + seed.CopyTo(labelSeed.AsSpan(label.Length)); + + if (PrfAlgorithm.tls_prf_legacy == prfAlgorithm) + return Prf_1_0(labelSeed, length); + + return Prf_1_2(prfAlgorithm, labelSeed, length); + } +#endif + protected virtual byte[] Prf_Ssl(byte[] seed, int length) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return Prf_Ssl(seed.AsSpan(), length); +#else IDigest md5 = m_crypto.CreateDigest(CryptoHashAlgorithm.md5); IDigest sha1 = m_crypto.CreateDigest(CryptoHashAlgorithm.sha1); @@ -226,20 +329,62 @@ protected virtual byte[] Prf_Ssl(byte[] seed, int length) } } + return result; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + protected virtual byte[] Prf_Ssl(ReadOnlySpan seed, int length) + { + IDigest md5 = m_crypto.CreateDigest(CryptoHashAlgorithm.md5); + IDigest sha1 = m_crypto.CreateDigest(CryptoHashAlgorithm.sha1); + + int md5Size = md5.GetDigestSize(); + int sha1Size = sha1.GetDigestSize(); + + Span tmp = stackalloc byte[System.Math.Max(md5Size, sha1Size)]; + byte[] result = new byte[length]; + + int constLen = 1, constPos = 0, resultPos = 0; + while (resultPos < length) + { + sha1.BlockUpdate(Ssl3Const.AsSpan(constPos, constLen)); + constPos += constLen++; + + sha1.BlockUpdate(m_data); + sha1.BlockUpdate(seed); + sha1.DoFinal(tmp); + + md5.BlockUpdate(m_data); + md5.BlockUpdate(tmp[..sha1Size]); + + int remaining = length - resultPos; + if (remaining < md5Size) + { + md5.DoFinal(tmp); + tmp[..remaining].CopyTo(result.AsSpan(resultPos)); + resultPos += remaining; + } + else + { + md5.DoFinal(result.AsSpan(resultPos)); + resultPos += md5Size; + } + } + return result; } +#endif protected virtual byte[] Prf_1_0(byte[] labelSeed, int length) { int s_half = (m_data.Length + 1) / 2; - IDigest md5 = m_crypto.CreateDigest(CryptoHashAlgorithm.md5); byte[] b1 = new byte[length]; - HmacHash(md5, m_data, 0, s_half, labelSeed, b1); + HmacHash(CryptoHashAlgorithm.md5, m_data, 0, s_half, labelSeed, b1); - IDigest sha1 = m_crypto.CreateDigest(CryptoHashAlgorithm.sha1); byte[] b2 = new byte[length]; - HmacHash(sha1, m_data, m_data.Length - s_half, s_half, labelSeed, b2); + HmacHash(CryptoHashAlgorithm.sha1, m_data, m_data.Length - s_half, s_half, labelSeed, b2); for (int i = 0; i < length; i++) { @@ -250,9 +395,9 @@ protected virtual byte[] Prf_1_0(byte[] labelSeed, int length) protected virtual byte[] Prf_1_2(int prfAlgorithm, byte[] labelSeed, int length) { - IDigest digest = m_crypto.CreateDigest(TlsCryptoUtilities.GetHashForPrf(prfAlgorithm)); + int cryptoHashAlgorithm = TlsCryptoUtilities.GetHashForPrf(prfAlgorithm); byte[] result = new byte[length]; - HmacHash(digest, m_data, 0, m_data.Length, labelSeed, result); + HmacHash(cryptoHashAlgorithm, m_data, 0, m_data.Length, labelSeed, result); return result; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsSigner.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsSigner.cs index a112221..fdc4f25 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsSigner.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsSigner.cs @@ -25,7 +25,10 @@ protected BcTlsSigner(BcTlsCrypto crypto, AsymmetricKeyParameter privateKey) this.m_privateKey = privateKey; } - public abstract byte[] GenerateRawSignature(SignatureAndHashAlgorithm algorithm, byte[] hash); + public virtual byte[] GenerateRawSignature(SignatureAndHashAlgorithm algorithm, byte[] hash) + { + throw new NotSupportedException(); + } public virtual TlsStreamSigner GetStreamSigner(SignatureAndHashAlgorithm algorithm) { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsStreamSigner.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsStreamSigner.cs index a87484d..30c86b6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsStreamSigner.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsStreamSigner.cs @@ -18,9 +18,9 @@ internal BcTlsStreamSigner(ISigner signer) this.m_output = new SignerSink(signer); } - public Stream GetOutputStream() + public Stream Stream { - return m_output; + get { return m_output; } } public byte[] GetSignature() diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsStreamVerifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsStreamVerifier.cs index 5de6a11..96fc283 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsStreamVerifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsStreamVerifier.cs @@ -20,9 +20,9 @@ internal BcTlsStreamVerifier(ISigner verifier, byte[] signature) this.m_signature = signature; } - public Stream GetOutputStream() + public Stream Stream { - return m_output; + get { return m_output; } } public bool IsVerified() diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsVerifier.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsVerifier.cs index e221c92..50ac598 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsVerifier.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcTlsVerifier.cs @@ -25,12 +25,15 @@ protected BcTlsVerifier(BcTlsCrypto crypto, AsymmetricKeyParameter publicKey) this.m_publicKey = publicKey; } - public virtual TlsStreamVerifier GetStreamVerifier(DigitallySigned signature) + public virtual TlsStreamVerifier GetStreamVerifier(DigitallySigned digitallySigned) { return null; } - public abstract bool VerifyRawSignature(DigitallySigned signature, byte[] hash); + public virtual bool VerifyRawSignature(DigitallySigned digitallySigned, byte[] hash) + { + throw new NotSupportedException(); + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcVerifyingStreamSigner.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcVerifyingStreamSigner.cs index 62c73e6..92b1e59 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcVerifyingStreamSigner.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tls/crypto/impl/bc/BcVerifyingStreamSigner.cs @@ -26,9 +26,9 @@ internal BcVerifyingStreamSigner(ISigner signer, ISigner verifier) this.m_output = new TeeOutputStream(outputSigner, outputVerifier); } - public Stream GetOutputStream() + public Stream Stream { - return m_output; + get { return m_output; } } public byte[] GetSignature() diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TSPAlgorithms.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TSPAlgorithms.cs index f001c16..18564a5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TSPAlgorithms.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TSPAlgorithms.cs @@ -1,6 +1,6 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.GM; @@ -9,14 +9,14 @@ 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; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tsp { /** * Recognised hash algorithms for the time stamp protocol. */ - public abstract class TspAlgorithms + public static class TspAlgorithms { public static readonly string MD5 = PkcsObjectIdentifiers.MD5.Id; @@ -37,20 +37,15 @@ public abstract class TspAlgorithms public static readonly string SM3 = GMObjectIdentifiers.sm3.Id; - public static readonly IList Allowed; + public static readonly IList Allowed; static TspAlgorithms() { - string[] algs = new string[] + Allowed = CollectionUtilities.ReadOnly(new List() { - 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); - } + Gost3411, Gost3411_2012_256, Gost3411_2012_512, MD5, RipeMD128, RipeMD160, RipeMD256, Sha1, Sha224, + Sha256, Sha384, Sha512, SM3 + }); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TSPException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TSPException.cs index 3771dd5..f38bb33 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TSPException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TSPException.cs @@ -1,29 +1,31 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; 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() + : base() { } - public TspException( - string message) + public TspException(string message) : base(message) { } - public TspException( - string message, - Exception e) - : base(message, e) + public TspException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected TspException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TSPUtil.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TSPUtil.cs index 617cc41..5f201c5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TSPUtil.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TSPUtil.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; @@ -24,50 +24,47 @@ 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(); + private static readonly Dictionary DigestLengths = new Dictionary(); + private static readonly Dictionary DigestNames = new Dictionary(); 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"); + 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"); } @@ -80,10 +77,10 @@ static TspUtil() * @return a collection of TimeStampToken objects * @throws TSPValidationException */ - public static ICollection GetSignatureTimestamps( + public static IList GetSignatureTimestamps( SignerInformation signerInfo) { - IList timestamps = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var timestamps = new List(); Asn1.Cms.AttributeTable unsignedAttrs = signerInfo.UnsignedAttributes; if (unsignedAttrs != null) @@ -150,7 +147,7 @@ public static void ValidateCertificate( ExtendedKeyUsage extKey = ExtendedKeyUsage.GetInstance( Asn1Object.FromByteArray(ext.GetOctets())); - if (!extKey.HasKeyPurposeId(KeyPurposeID.IdKPTimeStamping) || extKey.Count != 1) + if (!extKey.HasKeyPurposeId(KeyPurposeID.id_kp_timeStamping) || extKey.Count != 1) throw new TspValidationException("ExtendedKeyUsage not solely time stamping."); } catch (IOException) @@ -163,54 +160,45 @@ public static void ValidateCertificate( /// 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) + internal static string GetDigestAlgName(string digestAlgOid) { - string digestName = (string) digestNames[digestAlgOID]; - - return digestName != null ? digestName : digestAlgOID; + return CollectionUtilities.GetValueOrKey(DigestNames, digestAlgOid); } - internal static int GetDigestLength( - string digestAlgOID) + internal static int GetDigestLength(string digestAlgOid) { - if (!digestLengths.Contains(digestAlgOID)) + if (!DigestLengths.TryGetValue(digestAlgOid, out int length)) throw new TspException("digest algorithm cannot be found."); - return (int)digestLengths[digestAlgOID]; + return length; } - internal static IDigest CreateDigestInstance( - String digestAlgOID) + internal static IDigest CreateDigestInstance(string digestAlgOID) { string digestName = GetDigestAlgName(digestAlgOID); return DigestUtilities.GetDigest(digestName); } - internal static ISet GetCriticalExtensionOids(X509Extensions extensions) + internal static ISet GetCriticalExtensionOids(X509Extensions extensions) { - if (extensions == null) - return EmptySet; - - return CollectionUtilities.ReadOnly(new HashSet(extensions.GetCriticalExtensionOids())); + return extensions == null + ? new HashSet() + : new HashSet(extensions.GetCriticalExtensionOids()); } - internal static ISet GetNonCriticalExtensionOids(X509Extensions extensions) + 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())); + return extensions == null + ? new HashSet() + : 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())); + internal static IList GetExtensionOids(X509Extensions extensions) + { + return extensions == null + ? new List() + : new List(extensions.GetExtensionOids()); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TSPValidationException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TSPValidationException.cs index cb6b7e6..245f2a5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TSPValidationException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TSPValidationException.cs @@ -1,6 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tsp { @@ -10,37 +11,39 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tsp * 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; + protected readonly int m_failureCode; - public TspValidationException( - string message) - : base(message) + public TspValidationException(string message) + : this(message, -1) { - this.failureCode = -1; } - public TspValidationException( - string message, - int failureCode) + public TspValidationException(string message, int failureCode) : base(message) { - this.failureCode = failureCode; + m_failureCode = failureCode; + } + + protected TspValidationException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + m_failureCode = info.GetInt32("failureCode"); + } + + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + info.AddValue("failureCode", m_failureCode); } - /** - * Return the failure code associated with this exception - if one is set. - * - * @return the failure code if set, -1 otherwise. - */ + /// The failure code associated with this exception, if one is set. public int FailureCode { - get { return failureCode; } + get { return m_failureCode; } } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampRequest.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampRequest.cs index e8c3736..2963674 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampRequest.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampRequest.cs @@ -1,16 +1,14 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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 @@ -126,10 +124,7 @@ public bool CertReq * @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) + public void Validate(IList algorithms, IList policies, IList extensions) { if (!algorithms.Contains(this.MessageImprintAlgOid)) throw new TspValidationException("request contains unknown algorithm", PkiFailureInfo.BadAlg); @@ -175,7 +170,7 @@ public virtual X509Extension GetExtension(DerObjectIdentifier oid) return extensions == null ? null : extensions.GetExtension(oid); } - public virtual IList GetExtensionOids() + public virtual IList GetExtensionOids() { return TspUtil.GetExtensionOids(extensions); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampRequestGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampRequestGenerator.cs index 1487596..e439ffa 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampRequestGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampRequestGenerator.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Tsp; @@ -21,17 +21,16 @@ public class TimeStampRequestGenerator private DerBoolean certReq; - private IDictionary extensions = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - private IList extOrdering = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + private Dictionary m_extensions = + new Dictionary(); + private List m_ordering = new List(); - public void SetReqPolicy( - string reqPolicy) + public void SetReqPolicy(string reqPolicy) { this.reqPolicy = new DerObjectIdentifier(reqPolicy); } - public void SetCertReq( - bool certReq) + public void SetCertReq(bool certReq) { this.certReq = DerBoolean.GetInstance(certReq); } @@ -40,39 +39,7 @@ public void SetCertReq( * add a given extension field for the standard extensions tag (tag 3) * @throws IOException */ - - 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. - */ - - 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) + public virtual void AddExtension(DerObjectIdentifier oid, bool critical, Asn1Encodable extValue) { this.AddExtension(oid, critical, extValue.GetEncoded()); } @@ -82,47 +49,35 @@ public virtual void AddExtension( * The value parameter becomes the contents of the octet string associated * with the extension. */ - public virtual void AddExtension( - DerObjectIdentifier oid, - bool critical, - byte[] extValue) + public virtual void AddExtension(DerObjectIdentifier oid, bool critical, byte[] extValue) { - extensions.Add(oid, new X509Extension(critical, new DerOctetString(extValue))); - extOrdering.Add(oid); + m_extensions.Add(oid, new X509Extension(critical, new DerOctetString(extValue))); + m_ordering.Add(oid); } - public TimeStampRequest Generate( - string digestAlgorithm, - byte[] digest) + public TimeStampRequest Generate(string digestAlgorithm, byte[] digest) { - return this.Generate(digestAlgorithm, digest, null); + return Generate(digestAlgorithm, digest, null); } - public TimeStampRequest Generate( - string digestAlgorithmOid, - byte[] digest, - BigInteger nonce) + 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; + X509Extensions ext = null; - if (extOrdering.Count != 0) + if (m_ordering.Count > 0) { - ext = new X509Extensions(extOrdering, extensions); + ext = new X509Extensions(m_ordering, m_extensions); } - DerInteger derNonce = nonce == null - ? null - : new DerInteger(nonce); + DerInteger derNonce = nonce == null ? null : new DerInteger(nonce); return new TimeStampRequest( new TimeStampReq(messageImprint, reqPolicy, derNonce, certReq, ext)); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampResponseGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampResponseGenerator.cs index 78527db..7c243eb 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampResponseGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampResponseGenerator.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; @@ -10,7 +10,6 @@ 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.Date; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tsp { @@ -25,30 +24,30 @@ public class TimeStampResponseGenerator private int failInfo; private TimeStampTokenGenerator tokenGenerator; - private IList acceptedAlgorithms; - private IList acceptedPolicies; - private IList acceptedExtensions; + private IList acceptedAlgorithms; + private IList acceptedPolicies; + private IList acceptedExtensions; public TimeStampResponseGenerator( TimeStampTokenGenerator tokenGenerator, - IList acceptedAlgorithms) + IList acceptedAlgorithms) : this(tokenGenerator, acceptedAlgorithms, null, null) { } public TimeStampResponseGenerator( TimeStampTokenGenerator tokenGenerator, - IList acceptedAlgorithms, - IList acceptedPolicy) + IList acceptedAlgorithms, + IList acceptedPolicy) : this(tokenGenerator, acceptedAlgorithms, acceptedPolicy, null) { } public TimeStampResponseGenerator( TimeStampTokenGenerator tokenGenerator, - IList acceptedAlgorithms, - IList acceptedPolicies, - IList acceptedExtensions) + IList acceptedAlgorithms, + IList acceptedPolicies, + IList acceptedExtensions) { this.tokenGenerator = tokenGenerator; this.acceptedAlgorithms = acceptedAlgorithms; @@ -86,14 +85,6 @@ private PkiStatusInfo GetPkiStatusInfo() 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. *

@@ -109,10 +100,7 @@ public TimeStampResponse Generate( * @throws TSPException *

*/ - public TimeStampResponse Generate( - TimeStampRequest request, - BigInteger serialNumber, - DateTimeObject genTime) + public TimeStampResponse Generate(TimeStampRequest request, BigInteger serialNumber, DateTime? genTime) { TimeStampResp resp; @@ -166,13 +154,8 @@ public TimeStampResponse Generate( } } - - public TimeStampResponse GenerateGrantedResponse( - TimeStampRequest request, - BigInteger serialNumber, - DateTimeObject genTime, - String statusString, - X509Extensions additionalExtensions) + public TimeStampResponse GenerateGrantedResponse(TimeStampRequest request, BigInteger serialNumber, + DateTime? genTime, string statusString, X509Extensions additionalExtensions) { TimeStampResp resp; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampToken.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampToken.cs index 224f060..f420f14 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampToken.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampToken.cs @@ -1,7 +1,6 @@ #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; @@ -15,8 +14,8 @@ 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.X509; -using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tsp { @@ -44,7 +43,7 @@ public TimeStampToken( throw new TspValidationException("ContentInfo object not for a time stamp."); } - ICollection signers = tsToken.GetSignerInfos().GetSigners(); + var signers = tsToken.GetSignerInfos().GetSigners(); if (signers.Count != 1) { @@ -54,10 +53,10 @@ public TimeStampToken( } - IEnumerator signerEnum = signers.GetEnumerator(); + var signerEnum = signers.GetEnumerator(); signerEnum.MoveNext(); - tsaSignerInfo = (SignerInformation) signerEnum.Current; + tsaSignerInfo = signerEnum.Current; try { @@ -136,28 +135,11 @@ public Asn1.Cms.AttributeTable UnsignedAttributes get { return tsaSignerInfo.UnsignedAttributes; } } - public IX509Store GetCertificates( - string type) - { - return tsToken.GetCertificates(type); - } + public IStore GetAttributeCertificates() => tsToken.GetAttributeCertificates(); - public IX509Store GetCrls( - string type) - { - return tsToken.GetCrls(type); - } - - public IX509Store GetCertificates() - { - return tsToken.GetCertificates(); - } + public IStore GetCertificates() => tsToken.GetCertificates(); - public IX509Store GetAttributeCertificates( - string type) - { - return tsToken.GetAttributeCertificates(type); - } + public IStore GetCrls() => tsToken.GetCrls(); /** * Validate the time stamp token. diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampTokenGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampTokenGenerator.cs index 719e2ea..a0d7bdb 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampTokenGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampTokenGenerator.cs @@ -1,12 +1,12 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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.Cms; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Ess; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Oiw; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.Pkcs; @@ -17,8 +17,9 @@ using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Operators; 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; -using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tsp { @@ -36,8 +37,11 @@ public class TimeStampTokenGenerator private GeneralName tsa = null; private DerObjectIdentifier tsaPolicyOID; - private IX509Store x509Certs; - private IX509Store x509Crls; + private IStore x509Certs; + private IStore x509Crls; + private IStore x509AttrCerts; + // TODO Port changes from bc-java + //private Dictionary<> otherRevoc = new Dictionary<>(); private SignerInfoGenerator signerInfoGenerator; IDigestFactory digestCalculator; @@ -61,39 +65,37 @@ public TimeStampTokenGenerator( { } - public TimeStampTokenGenerator( SignerInfoGenerator signerInfoGen, IDigestFactory digestCalculator, DerObjectIdentifier tsaPolicy, bool isIssuerSerialIncluded) { - this.signerInfoGenerator = signerInfoGen; this.digestCalculator = digestCalculator; this.tsaPolicyOID = tsaPolicy; if (signerInfoGenerator.certificate == null) - { throw new ArgumentException("SignerInfoGenerator must have an associated certificate"); - } X509Certificate assocCert = signerInfoGenerator.certificate; TspUtil.ValidateCertificate(assocCert); try { - IStreamCalculator calculator = digestCalculator.CreateCalculator(); - Stream stream = calculator.Stream; byte[] certEnc = assocCert.GetEncoded(); - stream.Write(certEnc, 0, certEnc.Length); - stream.Flush(); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(stream); + + IStreamCalculator calculator = digestCalculator.CreateCalculator(); + + using (var stream = calculator.Stream) + { + stream.Write(certEnc, 0, certEnc.Length); + } if (((AlgorithmIdentifier)digestCalculator.AlgorithmDetails).Algorithm.Equals(OiwObjectIdentifiers.IdSha1)) { EssCertID essCertID = new EssCertID( - ((IBlockResult)calculator.GetResult()).Collect(), + calculator.GetResult().Collect(), isIssuerSerialIncluded ? new IssuerSerial( new GeneralNames( @@ -110,7 +112,7 @@ public TimeStampTokenGenerator( ((AlgorithmIdentifier)digestCalculator.AlgorithmDetails).Algorithm); EssCertIDv2 essCertID = new EssCertIDv2( - ((IBlockResult)calculator.GetResult()).Collect(), + calculator.GetResult().Collect(), isIssuerSerialIncluded ? new IssuerSerial( new GeneralNames( @@ -121,7 +123,6 @@ public TimeStampTokenGenerator( .WithSignedAttributeGenerator(new TableGen2(signerInfoGen, essCertID)) .Build(signerInfoGen.contentSigner, signerInfoGen.certificate); } - } catch (Exception ex) { @@ -145,30 +146,26 @@ public TimeStampTokenGenerator( { } - internal static SignerInfoGenerator makeInfoGenerator( AsymmetricKeyParameter key, X509Certificate cert, string digestOID, - Asn1.Cms.AttributeTable signedAttr, Asn1.Cms.AttributeTable unsignedAttr) { - - TspUtil.ValidateCertificate(cert); // // Add the ESSCertID attribute // - IDictionary signedAttrs; + IDictionary signedAttrs; if (signedAttr != null) { signedAttrs = signedAttr.ToDictionary(); } else { - signedAttrs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); + signedAttrs = new Dictionary(); } //try @@ -192,7 +189,6 @@ internal static SignerInfoGenerator makeInfoGenerator( // throw new TspException("Can't find a SHA-1 implementation.", e); //} - string digestName = CmsSignedHelper.Instance.GetDigestAlgName(digestOID); string signatureName = digestName + "with" + CmsSignedHelper.Instance.GetEncryptionAlgName(CmsSignedHelper.Instance.GetEncOid(key, digestOID)); @@ -206,15 +202,17 @@ internal static SignerInfoGenerator makeInfoGenerator( .Build(sigfact, cert); } + public void SetAttributeCertificates(IStore attributeCertificates) + { + this.x509AttrCerts = attributeCertificates; + } - public void SetCertificates( - IX509Store certificates) + public void SetCertificates(IStore certificates) { this.x509Certs = certificates; } - public void SetCrls( - IX509Store crls) + public void SetCrls(IStore crls) { this.x509Crls = crls; } @@ -341,21 +339,10 @@ public TimeStampToken Generate( respExtensions = extGen.Generate(); } - - - DerGeneralizedTime generalizedTime; - if (resolution != Resolution.R_SECONDS) - { - generalizedTime = new DerGeneralizedTime(createGeneralizedTime(genTime)); - } - else - { - generalizedTime = new DerGeneralizedTime(genTime); - } - + var timeStampTime = new Asn1GeneralizedTime(WithResolution(genTime, resolution)); TstInfo tstInfo = new TstInfo(tsaPolicy, messageImprint, - new DerInteger(serialNumber), generalizedTime, accuracy, + new DerInteger(serialNumber), timeStampTime, accuracy, derOrdering, nonce, tsa, respExtensions); try @@ -367,6 +354,7 @@ public TimeStampToken Generate( if (request.CertReq) { signedDataGenerator.AddCertificates(x509Certs); + signedDataGenerator.AddAttributeCertificates(x509AttrCerts); } signedDataGenerator.AddCrls(x509Crls); @@ -388,68 +376,31 @@ public TimeStampToken Generate( { 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); - // } + //catch (InvalidAlgorithmParameterException e) + //{ + // throw new TspException("Exception handling CertStore CRLs", e); + //} } - private string createGeneralizedTime(DateTime genTime) + private static DateTime WithResolution(DateTime dateTime, Resolution resolution) { - String format = "yyyyMMddHHmmss.fff"; - - StringBuilder sBuild = new StringBuilder(genTime.ToString(format)); - int dotIndex = sBuild.ToString().IndexOf("."); - - if (dotIndex <0) - { - sBuild.Append("Z"); - return sBuild.ToString(); - } - - switch(resolution) - { - case Resolution.R_TENTHS_OF_SECONDS: - if (sBuild.Length > dotIndex + 2) - { - sBuild.Remove(dotIndex + 2, sBuild.Length-(dotIndex+2)); - } - break; - case Resolution.R_HUNDREDTHS_OF_SECONDS: - if (sBuild.Length > dotIndex + 3) - { - sBuild.Remove(dotIndex + 3, sBuild.Length-(dotIndex+3)); - } - break; - - - case Resolution.R_SECONDS: - case Resolution.R_MILLISECONDS: - // do nothing. - break; - - } - - - while (sBuild[sBuild.Length - 1] == '0') + switch (resolution) { - sBuild.Remove(sBuild.Length - 1,1); + case Resolution.R_SECONDS: + return DateTimeUtilities.WithPrecisionSecond(dateTime); + case Resolution.R_TENTHS_OF_SECONDS: + return DateTimeUtilities.WithPrecisionDecisecond(dateTime); + case Resolution.R_HUNDREDTHS_OF_SECONDS: + return DateTimeUtilities.WithPrecisionCentisecond(dateTime); + case Resolution.R_MILLISECONDS: + return DateTimeUtilities.WithPrecisionMillisecond(dateTime); + default: + throw new InvalidOperationException(); } - - if (sBuild.Length - 1 == dotIndex) - { - sBuild.Remove(sBuild.Length - 1, 1); - } - - sBuild.Append("Z"); - return sBuild.ToString(); } - private class TableGen : CmsAttributeTableGenerator + private class TableGen + : CmsAttributeTableGenerator { private readonly SignerInfoGenerator infoGen; private readonly EssCertID essCertID; @@ -461,7 +412,7 @@ public TableGen(SignerInfoGenerator infoGen, EssCertID essCertID) this.essCertID = essCertID; } - public Asn1.Cms.AttributeTable GetAttributes(IDictionary parameters) + public Asn1.Cms.AttributeTable GetAttributes(IDictionary parameters) { Asn1.Cms.AttributeTable tab = infoGen.signedGen.GetAttributes(parameters); if (tab[PkcsObjectIdentifiers.IdAASigningCertificate] == null) @@ -472,7 +423,8 @@ public Asn1.Cms.AttributeTable GetAttributes(IDictionary parameters) } } - private class TableGen2 : CmsAttributeTableGenerator + private class TableGen2 + : CmsAttributeTableGenerator { private readonly SignerInfoGenerator infoGen; private readonly EssCertIDv2 essCertID; @@ -484,7 +436,7 @@ public TableGen2(SignerInfoGenerator infoGen, EssCertIDv2 essCertID) this.essCertID = essCertID; } - public Asn1.Cms.AttributeTable GetAttributes(IDictionary parameters) + public Asn1.Cms.AttributeTable GetAttributes(IDictionary parameters) { Asn1.Cms.AttributeTable tab = infoGen.signedGen.GetAttributes(parameters); if (tab[PkcsObjectIdentifiers.IdAASigningCertificateV2] == null) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampTokenInfo.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampTokenInfo.cs index 16d26df..aa4cb5d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampTokenInfo.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/tsp/TimeStampTokenInfo.cs @@ -10,10 +10,27 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Tsp { public class TimeStampTokenInfo { - private TstInfo tstInfo; + private static TstInfo ParseTstInfo(byte[] tstInfoEncoding) + { + try + { + return TstInfo.GetInstance(tstInfoEncoding); + } + catch (Exception e) + { + throw new TspException("unable to parse TstInfo encoding: " + e.Message); + } + } + + private TstInfo tstInfo; private DateTime genTime; - public TimeStampTokenInfo( + public TimeStampTokenInfo(byte[] tstInfoEncoding) + : this(ParseTstInfo(tstInfoEncoding)) + { + } + + public TimeStampTokenInfo( TstInfo tstInfo) { this.tstInfo = tstInfo; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Arrays.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Arrays.cs index e997079..da371d2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Arrays.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Arrays.cs @@ -3,17 +3,12 @@ using System; using System.Text; -using BestHTTP.PlatformSupport.Memory; using BestHTTP.SecureProtocol.Org.BouncyCastle.Math; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities { /// General array utilities. - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.NullChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.ArrayBoundsChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppSetOption(BestHTTP.PlatformSupport.IL2CPP.Option.DivideByZeroChecks, false)] - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] - public abstract class Arrays + public static class Arrays { public static readonly byte[] EmptyBytes = new byte[0]; public static readonly int[] EmptyInts = new int[0]; @@ -28,6 +23,18 @@ public static bool AreAllZeroes(byte[] buf, int off, int len) return bits == 0; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static bool AreAllZeroes(ReadOnlySpan buf) + { + uint bits = 0; + for (int i = 0; i < buf.Length; ++i) + { + bits |= buf[i]; + } + return bits == 0; + } +#endif + public static bool AreEqual( bool[] a, bool[] b) @@ -88,14 +95,6 @@ public static bool AreEqual(byte[] a, int aFromIndex, int aToIndex, byte[] b, in return true; } - - 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. @@ -123,26 +122,6 @@ public static bool ConstantTimeAreEqual(byte[] a, byte[] b) return 0 == nonEqual; } - public static bool ConstantTimeAreEqual(BufferSegment a, BufferSegment b) - { - if (null == a || null == b) - return false; - if (a == b) - return true; - - int len = System.Math.Min(a.Count, b.Count); - int nonEqual = a.Count ^ b.Count; - for (int i = 0; i < len; ++i) - { - nonEqual |= (a.Data[a.Offset + i] ^ b.Data[b.Offset + i]); - } - for (int i = len; i < b.Count; ++i) - { - nonEqual |= (b.Data[b.Offset + i] ^ ~b.Data[b.Offset + i]); - } - return 0 == nonEqual; - } - public static bool ConstantTimeAreEqual(int len, byte[] a, int aOff, byte[] b, int bOff) { if (null == a) @@ -159,11 +138,27 @@ public static bool ConstantTimeAreEqual(int len, byte[] a, int aOff, byte[] b, i int d = 0; for (int i = 0; i < len; ++i) { - d |= (a[aOff + i] ^ b[bOff + i]); + d |= a[aOff + i] ^ b[bOff + i]; } return 0 == d; } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static bool ConstantTimeAreEqual(Span a, Span b) + { + if (a.Length != b.Length) + throw new ArgumentException("Spans to compare must have equal length"); + + int d = 0; + for (int i = 0, count = a.Length; i < count; ++i) + { + d |= a[i] ^ b[i]; + } + return 0 == d; + + } +#endif + public static bool AreEqual( int[] a, int[] b) @@ -177,6 +172,7 @@ public static bool AreEqual( return HaveSameContents(a, b); } + [CLSCompliant(false)] public static bool AreEqual(uint[] a, uint[] b) { if (a == b) @@ -199,6 +195,7 @@ public static bool AreEqual(long[] a, long[] b) return HaveSameContents(a, b); } + [CLSCompliant(false)] public static bool AreEqual(ulong[] a, ulong[] b) { if (a == b) @@ -387,6 +384,7 @@ public static int GetHashCode(int[] data) return hc; } + [CLSCompliant(false)] public static int GetHashCode(ushort[] data) { if (data == null) @@ -421,6 +419,7 @@ public static int GetHashCode(int[] data, int off, int len) return hc; } + [CLSCompliant(false)] public static int GetHashCode(uint[] data) { if (data == null) @@ -438,6 +437,7 @@ public static int GetHashCode(uint[] data) return hc; } + [CLSCompliant(false)] public static int GetHashCode(uint[] data, int off, int len) { if (data == null) @@ -455,6 +455,7 @@ public static int GetHashCode(uint[] data, int off, int len) return hc; } + [CLSCompliant(false)] public static int GetHashCode(ulong[] data) { if (data == null) @@ -475,6 +476,7 @@ public static int GetHashCode(ulong[] data) return hc; } + [CLSCompliant(false)] public static int GetHashCode(ulong[] data, int off, int len) { if (data == null) @@ -510,6 +512,7 @@ public static short[] Clone(short[] data) return data == null ? null : (short[])data.Clone(); } + [CLSCompliant(false)] public static ushort[] Clone(ushort[] data) { return data == null ? null : (ushort[])data.Clone(); @@ -520,6 +523,7 @@ public static int[] Clone(int[] data) return data == null ? null : (int[])data.Clone(); } + [CLSCompliant(false)] public static uint[] Clone(uint[] data) { return data == null ? null : (uint[])data.Clone(); @@ -530,6 +534,7 @@ public static long[] Clone(long[] data) return data == null ? null : (long[])data.Clone(); } + [CLSCompliant(false)] public static ulong[] Clone(ulong[] data) { return data == null ? null : (ulong[])data.Clone(); @@ -545,6 +550,7 @@ public static byte[] Clone(byte[] data, byte[] existing) return existing; } + [CLSCompliant(false)] public static ulong[] Clone(ulong[] data, ulong[] existing) { if (data == null) @@ -596,6 +602,18 @@ public static void Fill( } } + [CLSCompliant(false)] + public static void Fill( + ulong[] buf, + ulong 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) @@ -604,6 +622,21 @@ public static void Fill(byte[] buf, int from, int to, byte b) } } + public static void Fill(T[] ts, T t) + { + for (int i = 0; i < ts.Length; ++i) + { + ts[i] = t; + } + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void Fill(Span ts, T t) + { + ts.Fill(t); + } +#endif + public static byte[] CopyOf(byte[] data, int newLength) { byte[] tmp = new byte[newLength]; @@ -625,6 +658,14 @@ public static int[] CopyOf(int[] data, int newLength) return tmp; } + [CLSCompliant(false)] + public static uint[] CopyOf(uint[] data, int newLength) + { + uint[] tmp = new uint[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]; @@ -739,6 +780,7 @@ public static byte[] Concatenate(byte[] a, byte[] b) return rv; } + [CLSCompliant(false)] public static ushort[] Concatenate(ushort[] a, ushort[] b) { if (a == null) @@ -794,6 +836,20 @@ public static int[] Concatenate(int[] a, int[] b) return rv; } + [CLSCompliant(false)] + public static uint[] Concatenate(uint[] a, uint[] b) + { + if (a == null) + return Clone(b); + if (b == null) + return Clone(a); + + uint[] rv = new uint[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) @@ -830,6 +886,17 @@ public static int[] Prepend(int[] a, int b) return result; } + public static T[] Prepend(T[] a, T b) + { + if (a == null) + return new T[1]{ b }; + + T[] result = new T[1 + a.Length]; + result[0] = b; + a.CopyTo(result, 1); + return result; + } + public static byte[] Reverse(byte[] a) { if (a == null) @@ -862,36 +929,13 @@ public static int[] Reverse(int[] a) return result; } - public static byte[] ReverseInPlace(byte[] a) - { - if (null == a) - return null; - - int p1 = 0, p2 = a.Length - 1; - while (p1 < p2) - { - byte t1 = a[p1], t2 = a[p2]; - a[p1++] = t2; - a[p2--] = t1; - } - - return a; - } - - public static int[] ReverseInPlace(int[] a) + public static T[] ReverseInPlace(T[] array) { - if (null == a) + if (null == array) return null; - int p1 = 0, p2 = a.Length - 1; - while (p1 < p2) - { - int t1 = a[p1], t2 = a[p2]; - a[p1++] = t2; - a[p2--] = t1; - } - - return a; + Array.Reverse(array); + return array; } public static void Clear(byte[] data) @@ -933,6 +977,38 @@ public static bool IsNullOrEmpty(object[] array) { return null == array || array.Length < 1; } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + + public static byte[] Concatenate(ReadOnlySpan a, ReadOnlySpan b) + { + byte[] rv = new byte[a.Length + b.Length]; + a.CopyTo(rv); + b.CopyTo(rv.AsSpan(a.Length)); + return rv; + } + + public static byte[] Concatenate(ReadOnlySpan a, ReadOnlySpan b, ReadOnlySpan c) + { + byte[] rv = new byte[a.Length + b.Length + c.Length]; + a.CopyTo(rv); + b.CopyTo(rv.AsSpan(a.Length)); + c.CopyTo(rv.AsSpan(a.Length + b.Length)); + return rv; + } + + public static byte[] Concatenate(ReadOnlySpan a, ReadOnlySpan b, ReadOnlySpan c, + ReadOnlySpan d) + { + byte[] rv = new byte[a.Length + b.Length + c.Length + d.Length]; + a.CopyTo(rv); + b.CopyTo(rv.AsSpan(a.Length)); + c.CopyTo(rv.AsSpan(a.Length + b.Length)); + d.CopyTo(rv.AsSpan(a.Length + b.Length + c.Length)); + return rv; + } + +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/BigIntegers.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/BigIntegers.cs index 7ded8b8..df260cd 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/BigIntegers.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/BigIntegers.cs @@ -11,7 +11,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities /** * BigInteger utilities. */ - public abstract class BigIntegers + public static class BigIntegers { public static readonly BigInteger Zero = BigInteger.Zero; public static readonly BigInteger One = BigInteger.One; @@ -24,8 +24,7 @@ public abstract class BigIntegers * @param value the 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) + public static byte[] AsUnsignedByteArray(BigInteger n) { return n.ToByteArrayUnsigned(); } @@ -39,24 +38,36 @@ public static byte[] AsUnsignedByteArray( */ public static byte[] AsUnsignedByteArray(int length, BigInteger n) { - byte[] bytes = n.ToByteArrayUnsigned(); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int bytesLength = n.GetLengthofByteArrayUnsigned(); + + if (bytesLength > length) + throw new ArgumentException("standard length exceeded", nameof(n)); - if (bytes.Length > length) - throw new ArgumentException("standard length exceeded", "n"); + byte[] bytes = new byte[length]; + n.ToByteArrayUnsigned(bytes.AsSpan(length - bytesLength)); + return bytes; +#else + byte[] bytes = n.ToByteArrayUnsigned(); + int bytesLength = bytes.Length; - if (bytes.Length == length) + if (bytesLength == length) return bytes; + if (bytesLength > length) + throw new ArgumentException("standard length exceeded", nameof(n)); + byte[] tmp = new byte[length]; - Array.Copy(bytes, 0, tmp, tmp.Length - bytes.Length, bytes.Length); + Array.Copy(bytes, 0, tmp, length - bytesLength, bytesLength); return tmp; +#endif } /** * Write the passed in value as unsigned bytes to the specified buffer range, padded with * leading zeros as necessary. * - * @param value + * @param n * the value to be converted. * @param buf * the buffer to which the value is written. @@ -65,25 +76,35 @@ public static byte[] AsUnsignedByteArray(int length, BigInteger n) * @param len * the fixed length of data written (possibly padded with leading zeros). */ - public static void AsUnsignedByteArray(BigInteger value, byte[] buf, int off, int len) + public static void AsUnsignedByteArray(BigInteger n, byte[] buf, int off, int len) { - byte[] bytes = value.ToByteArrayUnsigned(); - if (bytes.Length == len) - { - Array.Copy(bytes, 0, buf, off, len); - return; - } - - int start = bytes[0] == 0 ? 1 : 0; - int count = bytes.Length - start; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + AsUnsignedByteArray(n, buf.AsSpan(off, len)); +#else + byte[] bytes = n.ToByteArrayUnsigned(); + int bytesLength = bytes.Length; - if (count > len) - throw new ArgumentException("standard length exceeded for value"); + if (bytesLength > len) + throw new ArgumentException("standard length exceeded", nameof(n)); - int padLen = len - count; + int padLen = len - bytesLength; Arrays.Fill(buf, off, off + padLen, 0); - Array.Copy(bytes, start, buf, off + padLen, count); + Array.Copy(bytes, 0, buf, off + padLen, bytesLength); +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static void AsUnsignedByteArray(BigInteger n, Span buf) + { + int bytesLength = n.GetLengthofByteArrayUnsigned(); + + if (bytesLength > buf.Length) + throw new ArgumentException("standard length exceeded", nameof(n)); + + buf[..^bytesLength].Fill(0x00); + n.ToByteArrayUnsigned(buf[^bytesLength..]); } +#endif /// /// Creates a Random BigInteger from the secure random of a given bit length. @@ -149,13 +170,31 @@ public static BigInteger ModOddInverse(BigInteger M, BigInteger X) } int bits = M.BitLength; - uint[] m = Nat.FromBigInteger(bits, M); - uint[] x = Nat.FromBigInteger(bits, X); - int len = m.Length; - uint[] z = Nat.Create(len); - if (0 == Mod.ModOddInverse(m, x, z)) - throw new ArithmeticException("BigInteger not invertible"); - return Nat.ToBigInteger(len, z); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + if (bits <= 2048) + { + int len = Nat.GetLengthForBits(bits); + Span m = stackalloc uint[len]; + Span x = stackalloc uint[len]; + Span z = stackalloc uint[len]; + Nat.FromBigInteger(bits, M, m); + Nat.FromBigInteger(bits, X, x); + if (0 == Mod.ModOddInverse(m, x, z)) + throw new ArithmeticException("BigInteger not invertible"); + return Nat.ToBigInteger(len, z); + } + else +#endif + { + uint[] m = Nat.FromBigInteger(bits, M); + uint[] x = Nat.FromBigInteger(bits, X); + int len = m.Length; + uint[] z = Nat.Create(len); + if (0 == Mod.ModOddInverse(m, x, z)) + throw new ArithmeticException("BigInteger not invertible"); + return Nat.ToBigInteger(len, z); + } } public static BigInteger ModOddInverseVar(BigInteger M, BigInteger X) @@ -174,18 +213,41 @@ public static BigInteger ModOddInverseVar(BigInteger M, BigInteger X) return One; int bits = M.BitLength; - uint[] m = Nat.FromBigInteger(bits, M); - uint[] x = Nat.FromBigInteger(bits, X); - int len = m.Length; - uint[] z = Nat.Create(len); - if (!Mod.ModOddInverseVar(m, x, z)) - throw new ArithmeticException("BigInteger not invertible"); - return Nat.ToBigInteger(len, z); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + if (bits <= 2048) + { + int len = Nat.GetLengthForBits(bits); + Span m = stackalloc uint[len]; + Span x = stackalloc uint[len]; + Span z = stackalloc uint[len]; + Nat.FromBigInteger(bits, M, m); + Nat.FromBigInteger(bits, X, x); + if (!Mod.ModOddInverseVar(m, x, z)) + throw new ArithmeticException("BigInteger not invertible"); + return Nat.ToBigInteger(len, z); + } + else +#endif + { + uint[] m = Nat.FromBigInteger(bits, M); + uint[] x = Nat.FromBigInteger(bits, X); + int len = m.Length; + uint[] z = Nat.Create(len); + if (!Mod.ModOddInverseVar(m, x, z)) + throw new ArithmeticException("BigInteger not invertible"); + return Nat.ToBigInteger(len, z); + } + } + + public static int GetByteLength(BigInteger n) + { + return n.GetLengthofByteArray(); } public static int GetUnsignedByteLength(BigInteger n) { - return (n.BitLength + 7) / 8; + return n.GetLengthofByteArrayUnsigned(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Bytes.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Bytes.cs index ada843c..2515884 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Bytes.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Bytes.cs @@ -4,7 +4,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities { - public abstract class Bytes + public static class Bytes { public const int NumBits = 8; public const int NumBytes = 1; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Enums.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Enums.cs index e48c588..96d4188 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Enums.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Enums.cs @@ -1,80 +1,48 @@ #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 class Enums { - internal static Enum GetEnumValue(System.Type enumType, string s) + internal static TEnum GetEnumValue(string s) + where TEnum : struct, Enum { - 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); - } +#if NETCOREAPP2_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER + return Enum.Parse(s, false); #else - return (Enum)Enum.Parse(enumType, s, false); -#endif + return (TEnum)Enum.Parse(typeof(TEnum), s, false); +#endif } throw new ArgumentException(); } - internal static Array GetEnumValues(System.Type enumType) + internal static TEnum[] GetEnumValues() + where TEnum : struct, Enum { - 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; +#if NET5_0_OR_GREATER + return Enum.GetValues(); #else - return Enum.GetValues(enumType); + return (TEnum[])Enum.GetValues(typeof(TEnum)); #endif } - internal static Enum GetArbitraryValue(System.Type enumType) + internal static TEnum GetArbitraryValue() + where TEnum : struct, Enum { - Array values = GetEnumValues(enumType); + TEnum[] values = GetEnumValues(); 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 + return values[pos]; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/IEncodable.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/IEncodable.cs new file mode 100644 index 0000000..625f697 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/IEncodable.cs @@ -0,0 +1,16 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System.IO; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities +{ + public interface IEncodable + { + /// Return a byte array representing the implementing object. + /// An encoding of this object as a byte array. + /// + byte[] GetEncoded(); + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/IEncodable.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/IEncodable.cs.meta new file mode 100644 index 0000000..db4d0d7 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/IEncodable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 361d48ffae4de8140b1af6bbeb70bb80 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Integers.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Integers.cs index 1668dba..79ee53c 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Integers.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Integers.cs @@ -1,12 +1,19 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ +using System.Buffers.Binary; +#endif +#if NETCOREAPP3_0_OR_GREATER +using System.Numerics; +using System.Runtime.Intrinsics.X86; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities { - public abstract class Integers + public static class Integers { public const int NumBits = 32; public const int NumBytes = 4; @@ -15,8 +22,42 @@ public abstract class Integers 0x1F, 0x00, 0x1B, 0x01, 0x1C, 0x0D, 0x17, 0x02, 0x1D, 0x15, 0x13, 0x0E, 0x18, 0x10, 0x03, 0x07, 0x1E, 0x1A, 0x0C, 0x16, 0x14, 0x12, 0x0F, 0x06, 0x19, 0x0B, 0x11, 0x05, 0x0A, 0x04, 0x09, 0x08 }; + public static int HighestOneBit(int i) + { + return (int)HighestOneBit((uint)i); + } + + [CLSCompliant(false)] + public static uint HighestOneBit(uint i) + { + i |= i >> 1; + i |= i >> 2; + i |= i >> 4; + i |= i >> 8; + i |= i >> 16; + return i - (i >> 1); + } + + public static int LowestOneBit(int i) + { + return i & -i; + } + + [CLSCompliant(false)] + public static uint LowestOneBit(uint i) + { + return (uint)LowestOneBit((int)i); + } + public static int NumberOfLeadingZeros(int i) { +#if NETCOREAPP3_0_OR_GREATER + if (Lzcnt.IsSupported) + { + return (int)Lzcnt.LeadingZeroCount((uint)i); + } +#endif + if (i <= 0) return (~i >> (31 - 5)) & (1 << 5); @@ -32,6 +73,13 @@ public static int NumberOfLeadingZeros(int i) public static int NumberOfTrailingZeros(int i) { +#if NETCOREAPP3_0_OR_GREATER + if (Bmi1.IsSupported) + { + return (int)Bmi1.TrailingZeroCount((uint)i); + } +#endif + int n = DeBruijnTZ[(uint)((i & -i) * 0x0EF96A62) >> 27]; int m = (((i & 0xFFFF) | (int)((uint)i >> 16)) - 1) >> 31; return n - m; @@ -42,6 +90,7 @@ public static int Reverse(int i) return (int)Reverse((uint)i); } + [CLSCompliant(false)] public static uint Reverse(uint i) { i = Bits.BitPermuteStepSimple(i, 0x55555555U, 1); @@ -52,33 +101,60 @@ public static uint Reverse(uint i) public static int ReverseBytes(int i) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return BinaryPrimitives.ReverseEndianness(i); +#else return (int)ReverseBytes((uint)i); +#endif } + [CLSCompliant(false)] public static uint ReverseBytes(uint i) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return BinaryPrimitives.ReverseEndianness(i); +#else return RotateLeft(i & 0xFF00FF00U, 8) | RotateLeft(i & 0x00FF00FFU, 24); +#endif } public static int RotateLeft(int i, int distance) { - return (i << distance) ^ (int)((uint)i >> -distance); +#if NETCOREAPP3_0_OR_GREATER + return (int)BitOperations.RotateLeft((uint)i, distance); +#else + return (i << distance) | (int)((uint)i >> -distance); +#endif } + [CLSCompliant(false)] public static uint RotateLeft(uint i, int distance) { - return (i << distance) ^ (i >> -distance); +#if NETCOREAPP3_0_OR_GREATER + return BitOperations.RotateLeft(i, distance); +#else + return (i << distance) | (i >> -distance); +#endif } public static int RotateRight(int i, int distance) { - return (int)((uint)i >> distance) ^ (i << -distance); +#if NETCOREAPP3_0_OR_GREATER + return (int)BitOperations.RotateRight((uint)i, distance); +#else + return (int)((uint)i >> distance) | (i << -distance); +#endif } + [CLSCompliant(false)] public static uint RotateRight(uint i, int distance) { - return (i >> distance) ^ (i << -distance); +#if NETCOREAPP3_0_OR_GREATER + return BitOperations.RotateRight(i, distance); +#else + return (i >> distance) | (i << -distance); +#endif } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Longs.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Longs.cs index df1d154..10396b0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Longs.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Longs.cs @@ -1,12 +1,19 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ +using System.Buffers.Binary; +#endif +#if NETCOREAPP3_0_OR_GREATER +using System.Numerics; +using System.Runtime.Intrinsics.X86; +#endif using BestHTTP.SecureProtocol.Org.BouncyCastle.Math.Raw; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities { - public abstract class Longs + public static class Longs { public const int NumBits = 64; public const int NumBytes = 8; @@ -17,8 +24,43 @@ public abstract class Longs 0x3E, 0x33, 0x05, 0x19, 0x24, 0x27, 0x20, 0x2E, 0x3C, 0x2C, 0x2A, 0x14, 0x16, 0x39, 0x10, 0x09, 0x32, 0x18, 0x23, 0x1F, 0x3B, 0x13, 0x38, 0x0F, 0x31, 0x1E, 0x12, 0x0E, 0x1D, 0x0D, 0x0C, 0x0B }; + public static long HighestOneBit(long i) + { + return (long)HighestOneBit((ulong)i); + } + + [CLSCompliant(false)] + public static ulong HighestOneBit(ulong i) + { + i |= i >> 1; + i |= i >> 2; + i |= i >> 4; + i |= i >> 8; + i |= i >> 16; + i |= i >> 32; + return i - (i >> 1); + } + + public static long LowestOneBit(long i) + { + return i & -i; + } + + [CLSCompliant(false)] + public static ulong LowestOneBit(ulong i) + { + return (ulong)LowestOneBit((long)i); + } + public static int NumberOfLeadingZeros(long i) { +#if NETCOREAPP3_0_OR_GREATER + if (Lzcnt.X64.IsSupported) + { + return (int)Lzcnt.X64.LeadingZeroCount((ulong)i); + } +#endif + int x = (int)(i >> 32), n = 0; if (x == 0) { @@ -30,6 +72,13 @@ public static int NumberOfLeadingZeros(long i) public static int NumberOfTrailingZeros(long i) { +#if NETCOREAPP3_0_OR_GREATER + if (Bmi1.X64.IsSupported) + { + return (int)Bmi1.X64.TrailingZeroCount((ulong)i); + } +#endif + int n = DeBruijnTZ[(uint)((ulong)((i & -i) * 0x045FBAC7992A70DAL) >> 58)]; long m = (((i & 0xFFFFFFFFL) | (long)((ulong)i >> 32)) - 1L) >> 63; return n - (int)m; @@ -40,6 +89,7 @@ public static long Reverse(long i) return (long)Reverse((ulong)i); } + [CLSCompliant(false)] public static ulong Reverse(ulong i) { i = Bits.BitPermuteStepSimple(i, 0x5555555555555555UL, 1); @@ -50,35 +100,62 @@ public static ulong Reverse(ulong i) public static long ReverseBytes(long i) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return BinaryPrimitives.ReverseEndianness(i); +#else return (long)ReverseBytes((ulong)i); +#endif } + [CLSCompliant(false)] public static ulong ReverseBytes(ulong i) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return BinaryPrimitives.ReverseEndianness(i); +#else return RotateLeft(i & 0xFF000000FF000000UL, 8) | RotateLeft(i & 0x00FF000000FF0000UL, 24) | RotateLeft(i & 0x0000FF000000FF00UL, 40) | RotateLeft(i & 0x000000FF000000FFUL, 56); +#endif } public static long RotateLeft(long i, int distance) { - return (i << distance) ^ (long)((ulong)i >> -distance); +#if NETCOREAPP3_0_OR_GREATER + return (long)BitOperations.RotateLeft((ulong)i, distance); +#else + return (i << distance) | (long)((ulong)i >> -distance); +#endif } + [CLSCompliant(false)] public static ulong RotateLeft(ulong i, int distance) { - return (i << distance) ^ (i >> -distance); +#if NETCOREAPP3_0_OR_GREATER + return BitOperations.RotateLeft(i, distance); +#else + return (i << distance) | (i >> -distance); +#endif } public static long RotateRight(long i, int distance) { - return (long)((ulong)i >> distance) ^ (i << -distance); +#if NETCOREAPP3_0_OR_GREATER + return (long)BitOperations.RotateRight((ulong)i, distance); +#else + return (long)((ulong)i >> distance) | (i << -distance); +#endif } + [CLSCompliant(false)] public static ulong RotateRight(ulong i, int distance) { - return (i >> distance) ^ (i << -distance); +#if NETCOREAPP3_0_OR_GREATER + return BitOperations.RotateRight(i, distance); +#else + return (i >> distance) | (i << -distance); +#endif } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/MemoableResetException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/MemoableResetException.cs index 9b5d14e..7744506 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/MemoableResetException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/MemoableResetException.cs @@ -1,30 +1,41 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; 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 + [Serializable] + public class MemoableResetException : InvalidCastException { - /** - * Basic Constructor. - * - * @param msg message to be associated with this exception. - */ - public MemoableResetException(string msg) - : base(msg) - { - } - } + public MemoableResetException() + : base() + { + } + public MemoableResetException(string message) + : base(message) + { + } + + public MemoableResetException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected MemoableResetException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Objects.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Objects.cs new file mode 100644 index 0000000..6771824 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Objects.cs @@ -0,0 +1,14 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities +{ + public static class Objects + { + public static int GetHashCode(object obj) + { + return null == obj ? 0 : obj.GetHashCode(); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Objects.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Objects.cs.meta new file mode 100644 index 0000000..f97b14a --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Objects.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 81337102137f3814c94821e995ceb992 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Platform.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Platform.cs index 6450fe2..86da2a3 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Platform.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Platform.cs @@ -2,56 +2,19 @@ #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 + internal static 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 + return string.Equals(a, b, StringComparison.OrdinalIgnoreCase); } -#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) + internal static string GetEnvironmentVariable(string variable) { try { @@ -64,148 +27,25 @@ internal static string GetEnvironmentVariable( 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) + internal static int IndexOf(string source, char value) { -#if PORTABLE || NETFX_CORE - return s.ToLowerInvariant(); -#else - return s.ToLower(CultureInfo.InvariantCulture); -#endif + return InvariantCompareInfo.IndexOf(source, value, CompareOptions.Ordinal); } - internal static string ToUpperInvariant(string s) + internal static int IndexOf(string source, string value) { -#if PORTABLE || NETFX_CORE - return s.ToUpperInvariant(); -#else - return s.ToUpper(CultureInfo.InvariantCulture); -#endif + return InvariantCompareInfo.IndexOf(source, value, CompareOptions.Ordinal); } - internal static readonly string NewLine = GetNewLine(); - -#if PORTABLE || NETFX_CORE - internal static void Dispose(IDisposable d) + internal static int IndexOf(string source, char value, int startIndex) { - d.Dispose(); + return InvariantCompareInfo.IndexOf(source, value, startIndex, CompareOptions.Ordinal); } -#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) + internal static int IndexOf(string source, string value, int startIndex) { - return InvariantCompareInfo.IndexOf(source, value, CompareOptions.Ordinal); + return InvariantCompareInfo.IndexOf(source, value, startIndex, CompareOptions.Ordinal); } internal static int LastIndexOf(string source, string value) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Shorts.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Shorts.cs new file mode 100644 index 0000000..be7b723 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Shorts.cs @@ -0,0 +1,58 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ +using System.Buffers.Binary; +#endif + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities +{ + public static class Shorts + { + public const int NumBits = 16; + public const int NumBytes = 2; + + public static short ReverseBytes(short i) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return BinaryPrimitives.ReverseEndianness(i); +#else + return RotateLeft(i, 8); +#endif + } + + [CLSCompliant(false)] + public static ushort ReverseBytes(ushort i) + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return BinaryPrimitives.ReverseEndianness(i); +#else + return RotateLeft(i, 8); +#endif + } + + public static short RotateLeft(short i, int distance) + { + return (short)RotateLeft((ushort)i, distance); + } + + [CLSCompliant(false)] + public static ushort RotateLeft(ushort i, int distance) + { + return (ushort)((i << distance) | (i >> (16 - distance))); + } + + public static short RotateRight(short i, int distance) + { + return (short)RotateRight((ushort)i, distance); + } + + [CLSCompliant(false)] + public static ushort RotateRight(ushort i, int distance) + { + return (ushort)((i >> distance) | (i << (16 - distance))); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Shorts.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Shorts.cs.meta new file mode 100644 index 0000000..f9f10c1 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Shorts.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 64f79d897b653fb48a890b7df96822bf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Spans.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Spans.cs new file mode 100644 index 0000000..2118518 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Spans.cs @@ -0,0 +1,46 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ +using System; +using System.Runtime.CompilerServices; + +//#nullable enable + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities +{ + internal static class Spans + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void CopyFrom(this Span output, ReadOnlySpan input) + { + input[..output.Length].CopyTo(output); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static Span FromNullable(T[]? array) + { + return array == null ? Span.Empty : array.AsSpan(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static Span FromNullable(T[]? array, int start) + { + return array == null ? Span.Empty : array.AsSpan(start); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static ReadOnlySpan FromNullableReadOnly(T[]? array) + { + return array == null ? Span.Empty : array.AsSpan(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static ReadOnlySpan FromNullableReadOnly(T[]? array, int start) + { + return array == null ? Span.Empty : array.AsSpan(start); + } + } +} +#endif +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Spans.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Spans.cs.meta new file mode 100644 index 0000000..c4fa399 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Spans.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e1011a1c49304df47bc72fae41c46624 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Strings.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Strings.cs index 1f606ee..4814c16 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/Strings.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/Strings.cs @@ -6,33 +6,8 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities { /// General string utilities. - public abstract class Strings + public static class Strings { - - public static string ToUpperCase(string original) - { - bool changed = false; - char[] chars = original.ToCharArray(); - - for (int i = 0; i != chars.Length; i++) - { - char ch = chars[i]; - if ('a' <= ch && 'z' >= ch) - { - changed = true; - chars[i] = (char)(ch - 'a' + 'A'); - } - } - - if (changed) - { - return new String(chars); - } - - return original; - } - - internal static bool IsOneOf(string s, params string[] candidates) { foreach (string candidate in candidates) @@ -43,8 +18,7 @@ internal static bool IsOneOf(string s, params string[] candidates) return false; } - public static string FromByteArray( - byte[] bs) + public static string FromByteArray(byte[] bs) { char[] cs = new char[bs.Length]; for (int i = 0; i < cs.Length; ++i) @@ -54,8 +28,7 @@ public static string FromByteArray( return new string(cs); } - public static byte[] ToByteArray( - char[] cs) + public static byte[] ToByteArray(char[] cs) { byte[] bs = new byte[cs.Length]; for (int i = 0; i < bs.Length; ++i) @@ -65,8 +38,7 @@ public static byte[] ToByteArray( return bs; } - public static byte[] ToByteArray( - string s) + public static byte[] ToByteArray(string s) { byte[] bs = new byte[s.Length]; for (int i = 0; i < bs.Length; ++i) @@ -76,53 +48,32 @@ public static byte[] ToByteArray( return bs; } - public static string FromAsciiByteArray( - byte[] bytes) + 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 + return Encoding.ASCII.GetString(bytes); } - public static byte[] ToAsciiByteArray( - char[] cs) + 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) + 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) + public static string FromUtf8ByteArray(byte[] bytes) { - return Encoding.UTF8.GetString(bytes, 0, bytes.Length); + return Encoding.UTF8.GetString(bytes); } - public static byte[] ToUtf8ByteArray( - char[] cs) + public static byte[] ToUtf8ByteArray(char[] cs) { return Encoding.UTF8.GetBytes(cs); } - public static byte[] ToUtf8ByteArray( - string s) + public static byte[] ToUtf8ByteArray(string s) { return Encoding.UTF8.GetBytes(s); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2.meta new file mode 100644 index 0000000..28eff04 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 71a439503264c6c4ba4e2d3ebdd0fc1e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/BZip2Constants.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/BZip2Constants.cs new file mode 100644 index 0000000..fa1779e --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/BZip2Constants.cs @@ -0,0 +1,51 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +/* + * This package is based on the work done by Keiron Liddle, Aftex Software + * to whom the Ant project is very grateful for his + * great code. + */ + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Bzip2 +{ + /** + * Base class for both the compress and decompress classes. + * Holds common arrays, and static data. + * + * @author Keiron Liddle + */ + public class BZip2Constants + { + public const int baseBlockSize = 100000; + public const int MAX_ALPHA_SIZE = 258; + public const int MAX_CODE_LEN = 20; + public const int MAX_CODE_LEN_GEN = 17; + public const int RUNA = 0; + public const int RUNB = 1; + public const int N_GROUPS = 6; + public const int G_SIZE = 50; + public const int N_ITERS = 4; + public const int MAX_SELECTORS = 2 + (900000 / G_SIZE); + public const int NUM_OVERSHOOT_BYTES = 20; + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/BZip2Constants.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/BZip2Constants.cs.meta new file mode 100644 index 0000000..7f2f119 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/BZip2Constants.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 51385589e08abc14c881532858ab77aa +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/CBZip2InputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/CBZip2InputStream.cs new file mode 100644 index 0000000..fa8dbb7 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/CBZip2InputStream.cs @@ -0,0 +1,813 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +/* + * This package is based on the work done by Keiron Liddle, Aftex Software + * to whom the Ant project is very grateful for his + * great code. + */ + +using System; +using System.Diagnostics; +using System.IO; + +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Bzip2 +{ + /** + * An input stream that decompresses from the BZip2 format (with the file + * header chars) to be read as any other stream. + * + * @author Keiron Liddle + * + * NB: note this class has been modified to read the leading BZ from the + * start of the BZIP2 stream to make it compatible with other PGP programs. + */ + public class CBZip2InputStream + : BaseInputStream + { + /* + index of the last char in the block, so + the block size == last + 1. + */ + private int last; + + /* + index in zptr[] of original string after sorting. + */ + private int origPtr; + + /* + always: in the range 0 .. 9. + The current block size is 100000 * this number. + */ + private int blockSize100k; + + private int bsBuff; + private int bsLive; + private readonly CRC m_blockCrc = new CRC(); + + private int nInUse; + + private byte[] seqToUnseq = new byte[256]; + + private byte[] m_selectors = new byte[BZip2Constants.MAX_SELECTORS]; + + private int[] tt; + private byte[] ll8; + + /* + freq table collected to save a pass over the data + during decompression. + */ + private int[] unzftab = new int[256]; + + private int[][] limit = CreateIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_CODE_LEN + 1); + private int[][] basev = CreateIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_CODE_LEN + 1); + private int[][] perm = CreateIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); + private int[] minLens = new int[BZip2Constants.N_GROUPS]; + + private Stream bsStream; + + private bool streamEnd = false; + + private int currentByte = -1; + + private const int RAND_PART_B_STATE = 1; + private const int RAND_PART_C_STATE = 2; + private const int NO_RAND_PART_B_STATE = 3; + private const int NO_RAND_PART_C_STATE = 4; + + private int currentState = 0; + + private int m_expectedBlockCrc, m_expectedStreamCrc, m_streamCrc; + + int i2, count, chPrev, ch2; + int i, tPos; + int rNToGo = 0; + int rTPos = 0; + int j2; + int z; + + public CBZip2InputStream(Stream zStream) + { + ll8 = null; + tt = null; + bsStream = zStream; + bsLive = 0; + bsBuff = 0; + + int magic1 = bsStream.ReadByte(); + int magic2 = bsStream.ReadByte(); + int version = bsStream.ReadByte(); + int level = bsStream.ReadByte(); + if (level < 0) + throw new EndOfStreamException(); + + if (magic1 != 'B' | magic2 != 'Z' | version != 'h' | level < '1' | level > '9') + throw new IOException("Invalid stream header"); + + blockSize100k = level - '0'; + + int n = BZip2Constants.baseBlockSize * blockSize100k; + ll8 = new byte[n]; + tt = new int[n]; + + m_streamCrc = 0; + + BeginBlock(); + } + + public override int Read(byte[] buffer, int offset, int count) + { + Streams.ValidateBufferArguments(buffer, offset, count); + + /* + * TODO The base class implementation allows to return partial data if/when ReadByte throws. That would be + * be preferable here too (so don't override), but it would require that exceptions cause this instance to + * permanently fail, and that needs review. + */ + int pos = 0; + while (pos < count) + { + int b = ReadByte(); + if (b < 0) + break; + + buffer[offset + pos++] = (byte)b; + } + return pos; + } + + public override int ReadByte() + { + if (streamEnd) + return -1; + + int result = currentByte; + switch (currentState) + { + case RAND_PART_B_STATE: + SetupRandPartB(); + break; + case RAND_PART_C_STATE: + SetupRandPartC(); + break; + case NO_RAND_PART_B_STATE: + SetupNoRandPartB(); + break; + case NO_RAND_PART_C_STATE: + SetupNoRandPartC(); + break; + default: + throw new InvalidOperationException(); + } + return result; + } + + private void BeginBlock() + { + long magic48 = BsGetLong48(); + if (magic48 != 0x314159265359L) + { + if (magic48 != 0x177245385090L) + throw new IOException("Block header error"); + + m_expectedStreamCrc = BsGetInt32(); + if (m_expectedStreamCrc != m_streamCrc) + throw new IOException("Stream CRC error"); + + BsFinishedWithStream(); + streamEnd = true; + return; + } + + m_expectedBlockCrc = BsGetInt32(); + + bool blockRandomised = BsGetBit() == 1; + + GetAndMoveToFrontDecode(); + + m_blockCrc.Initialise(); + + int[] cftab = new int[257]; + { + int accum = 0; + cftab[0] = 0; + for (i = 0; i < 256; ++i) + { + accum += unzftab[i]; + cftab[i + 1] = accum; + } + if (accum != (last + 1)) + throw new InvalidOperationException(); + } + + for (i = 0; i <= last; i++) + { + byte ch = ll8[i]; + tt[cftab[ch]++] = i; + } + + tPos = tt[origPtr]; + + count = 0; + i2 = 0; + ch2 = 256; /* not a char and not EOF */ + + if (blockRandomised) + { + rNToGo = 0; + rTPos = 0; + SetupRandPartA(); + } + else + { + SetupNoRandPartA(); + } + } + + private void EndBlock() + { + int blockFinalCrc = m_blockCrc.GetFinal(); + if (m_expectedBlockCrc != blockFinalCrc) + throw new IOException("Block CRC error"); + + m_streamCrc = Integers.RotateLeft(m_streamCrc, 1) ^ blockFinalCrc; + } + + private void BsFinishedWithStream() + { + try + { + if (this.bsStream != null) + { + this.bsStream.Dispose(); + this.bsStream = null; + } + } + catch + { + //ignore + } + } + + private int BsGetBit() + { + if (bsLive == 0) + { + bsBuff = RequireByte(); + bsLive = 7; + return (int)((uint)bsBuff >> 7); + } + + --bsLive; + + return (bsBuff >> bsLive) & 1; + } + + private int BsGetBits(int n) + { + Debug.Assert(1 <= n && n <= 24); + + while (bsLive < n) + { + bsBuff = (bsBuff << 8) | RequireByte(); + bsLive += 8; + } + + bsLive -= n; + + return (bsBuff >> bsLive) & ((1 << n) - 1); + } + + private int BsGetBitsSmall(int n) + { + Debug.Assert(1 <= n && n <= 8); + + if (bsLive < n) + { + bsBuff = (bsBuff << 8) | RequireByte(); + bsLive += 8; + } + + bsLive -= n; + + return (bsBuff >> bsLive) & ((1 << n) - 1); + } + + private int BsGetInt32() + { + int u = BsGetBits(16) << 16; + return u | BsGetBits(16); + } + + private long BsGetLong48() + { + long u = (long)BsGetBits(24) << 24; + return u | (long)BsGetBits(24); + } + + private void HbCreateDecodeTables(int[] limit, int[] basev, int[] perm, byte[] length, int minLen, int maxLen, + int alphaSize) + { + Array.Clear(basev, 0, basev.Length); + Array.Clear(limit, 0, limit.Length); + + int pp = 0, baseVal = 0; + for (int i = minLen; i <= maxLen; i++) + { + for (int j = 0; j < alphaSize; j++) + { + if (length[j] == i) + { + perm[pp++] = j; + } + } + basev[i] = baseVal; + limit[i] = baseVal + pp; + baseVal += baseVal + pp; + } + } + + private int RecvDecodingTables() + { + int i, j; + + nInUse = 0; + + /* Receive the mapping table */ + int inUse16 = BsGetBits(16); + + for (i = 0; i < 16; ++i) + { + if ((inUse16 & (0x8000 >> i)) != 0) + { + int inUse = BsGetBits(16); + + int i16 = i * 16; + for (j = 0; j < 16; ++j) + { + if ((inUse & (0x8000 >> j)) != 0) + { + seqToUnseq[nInUse++] = (byte)(i16 + j); + } + } + } + } + + if (nInUse < 1) + throw new InvalidOperationException(); + + int alphaSize = nInUse + 2; + + /* Now the selectors */ + int nGroups = BsGetBitsSmall(3); + if (nGroups < 2 || nGroups > BZip2Constants.N_GROUPS) + throw new InvalidOperationException(); + + int nSelectors = BsGetBits(15); + if (nSelectors < 1) + throw new InvalidOperationException(); + + uint mtfGroups = 0x00543210U; + for (i = 0; i < nSelectors; i++) + { + int mtfSelector = 0; + while (BsGetBit() == 1) + { + if (++mtfSelector >= nGroups) + throw new InvalidOperationException(); + } + + // Ignore declared selectors in excess of the maximum usable number + if (i >= BZip2Constants.MAX_SELECTORS) + continue; + + // Undo the MTF value for the selector. + switch (mtfSelector) + { + case 0: + break; + case 1: + mtfGroups = (mtfGroups >> 4) & 0x00000FU | (mtfGroups << 4) & 0x0000F0U | mtfGroups & 0xFFFF00U; + break; + case 2: + mtfGroups = (mtfGroups >> 8) & 0x00000FU | (mtfGroups << 4) & 0x000FF0U | mtfGroups & 0xFFF000U; + break; + case 3: + mtfGroups = (mtfGroups >> 12) & 0x00000FU | (mtfGroups << 4) & 0x00FFF0U | mtfGroups & 0xFF0000U; + break; + case 4: + mtfGroups = (mtfGroups >> 16) & 0x00000FU | (mtfGroups << 4) & 0x0FFFF0U | mtfGroups & 0xF00000U; + break; + case 5: + mtfGroups = (mtfGroups >> 20) & 0x00000FU | (mtfGroups << 4) & 0xFFFFF0U; + break; + default: + throw new InvalidOperationException(); + } + + m_selectors[i] = (byte)(mtfGroups & 0xF); + } + + byte[] len_t = new byte[alphaSize]; + + /* Now the coding tables */ + for (int t = 0; t < nGroups; t++) + { + int maxLen = 0, minLen = 32; + int curr = BsGetBitsSmall(5); + if ((curr < 1) | (curr > BZip2Constants.MAX_CODE_LEN)) + throw new InvalidOperationException(); + + for (i = 0; i < alphaSize; i++) + { + int markerBit = BsGetBit(); + while (markerBit != 0) + { + int nextTwoBits = BsGetBitsSmall(2); + curr += 1 - (nextTwoBits & 2); + if ((curr < 1) | (curr > BZip2Constants.MAX_CODE_LEN)) + throw new InvalidOperationException(); + markerBit = nextTwoBits & 1; + } + + len_t[i] = (byte)curr; + maxLen = System.Math.Max(maxLen, curr); + minLen = System.Math.Min(minLen, curr); + } + + /* Create the Huffman decoding tables */ + HbCreateDecodeTables(limit[t], basev[t], perm[t], len_t, minLen, maxLen, alphaSize); + minLens[t] = minLen; + } + + return nSelectors; + } + + private void GetAndMoveToFrontDecode() + { + int i, j, nextSym; + + int limitLast = BZip2Constants.baseBlockSize * blockSize100k; + + origPtr = BsGetBits(24); + if (origPtr > 10 + limitLast) + throw new InvalidOperationException(); + + int nSelectors = RecvDecodingTables(); + + int alphaSize = nInUse + 2; + int EOB = nInUse + 1; + + /* + Setting up the unzftab entries here is not strictly + necessary, but it does save having to do it later + in a separate pass, and so saves a block's worth of + cache misses. + */ + Array.Clear(unzftab, 0, unzftab.Length); + + byte[] yy = new byte[nInUse]; + for (i = 0; i < nInUse; ++i) + { + yy[i] = seqToUnseq[i]; + } + + last = -1; + + int groupNo = 0; + int groupPos = BZip2Constants.G_SIZE - 1; + int groupSel = m_selectors[groupNo]; + int groupMinLen = minLens[groupSel]; + int[] groupLimits = limit[groupSel]; + int[] groupPerm = perm[groupSel]; + int[] groupBase = basev[groupSel]; + + { + int zn = groupMinLen; + int zvec = BsGetBits(groupMinLen); + while (zvec >= groupLimits[zn]) + { + if (++zn > BZip2Constants.MAX_CODE_LEN) + throw new InvalidOperationException(); + + zvec = (zvec << 1) | BsGetBit(); + } + int permIndex = zvec - groupBase[zn]; + if (permIndex >= alphaSize) + throw new InvalidOperationException(); + + nextSym = groupPerm[permIndex]; + } + + while (nextSym != EOB) + { + //if (nextSym == BZip2Constants.RUNA || nextSym == BZip2Constants.RUNB) + if (nextSym <= BZip2Constants.RUNB) + { + int n = 1, s = 0; + do + { + if (n > 1024 * 1024) + throw new InvalidOperationException(); + + s += n << nextSym; + n <<= 1; + + { + if (groupPos == 0) + { + if (++groupNo >= nSelectors) + throw new InvalidOperationException(); + + groupPos = BZip2Constants.G_SIZE; + groupSel = m_selectors[groupNo]; + groupMinLen = minLens[groupSel]; + groupLimits = limit[groupSel]; + groupPerm = perm[groupSel]; + groupBase = basev[groupSel]; + } + groupPos--; + + int zn = groupMinLen; + int zvec = BsGetBits(groupMinLen); + while (zvec >= groupLimits[zn]) + { + if (++zn > BZip2Constants.MAX_CODE_LEN) + throw new InvalidOperationException(); + + zvec = (zvec << 1) | BsGetBit(); + } + int permIndex = zvec - groupBase[zn]; + if (permIndex >= alphaSize) + throw new InvalidOperationException(); + + nextSym = groupPerm[permIndex]; + } + } + //while (nextSym == BZip2Constants.RUNA || nextSym == BZip2Constants.RUNB); + while (nextSym <= BZip2Constants.RUNB); + + byte ch = yy[0]; + unzftab[ch] += s; + + if (last >= limitLast - s) + throw new InvalidOperationException("Block overrun"); + + while (--s >= 0) + { + ll8[++last] = ch; + } + + continue; + } + else + { + if (++last >= limitLast) + throw new InvalidOperationException("Block overrun"); + + byte tmp = yy[nextSym - 1]; + unzftab[tmp]++; + ll8[last] = tmp; + + /* + * This loop is hammered during decompression, hence avoid + * native method call overhead of Array.Copy for very + * small ranges to copy. + */ + if (nextSym <= 16) + { + for (j = nextSym - 1; j > 0; --j) + { + yy[j] = yy[j - 1]; + } + } + else + { + Array.Copy(yy, 0, yy, 1, nextSym - 1); + } + + yy[0] = tmp; + + { + if (groupPos == 0) + { + if (++groupNo >= nSelectors) + throw new InvalidOperationException(); + + groupPos = BZip2Constants.G_SIZE; + groupSel = m_selectors[groupNo]; + groupMinLen = minLens[groupSel]; + groupLimits = limit[groupSel]; + groupPerm = perm[groupSel]; + groupBase = basev[groupSel]; + } + groupPos--; + + int zn = groupMinLen; + int zvec = BsGetBits(groupMinLen); + while (zvec >= groupLimits[zn]) + { + if (++zn > BZip2Constants.MAX_CODE_LEN) + throw new InvalidOperationException(); + + zvec = (zvec << 1) | BsGetBit(); + } + int permIndex = zvec - groupBase[zn]; + if (permIndex >= alphaSize) + throw new InvalidOperationException(); + + nextSym = groupPerm[permIndex]; + } + continue; + } + } + + if (origPtr > last) + throw new InvalidOperationException(); + + // Check unzftab entries are in range. + { + int nblock = last + 1; + int check = 0; + + for (i = 0; i <= 255; i++) + { + int t = unzftab[i]; + check |= t; + check |= nblock - t; + } + if (check < 0) + throw new InvalidOperationException(); + } + } + + private int RequireByte() + { + int b = bsStream.ReadByte(); + if (b < 0) + throw new EndOfStreamException(); + return b & 0xFF; + } + + private void SetupRandPartA() + { + if (i2 <= last) + { + chPrev = ch2; + ch2 = ll8[tPos]; + tPos = tt[tPos]; + if (rNToGo == 0) + { + rNToGo = CBZip2OutputStream.RNums[rTPos++]; + rTPos &= 0x1FF; + } + rNToGo--; + ch2 ^= rNToGo == 1 ? 1 : 0; + i2++; + + currentByte = ch2; + currentState = RAND_PART_B_STATE; + m_blockCrc.Update((byte)ch2); + } + else + { + EndBlock(); + BeginBlock(); + } + } + + private void SetupNoRandPartA() + { + if (i2 <= last) + { + chPrev = ch2; + ch2 = ll8[tPos]; + tPos = tt[tPos]; + i2++; + + currentByte = ch2; + currentState = NO_RAND_PART_B_STATE; + m_blockCrc.Update((byte)ch2); + } + else + { + EndBlock(); + BeginBlock(); + } + } + + private void SetupRandPartB() + { + if (ch2 != chPrev) + { + count = 1; + SetupRandPartA(); + } + else if (++count < 4) + { + SetupRandPartA(); + } + else + { + z = ll8[tPos]; + tPos = tt[tPos]; + if (rNToGo == 0) + { + rNToGo = CBZip2OutputStream.RNums[rTPos++]; + rTPos &= 0x1FF; + } + rNToGo--; + z ^= rNToGo == 1 ? 1 : 0; + j2 = 0; + currentState = RAND_PART_C_STATE; + SetupRandPartC(); + } + } + + private void SetupNoRandPartB() + { + if (ch2 != chPrev) + { + count = 1; + SetupNoRandPartA(); + } + else if (++count < 4) + { + SetupNoRandPartA(); + } + else + { + z = ll8[tPos]; + tPos = tt[tPos]; + currentState = NO_RAND_PART_C_STATE; + j2 = 0; + SetupNoRandPartC(); + } + } + + private void SetupRandPartC() + { + if (j2 < z) + { + currentByte = ch2; + m_blockCrc.Update((byte)ch2); + j2++; + } + else + { + i2++; + count = 0; + SetupRandPartA(); + } + } + + private void SetupNoRandPartC() + { + if (j2 < z) + { + currentByte = ch2; + m_blockCrc.Update((byte)ch2); + j2++; + } + else + { + i2++; + count = 0; + SetupNoRandPartA(); + } + } + + internal static int[][] CreateIntArray(int n1, int n2) + { + int[][] a = new int[n1][]; + for (int k = 0; k < n1; ++k) + { + a[k] = new int[n2]; + } + return a; + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/CBZip2InputStream.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/CBZip2InputStream.cs.meta new file mode 100644 index 0000000..93cecc8 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/CBZip2InputStream.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7a4666f98f6a8d540ae1d0d2f61b9262 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/CBZip2OutputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/CBZip2OutputStream.cs new file mode 100644 index 0000000..d22ab55 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/CBZip2OutputStream.cs @@ -0,0 +1,1623 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +/* + * This package is based on the work done by Keiron Liddle, Aftex Software + * to whom the Ant project is very grateful for his + * great code. + */ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; + +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Bzip2 +{ + /** + * An output stream that compresses into the BZip2 format (with the file + * header chars) into another stream. + * + * @author Keiron Liddle + * + * TODO: Update to BZip2 1.0.1 + * NB: note this class has been modified to add a leading BZ to the + * start of the BZIP2 stream to make it compatible with other PGP programs. + */ + public class CBZip2OutputStream + : BaseOutputStream + { + protected const int SETMASK = 1 << 21; + protected const int CLEARMASK = ~SETMASK; + protected const int GREATER_ICOST = 15; + protected const int LESSER_ICOST = 0; + protected const int SMALL_THRESH = 20; + protected const int DEPTH_THRESH = 10; + + internal static readonly ushort[] RNums = { + 619, 720, 127, 481, 931, 816, 813, 233, 566, 247, 985, 724, 205, 454, 863, 491, 741, 242, 949, 214, 733, + 859, 335, 708, 621, 574, 73, 654, 730, 472, 419, 436, 278, 496, 867, 210, 399, 680, 480, 51, 878, 465, 811, + 169, 869, 675, 611, 697, 867, 561, 862, 687, 507, 283, 482, 129, 807, 591, 733, 623, 150, 238, 59, 379, 684, + 877, 625, 169, 643, 105, 170, 607, 520, 932, 727, 476, 693, 425, 174, 647, 73, 122, 335, 530, 442, 853, 695, + 249, 445, 515, 909, 545, 703, 919, 874, 474, 882, 500, 594, 612, 641, 801, 220, 162, 819, 984, 589, 513, + 495, 799, 161, 604, 958, 533, 221, 400, 386, 867, 600, 782, 382, 596, 414, 171, 516, 375, 682, 485, 911, + 276, 98, 553, 163, 354, 666, 933, 424, 341, 533, 870, 227, 730, 475, 186, 263, 647, 537, 686, 600, 224, 469, + 68, 770, 919, 190, 373, 294, 822, 808, 206, 184, 943, 795, 384, 383, 461, 404, 758, 839, 887, 715, 67, 618, + 276, 204, 918, 873, 777, 604, 560, 951, 160, 578, 722, 79, 804, 96, 409, 713, 940, 652, 934, 970, 447, 318, + 353, 859, 672, 112, 785, 645, 863, 803, 350, 139, 93, 354, 99, 820, 908, 609, 772, 154, 274, 580, 184, 79, + 626, 630, 742, 653, 282, 762, 623, 680, 81, 927, 626, 789, 125, 411, 521, 938, 300, 821, 78, 343, 175, 128, + 250, 170, 774, 972, 275, 999, 639, 495, 78, 352, 126, 857, 956, 358, 619, 580, 124, 737, 594, 701, 612, 669, + 112, 134, 694, 363, 992, 809, 743, 168, 974, 944, 375, 748, 52, 600, 747, 642, 182, 862, 81, 344, 805, 988, + 739, 511, 655, 814, 334, 249, 515, 897, 955, 664, 981, 649, 113, 974, 459, 893, 228, 433, 837, 553, 268, + 926, 240, 102, 654, 459, 51, 686, 754, 806, 760, 493, 403, 415, 394, 687, 700, 946, 670, 656, 610, 738, 392, + 760, 799, 887, 653, 978, 321, 576, 617, 626, 502, 894, 679, 243, 440, 680, 879, 194, 572, 640, 724, 926, 56, + 204, 700, 707, 151, 457, 449, 797, 195, 791, 558, 945, 679, 297, 59, 87, 824, 713, 663, 412, 693, 342, 606, + 134, 108, 571, 364, 631, 212, 174, 643, 304, 329, 343, 97, 430, 751, 497, 314, 983, 374, 822, 928, 140, 206, + 73, 263, 980, 736, 876, 478, 430, 305, 170, 514, 364, 692, 829, 82, 855, 953, 676, 246, 369, 970, 294, 750, + 807, 827, 150, 790, 288, 923, 804, 378, 215, 828, 592, 281, 565, 555, 710, 82, 896, 831, 547, 261, 524, 462, + 293, 465, 502, 56, 661, 821, 976, 991, 658, 869, 905, 758, 745, 193, 768, 550, 608, 933, 378, 286, 215, 979, + 792, 961, 61, 688, 793, 644, 986, 403, 106, 366, 905, 644, 372, 567, 466, 434, 645, 210, 389, 550, 919, 135, + 780, 773, 635, 389, 707, 100, 626, 958, 165, 504, 920, 176, 193, 713, 857, 265, 203, 50, 668, 108, 645, 990, + 626, 197, 510, 357, 358, 850, 858, 364, 936, 638 }; + + /* + * Knuth's increments seem to work better than Incerpi-Sedgewick here, possibly because the number of elements + * to sort is usually small, typically <= 20. + */ + private static readonly int[] Incs = { 1, 4, 13, 40, 121, 364, 1093, 3280, 9841, 29524, 88573, 265720, 797161, + 2391484 }; + + private bool finished; + + protected static void HbMakeCodeLengths(byte[] len, int[] freq, int alphaSize, int maxLen) + { + /* + Nodes and heap entries run from 1. Entry 0 + for both the heap and nodes is a sentinel. + */ + int[] heap = new int[BZip2Constants.MAX_ALPHA_SIZE + 2]; + int[] weight = new int[BZip2Constants.MAX_ALPHA_SIZE * 2]; + int[] parent = new int[BZip2Constants.MAX_ALPHA_SIZE * 2]; + + for (int i = 0; i < alphaSize; i++) + { + weight[i + 1] = (freq[i] == 0 ? 1 : freq[i]) << 8; + } + + while (true) + { + int nNodes = alphaSize; + int nHeap = 0; + + heap[0] = 0; + weight[0] = 0; + parent[0] = -2; + + for (int i = 1; i <= alphaSize; i++) + { + parent[i] = -1; + heap[++nHeap] = i; + { + int zz = nHeap; + int tmp = heap[zz]; + while (weight[tmp] < weight[heap[zz >> 1]]) + { + heap[zz] = heap[zz >> 1]; + zz >>= 1; + } + heap[zz] = tmp; + } + } + if (!(nHeap < (BZip2Constants.MAX_ALPHA_SIZE + 2))) + throw new InvalidOperationException(); + + while (nHeap > 1) + { + int n1 = heap[1]; + heap[1] = heap[nHeap--]; + { + int zz = 1; + int tmp = heap[zz]; + while (true) + { + int yy = zz << 1; + if (yy > nHeap) + break; + + if (yy < nHeap + && weight[heap[yy + 1]] < weight[heap[yy]]) + { + yy++; + } + + if (weight[tmp] < weight[heap[yy]]) + break; + + heap[zz] = heap[yy]; + zz = yy; + } + heap[zz] = tmp; + } + int n2 = heap[1]; + heap[1] = heap[nHeap--]; + { + int zz = 1; + int tmp = heap[zz]; + while (true) + { + int yy = zz << 1; + if (yy > nHeap) + break; + + if (yy < nHeap + && weight[heap[yy + 1]] < weight[heap[yy]]) + { + yy++; + } + + if (weight[tmp] < weight[heap[yy]]) + break; + + heap[zz] = heap[yy]; + zz = yy; + } + heap[zz] = tmp; + } + nNodes++; + parent[n1] = parent[n2] = nNodes; + + weight[nNodes] = (int)((uint)((weight[n1] & 0xffffff00) + + (weight[n2] & 0xffffff00)) + | (uint)(1 + (((weight[n1] & 0x000000ff) > + (weight[n2] & 0x000000ff)) ? + (weight[n1] & 0x000000ff) : + (weight[n2] & 0x000000ff)))); + + parent[nNodes] = -1; + heap[++nHeap] = nNodes; + { + int zz = nHeap; + int tmp = heap[zz]; + while (weight[tmp] < weight[heap[zz >> 1]]) + { + heap[zz] = heap[zz >> 1]; + zz >>= 1; + } + heap[zz] = tmp; + } + } + if (!(nNodes < (BZip2Constants.MAX_ALPHA_SIZE * 2))) + throw new InvalidOperationException(); + + //bool tooLong = false; + int tooLongBits = 0; + for (int i = 1; i <= alphaSize; i++) + { + int j = 0; + int k = i; + while (parent[k] >= 0) + { + k = parent[k]; + j++; + } + len[i - 1] = (byte)j; + //tooLong |= j > maxLen; + tooLongBits |= maxLen - j; + } + + //if (!tooLong) + if (tooLongBits >= 0) + break; + + for (int i = 1; i <= alphaSize; i++) + { + int j = weight[i] >> 8; + j = 1 + (j / 2); + weight[i] = j << 8; + } + } + } + + /* + * number of characters in the block + */ + int count; + + /* + index in zptr[] of original string after sorting. + */ + int origPtr; + + /* + always: in the range 0 .. 9. + The current block size is 100000 * this number. + */ + private readonly int blockSize100k; + private readonly int allowableBlockSize; + + bool blockRandomised; + private readonly IList blocksortStack = new List(); + + int bsBuff; + int bsLivePos; + private readonly CRC m_blockCrc = new CRC(); + + private bool[] inUse = new bool[256]; + private int nInUse; + + private byte[] m_selectors = new byte[BZip2Constants.MAX_SELECTORS]; + + private byte[] blockBytes; + private ushort[] quadrantShorts; + private int[] zptr; + private int[] szptr; + private int[] ftab; + + private int nMTF; + + private int[] mtfFreq = new int[BZip2Constants.MAX_ALPHA_SIZE]; + + /* + * Used when sorting. If too many long comparisons + * happen, we stop sorting, randomise the block + * slightly, and try again. + */ + private int workFactor; + private int workDone; + private int workLimit; + private bool firstAttempt; + + private int currentByte = -1; + private int runLength = 0; + private int m_streamCrc; + + public CBZip2OutputStream(Stream outStream) + : this(outStream, 9) + { + } + + public CBZip2OutputStream(Stream outStream, int blockSize) + { + blockBytes = null; + quadrantShorts = null; + zptr = null; + ftab = null; + + outStream.WriteByte((byte)'B'); + outStream.WriteByte((byte)'Z'); + + bsStream = outStream; + bsBuff = 0; + bsLivePos = 32; + + workFactor = 50; + if (blockSize > 9) + { + blockSize = 9; + } + else if (blockSize < 1) + { + blockSize = 1; + } + blockSize100k = blockSize; + + /* 20 is just a paranoia constant */ + allowableBlockSize = BZip2Constants.baseBlockSize * blockSize100k - 20; + + int n = BZip2Constants.baseBlockSize * blockSize100k; + blockBytes = new byte[(n + 1 + BZip2Constants.NUM_OVERSHOOT_BYTES)]; + quadrantShorts = new ushort[(n + 1 + BZip2Constants.NUM_OVERSHOOT_BYTES)]; + zptr = new int[n]; + ftab = new int[65537]; + + /* + The back end needs a place to store the MTF values + whilst it calculates the coding tables. We could + put them in the zptr array. However, these values + will fit in a short, so we overlay szptr at the + start of zptr, in the hope of reducing the number + of cache misses induced by the multiple traversals + of the MTF values when calculating coding tables. + Seems to improve compression speed by about 1%. + */ + // NOTE: We can't "overlay" in C#, so we just share zptr + szptr = zptr; + + // Write `magic' bytes h indicating file-format == huffmanised, followed by a digit indicating blockSize100k + outStream.WriteByte((byte)'h'); + outStream.WriteByte((byte)('0' + blockSize100k)); + + m_streamCrc = 0; + + InitBlock(); + } + + /** + * + * modified by Oliver Merkel, 010128 + * + */ + public override void WriteByte(byte value) + { + if (currentByte == value) + { + if (++runLength > 254) + { + WriteRun(); + currentByte = -1; + runLength = 0; + } + return; + } + + if (currentByte >= 0) + { + WriteRun(); + } + + currentByte = value; + runLength = 1; + } + + private void WriteRun() + { + if (count > allowableBlockSize) + { + EndBlock(); + InitBlock(); + } + + inUse[currentByte] = true; + + switch (runLength) + { + case 1: + blockBytes[++count] = (byte)currentByte; + m_blockCrc.Update((byte)currentByte); + break; + case 2: + blockBytes[++count] = (byte)currentByte; + blockBytes[++count] = (byte)currentByte; + m_blockCrc.Update((byte)currentByte); + m_blockCrc.Update((byte)currentByte); + break; + case 3: + blockBytes[++count] = (byte)currentByte; + blockBytes[++count] = (byte)currentByte; + blockBytes[++count] = (byte)currentByte; + m_blockCrc.Update((byte)currentByte); + m_blockCrc.Update((byte)currentByte); + m_blockCrc.Update((byte)currentByte); + break; + default: + blockBytes[++count] = (byte)currentByte; + blockBytes[++count] = (byte)currentByte; + blockBytes[++count] = (byte)currentByte; + blockBytes[++count] = (byte)currentByte; + blockBytes[++count] = (byte)(runLength - 4); + inUse[runLength - 4] = true; + m_blockCrc.UpdateRun((byte)currentByte, runLength); + break; + } + } + + bool closed = false; + + protected void Detach(bool disposing) + { + if (disposing) + { + if (!closed) + { + Finish(); + closed = true; + } + } + base.Dispose(disposing); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (!closed) + { + Finish(); + closed = true; + this.bsStream.Dispose(); + } + } + base.Dispose(disposing); + } + + public void Finish() + { + if (finished) + return; + + if (runLength > 0) + { + WriteRun(); + } + currentByte = -1; + if (count > 0) + { + EndBlock(); + } + EndCompression(); + finished = true; + Flush(); + } + + public override void Flush() + { + bsStream.Flush(); + } + + private void InitBlock() + { + m_blockCrc.Initialise(); + count = 0; + + for (int i = 0; i < 256; i++) + { + inUse[i] = false; + } + } + + private void EndBlock() + { + int blockFinalCrc = m_blockCrc.GetFinal(); + m_streamCrc = Integers.RotateLeft(m_streamCrc, 1) ^ blockFinalCrc; + + /* sort the block and establish posn of original string */ + DoReversibleTransformation(); + + /* + A 6-byte block header, the value chosen arbitrarily + as 0x314159265359 :-). A 32 bit value does not really + give a strong enough guarantee that the value will not + appear by chance in the compressed datastream. Worst-case + probability of this event, for a 900k block, is about + 2.0e-3 for 32 bits, 1.0e-5 for 40 bits and 4.0e-8 for 48 bits. + For a compressed file of size 100Gb -- about 100000 blocks -- + only a 48-bit marker will do. NB: normal compression/ + decompression do *not* rely on these statistical properties. + They are only important when trying to recover blocks from + damaged files. + */ + BsPutLong48(0x314159265359L); + + /* Now the block's CRC, so it is in a known place. */ + BsPutInt32(blockFinalCrc); + + /* Now a single bit indicating randomisation. */ + BsPutBit(blockRandomised ? 1 : 0); + + /* Finally, block's contents proper. */ + MoveToFrontCodeAndSend(); + } + + private void EndCompression() + { + /* + Now another magic 48-bit number, 0x177245385090, to + indicate the end of the last block. (Sqrt(pi), if + you want to know. I did want to use e, but it contains + too much repetition -- 27 18 28 18 28 46 -- for me + to feel statistically comfortable. Call me paranoid.) + */ + BsPutLong48(0x177245385090L); + + BsPutInt32(m_streamCrc); + + BsFinishedWithStream(); + } + + private void HbAssignCodes(int[] code, byte[] length, int minLen, int maxLen, int alphaSize) + { + int vec = 0; + for (int n = minLen; n <= maxLen; n++) + { + for (int i = 0; i < alphaSize; i++) + { + if (length[i] == n) + { + code[i] = vec++; + } + } + vec <<= 1; + } + } + + private void BsFinishedWithStream() + { + if (bsLivePos < 32) + { + bsStream.WriteByte((byte)(bsBuff >> 24)); + bsBuff = 0; + bsLivePos = 32; + } + } + + private void BsPutBit(int v) + { + --bsLivePos; + bsBuff |= v << bsLivePos; + + if (bsLivePos <= 24) + { + bsStream.WriteByte((byte)(bsBuff >> 24)); + bsBuff <<= 8; + bsLivePos += 8; + } + } + + private void BsPutBits(int n, int v) + { + Debug.Assert(1 <= n && n <= 24); + + bsLivePos -= n; + bsBuff |= v << bsLivePos; + + while (bsLivePos <= 24) + { + bsStream.WriteByte((byte)(bsBuff >> 24)); + bsBuff <<= 8; + bsLivePos += 8; + } + } + + private void BsPutBitsSmall(int n, int v) + { + Debug.Assert(1 <= n && n <= 8); + + bsLivePos -= n; + bsBuff |= v << bsLivePos; + + if (bsLivePos <= 24) + { + bsStream.WriteByte((byte)(bsBuff >> 24)); + bsBuff <<= 8; + bsLivePos += 8; + } + } + + private void BsPutInt32(int u) + { + BsPutBits(16, (u >> 16) & 0xFFFF); + BsPutBits(16, u & 0xFFFF); + } + + private void BsPutLong48(long u) + { + BsPutBits(24, (int)(u >> 24) & 0xFFFFFF); + BsPutBits(24, (int)u & 0xFFFFFF); + } + + private void SendMtfValues() + { + + int v, t, i, j, bt, bc, iter; + + int alphaSize = nInUse + 2; + + /* Decide how many coding tables to use */ + if (nMTF <= 0) + throw new InvalidOperationException(); + + int nGroups; + if (nMTF < 200) + { + nGroups = 2; + } + else if (nMTF < 600) + { + nGroups = 3; + } + else if (nMTF < 1200) + { + nGroups = 4; + } + else if (nMTF < 2400) + { + nGroups = 5; + } + else + { + nGroups = 6; + } + + byte[][] len = CreateByteArray(nGroups, alphaSize); + for (t = 0; t < nGroups; t++) + { + Arrays.Fill(len[t], GREATER_ICOST); + } + + /* Generate an initial set of coding tables */ + { + int nPart = nGroups; + int remF = nMTF; + int ge = -1; + while (nPart > 0) + { + int gs = ge + 1; + int aFreq = 0, tFreq = remF / nPart; + while (aFreq < tFreq && ge < alphaSize - 1) + { + aFreq += mtfFreq[++ge]; + } + + if (ge > gs && nPart != nGroups && nPart != 1 + && ((nGroups - nPart) % 2 == 1)) + { + aFreq -= mtfFreq[ge--]; + } + + byte[] len_np = len[nPart - 1]; + for (v = 0; v < alphaSize; v++) + { + if (v >= gs && v <= ge) + { + len_np[v] = LESSER_ICOST; + } + else + { + len_np[v] = GREATER_ICOST; + } + } + + nPart--; + remF -= aFreq; + } + } + + int[][] rfreq = CBZip2InputStream.CreateIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); + int[] fave = new int[BZip2Constants.N_GROUPS]; + short[] cost = new short[BZip2Constants.N_GROUPS]; + + // Iterate up to N_ITERS times to improve the tables. + int nSelectors = 0; + for (iter = 0; iter < BZip2Constants.N_ITERS; iter++) + { + for (t = 0; t < nGroups; t++) + { + fave[t] = 0; + + int[] rfreq_t = rfreq[t]; + for (v = 0; v < alphaSize; v++) + { + rfreq_t[v] = 0; + } + } + + nSelectors = 0; + int gs = 0; + while (gs < nMTF) + { + /* Set group start & end marks. */ + + /* + * Calculate the cost of this group as coded by each of the coding tables. + */ + + int ge = System.Math.Min(gs + BZip2Constants.G_SIZE - 1, nMTF - 1); + + if (nGroups == 6) + { + byte[] len_0 = len[0], len_1 = len[1], len_2 = len[2], len_3 = len[3], len_4 = len[4], len_5 = len[5]; + short cost0 = 0, cost1 = 0, cost2 = 0, cost3 = 0, cost4 = 0, cost5 = 0; + + for (i = gs; i <= ge; i++) + { + int icv = szptr[i]; + cost0 += len_0[icv]; + cost1 += len_1[icv]; + cost2 += len_2[icv]; + cost3 += len_3[icv]; + cost4 += len_4[icv]; + cost5 += len_5[icv]; + } + + cost[0] = cost0; + cost[1] = cost1; + cost[2] = cost2; + cost[3] = cost3; + cost[4] = cost4; + cost[5] = cost5; + } + else + { + for (t = 0; t < nGroups; t++) + { + cost[t] = 0; + } + + for (i = gs; i <= ge; i++) + { + int icv = szptr[i]; + for (t = 0; t < nGroups; t++) + { + cost[t] += len[t][icv]; + } + } + } + + /* + Find the coding table which is best for this group, + and record its identity in the selector table. + */ + bc = cost[0]; + bt = 0; + for (t = 1; t < nGroups; t++) + { + short cost_t = cost[t]; + if (cost_t < bc) + { + bc = cost_t; + bt = t; + } + } + fave[bt]++; + m_selectors[nSelectors] = (byte)bt; + nSelectors++; + + /* + Increment the symbol frequencies for the selected table. + */ + int[] rfreq_bt = rfreq[bt]; + for (i = gs; i <= ge; i++) + { + rfreq_bt[szptr[i]]++; + } + + gs = ge + 1; + } + + /* + Recompute the tables based on the accumulated frequencies. + */ + for (t = 0; t < nGroups; t++) + { + HbMakeCodeLengths(len[t], rfreq[t], alphaSize, BZip2Constants.MAX_CODE_LEN_GEN); + } + } + + if (nGroups >= 8 || nGroups > BZip2Constants.N_GROUPS) + throw new InvalidOperationException(); + if (nSelectors >= 32768 || nSelectors > BZip2Constants.MAX_SELECTORS) + throw new InvalidOperationException(); + + int[][] code = CBZip2InputStream.CreateIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); + + /* Assign actual codes for the tables. */ + for (t = 0; t < nGroups; t++) + { + int maxLen = 0, minLen = 32; + byte[] len_t = len[t]; + for (i = 0; i < alphaSize; i++) + { + int lti = len_t[i]; + maxLen = System.Math.Max(maxLen, lti); + minLen = System.Math.Min(minLen, lti); + } + if (minLen < 1 | maxLen > BZip2Constants.MAX_CODE_LEN_GEN) + throw new InvalidOperationException(); + + HbAssignCodes(code[t], len_t, minLen, maxLen, alphaSize); + } + + /* Transmit the mapping table. */ + { + bool[] inUse16 = new bool[16]; + for (i = 0; i < 16; i++) + { + inUse16[i] = false; + int i16 = i * 16; + for (j = 0; j < 16; j++) + { + if (inUse[i16 + j]) + { + inUse16[i] = true; + break; + } + } + } + + for (i = 0; i < 16; i++) + { + BsPutBit(inUse16[i] ? 1 : 0); + } + + for (i = 0; i < 16; i++) + { + if (inUse16[i]) + { + int i16 = i * 16; + for (j = 0; j < 16; j++) + { + BsPutBit(inUse[i16 + j] ? 1 : 0); + } + } + } + } + + /* Now the selectors. */ + BsPutBitsSmall(3, nGroups); + BsPutBits(15, nSelectors); + { + int mtfSelectors = 0x00654321; + + for (i = 0; i < nSelectors; i++) + { + // Compute MTF value for the selector. + int ll_i = m_selectors[i]; + int bitPos = ll_i << 2; + int mtfSelector = (mtfSelectors >> bitPos) & 0xF; + + if (mtfSelector != 1) + { + int mtfIncMask = (0x00888888 - mtfSelectors + 0x00111111 * mtfSelector) & 0x00888888; + mtfSelectors = mtfSelectors - (mtfSelector << bitPos) + (mtfIncMask >> 3); + } + + BsPutBitsSmall(mtfSelector, (1 << mtfSelector) - 2); + } + } + + /* Now the coding tables. */ + for (t = 0; t < nGroups; t++) + { + byte[] len_t = len[t]; + int curr = len_t[0]; + BsPutBitsSmall(6, curr << 1); + for (i = 1; i < alphaSize; i++) + { + int lti = len_t[i]; + while (curr < lti) + { + BsPutBitsSmall(2, 2); + curr++; /* 10 */ + } + while (curr > lti) + { + BsPutBitsSmall(2, 3); + curr--; /* 11 */ + } + BsPutBit(0); + } + } + + /* And finally, the block data proper */ + { + int selCtr = 0; + int gs = 0; + while (gs < nMTF) + { + int ge = System.Math.Min(gs + BZip2Constants.G_SIZE - 1, nMTF - 1); + + int selector_selCtr = m_selectors[selCtr]; + byte[] len_selCtr = len[selector_selCtr]; + int[] code_selCtr = code[selector_selCtr]; + + for (i = gs; i <= ge; i++) + { + int sfmap_i = szptr[i]; + BsPutBits(len_selCtr[sfmap_i], code_selCtr[sfmap_i]); + } + + gs = ge + 1; + selCtr++; + } + if (selCtr != nSelectors) + throw new InvalidOperationException(); + } + } + + private void MoveToFrontCodeAndSend() + { + BsPutBits(24, origPtr); + GenerateMtfValues(); + SendMtfValues(); + } + + private Stream bsStream; + + private void SimpleSort(int lo, int hi, int d) + { + int i, j, h, v; + + int bigN = hi - lo + 1; + if (bigN < 2) + return; + + int hp = 0; + while (Incs[hp] < bigN) + { + hp++; + } + hp--; + + for (; hp >= 0; hp--) + { + h = Incs[hp]; + + i = lo + h; + while (i <= hi) + { + /* copy 1 */ + v = zptr[i]; + j = i; + while (FullGtU(zptr[j - h] + d, v + d)) + { + zptr[j] = zptr[j - h]; + j = j - h; + if (j <= (lo + h - 1)) + break; + } + zptr[j] = v; + + /* copy 2 */ + if (++i > hi) + break; + + v = zptr[i]; + j = i; + while (FullGtU(zptr[j - h] + d, v + d)) + { + zptr[j] = zptr[j - h]; + j = j - h; + if (j <= (lo + h - 1)) + break; + } + zptr[j] = v; + + /* copy 3 */ + if (++i > hi) + break; + + v = zptr[i]; + j = i; + while (FullGtU(zptr[j - h] + d, v + d)) + { + zptr[j] = zptr[j - h]; + j = j - h; + if (j <= (lo + h - 1)) + break; + } + zptr[j] = v; + i++; + + if (workDone > workLimit && firstAttempt) + return; + } + } + } + + private void Vswap(int p1, int p2, int n) + { + while (--n >= 0) + { + int t1 = zptr[p1], t2 = zptr[p2]; + zptr[p1++] = t2; + zptr[p2++] = t1; + } + } + + private int Med3(int a, int b, int c) + { + return a > b + ? (c < b ? b : c > a ? a : c) + : (c < a ? a : c > b ? b : c); + } + + internal class StackElem + { + internal int ll; + internal int hh; + internal int dd; + } + + private static void PushStackElem(IList stack, int stackCount, int ll, int hh, int dd) + { + StackElem stackElem; + if (stackCount < stack.Count) + { + stackElem = stack[stackCount]; + } + else + { + stackElem = new StackElem(); + stack.Add(stackElem); + } + + stackElem.ll = ll; + stackElem.hh = hh; + stackElem.dd = dd; + } + + private void QSort3(int loSt, int hiSt, int dSt) + { + int unLo, unHi, ltLo, gtHi, n, m; + + var stack = blocksortStack; + int stackCount = 0; + StackElem stackElem; + + int lo = loSt; + int hi = hiSt; + int d = dSt; + + for (;;) + { + if (hi - lo < SMALL_THRESH || d > DEPTH_THRESH) + { + SimpleSort(lo, hi, d); + if (stackCount < 1 || (workDone > workLimit && firstAttempt)) + return; + + stackElem = stack[--stackCount]; + lo = stackElem.ll; + hi = stackElem.hh; + d = stackElem.dd; + continue; + } + + int d1 = d + 1; + int med = Med3( + blockBytes[zptr[lo] + d1], + blockBytes[zptr[hi] + d1], + blockBytes[zptr[(lo + hi) >> 1] + d1]); + + unLo = ltLo = lo; + unHi = gtHi = hi; + + while (true) + { + while (unLo <= unHi) + { + int zUnLo = zptr[unLo]; + n = blockBytes[zUnLo + d1] - med; + if (n > 0) + break; + + if (n == 0) + { + zptr[unLo] = zptr[ltLo]; + zptr[ltLo++] = zUnLo; + } + unLo++; + } + while (unLo <= unHi) + { + int zUnHi = zptr[unHi]; + n = blockBytes[zUnHi + d1] - med; + if (n < 0) + break; + + if (n == 0) + { + zptr[unHi] = zptr[gtHi]; + zptr[gtHi--] = zUnHi; + } + unHi--; + } + if (unLo > unHi) + break; + + int temp = zptr[unLo]; + zptr[unLo++] = zptr[unHi]; + zptr[unHi--] = temp; + } + + if (gtHi < ltLo) + { + d = d1; + continue; + } + + n = System.Math.Min(ltLo - lo, unLo - ltLo); + Vswap(lo, unLo - n, n); + + m = System.Math.Min(hi - gtHi, gtHi - unHi); + Vswap(unLo, hi - m + 1, m); + + n = lo + (unLo - ltLo); + m = hi - (gtHi - unHi); + + PushStackElem(stack, stackCount++, lo, n - 1, d); + PushStackElem(stack, stackCount++, n, m, d1); + + lo = m + 1; + } + } + + private void MainSort() + { + int i, j, ss, sb; + int[] runningOrder = new int[256]; + int[] copy = new int[256]; + bool[] bigDone = new bool[256]; + int c1, c2; + + /* + In the various block-sized structures, live data runs + from 0 to last+NUM_OVERSHOOT_BYTES inclusive. First, + set up the overshoot area for block. + */ + for (i = 0; i < BZip2Constants.NUM_OVERSHOOT_BYTES; i++) + { + blockBytes[count + i + 1] = blockBytes[(i % count) + 1]; + } + for (i = 0; i <= count + BZip2Constants.NUM_OVERSHOOT_BYTES; i++) + { + quadrantShorts[i] = 0; + } + + blockBytes[0] = blockBytes[count]; + + if (count <= 4000) + { + /* + Use SimpleSort(), since the full sorting mechanism + has quite a large constant overhead. + */ + for (i = 0; i < count; i++) + { + zptr[i] = i; + } + firstAttempt = false; + workDone = workLimit = 0; + SimpleSort(0, count - 1, 0); + } + else + { + for (i = 0; i <= 255; i++) + { + bigDone[i] = false; + } + + for (i = 0; i <= 65536; i++) + { + ftab[i] = 0; + } + + c1 = blockBytes[0]; + for (i = 1; i <= count; i++) + { + c2 = blockBytes[i]; + ftab[(c1 << 8) + c2]++; + c1 = c2; + } + + for (i = 0; i < 65536; i++) + { + ftab[i + 1] += ftab[i]; + } + + c1 = blockBytes[1]; + for (i = 0; i < (count - 1); i++) + { + c2 = blockBytes[i + 2]; + j = (c1 << 8) + c2; + c1 = c2; + ftab[j]--; + zptr[ftab[j]] = i; + } + + j = ((int)blockBytes[count] << 8) + blockBytes[1]; + ftab[j]--; + zptr[ftab[j]] = count - 1; + + /* + Now ftab contains the first loc of every small bucket. + Calculate the running order, from smallest to largest + big bucket. + */ + + for (i = 0; i <= 255; i++) + { + runningOrder[i] = i; + } + + { + int h = 1; + do + { + h = 3 * h + 1; + } + while (h <= 256); + do + { + h = h / 3; + for (i = h; i <= 255; i++) + { + int vv = runningOrder[i]; + j = i; + while ((ftab[(runningOrder[j - h] + 1) << 8] - ftab[runningOrder[j - h] << 8]) + > (ftab[(vv + 1) << 8] - ftab[vv << 8])) + { + runningOrder[j] = runningOrder[j - h]; + j = j - h; + if (j < h) + break; + } + runningOrder[j] = vv; + } + } + while (h != 1); + } + + /* + The main sorting loop. + */ + for (i = 0; i <= 255; i++) + { + /* + Process big buckets, starting with the least full. + */ + ss = runningOrder[i]; + + /* + Complete the big bucket [ss] by quicksorting + any unsorted small buckets [ss, j]. Hopefully + previous pointer-scanning phases have already + completed many of the small buckets [ss, j], so + we don't have to sort them at all. + */ + for (j = 0; j <= 255; j++) + { + sb = (ss << 8) + j; + if ((ftab[sb] & SETMASK) != SETMASK) + { + int lo = ftab[sb] & CLEARMASK; + int hi = (ftab[sb + 1] & CLEARMASK) - 1; + if (hi > lo) + { + QSort3(lo, hi, 2); + if (workDone > workLimit && firstAttempt) + return; + } + ftab[sb] |= SETMASK; + } + } + + /* + The ss big bucket is now done. Record this fact, + and update the quadrant descriptors. Remember to + update quadrants in the overshoot area too, if + necessary. The "if (i < 255)" test merely skips + this updating for the last bucket processed, since + updating for the last bucket is pointless. + */ + bigDone[ss] = true; + + if (i < 255) + { + int bbStart = ftab[ss << 8] & CLEARMASK; + int bbSize = (ftab[(ss + 1) << 8] & CLEARMASK) - bbStart; + + int shifts = 0; + while ((bbSize >> shifts) > 65534) + { + shifts++; + } + + for (j = 0; j < bbSize; j++) + { + int a2update = zptr[bbStart + j] + 1; + ushort qVal = (ushort)(j >> shifts); + quadrantShorts[a2update] = qVal; + if (a2update <= BZip2Constants.NUM_OVERSHOOT_BYTES) + { + quadrantShorts[a2update + count] = qVal; + } + } + + if (!(((bbSize - 1) >> shifts) <= 65535)) + throw new InvalidOperationException(); + } + + /* + Now scan this big bucket so as to synthesise the + sorted order for small buckets [t, ss] for all t != ss. + */ + for (j = 0; j <= 255; j++) + { + copy[j] = ftab[(j << 8) + ss] & CLEARMASK; + } + + for (j = ftab[ss << 8] & CLEARMASK; + j < (ftab[(ss + 1) << 8] & CLEARMASK); j++) + { + int zptr_j = zptr[j]; + c1 = blockBytes[zptr_j]; + if (!bigDone[c1]) + { + zptr[copy[c1]] = (zptr_j == 0 ? count : zptr_j) - 1; + copy[c1]++; + } + } + + for (j = 0; j <= 255; j++) + { + ftab[(j << 8) + ss] |= SETMASK; + } + } + } + } + + private void RandomiseBlock() + { + for (int i = 0; i < 256; i++) + { + inUse[i] = false; + } + + int rNToGo = 0, rTPos = 0; + + for (int i = 1; i <= count; i++) + { + if (rNToGo == 0) + { + rNToGo = RNums[rTPos++]; + rTPos &= 0x1FF; + } + rNToGo--; + blockBytes[i] ^= (byte)(rNToGo == 1 ? 1 : 0); + + inUse[blockBytes[i]] = true; + } + } + + private void DoReversibleTransformation() + { + workLimit = workFactor * (count - 1); + workDone = 0; + blockRandomised = false; + firstAttempt = true; + + MainSort(); + + if (workDone > workLimit && firstAttempt) + { + RandomiseBlock(); + workLimit = workDone = 0; + blockRandomised = true; + firstAttempt = false; + MainSort(); + } + + origPtr = -1; + for (int i = 0; i < count; i++) + { + if (zptr[i] == 0) + { + origPtr = i; + break; + } + } + + if (origPtr == -1) + throw new InvalidOperationException(); + } + + private bool FullGtU(int i1, int i2) + { + int c1, c2; + + c1 = blockBytes[++i1]; + c2 = blockBytes[++i2]; + if (c1 != c2) + return c1 > c2; + + c1 = blockBytes[++i1]; + c2 = blockBytes[++i2]; + if (c1 != c2) + return c1 > c2; + + c1 = blockBytes[++i1]; + c2 = blockBytes[++i2]; + if (c1 != c2) + return c1 > c2; + + c1 = blockBytes[++i1]; + c2 = blockBytes[++i2]; + if (c1 != c2) + return c1 > c2; + + c1 = blockBytes[++i1]; + c2 = blockBytes[++i2]; + if (c1 != c2) + return c1 > c2; + + c1 = blockBytes[++i1]; + c2 = blockBytes[++i2]; + if (c1 != c2) + return c1 > c2; + + int k = count; + int s1, s2; + + do + { + c1 = blockBytes[++i1]; + c2 = blockBytes[++i2]; + if (c1 != c2) + return c1 > c2; + + s1 = quadrantShorts[i1]; + s2 = quadrantShorts[i2]; + if (s1 != s2) + return s1 > s2; + + c1 = blockBytes[++i1]; + c2 = blockBytes[++i2]; + if (c1 != c2) + return c1 > c2; + + s1 = quadrantShorts[i1]; + s2 = quadrantShorts[i2]; + if (s1 != s2) + return s1 > s2; + + c1 = blockBytes[++i1]; + c2 = blockBytes[++i2]; + if (c1 != c2) + return c1 > c2; + + s1 = quadrantShorts[i1]; + s2 = quadrantShorts[i2]; + if (s1 != s2) + return s1 > s2; + + c1 = blockBytes[++i1]; + c2 = blockBytes[++i2]; + if (c1 != c2) + return c1 > c2; + + s1 = quadrantShorts[i1]; + s2 = quadrantShorts[i2]; + if (s1 != s2) + return s1 > s2; + + if (i1 >= count) + { + i1 -= count; + } + if (i2 >= count) + { + i2 -= count; + } + + k -= 4; + workDone++; + } + while (k >= 0); + + return false; + } + + private void GenerateMtfValues() + { + int i; + + nInUse = 0; + + byte[] yy = new byte[256]; + for (i = 0; i < 256; i++) + { + if (inUse[i]) + { + yy[nInUse++] = (byte)i; + } + } + + int EOB = nInUse + 1; + + for (i = 0; i <= EOB; i++) + { + mtfFreq[i] = 0; + } + + int wr = 0, zPend = 0; + for (i = 0; i < count; i++) + { + byte blockByte = blockBytes[zptr[i]]; + + byte tmp = yy[0]; + if (blockByte == tmp) + { + zPend++; + continue; + } + + int sym = 1; + do + { + byte tmp2 = tmp; + tmp = yy[sym]; + yy[sym++] = tmp2; + } + while (blockByte != tmp); + yy[0] = tmp; + + while (zPend > 0) + { + // RUNA or RUNB + int run = --zPend & 1; + szptr[wr++] = run; + mtfFreq[run]++; + zPend >>= 1; + } + + szptr[wr++] = sym; + mtfFreq[sym]++; + } + + while (zPend > 0) + { + // RUNA or RUNB + int run = --zPend & 1; + szptr[wr++] = run; + mtfFreq[run]++; + zPend >>= 1; + } + + szptr[wr++] = EOB; + mtfFreq[EOB]++; + + nMTF = wr; + } + + internal static byte[][] CreateByteArray(int n1, int n2) + { + byte[][] a = new byte[n1][]; + for (int k = 0; k < n1; ++k) + { + a[k] = new byte[n2]; + } + return a; + } + } + + public class CBZip2OutputStreamLeaveOpen + : CBZip2OutputStream + { + public CBZip2OutputStreamLeaveOpen(Stream outStream) + : base(outStream) + { + } + + public CBZip2OutputStreamLeaveOpen(Stream outStream, int blockSize) + : base(outStream, blockSize) + { + } + + protected override void Dispose(bool disposing) + { + Detach(disposing); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/CBZip2OutputStream.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/CBZip2OutputStream.cs.meta new file mode 100644 index 0000000..5f11c0d --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/CBZip2OutputStream.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bf3dffeb38ff3b74983e5d723d21417c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/CRC.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/CRC.cs new file mode 100644 index 0000000..efbbfdc --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/CRC.cs @@ -0,0 +1,162 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +/* + * This package is based on the work done by Keiron Liddle), Aftex Software + * to whom the Ant project is very grateful for his + * great code. + */ + +using System.Diagnostics; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Bzip2 +{ + /** + * A simple class the hold and calculate the CRC for sanity checking + * of the data. + * + * @author Keiron Liddle + */ + internal class CRC + { + // Values are byte-reversed + private static readonly uint[] Crc32Table = { + 0x00000000, 0xB71DC104, 0x6E3B8209, 0xD926430D, + 0xDC760413, 0x6B6BC517, 0xB24D861A, 0x0550471E, + 0xB8ED0826, 0x0FF0C922, 0xD6D68A2F, 0x61CB4B2B, + 0x649B0C35, 0xD386CD31, 0x0AA08E3C, 0xBDBD4F38, + 0x70DB114C, 0xC7C6D048, 0x1EE09345, 0xA9FD5241, + 0xACAD155F, 0x1BB0D45B, 0xC2969756, 0x758B5652, + 0xC836196A, 0x7F2BD86E, 0xA60D9B63, 0x11105A67, + 0x14401D79, 0xA35DDC7D, 0x7A7B9F70, 0xCD665E74, + 0xE0B62398, 0x57ABE29C, 0x8E8DA191, 0x39906095, + 0x3CC0278B, 0x8BDDE68F, 0x52FBA582, 0xE5E66486, + 0x585B2BBE, 0xEF46EABA, 0x3660A9B7, 0x817D68B3, + 0x842D2FAD, 0x3330EEA9, 0xEA16ADA4, 0x5D0B6CA0, + 0x906D32D4, 0x2770F3D0, 0xFE56B0DD, 0x494B71D9, + 0x4C1B36C7, 0xFB06F7C3, 0x2220B4CE, 0x953D75CA, + 0x28803AF2, 0x9F9DFBF6, 0x46BBB8FB, 0xF1A679FF, + 0xF4F63EE1, 0x43EBFFE5, 0x9ACDBCE8, 0x2DD07DEC, + 0x77708634, 0xC06D4730, 0x194B043D, 0xAE56C539, + 0xAB068227, 0x1C1B4323, 0xC53D002E, 0x7220C12A, + 0xCF9D8E12, 0x78804F16, 0xA1A60C1B, 0x16BBCD1F, + 0x13EB8A01, 0xA4F64B05, 0x7DD00808, 0xCACDC90C, + 0x07AB9778, 0xB0B6567C, 0x69901571, 0xDE8DD475, + 0xDBDD936B, 0x6CC0526F, 0xB5E61162, 0x02FBD066, + 0xBF469F5E, 0x085B5E5A, 0xD17D1D57, 0x6660DC53, + 0x63309B4D, 0xD42D5A49, 0x0D0B1944, 0xBA16D840, + 0x97C6A5AC, 0x20DB64A8, 0xF9FD27A5, 0x4EE0E6A1, + 0x4BB0A1BF, 0xFCAD60BB, 0x258B23B6, 0x9296E2B2, + 0x2F2BAD8A, 0x98366C8E, 0x41102F83, 0xF60DEE87, + 0xF35DA999, 0x4440689D, 0x9D662B90, 0x2A7BEA94, + 0xE71DB4E0, 0x500075E4, 0x892636E9, 0x3E3BF7ED, + 0x3B6BB0F3, 0x8C7671F7, 0x555032FA, 0xE24DF3FE, + 0x5FF0BCC6, 0xE8ED7DC2, 0x31CB3ECF, 0x86D6FFCB, + 0x8386B8D5, 0x349B79D1, 0xEDBD3ADC, 0x5AA0FBD8, + 0xEEE00C69, 0x59FDCD6D, 0x80DB8E60, 0x37C64F64, + 0x3296087A, 0x858BC97E, 0x5CAD8A73, 0xEBB04B77, + 0x560D044F, 0xE110C54B, 0x38368646, 0x8F2B4742, + 0x8A7B005C, 0x3D66C158, 0xE4408255, 0x535D4351, + 0x9E3B1D25, 0x2926DC21, 0xF0009F2C, 0x471D5E28, + 0x424D1936, 0xF550D832, 0x2C769B3F, 0x9B6B5A3B, + 0x26D61503, 0x91CBD407, 0x48ED970A, 0xFFF0560E, + 0xFAA01110, 0x4DBDD014, 0x949B9319, 0x2386521D, + 0x0E562FF1, 0xB94BEEF5, 0x606DADF8, 0xD7706CFC, + 0xD2202BE2, 0x653DEAE6, 0xBC1BA9EB, 0x0B0668EF, + 0xB6BB27D7, 0x01A6E6D3, 0xD880A5DE, 0x6F9D64DA, + 0x6ACD23C4, 0xDDD0E2C0, 0x04F6A1CD, 0xB3EB60C9, + 0x7E8D3EBD, 0xC990FFB9, 0x10B6BCB4, 0xA7AB7DB0, + 0xA2FB3AAE, 0x15E6FBAA, 0xCCC0B8A7, 0x7BDD79A3, + 0xC660369B, 0x717DF79F, 0xA85BB492, 0x1F467596, + 0x1A163288, 0xAD0BF38C, 0x742DB081, 0xC3307185, + 0x99908A5D, 0x2E8D4B59, 0xF7AB0854, 0x40B6C950, + 0x45E68E4E, 0xF2FB4F4A, 0x2BDD0C47, 0x9CC0CD43, + 0x217D827B, 0x9660437F, 0x4F460072, 0xF85BC176, + 0xFD0B8668, 0x4A16476C, 0x93300461, 0x242DC565, + 0xE94B9B11, 0x5E565A15, 0x87701918, 0x306DD81C, + 0x353D9F02, 0x82205E06, 0x5B061D0B, 0xEC1BDC0F, + 0x51A69337, 0xE6BB5233, 0x3F9D113E, 0x8880D03A, + 0x8DD09724, 0x3ACD5620, 0xE3EB152D, 0x54F6D429, + 0x7926A9C5, 0xCE3B68C1, 0x171D2BCC, 0xA000EAC8, + 0xA550ADD6, 0x124D6CD2, 0xCB6B2FDF, 0x7C76EEDB, + 0xC1CBA1E3, 0x76D660E7, 0xAFF023EA, 0x18EDE2EE, + 0x1DBDA5F0, 0xAAA064F4, 0x738627F9, 0xC49BE6FD, + 0x09FDB889, 0xBEE0798D, 0x67C63A80, 0xD0DBFB84, + 0xD58BBC9A, 0x62967D9E, 0xBBB03E93, 0x0CADFF97, + 0xB110B0AF, 0x060D71AB, 0xDF2B32A6, 0x6836F3A2, + 0x6D66B4BC, 0xDA7B75B8, 0x035D36B5, 0xB440F7B1, + }; + + private uint m_value = 0U; + + internal void Initialise() + { + m_value = 0xFFFFFFFF; + } + + internal int GetFinal() + { + return (int)~Integers.ReverseBytes(m_value); + } + + internal void Update(byte inCh) + { + m_value = (m_value >> 8) ^ Crc32Table[(byte)(m_value ^ inCh)]; + } + + internal void UpdateRun(byte inCh, int runLength) + { + Debug.Assert(runLength >= 4); + + uint inCh2 = (uint)inCh << 8 | inCh; + uint inCh4 = inCh2 << 16 | inCh2; + + do + { + m_value ^= inCh4; + m_value = (m_value >> 8) ^ Crc32Table[(byte)m_value]; + m_value = (m_value >> 8) ^ Crc32Table[(byte)m_value]; + m_value = (m_value >> 8) ^ Crc32Table[(byte)m_value]; + m_value = (m_value >> 8) ^ Crc32Table[(byte)m_value]; + } + while ((runLength -= 4) >= 4); + + switch (runLength & 3) + { + case 0: + break; + case 1: + Update(inCh); + break; + case 2: + Update(inCh); + Update(inCh); + break; + case 3: + Update(inCh); + Update(inCh); + Update(inCh); + break; + } + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/CRC.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/CRC.cs.meta new file mode 100644 index 0000000..23dde28 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/bzip2/CRC.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8ef54f297138cd845a76621ec767e6a3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/CollectionUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/CollectionUtilities.cs index 7cf7512..e5c40ea 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/CollectionUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/CollectionUtilities.cs @@ -1,50 +1,84 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; -#if UNITY_WSA && !UNITY_EDITOR && !ENABLE_IL2CPP -using System.TypeFix; -#endif +using System.Collections.Generic; using System.Text; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections { public abstract class CollectionUtilities { - public static void AddRange(IList to, IEnumerable range) + public static void CollectMatches(ICollection matches, ISelector selector, + IEnumerable> stores) { - foreach (object o in range) + if (matches == null) + throw new ArgumentNullException(nameof(matches)); + if (stores == null) + return; + + foreach (var store in stores) { - to.Add(o); + if (store == null) + continue; + + foreach (T match in store.EnumerateMatches(selector)) + { + matches.Add(match); + } } } - public static bool CheckElementsAreOfType(IEnumerable e, Type t) + public static IStore CreateStore(IEnumerable contents) { - foreach (object o in e) - { - if (!t.IsInstanceOfType(o)) - return false; - } - return true; + return new StoreImpl(contents); + } + + public static T GetValueOrKey(IDictionary d, T k) + { + return d.TryGetValue(k, out var v) ? v : k; + } + + public static V GetValueOrNull(IDictionary d, K k) + where V : class + { + return d.TryGetValue(k, out var v) ? v : null; } - public static IDictionary ReadOnly(IDictionary d) + public static IEnumerable Proxy(IEnumerable e) { - return new UnmodifiableDictionaryProxy(d); + return new EnumerableProxy(e); } - public static IList ReadOnly(IList l) + public static ICollection ReadOnly(ICollection c) { - return new UnmodifiableListProxy(l); + return new ReadOnlyCollectionProxy(c); } - public static ISet ReadOnly(ISet s) + public static IDictionary ReadOnly(IDictionary d) { - return new UnmodifiableSetProxy(s); + return new ReadOnlyDictionaryProxy(d); + } + + public static IList ReadOnly(IList l) + { + return new ReadOnlyListProxy(l); + } + + public static ISet ReadOnly(ISet s) + { + return new ReadOnlySetProxy(s); + } + + public static bool Remove(IDictionary d, K k, out V v) + { + if (!d.TryGetValue(k, out v)) + return false; + + d.Remove(k); + return true; } - public static object RequireNext(IEnumerator e) + public static T RequireNext(IEnumerator e) { if (!e.MoveNext()) throw new InvalidOperationException(); @@ -52,18 +86,18 @@ public static object RequireNext(IEnumerator e) return e.Current; } - public static string ToString(IEnumerable c) + public static string ToString(IEnumerable c) { - IEnumerator e = c.GetEnumerator(); + IEnumerator e = c.GetEnumerator(); if (!e.MoveNext()) return "[]"; StringBuilder sb = new StringBuilder("["); - sb.Append(e.Current.ToString()); + sb.Append(e.Current); while (e.MoveNext()) { sb.Append(", "); - sb.Append(e.Current.ToString()); + sb.Append(e.Current); } sb.Append(']'); return sb.ToString(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/EnumerableProxy.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/EnumerableProxy.cs index 562f380..5dcff82 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/EnumerableProxy.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/EnumerableProxy.cs @@ -1,27 +1,31 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections { - public sealed class EnumerableProxy - : IEnumerable + internal sealed class EnumerableProxy + : IEnumerable { - private readonly IEnumerable inner; + private readonly IEnumerable m_target; - public EnumerableProxy( - IEnumerable inner) + internal EnumerableProxy(IEnumerable target) { - if (inner == null) - throw new ArgumentNullException("inner"); + if (target == null) + throw new ArgumentNullException(nameof(target)); - this.inner = inner; + m_target = target; } - public IEnumerator GetEnumerator() + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { - return inner.GetEnumerator(); + return m_target.GetEnumerator(); + } + + public IEnumerator GetEnumerator() + { + return m_target.GetEnumerator(); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/HashSet.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/HashSet.cs index 12c399b..0454b34 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/HashSet.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/HashSet.cs @@ -1,103 +1,3 @@ #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/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/HashSet.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/HashSet.cs.meta index 58836e7..afa5c36 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/HashSet.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/HashSet.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 7324bf9bc59776949bf134abc958ddeb +guid: be205234b98d61744b11c4318e87ac85 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ISelector.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ISelector.cs new file mode 100644 index 0000000..10e8348 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ISelector.cs @@ -0,0 +1,20 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections +{ + /// Interface for matching objects in an . + /// The contravariant type of selectable objects. + public interface ISelector + : ICloneable + { + /// Match the passed in object, returning true if it would be selected by this selector, false + /// otherwise. + /// The object to be matched. + /// true if the objects is matched by this selector, false otherwise. + bool Match(T candidate); + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ISelector.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ISelector.cs.meta new file mode 100644 index 0000000..2c249f4 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ISelector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ac9912de47b494548bad468a96736ce4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/IStore.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/IStore.cs new file mode 100644 index 0000000..5345349 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/IStore.cs @@ -0,0 +1,19 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.Collections.Generic; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections +{ + /// A generic interface describing a simple store of objects. + /// The covariant type of stored objects. + public interface IStore + { + /// Enumerate the (possibly empty) collection of objects matched by the given selector. + /// The used to select matching objects. + /// An of the matching objects. + IEnumerable EnumerateMatches(ISelector selector); + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/IStore.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/IStore.cs.meta new file mode 100644 index 0000000..2198ae0 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/IStore.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d42fa3793a9494946985bb14484c7dcf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/LinkedDictionary.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/LinkedDictionary.cs index bb9b4fb..0454b34 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/LinkedDictionary.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/LinkedDictionary.cs @@ -1,182 +1,3 @@ #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/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/LinkedDictionary.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/LinkedDictionary.cs.meta index 4edadcc..ce18137 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/LinkedDictionary.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/LinkedDictionary.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 1c21a553327fa1d4aadd4151e30aa090 +guid: e5f1de8474468a840953808b84fc6f96 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlyCollection.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlyCollection.cs new file mode 100644 index 0000000..ed9393b --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlyCollection.cs @@ -0,0 +1,48 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.Collections.Generic; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections +{ + internal abstract class ReadOnlyCollection + : ICollection + { + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public bool IsReadOnly => true; + + public void Add(T item) => throw new NotSupportedException(); + public void Clear() => throw new NotSupportedException(); + public bool Remove(T item) => throw new NotSupportedException(); + + public abstract bool Contains(T item); + public abstract int Count { get; } + public abstract void CopyTo(T[] array, int arrayIndex); + public abstract IEnumerator GetEnumerator(); + } + + internal class ReadOnlyCollectionProxy + : ReadOnlyCollection + { + private readonly ICollection m_target; + + internal ReadOnlyCollectionProxy(ICollection target) + { + if (target == null) + throw new ArgumentNullException(nameof(target)); + + m_target = target; + } + + public override bool Contains(T item) => m_target.Contains(item); + public override int Count => m_target.Count; + public override void CopyTo(T[] array, int arrayIndex) => m_target.CopyTo(array, arrayIndex); + public override IEnumerator GetEnumerator() => m_target.GetEnumerator(); + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlyCollection.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlyCollection.cs.meta new file mode 100644 index 0000000..0da308e --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlyCollection.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a48902e1e6ee3a0448224787f2a690c9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlyDictionary.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlyDictionary.cs new file mode 100644 index 0000000..c3fbb46 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlyDictionary.cs @@ -0,0 +1,68 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.Collections.Generic; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections +{ + internal abstract class ReadOnlyDictionary + : IDictionary + { + public V this[K key] + { + get { return Lookup(key); } + set { throw new NotSupportedException(); } + } + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public bool IsReadOnly => true; + + public void Add(K key, V value) => throw new NotSupportedException(); + public void Add(KeyValuePair item) => throw new NotSupportedException(); + public void Clear() => throw new NotSupportedException(); + public bool Remove(K key) => throw new NotSupportedException(); + public bool Remove(KeyValuePair item) => throw new NotSupportedException(); + + public abstract bool Contains(KeyValuePair item); + public abstract bool ContainsKey(K key); + public abstract void CopyTo(KeyValuePair[] array, int arrayIndex); + public abstract int Count { get; } + public abstract IEnumerator> GetEnumerator(); + public abstract ICollection Keys { get; } + public abstract bool TryGetValue(K key, out V value); + public abstract ICollection Values { get; } + + protected abstract V Lookup(K key); + } + + internal class ReadOnlyDictionaryProxy + : ReadOnlyDictionary + { + private readonly IDictionary m_target; + + internal ReadOnlyDictionaryProxy(IDictionary target) + { + if (target == null) + throw new ArgumentNullException(nameof(target)); + + m_target = target; + } + + public override bool Contains(KeyValuePair item) => m_target.Contains(item); + public override bool ContainsKey(K key) => m_target.ContainsKey(key); + public override void CopyTo(KeyValuePair[] array, int arrayIndex) => m_target.CopyTo(array, arrayIndex); + public override int Count => m_target.Count; + public override IEnumerator> GetEnumerator() => m_target.GetEnumerator(); + public override ICollection Keys => new ReadOnlyCollectionProxy(m_target.Keys); + public override bool TryGetValue(K key, out V value) => m_target.TryGetValue(key, out value); + public override ICollection Values => new ReadOnlyCollectionProxy(m_target.Values); + + protected override V Lookup(K key) => m_target[key]; + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlyDictionary.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlyDictionary.cs.meta new file mode 100644 index 0000000..9926c89 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlyDictionary.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9a4f69721ea2e274f8e93b1fdaf45141 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlyList.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlyList.cs new file mode 100644 index 0000000..c946cba --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlyList.cs @@ -0,0 +1,63 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.Collections.Generic; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections +{ + internal abstract class ReadOnlyList + : IList + { + public T this[int index] + { + get { return Lookup(index); } + set { throw new NotSupportedException(); } + } + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public bool IsReadOnly => true; + + public void Add(T item) => throw new NotSupportedException(); + public void Clear() => throw new NotSupportedException(); + public void Insert(int index, T item) => throw new NotSupportedException(); + public bool Remove(T item) => throw new NotSupportedException(); + public void RemoveAt(int index) => throw new NotSupportedException(); + + + public abstract bool Contains(T item); + public abstract void CopyTo(T[] array, int arrayIndex); + public abstract int Count { get; } + public abstract IEnumerator GetEnumerator(); + public abstract int IndexOf(T item); + + protected abstract T Lookup(int index); + } + + internal class ReadOnlyListProxy + : ReadOnlyList + { + private readonly IList m_target; + + internal ReadOnlyListProxy(IList target) + { + if (target == null) + throw new ArgumentNullException(nameof(target)); + + m_target = target; + } + + public override int Count => m_target.Count; + public override bool Contains(T item) => m_target.Contains(item); + public override void CopyTo(T[] array, int arrayIndex) => m_target.CopyTo(array, arrayIndex); + public override IEnumerator GetEnumerator() => m_target.GetEnumerator(); + public override int IndexOf(T item) => m_target.IndexOf(item); + + protected override T Lookup(int index) => m_target[index]; + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlyList.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlyList.cs.meta new file mode 100644 index 0000000..13867e1 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlyList.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a7fb52e360eebb940b519bf3dab83424 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlySet.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlySet.cs new file mode 100644 index 0000000..b9b038c --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlySet.cs @@ -0,0 +1,65 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.Collections.Generic; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections +{ + internal abstract class ReadOnlySet + : ISet + { + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + public bool IsReadOnly => true; + + void ICollection.Add(T item) => throw new NotSupportedException(); + + public bool Add(T item) => throw new NotSupportedException(); + public void Clear() => throw new NotSupportedException(); + public void ExceptWith(IEnumerable other) => throw new NotSupportedException(); + public void IntersectWith(IEnumerable other) => throw new NotSupportedException(); + public bool Remove(T item) => throw new NotSupportedException(); + public bool SetEquals(IEnumerable other) => throw new NotSupportedException(); + public void SymmetricExceptWith(IEnumerable other) => throw new NotSupportedException(); + public void UnionWith(IEnumerable other) => throw new NotSupportedException(); + + public abstract bool Contains(T item); + public abstract void CopyTo(T[] array, int arrayIndex); + public abstract int Count { get; } + public abstract IEnumerator GetEnumerator(); + public abstract bool IsProperSubsetOf(IEnumerable other); + public abstract bool IsProperSupersetOf(IEnumerable other); + public abstract bool IsSubsetOf(IEnumerable other); + public abstract bool IsSupersetOf(IEnumerable other); + public abstract bool Overlaps(IEnumerable other); + } + + internal class ReadOnlySetProxy + : ReadOnlySet + { + private readonly ISet m_target; + + internal ReadOnlySetProxy(ISet target) + { + if (target == null) + throw new ArgumentNullException(nameof(target)); + + m_target = target; + } + + public override bool Contains(T item) => m_target.Contains(item); + public override void CopyTo(T[] array, int arrayIndex) => m_target.CopyTo(array, arrayIndex); + public override int Count => m_target.Count; + public override IEnumerator GetEnumerator() => m_target.GetEnumerator(); + public override bool IsProperSubsetOf(IEnumerable other) => m_target.IsProperSubsetOf(other); + public override bool IsProperSupersetOf(IEnumerable other) => m_target.IsProperSupersetOf(other); + public override bool IsSubsetOf(IEnumerable other) => m_target.IsSubsetOf(other); + public override bool IsSupersetOf(IEnumerable other) => m_target.IsSupersetOf(other); + public override bool Overlaps(IEnumerable other) => m_target.Overlaps(other); + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlySet.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlySet.cs.meta new file mode 100644 index 0000000..6b65f33 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/ReadOnlySet.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 24bbf770e59530f4cb957c11b0b50001 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/StoreImpl.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/StoreImpl.cs new file mode 100644 index 0000000..d3bfebe --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/StoreImpl.cs @@ -0,0 +1,29 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System; +using System.Collections.Generic; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections +{ + internal sealed class StoreImpl + : IStore + { + private readonly List m_contents; + + internal StoreImpl(IEnumerable e) + { + m_contents = new List(e); + } + + IEnumerable IStore.EnumerateMatches(ISelector selector) + { + foreach (T candidate in m_contents) + { + if (selector == null || selector.Match(candidate)) + yield return candidate; + } + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/StoreImpl.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/StoreImpl.cs.meta new file mode 100644 index 0000000..fcd4797 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/collections/StoreImpl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 72bf42ed5d4da8a47915e3c158f0305b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/date/DateTimeUtilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/date/DateTimeUtilities.cs index be93193..5aaa3ea 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/date/DateTimeUtilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/date/DateTimeUtilities.cs @@ -4,38 +4,48 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Date { - public class DateTimeUtilities + public static class DateTimeUtilities { - public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static readonly DateTime UnixEpoch = DateTime.UnixEpoch; +#else + public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); +#endif - private DateTimeUtilities() - { - } + public static readonly long MaxUnixMs = + (DateTime.MaxValue.Ticks - UnixEpoch.Ticks) / TimeSpan.TicksPerMillisecond; + public static readonly long MinUnixMs = 0L; - /// - /// 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) + /// + /// Return the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC) for a given DateTime value. + /// + /// The DateTime value will be converted to UTC (using before + /// conversion. + /// A DateTime value not before the epoch. + /// Number of whole milliseconds after epoch. + /// 'dateTime' is before the epoch. + public static long DateTimeToUnixMs(DateTime dateTime) { - if (dateTime.CompareTo(UnixEpoch) < 0) - throw new ArgumentException("DateTime value may not be before the epoch", "dateTime"); + DateTime utc = dateTime.ToUniversalTime(); + if (utc.CompareTo(UnixEpoch) < 0) + throw new ArgumentOutOfRangeException(nameof(dateTime), "DateTime value may not be before the epoch"); - return (dateTime.Ticks - UnixEpoch.Ticks) / TimeSpan.TicksPerMillisecond; + return (utc.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) + /// + /// Create a UTC 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 + /// 'unixMs' is before 'MinUnixMs' or after 'MaxUnixMs'. + /// + public static DateTime UnixMsToDateTime(long unixMs) { - return new DateTime(unixMs * TimeSpan.TicksPerMillisecond + UnixEpoch.Ticks); + if (unixMs < MinUnixMs || unixMs > MaxUnixMs) + throw new ArgumentOutOfRangeException(nameof(unixMs)); + + return new DateTime(unixMs * TimeSpan.TicksPerMillisecond + UnixEpoch.Ticks, DateTimeKind.Utc); } /// @@ -45,7 +55,33 @@ public static long CurrentUnixMs() { return DateTimeToUnixMs(DateTime.UtcNow); } - } + + public static DateTime WithPrecisionCentisecond(DateTime dateTime) + { + int millisecond = dateTime.Millisecond - (dateTime.Millisecond % 10); + return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, + dateTime.Hour, dateTime.Minute, dateTime.Second, millisecond, dateTime.Kind); + } + + public static DateTime WithPrecisionDecisecond(DateTime dateTime) + { + int millisecond = dateTime.Millisecond - (dateTime.Millisecond % 100); + return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, + dateTime.Hour, dateTime.Minute, dateTime.Second, millisecond, dateTime.Kind); + } + + public static DateTime WithPrecisionMillisecond(DateTime dateTime) + { + return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, + dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Millisecond, dateTime.Kind); + } + + public static DateTime WithPrecisionSecond(DateTime dateTime) + { + return new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, + dateTime.Hour, dateTime.Minute, dateTime.Second, dateTime.Kind); + } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/encoders/Base64Encoder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/encoders/Base64Encoder.cs index 20cb09c..7c31c0d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/encoders/Base64Encoder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/encoders/Base64Encoder.cs @@ -48,6 +48,9 @@ public Base64Encoder() public int Encode(byte[] inBuf, int inOff, int inLen, byte[] outBuf, int outOff) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return Encode(inBuf.AsSpan(inOff, inLen), outBuf.AsSpan(outOff)); +#else int inPos = inOff; int inEnd = inOff + inLen - 2; int outPos = outOff; @@ -90,7 +93,56 @@ public int Encode(byte[] inBuf, int inOff, int inLen, byte[] outBuf, int outOff) } return outPos - outOff; +#endif + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int Encode(ReadOnlySpan input, Span output) + { + int inPos = 0; + int inEnd = input.Length - 2; + int outPos = 0; + + while (inPos < inEnd) + { + uint a1 = input[inPos++]; + uint a2 = input[inPos++]; + uint a3 = input[inPos++]; + + output[outPos++] = encodingTable[(a1 >> 2) & 0x3F]; + output[outPos++] = encodingTable[((a1 << 4) | (a2 >> 4)) & 0x3F]; + output[outPos++] = encodingTable[((a2 << 2) | (a3 >> 6)) & 0x3F]; + output[outPos++] = encodingTable[a3 & 0x3F]; + } + + switch (input.Length - inPos) + { + case 1: + { + uint a1 = input[inPos++]; + + output[outPos++] = encodingTable[(a1 >> 2) & 0x3F]; + output[outPos++] = encodingTable[(a1 << 4) & 0x3F]; + output[outPos++] = padding; + output[outPos++] = padding; + break; + } + case 2: + { + uint a1 = input[inPos++]; + uint a2 = input[inPos++]; + + output[outPos++] = encodingTable[(a1 >> 2) & 0x3F]; + output[outPos++] = encodingTable[((a1 << 4) | (a2 >> 4)) & 0x3F]; + output[outPos++] = encodingTable[(a2 << 2) & 0x3F]; + output[outPos++] = padding; + break; + } + } + + return outPos; } +#endif /** * encode the input data producing a base 64 output stream. @@ -99,6 +151,9 @@ public int Encode(byte[] inBuf, int inOff, int inLen, byte[] outBuf, int outOff) */ public int Encode(byte[] buf, int off, int len, Stream outStream) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return Encode(buf.AsSpan(off, len), outStream); +#else if (len < 0) return 0; @@ -113,8 +168,25 @@ public int Encode(byte[] buf, int off, int len, Stream outStream) remaining -= inLen; } return (len + 2) / 3 * 4; +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int Encode(ReadOnlySpan data, Stream outStream) + { + Span tmp = stackalloc byte[72]; + int result = (data.Length + 2) / 3 * 4; + while (!data.IsEmpty) + { + int inLen = System.Math.Min(54, data.Length); + int outLen = Encode(data[..inLen], tmp); + outStream.Write(tmp[..outLen]); + data = data[inLen..]; + } + return result; + } +#endif + private bool Ignore(char c) { return c == '\n' || c =='\r' || c == '\t' || c == ' '; @@ -128,6 +200,9 @@ private bool Ignore(char c) */ public int Decode(byte[] data, int off, int length, Stream outStream) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return Decode(data.AsSpan(off, length), outStream); +#else byte b1, b2, b3, b4; byte[] outBuffer = new byte[54]; // S/MIME standard int bufOff = 0; @@ -142,10 +217,8 @@ public int Decode(byte[] data, int off, int length, Stream outStream) end--; } - int i = off; - int finish = end - 4; - - i = NextI(data, i, finish); + int finish = end - 4; + int i = NextI(data, off, finish); while (i < finish) { @@ -194,12 +267,84 @@ public int Decode(byte[] data, int off, int length, Stream outStream) outLen += DecodeLastBlock(outStream, (char)data[e0], (char)data[e1], (char)data[e2], (char)data[e3]); return outLen; +#endif } - private int NextI( - byte[] data, - int i, - int finish) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int Decode(ReadOnlySpan data, Stream outStream) + { + byte b1, b2, b3, b4; + Span outBuffer = stackalloc byte[54]; // S/MIME standard + int bufOff = 0; + int outLen = 0; + int end = data.Length; + + while (end > 0) + { + if (!Ignore((char)data[end - 1])) + break; + + end--; + } + + int finish = end - 4; + int i = NextI(data, 0, 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"); + + outBuffer[bufOff++] = (byte)((b1 << 2) | (b2 >> 4)); + outBuffer[bufOff++] = (byte)((b2 << 4) | (b3 >> 2)); + outBuffer[bufOff++] = (byte)((b3 << 6) | b4); + + if (bufOff == outBuffer.Length) + { + outStream.Write(outBuffer); + bufOff = 0; + } + + outLen += 3; + + i = NextI(data, i, finish); + } + + if (bufOff > 0) + { + outStream.Write(outBuffer[..bufOff]); + } + + int e0 = NextI(data, i, end); + int e1 = NextI(data, e0 + 1, end); + int e2 = NextI(data, e1 + 1, end); + int e3 = NextI(data, e2 + 1, end); + + outLen += DecodeLastBlock(outStream, (char)data[e0], (char)data[e1], (char)data[e2], (char)data[e3]); + + return outLen; + } +#endif + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + private int NextI(ReadOnlySpan data, int i, int finish) +#else + private int NextI(byte[] data, int i, int finish) +#endif { while ((i < finish) && Ignore((char)data[i])) { @@ -234,10 +379,11 @@ public int DecodeString(string data, Stream outStream) end--; } - int i = 0; - int finish = end - 4; - - i = NextI(data, i, finish); + int finish = end - 4; + int i = NextI(data, 0, finish); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span buf = stackalloc byte[3]; +#endif while (i < finish) { @@ -258,9 +404,16 @@ public int DecodeString(string data, Stream outStream) if ((b1 | b2 | b3 | b4) >= 0x80) throw new IOException("invalid characters encountered in base64 data"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + buf[0] = (byte)((b1 << 2) | (b2 >> 4)); + buf[1] = (byte)((b2 << 4) | (b3 >> 2)); + buf[2] = (byte)((b3 << 6) | b4); + outStream.Write(buf); +#else outStream.WriteByte((byte)((b1 << 2) | (b2 >> 4))); outStream.WriteByte((byte)((b2 << 4) | (b3 >> 2))); outStream.WriteByte((byte)((b3 << 6) | b4)); +#endif length += 3; @@ -304,8 +457,16 @@ private int DecodeLastBlock( if ((b1 | b2 | b3) >= 0x80) throw new IOException("invalid characters encountered at end of base64 data"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span buf = stackalloc byte[2] { + (byte)((b1 << 2) | (b2 >> 4)), + (byte)((b2 << 4) | (b3 >> 2)), + }; + outStream.Write(buf); +#else outStream.WriteByte((byte)((b1 << 2) | (b2 >> 4))); outStream.WriteByte((byte)((b2 << 4) | (b3 >> 2))); +#endif return 2; } @@ -319,9 +480,18 @@ private int DecodeLastBlock( if ((b1 | b2 | b3 | b4) >= 0x80) throw new IOException("invalid characters encountered at end of base64 data"); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span buf = stackalloc byte[3] { + (byte)((b1 << 2) | (b2 >> 4)), + (byte)((b2 << 4) | (b3 >> 2)), + (byte)((b3 << 6) | b4), + }; + outStream.Write(buf); +#else outStream.WriteByte((byte)((b1 << 2) | (b2 >> 4))); outStream.WriteByte((byte)((b2 << 4) | (b3 >> 2))); outStream.WriteByte((byte)((b3 << 6) | b4)); +#endif return 3; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/encoders/HexEncoder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/encoders/HexEncoder.cs index 0d63d0d..27c7bb2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/encoders/HexEncoder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/encoders/HexEncoder.cs @@ -1,5 +1,6 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable +using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto; using System; using System.IO; @@ -43,6 +44,9 @@ public HexEncoder() public int Encode(byte[] inBuf, int inOff, int inLen, byte[] outBuf, int outOff) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return Encode(inBuf.AsSpan(inOff, inLen), outBuf.AsSpan(outOff)); +#else int inPos = inOff; int inEnd = inOff + inLen; int outPos = outOff; @@ -56,8 +60,28 @@ public int Encode(byte[] inBuf, int inOff, int inLen, byte[] outBuf, int outOff) } return outPos - outOff; +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int Encode(ReadOnlySpan input, Span output) + { + int inPos = 0; + int inEnd = input.Length; + int outPos = 0; + + while (inPos < inEnd) + { + uint b = input[inPos++]; + + output[outPos++] = encodingTable[b >> 4]; + output[outPos++] = encodingTable[b & 0xF]; + } + + return outPos; + } +#endif + /** * encode the input data producing a Hex output stream. * @@ -65,6 +89,9 @@ public int Encode(byte[] inBuf, int inOff, int inLen, byte[] outBuf, int outOff) */ public int Encode(byte[] buf, int off, int len, Stream outStream) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return Encode(buf.AsSpan(off, len), outStream); +#else if (len < 0) return 0; @@ -79,8 +106,25 @@ public int Encode(byte[] buf, int off, int len, Stream outStream) remaining -= inLen; } return len * 2; +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int Encode(ReadOnlySpan data, Stream outStream) + { + Span tmp = stackalloc byte[72]; + int result = data.Length * 2; + while (!data.IsEmpty) + { + int inLen = System.Math.Min(36, data.Length); + int outLen = Encode(data[..inLen], tmp); + outStream.Write(tmp[..outLen]); + data = data[inLen..]; + } + return result; + } +#endif + private static bool Ignore(char c) { return c == '\n' || c =='\r' || c == '\t' || c == ' '; @@ -92,12 +136,11 @@ private static bool Ignore(char c) * * @return the number of bytes produced. */ - public int Decode( - byte[] data, - int off, - int length, - Stream outStream) + public int Decode(byte[] data, int off, int length, Stream outStream) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + return Decode(data.AsSpan(off, length), outStream); +#else byte b1, b2; int outLen = 0; byte[] buf = new byte[36]; @@ -149,21 +192,81 @@ public int Decode( } return outLen; +#endif } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public int Decode(ReadOnlySpan data, Stream outStream) + { + byte b1, b2; + int outLen = 0; + Span buf = stackalloc byte[36]; + int bufOff = 0; + int end = data.Length; + + while (end > 0) + { + if (!Ignore((char)data[end - 1])) + break; + + end--; + } + + int i = 0; + 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"); + + buf[bufOff++] = (byte)((b1 << 4) | b2); + + if (bufOff == buf.Length) + { + outStream.Write(buf); + bufOff = 0; + } + + outLen++; + } + + if (bufOff > 0) + { + outStream.Write(buf[..bufOff]); + } + + return outLen; + } +#endif + /** * 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) + public int DecodeString(string data, Stream outStream) { byte b1, b2; int length = 0; +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + Span buf = stackalloc byte[36]; +#else byte[] buf = new byte[36]; +#endif int bufOff = 0; int end = data.Length; @@ -199,7 +302,11 @@ public int DecodeString( if (bufOff == buf.Length) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + outStream.Write(buf); +#else outStream.Write(buf, 0, bufOff); +#endif bufOff = 0; } @@ -208,7 +315,11 @@ public int DecodeString( if (bufOff > 0) { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + outStream.Write(buf[..bufOff]); +#else outStream.Write(buf, 0, bufOff); +#endif } return length; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/encoders/IEncoder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/encoders/IEncoder.cs index 80fc0a5..e0a3783 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/encoders/IEncoder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/encoders/IEncoder.cs @@ -13,8 +13,16 @@ public interface IEncoder { int Encode(byte[] data, int off, int length, Stream outStream); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int Encode(ReadOnlySpan data, Stream outStream); +#endif + int Decode(byte[] data, int off, int length, Stream outStream); +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + int Decode(ReadOnlySpan data, Stream outStream); +#endif + int DecodeString(string data, Stream outStream); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BaseInputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BaseInputStream.cs index 024694f..709068a 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BaseInputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BaseInputStream.cs @@ -1,36 +1,17 @@ #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 + public abstract class BaseInputStream + : Stream { - private bool closed; - - public sealed override bool CanRead { get { return !closed; } } + public sealed override bool CanRead { get { return true; } } 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 @@ -41,27 +22,35 @@ public sealed override long Position public override int Read(byte[] buffer, int offset, int count) { - int pos = offset; + Streams.ValidateBufferArguments(buffer, offset, count); + + int pos = 0; try { - int end = offset + count; - while (pos < end) + while (pos < count) { int b = ReadByte(); - if (b == -1) break; - buffer[pos++] = (byte) b; + if (b < 0) + break; + + buffer[offset + pos++] = (byte)b; } } catch (IOException) { - if (pos == offset) throw; + if (pos == 0) + throw; } - return pos - offset; + return pos; } 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(); } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) { throw new NotSupportedException(); } +#endif } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BaseOutputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BaseOutputStream.cs index 5536de2..96e0b53 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BaseOutputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BaseOutputStream.cs @@ -1,37 +1,21 @@ #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 + public abstract class BaseOutputStream + : Stream { - private bool closed; - - public sealed override bool CanRead { get { return false; } } + public sealed override bool CanRead { get { return false; } } public sealed override bool CanSeek { get { return false; } } - public sealed override bool CanWrite { get { return !closed; } } + public sealed override bool CanWrite { get { return true; } } -#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(); - } +#if NETCOREAPP2_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER || (UNITY_2021_2_OR_NEWER && (NET_STANDARD_2_0 || NET_STANDARD_2_1)) + public override void CopyTo(Stream destination, int bufferSize) { throw new NotSupportedException(); } #endif - - public override void Flush() { } + public override void Flush() {} public sealed override long Length { get { throw new NotSupportedException(); } } public sealed override long Position { @@ -39,33 +23,25 @@ public sealed override long Position set { throw new NotSupportedException(); } } public sealed override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public sealed override int Read(Span buffer) { throw new NotSupportedException(); } +#endif 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); + Streams.ValidateBufferArguments(buffer, offset, count); - int end = offset + count; - - Debug.Assert(0 <= end && end <= buffer.Length); - - for (int i = offset; i < end; ++i) + for (int i = 0; i < count; ++i) { - this.WriteByte(buffer[i]); + WriteByte(buffer[offset + i]); } } - public virtual void Write(params byte[] buffer) - { - Write(buffer, 0, buffer.Length); - } - - public override void WriteByte(byte b) + public virtual void Write(params byte[] buffer) { - Write(new byte[]{ b }, 0, 1); + Write(buffer, 0, buffer.Length); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BinaryReaders.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BinaryReaders.cs new file mode 100644 index 0000000..7040d46 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BinaryReaders.cs @@ -0,0 +1,98 @@ +#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 static class BinaryReaders + { + public static byte[] ReadBytesFully(BinaryReader binaryReader, int count) + { + byte[] bytes = binaryReader.ReadBytes(count); + if (bytes == null || bytes.Length != count) + throw new EndOfStreamException(); + return bytes; + } + + public static short ReadInt16BigEndian(BinaryReader binaryReader) + { + short n = binaryReader.ReadInt16(); + return BitConverter.IsLittleEndian ? Shorts.ReverseBytes(n) : n; + } + + public static short ReadInt16LittleEndian(BinaryReader binaryReader) + { + short n = binaryReader.ReadInt16(); + return BitConverter.IsLittleEndian ? n : Shorts.ReverseBytes(n); + } + + public static int ReadInt32BigEndian(BinaryReader binaryReader) + { + int n = binaryReader.ReadInt32(); + return BitConverter.IsLittleEndian ? Integers.ReverseBytes(n) : n; + } + + public static int ReadInt32LittleEndian(BinaryReader binaryReader) + { + int n = binaryReader.ReadInt32(); + return BitConverter.IsLittleEndian ? n : Integers.ReverseBytes(n); + } + + public static long ReadInt64BigEndian(BinaryReader binaryReader) + { + long n = binaryReader.ReadInt64(); + return BitConverter.IsLittleEndian ? Longs.ReverseBytes(n) : n; + } + + public static long ReadInt64LittleEndian(BinaryReader binaryReader) + { + long n = binaryReader.ReadInt64(); + return BitConverter.IsLittleEndian ? n : Longs.ReverseBytes(n); + } + + [CLSCompliant(false)] + public static ushort ReadUInt16BigEndian(BinaryReader binaryReader) + { + ushort n = binaryReader.ReadUInt16(); + return BitConverter.IsLittleEndian ? Shorts.ReverseBytes(n) : n; + } + + [CLSCompliant(false)] + public static ushort ReadUInt16LittleEndian(BinaryReader binaryReader) + { + ushort n = binaryReader.ReadUInt16(); + return BitConverter.IsLittleEndian ? n : Shorts.ReverseBytes(n); + } + + [CLSCompliant(false)] + public static uint ReadUInt32BigEndian(BinaryReader binaryReader) + { + uint n = binaryReader.ReadUInt32(); + return BitConverter.IsLittleEndian ? Integers.ReverseBytes(n) : n; + } + + [CLSCompliant(false)] + public static uint ReadUInt32LittleEndian(BinaryReader binaryReader) + { + uint n = binaryReader.ReadUInt32(); + return BitConverter.IsLittleEndian ? n : Integers.ReverseBytes(n); + } + + [CLSCompliant(false)] + public static ulong ReadUInt64BigEndian(BinaryReader binaryReader) + { + ulong n = binaryReader.ReadUInt64(); + return BitConverter.IsLittleEndian ? Longs.ReverseBytes(n) : n; + } + + [CLSCompliant(false)] + public static ulong ReadUInt64LittleEndian(BinaryReader binaryReader) + { + ulong n = binaryReader.ReadUInt64(); + return BitConverter.IsLittleEndian ? n : Longs.ReverseBytes(n); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BinaryReaders.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BinaryReaders.cs.meta new file mode 100644 index 0000000..9c8bf81 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BinaryReaders.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 363e4c910179d7244a77ced662a52003 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BinaryWriters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BinaryWriters.cs new file mode 100644 index 0000000..fcd3bbc --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BinaryWriters.cs @@ -0,0 +1,90 @@ +#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 static class BinaryWriters + { + public static void WriteInt16BigEndian(BinaryWriter binaryWriter, short n) + { + short bigEndian = BitConverter.IsLittleEndian ? Shorts.ReverseBytes(n) : n; + binaryWriter.Write(bigEndian); + } + + public static void WriteInt16LittleEndian(BinaryWriter binaryWriter, short n) + { + short littleEndian = BitConverter.IsLittleEndian ? n : Shorts.ReverseBytes(n); + binaryWriter.Write(littleEndian); + } + + public static void WriteInt32BigEndian(BinaryWriter binaryWriter, int n) + { + int bigEndian = BitConverter.IsLittleEndian ? Integers.ReverseBytes(n) : n; + binaryWriter.Write(bigEndian); + } + + public static void WriteInt32LittleEndian(BinaryWriter binaryWriter, int n) + { + int littleEndian = BitConverter.IsLittleEndian ? n : Integers.ReverseBytes(n); + binaryWriter.Write(littleEndian); + } + + public static void WriteInt64BigEndian(BinaryWriter binaryWriter, long n) + { + long bigEndian = BitConverter.IsLittleEndian ? Longs.ReverseBytes(n) : n; + binaryWriter.Write(bigEndian); + } + + public static void WriteInt64LittleEndian(BinaryWriter binaryWriter, long n) + { + long littleEndian = BitConverter.IsLittleEndian ? n : Longs.ReverseBytes(n); + binaryWriter.Write(littleEndian); + } + + [CLSCompliant(false)] + public static void WriteUInt16BigEndian(BinaryWriter binaryWriter, ushort n) + { + ushort bigEndian = BitConverter.IsLittleEndian ? Shorts.ReverseBytes(n) : n; + binaryWriter.Write(bigEndian); + } + + [CLSCompliant(false)] + public static void WriteUInt16LittleEndian(BinaryWriter binaryWriter, ushort n) + { + ushort littleEndian = BitConverter.IsLittleEndian ? n : Shorts.ReverseBytes(n); + binaryWriter.Write(littleEndian); + } + + [CLSCompliant(false)] + public static void WriteUInt32BigEndian(BinaryWriter binaryWriter, uint n) + { + uint bigEndian = BitConverter.IsLittleEndian ? Integers.ReverseBytes(n) : n; + binaryWriter.Write(bigEndian); + } + + [CLSCompliant(false)] + public static void WriteUInt32LittleEndian(BinaryWriter binaryWriter, uint n) + { + uint littleEndian = BitConverter.IsLittleEndian ? n : Integers.ReverseBytes(n); + binaryWriter.Write(littleEndian); + } + + [CLSCompliant(false)] + public static void WriteUInt64BigEndian(BinaryWriter binaryWriter, ulong n) + { + ulong bigEndian = BitConverter.IsLittleEndian ? Longs.ReverseBytes(n) : n; + binaryWriter.Write(bigEndian); + } + + [CLSCompliant(false)] + public static void WriteUInt64LittleEndian(BinaryWriter binaryWriter, ulong n) + { + ulong littleEndian = BitConverter.IsLittleEndian ? n : Longs.ReverseBytes(n); + binaryWriter.Write(littleEndian); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BinaryWriters.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BinaryWriters.cs.meta new file mode 100644 index 0000000..20c8690 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/BinaryWriters.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7f41708fc94768343bede3d0cee338ba +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/FilterStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/FilterStream.cs index 4fe8486..658dc69 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/FilterStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/FilterStream.cs @@ -1,14 +1,18 @@ #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 class FilterStream : Stream + public class FilterStream + : Stream { + protected readonly Stream s; + public FilterStream(Stream s) { - this.s = s; + this.s = s ?? throw new ArgumentNullException(nameof(s)); } public override bool CanRead { @@ -22,6 +26,16 @@ public override bool CanWrite { get { return s.CanWrite; } } +#if NETCOREAPP2_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER || (UNITY_2021_2_OR_NEWER && (NET_STANDARD_2_0 || NET_STANDARD_2_1)) + public override void CopyTo(Stream destination, int bufferSize) + { + s.CopyTo(destination, bufferSize); + } +#endif + public override void Flush() + { + s.Flush(); + } public override long Length { get { return s.Length; } @@ -31,25 +45,19 @@ public override long Position get { return s.Position; } set { s.Position = value; } } -#if PORTABLE || NETFX_CORE - protected override void Dispose(bool disposing) + public override int Read(byte[] buffer, int offset, int count) { - if (disposing) - { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(s); - } - base.Dispose(disposing); + return s.Read(buffer, offset, count); } -#else - public override void Close() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int Read(Span buffer) { - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(s); - base.Close(); + return s.Read(buffer); } #endif - public override void Flush() + public override int ReadByte() { - s.Flush(); + return s.ReadByte(); } public override long Seek(long offset, SeekOrigin origin) { @@ -59,23 +67,33 @@ 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); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) + { + s.Write(buffer); + } +#endif public override void WriteByte(byte value) { s.WriteByte(value); } - protected readonly Stream s; + protected void Detach(bool disposing) + { + base.Dispose(disposing); + } + protected override void Dispose(bool disposing) + { + if (disposing) + { + s.Dispose(); + } + + base.Dispose(disposing); + } } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/LimitedInputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/LimitedInputStream.cs new file mode 100644 index 0000000..5359207 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/LimitedInputStream.cs @@ -0,0 +1,60 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Zlib; +using System; +using System.IO; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO +{ + internal class LimitedInputStream + : BaseInputStream + { + private readonly Stream m_stream; + private long m_limit; + + internal LimitedInputStream(Stream stream, long limit) + { + this.m_stream = stream; + this.m_limit = limit; + } + + internal long CurrentLimit => m_limit; + + public override int Read(byte[] buffer, int offset, int count) + { + int numRead = m_stream.Read(buffer, offset, count); + if (numRead > 0) + { + if ((m_limit -= numRead) < 0) + throw new StreamOverflowException("Data Overflow"); + } + return numRead; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int Read(Span buffer) + { + int numRead = m_stream.Read(buffer); + if (numRead > 0) + { + if ((m_limit -= numRead) < 0) + throw new StreamOverflowException("Data Overflow"); + } + return numRead; + } +#endif + + public override int ReadByte() + { + int b = m_stream.ReadByte(); + if (b >= 0) + { + if (--m_limit < 0) + throw new StreamOverflowException("Data Overflow"); + } + return b; + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/LimitedInputStream.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/LimitedInputStream.cs.meta new file mode 100644 index 0000000..b14b954 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/LimitedInputStream.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 51e6e462295cfec4893c651eb750729f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/PushbackStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/PushbackStream.cs index 85b666b..571228b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/PushbackStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/PushbackStream.cs @@ -3,52 +3,83 @@ 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; + private int m_buf = -1; - public PushbackStream( - Stream s) + public PushbackStream(Stream s) : base(s) { } - public override int ReadByte() +#if NETCOREAPP2_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER || (UNITY_2021_2_OR_NEWER && (NET_STANDARD_2_0 || NET_STANDARD_2_1)) + public override void CopyTo(Stream destination, int bufferSize) + { + if (m_buf != -1) + { + destination.WriteByte((byte)m_buf); + m_buf = -1; + } + + s.CopyTo(destination, bufferSize); + } +#endif + + public override int Read(byte[] buffer, int offset, int count) { - if (buf != -1) + Streams.ValidateBufferArguments(buffer, offset, count); + + if (m_buf != -1) { - int tmp = buf; - buf = -1; - return tmp; + if (count < 1) + return 0; + + buffer[offset] = (byte)m_buf; + m_buf = -1; + return 1; } - return base.ReadByte(); + return s.Read(buffer, offset, count); } - public override int Read(byte[] buffer, int offset, int count) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int Read(Span buffer) + { + if (m_buf != -1) + { + if (buffer.IsEmpty) + return 0; + + buffer[0] = (byte)m_buf; + m_buf = -1; + return 1; + } + + return s.Read(buffer); + } +#endif + + public override int ReadByte() { - if (buf != -1 && count > 0) + if (m_buf != -1) { - // TODO Can this case be made more efficient? - buffer[offset] = (byte) buf; - buf = -1; - return 1; + int tmp = m_buf; + m_buf = -1; + return tmp; } - return base.Read(buffer, offset, count); + return base.ReadByte(); } public virtual void Unread(int b) { - if (buf != -1) + if (m_buf != -1) throw new InvalidOperationException("Can only push back one byte"); - buf = b & 0xFF; + m_buf = b & 0xFF; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/StreamOverflowException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/StreamOverflowException.cs index 97218c1..074f7af 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/StreamOverflowException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/StreamOverflowException.cs @@ -2,12 +2,11 @@ #pragma warning disable using System; using System.IO; +using System.Runtime.Serialization; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO { -#if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || PORTABLE || NETFX_CORE) [Serializable] -#endif public class StreamOverflowException : IOException { @@ -16,16 +15,18 @@ public StreamOverflowException() { } - public StreamOverflowException( - string message) + public StreamOverflowException(string message) : base(message) { } - public StreamOverflowException( - string message, - Exception exception) - : base(message, exception) + public StreamOverflowException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected StreamOverflowException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/Streams.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/Streams.cs index d694abc..4205534 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/Streams.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/Streams.cs @@ -5,52 +5,13 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO { - public sealed class Streams + public static class Streams { private const int BufferSize = 4096; - 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; + inStr.CopyTo(Stream.Null, BufferSize); } /// Write the full contents of inStr to the destination stream outStr. @@ -59,7 +20,7 @@ public static int ReadFully(Stream inStr, byte[] buf, int off, int len) /// In case of IO failure. public static void PipeAll(Stream inStr, Stream outStr) { - PipeAll(inStr, outStr, BufferSize); + inStr.CopyTo(outStr, BufferSize); } /// Write the full contents of inStr to the destination stream outStr. @@ -69,12 +30,7 @@ public static void PipeAll(Stream inStr, Stream outStr) /// In case of IO failure. public static void PipeAll(Stream inStr, Stream outStr, int bufferSize) { - byte[] bs = new byte[bufferSize]; - int numRead; - while ((numRead = inStr.Read(bs, 0, bs.Length)) > 0) - { - outStr.Write(bs, 0, numRead); - } + inStr.CopyTo(outStr, bufferSize); } /// @@ -94,42 +50,89 @@ public static void PipeAll(Stream inStr, Stream outStr, int bufferSize) /// 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) + var limited = new LimitedInputStream(inStr, limit); + limited.CopyTo(outStr, BufferSize); + return limit - limited.CurrentLimit; + } + + public static byte[] ReadAll(Stream inStr) + { + MemoryStream buf = new MemoryStream(); + PipeAll(inStr, buf); + return buf.ToArray(); + } + + public static byte[] ReadAll(MemoryStream inStr) + { + return inStr.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) { - if ((limit - total) < numRead) - throw new StreamOverflowException("Data Overflow"); - total += numRead; - outStr.Write(bs, 0, numRead); + int numRead = inStr.Read(buf, off + totalRead, len - totalRead); + if (numRead < 1) + break; + totalRead += numRead; } - return total; + return totalRead; } - /// - public static void WriteBufTo(MemoryStream buf, Stream output) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public static int ReadFully(Stream inStr, Span buffer) { - buf.WriteTo(output); + int totalRead = 0; + while (totalRead < buffer.Length) + { + int numRead = inStr.Read(buffer[totalRead..]); + if (numRead < 1) + break; + totalRead += numRead; + } + return totalRead; } +#endif - /// - public static int WriteBufTo(MemoryStream buf, byte[] output, int offset) + public static void ValidateBufferArguments(byte[] buffer, int offset, int count) { - int size = (int)buf.Length; - WriteBufTo(buf, new MemoryStream(output, offset, size)); - return size; - } + if (buffer == null) + throw new ArgumentNullException("buffer"); + int available = buffer.Length - offset; + if ((offset | available) < 0) + throw new ArgumentOutOfRangeException("offset"); + int remaining = available - count; + if ((count | remaining) < 0) + throw new ArgumentOutOfRangeException("count"); + } - public static void WriteZeroes(Stream outStr, long count) + /// + public static int WriteBufTo(MemoryStream buf, byte[] output, int offset) { - byte[] zeroes = new byte[BufferSize]; - while (count > BufferSize) +#if NETCOREAPP2_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER || UNITY_2021_2_OR_NEWER + if (buf.TryGetBuffer(out var buffer)) { - outStr.Write(zeroes, 0, BufferSize); - count -= BufferSize; + buffer.CopyTo(output, offset); + return buffer.Count; } - outStr.Write(zeroes, 0, (int)count); +#endif + + int size = Convert.ToInt32(buf.Length); + buf.WriteTo(new MemoryStream(output, offset, size)); + return size; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/TeeInputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/TeeInputStream.cs index 1f0d169..599b956 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/TeeInputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/TeeInputStream.cs @@ -20,38 +20,43 @@ public TeeInputStream(Stream input, Stream tee) 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); + input.Dispose(); + tee.Dispose(); } 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) + public override int Read(byte[] buffer, int offset, int count) { - int i = input.Read(buf, off, len); + int i = input.Read(buffer, offset, count); if (i > 0) { - tee.Write(buf, off, i); + tee.Write(buffer, offset, i); } return i; } - public override int ReadByte() +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override int Read(Span buffer) + { + int i = input.Read(buffer); + + if (i > 0) + { + tee.Write(buffer[..i]); + } + + return i; + } +#endif + + public override int ReadByte() { int i = input.ReadByte(); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/TeeOutputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/TeeOutputStream.cs index c19eb28..3962c84 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/TeeOutputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/TeeOutputStream.cs @@ -20,24 +20,15 @@ public TeeOutputStream(Stream output, Stream tee) 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); + output.Dispose(); + tee.Dispose(); } 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) { @@ -45,10 +36,18 @@ public override void Write(byte[] buffer, int offset, int count) tee.Write(buffer, offset, count); } - public override void WriteByte(byte b) +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER || _UNITY_2021_2_OR_NEWER_ + public override void Write(ReadOnlySpan buffer) + { + output.Write(buffer); + tee.Write(buffer); + } +#endif + + public override void WriteByte(byte value) { - output.WriteByte(b); - tee.WriteByte(b); + output.WriteByte(value); + tee.WriteByte(value); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression.meta new file mode 100644 index 0000000..f96feb4 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5722b9b60bf804d4cb4e3a0bd11b29a0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression/Bzip2.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression/Bzip2.cs new file mode 100644 index 0000000..003b92a --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression/Bzip2.cs @@ -0,0 +1,25 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System.IO; + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Compression +{ + using Impl = Utilities.Bzip2; + + internal static class Bzip2 + { + internal static Stream CompressOutput(Stream stream, bool leaveOpen = false) + { + return leaveOpen + ? new Impl.CBZip2OutputStreamLeaveOpen(stream) + : new Impl.CBZip2OutputStream(stream); + } + + internal static Stream DecompressInput(Stream stream) + { + return new Impl.CBZip2InputStream(stream); + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression/Bzip2.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression/Bzip2.cs.meta new file mode 100644 index 0000000..7a924fb --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression/Bzip2.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 432a2f67bb53c314e9868625567e180e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression/ZLib.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression/ZLib.cs new file mode 100644 index 0000000..dc4262c --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression/ZLib.cs @@ -0,0 +1,50 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System.IO; + +#if NET6_0_OR_GREATER +using System.IO.Compression; +#else +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Zlib; +#endif + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Compression +{ + internal static class ZLib + { + internal static Stream CompressOutput(Stream stream, int zlibCompressionLevel, bool leaveOpen = false) + { +#if NET6_0_OR_GREATER + return new ZLibStream(stream, GetCompressionLevel(zlibCompressionLevel), leaveOpen); +#else + return leaveOpen + ? new ZOutputStreamLeaveOpen(stream, zlibCompressionLevel, false) + : new ZOutputStream(stream, zlibCompressionLevel, false); +#endif + } + + internal static Stream DecompressInput(Stream stream) + { +#if NET6_0_OR_GREATER + return new ZLibStream(stream, CompressionMode.Decompress, leaveOpen: false); +#else + return new ZInputStream(stream); +#endif + } + +#if NET6_0_OR_GREATER + internal static CompressionLevel GetCompressionLevel(int zlibCompressionLevel) + { + return zlibCompressionLevel switch + { + 0 => CompressionLevel.NoCompression, + 1 or 2 or 3 => CompressionLevel.Fastest, + 7 or 8 or 9 => CompressionLevel.SmallestSize, + _ => CompressionLevel.Optimal, + }; + } +#endif + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression/ZLib.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression/ZLib.cs.meta new file mode 100644 index 0000000..3f0846c --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression/ZLib.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2cef2db8934718a42b4eb5995cd362b2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression/Zip.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression/Zip.cs new file mode 100644 index 0000000..4219452 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression/Zip.cs @@ -0,0 +1,37 @@ +#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) +#pragma warning disable +using System.IO; + +#if NET6_0_OR_GREATER +using System.IO.Compression; +#else +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Zlib; +#endif + +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Compression +{ + internal static class Zip + { + internal static Stream CompressOutput(Stream stream, int zlibCompressionLevel, bool leaveOpen = false) + { +#if NET6_0_OR_GREATER + return new DeflateStream(stream, ZLib.GetCompressionLevel(zlibCompressionLevel), leaveOpen); +#else + return leaveOpen + ? new ZOutputStreamLeaveOpen(stream, zlibCompressionLevel, true) + : new ZOutputStream(stream, zlibCompressionLevel, true); +#endif + } + + internal static Stream DecompressInput(Stream stream) + { +#if NET6_0_OR_GREATER + return new DeflateStream(stream, CompressionMode.Decompress, leaveOpen: false); +#else + return new ZInputStream(stream, true); +#endif + } + } +} +#pragma warning restore +#endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression/Zip.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression/Zip.cs.meta new file mode 100644 index 0000000..29903e7 --- /dev/null +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/compression/Zip.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b165e8b3c4017df44b2805807d06513f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemGenerationException.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemGenerationException.cs index aac38dc..f61aca6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemGenerationException.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemGenerationException.cs @@ -1,12 +1,11 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Runtime.Serialization; 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 { @@ -15,16 +14,18 @@ public PemGenerationException() { } - public PemGenerationException( - string message) + public PemGenerationException(string message) : base(message) { } - public PemGenerationException( - string message, - Exception exception) - : base(message, exception) + public PemGenerationException(string message, Exception innerException) + : base(message, innerException) + { + } + + protected PemGenerationException(SerializationInfo info, StreamingContext context) + : base(info, context) { } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemHeader.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemHeader.cs index cd542a3..62df2eb 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemHeader.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemHeader.cs @@ -40,8 +40,8 @@ public override bool Equals(object obj) 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); + return Org.BouncyCastle.Utilities.Platform.Equals(this.name, other.name) + && Org.BouncyCastle.Utilities.Platform.Equals(this.val, other.val); } private int GetHashCode(string s) diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemObject.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemObject.cs index 5d7b1dc..c4da1a5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemObject.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemObject.cs @@ -1,28 +1,26 @@ #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 System.Collections.Generic; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Pem { public class PemObject : PemObjectGenerator { - private string type; - private IList headers; - private byte[] content; + 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) + : this(type, new List(), content) { } - public PemObject(String type, IList headers, byte[] content) + public PemObject(string type, IList headers, byte[] content) { this.type = type; - this.headers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(headers); + this.headers = new List(headers); this.content = content; } @@ -31,7 +29,7 @@ public string Type get { return type; } } - public IList Headers + public IList Headers { get { return headers; } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemObjectParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemObjectParser.cs index ab465a4..48ba570 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemObjectParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemObjectParser.cs @@ -11,7 +11,7 @@ public interface PemObjectParser /// A /// /// - /// A + /// An /// /// object ParseObject(PemObject obj); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemReader.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemReader.cs index f0b792d..48a2b2f 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemReader.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemReader.cs @@ -1,38 +1,48 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; - using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Pem { - public class PemReader + : IDisposable { private readonly TextReader reader; private readonly MemoryStream buffer; private readonly StreamWriter textBuffer; - private readonly IList pushback = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + private readonly List pushback = new List(); int c = 0; - - public PemReader(TextReader reader) { - if (reader == null) - throw new ArgumentNullException("reader"); + this.reader = reader ?? throw new ArgumentNullException(nameof(reader)); + this.buffer = new MemoryStream(); + this.textBuffer = new StreamWriter(buffer); + } + #region IDisposable - buffer = new MemoryStream(); - textBuffer = new StreamWriter(buffer); + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } - this.reader = reader; - } + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + reader.Dispose(); + } + } + + #endregion - public TextReader Reader + public TextReader Reader { get { return reader; } } @@ -49,7 +59,7 @@ public PemObject ReadPemObject() // Look for BEGIN // - for (; ; ) + for (;;) { // Seek a leading dash, ignore anything up to that point. @@ -109,7 +119,7 @@ public PemObject ReadPemObject() // Look for a colon for up to 64 characters, as an indication there might be a header. // - IList headers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var headers = new List(); while (seekColon(64)) { @@ -229,7 +239,7 @@ private bool seekColon(int upTo) { c = 0; bool colonFound = false; - IList read = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var read = new List(); for (; upTo>=0 && c >=0; upTo--) { @@ -294,7 +304,7 @@ private void skipWhiteSpace() /// expected string /// false if not consumed - private bool expect(String value) + private bool expect(string value) { for (int t=0; t /// Consume until dash. @@ -340,8 +349,6 @@ private bool bufferUntilStopChar(char stopChar, bool skipWhiteSpace) return c > -1; } - - private void PushBack(int value) { if (pushback.Count == 0) @@ -353,22 +360,17 @@ private void PushBack(int value) } } - private int Read() { - if (pushback.Count>0) + if (pushback.Count > 0) { - int i = (int)pushback[0]; + int i = pushback[0]; pushback.RemoveAt(0); return i; } return reader.Read(); } - - - - } } #pragma warning restore diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemWriter.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemWriter.cs index 7074a04..365afe1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemWriter.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/io/pem/PemWriter.cs @@ -1,7 +1,6 @@ #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; @@ -12,13 +11,14 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.IO.Pem * A generic PEM writer, based on RFC 1421 */ public class PemWriter + : IDisposable { private const int LineLength = 64; private readonly TextWriter writer; private readonly int nlLength; private char[] buf = new char[LineLength]; - + /** * Base constructor. * @@ -26,14 +26,29 @@ public class PemWriter */ public PemWriter(TextWriter writer) { - if (writer == null) - throw new ArgumentNullException("writer"); - - this.writer = writer; - this.nlLength = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.NewLine.Length; + this.writer = writer ?? throw new ArgumentNullException(nameof(writer)); + this.nlLength = Environment.NewLine.Length; } - public TextWriter Writer + #region IDisposable + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + writer.Dispose(); + } + } + + #endregion + + public TextWriter Writer { get { return writer; } } @@ -118,7 +133,7 @@ private void WritePostEncapsulationBoundary(string type) { writer.WriteLine("-----END " + type + "-----"); } - } + } } #pragma warning restore #endif diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/net/IPAddress.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/net/IPAddress.cs index e5a501c..58f62c1 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/net/IPAddress.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/net/IPAddress.cs @@ -72,7 +72,7 @@ private static bool unsafeIsValidIPv4( return false; string octetStr = temp.Substring(start, pos - start); - int octet = Int32.Parse(octetStr); + int octet = int.Parse(octetStr); if (octet < 0 || octet > 255) return false; @@ -108,7 +108,7 @@ private static bool IsMaskValue( string component, int size) { - int val = Int32.Parse(component); + int val = int.Parse(component); try { return val >= 0 && val <= size; @@ -175,7 +175,7 @@ private static bool unsafeIsValidIPv6( else { string octetStr = temp.Substring(start, pos - start); - int octet = Int32.Parse(octetStr, NumberStyles.AllowHexSpecifier); + int octet = int.Parse(octetStr, NumberStyles.AllowHexSpecifier); if (octet < 0 || octet > 0xffff) return false; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/Deflate.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/Deflate.cs index 63e8138..26c486d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/Deflate.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/Deflate.cs @@ -84,7 +84,7 @@ static Deflate(){ config_table[9]=new Config(32, 258, 258, 4096, SLOW); } - private static readonly String[] z_errmsg = { + private static readonly string[] z_errmsg = { "need dictionary", // Z_NEED_DICT 2 "stream end", // Z_STREAM_END 1 "", // Z_OK 0 @@ -260,9 +260,9 @@ static Deflate(){ 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 + internal Tree l_desc=new Tree(); // desc for literal tree + internal Tree d_desc=new Tree(); // desc for distance tree + internal Tree bl_desc=new Tree(); // 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]; @@ -477,7 +477,7 @@ internal int build_bl_tree(){ // requires that at least 4 bit length codes be sent. (appnote.txt says // 3 but the actual value used is 4.) for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { - if (bl_tree[ZTree.bl_order[max_blindex]*2+1] != 0) break; + if (bl_tree[Tree.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; @@ -496,7 +496,7 @@ internal void send_all_trees(int lcodes, int dcodes, int blcodes){ 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_bits(bl_tree[Tree.bl_order[rank]*2+1], 3); } send_tree(dyn_ltree, lcodes-1); // literal tree send_tree(dyn_dtree, dcodes-1); // distance tree @@ -650,8 +650,8 @@ internal bool _tr_tally (int dist, // distance of matched string 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]++; + dyn_ltree[(Tree._length_code[lc]+LITERALS+1)*2]++; + dyn_dtree[Tree.d_code(dist)*2]++; } if ((last_lit & 0x1fff) == 0 && level > 2) { @@ -661,7 +661,7 @@ internal bool _tr_tally (int dist, // distance of matched string int dcode; for (dcode = 0; dcode < D_CODES; dcode++) { out_length += (int)((int)dyn_dtree[dcode*2] * - (5L+ZTree.extra_dbits[dcode])); + (5L+Tree.extra_dbits[dcode])); } out_length >>= 3; if ((matches < (last_lit/2)) && out_length < in_length/2) return true; @@ -692,21 +692,21 @@ internal void compress_block(short[] ltree, short[] dtree){ } else{ // Here, lc is the match length - MIN_MATCH - code = ZTree._length_code[lc]; + code = Tree._length_code[lc]; send_code(code+LITERALS+1, ltree); // send the length code - extra = ZTree.extra_lbits[code]; + extra = Tree.extra_lbits[code]; if(extra != 0){ - lc -= ZTree.base_length[code]; + lc -= Tree.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); + code = Tree.d_code(dist); send_code(code, dtree); // send the distance code - extra = ZTree.extra_dbits[code]; + extra = Tree.extra_dbits[code]; if (extra != 0) { - dist -= ZTree.base_dist[code]; + dist -= Tree.base_dist[code]; send_bits(dist, extra); // send the extra distance bits } } // literal or match pair ? diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/InfBlocks.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/InfBlocks.cs index e8de203..97c4db6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/InfBlocks.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/InfBlocks.cs @@ -97,12 +97,12 @@ internal sealed class InfBlocks{ 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 object checkfn; // check function internal long check; // check on output internal InfTree inftree=new InfTree(); - internal InfBlocks(ZStream z, Object checkfn, int w){ + internal InfBlocks(ZStream z, object checkfn, int w){ hufts=new int[MANY*3]; window=new byte[w]; end=w; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/JZlib.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/JZlib.cs index f387698..23cdea9 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/JZlib.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/JZlib.cs @@ -36,11 +36,12 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * and contributors of zlib. */ -namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Zlib { - - public sealed class JZlib{ - private const String _version="1.0.7"; - public static String version() +namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Zlib +{ + public sealed class JZlib + { + private const string _version="1.0.7"; + public static string version() { return _version; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/StaticTree.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/StaticTree.cs index 3170e0f..d47a0b4 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/StaticTree.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/StaticTree.cs @@ -121,15 +121,15 @@ internal sealed class StaticTree{ }; internal static readonly StaticTree static_l_desc = - new StaticTree(static_ltree, ZTree.extra_lbits, + new StaticTree(static_ltree, Tree.extra_lbits, LITERALS+1, L_CODES, MAX_BITS); internal static readonly StaticTree static_d_desc = - new StaticTree(static_dtree, ZTree.extra_dbits, + new StaticTree(static_dtree, Tree.extra_dbits, 0, D_CODES, MAX_BITS); internal static readonly StaticTree static_bl_desc = - new StaticTree(null, ZTree.extra_blbits, + new StaticTree(null, Tree.extra_blbits, 0, BL_CODES, MAX_BL_BITS); internal short[] static_tree; // static tree or null diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZDeflaterOutputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZDeflaterOutputStream.cs index 4e09c48..0454b34 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZDeflaterOutputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZDeflaterOutputStream.cs @@ -1,175 +1,3 @@ #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. - /// - - 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/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZDeflaterOutputStream.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZDeflaterOutputStream.cs.meta index 7fdbca2..ef144a5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZDeflaterOutputStream.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZDeflaterOutputStream.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 1235cf9b25f415a43af3b5e12ebb8a8d +guid: ad559b772c7a9cb4ca4176fb6ae72d82 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZInflaterInputStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZInflaterInputStream.cs index d39be2a..0454b34 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZInflaterInputStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZInflaterInputStream.cs @@ -1,144 +1,3 @@ #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. - /// - - 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) { - // Ignore + output.Write(buf, 0, count); } } - finally + 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 virtual long TotalIn + { + get { return z.total_in; } + } + + public virtual long TotalOut + { + get { return z.total_out; } + } + + public override void Write(byte[] buffer, int offset, int count) + { + Streams.ValidateBufferArguments(buffer, offset, count); + + if (count == 0) + return; + + z.next_in = buffer; + z.next_in_index = offset; + z.avail_in = count; + + do { - this.closed = true; - End(); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(output); - output = null; + 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 virtual void End() - { - if (z == null) - return; - if (compress) - z.deflateEnd(); - else - z.inflateEnd(); - z.free(); - z = null; - } - - public virtual void Finish() - { - do - { - z.next_out = buf; - z.next_out_index = 0; - z.avail_out = buf.Length; - - int err = compress - ? z.deflate(JZlib.Z_FINISH) - : z.inflate(JZlib.Z_FINISH); - - if (err != JZlib.Z_STREAM_END && err != JZlib.Z_OK) - // TODO -// throw new ZStreamException((compress?"de":"in")+"flating: "+z.msg); - throw new IOException((compress ? "de" : "in") + "flating: " + z.msg); - - int count = buf.Length - z.avail_out; - if (count > 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 + public override void WriteByte(byte value) + { + buf1[0] = value; + Write(buf1, 0, 1); + } + } + + public class ZOutputStreamLeaveOpen + : ZOutputStream + { + public ZOutputStreamLeaveOpen(Stream output) + : base(output) + { + } + + public ZOutputStreamLeaveOpen(Stream output, bool nowrap) + : base(output, nowrap) + { + } + + public ZOutputStreamLeaveOpen(Stream output, ZStream z) + : base(output, z) + { + } + + public ZOutputStreamLeaveOpen(Stream output, int level) + : base(output, level) + { + } + + public ZOutputStreamLeaveOpen(Stream output, int level, bool nowrap) + : base(output, level, nowrap) + { + } + + protected override void Dispose(bool disposing) { - get { throw new NotSupportedException(); } - set { throw new NotSupportedException(); } + Detach(disposing); } - 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/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZStream.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZStream.cs index ea4c53e..2eded6b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZStream.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZStream.cs @@ -71,7 +71,7 @@ public sealed class ZStream{ public int avail_out; // remaining free space at next_out public long total_out; // total nb of bytes output so far - public String msg; + public string msg; internal Deflate dstate; internal Inflate istate; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZTree.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZTree.cs index 068f027..bd12319 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZTree.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZTree.cs @@ -38,7 +38,7 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Zlib { - internal sealed class ZTree{ + internal sealed class Tree{ private const int MAX_BITS=15; private const int BL_CODES=19; private const int D_CODES=30; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZTree.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZTree.cs.meta index 592f74a..5899c95 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZTree.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/util/zlib/ZTree.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: d2dd18c0bd8312245a55bc7cbe90b8b8 +guid: 834fa3fb1cac3254fb41c39d4f5b2957 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/AttributeCertificateHolder.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/AttributeCertificateHolder.cs index ba1cd3d..3305b90 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/AttributeCertificateHolder.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/AttributeCertificateHolder.cs @@ -1,7 +1,6 @@ #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; @@ -10,7 +9,7 @@ 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; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509 { @@ -31,7 +30,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509 /// public class AttributeCertificateHolder //: CertSelector, Selector - : IX509Selector + : ISelector { internal readonly Holder holder; @@ -328,9 +327,11 @@ public object Clone() return new AttributeCertificateHolder((Asn1Sequence)holder.ToAsn1Object()); } - public bool Match( - X509Certificate x509Cert) + public bool Match(X509Certificate x509Cert) { + if (x509Cert == null) + return false; + try { if (holder.BaseCertificateID != null) @@ -420,18 +421,6 @@ 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 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/AttributeCertificateIssuer.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/AttributeCertificateIssuer.cs index 8a53b0f..ffb1e40 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/AttributeCertificateIssuer.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/AttributeCertificateIssuer.cs @@ -1,13 +1,10 @@ #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; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509 { @@ -16,7 +13,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509 */ public class AttributeCertificateIssuer //: CertSelector, Selector - : IX509Selector + : ISelector { internal readonly Asn1Encodable form; @@ -137,9 +134,11 @@ public object Clone() return new AttributeCertificateIssuer(AttCertIssuer.GetInstance(form)); } - public bool Match( - X509Certificate x509Cert) + public bool Match(X509Certificate x509Cert) { + if (x509Cert == null) + return false; + if (form is V2Form) { V2Form issuer = (V2Form) form; @@ -177,18 +176,6 @@ 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 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/IX509Extension.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/IX509Extension.cs index 260391d..a55a0c0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/IX509Extension.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/IX509Extension.cs @@ -1,9 +1,9 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509 { @@ -13,16 +13,13 @@ public interface IX509Extension /// Get all critical extension values, by oid /// /// IDictionary with string (OID) keys and Asn1OctetString values - ISet GetCriticalExtensionOids(); + ISet GetCriticalExtensionOids(); /// /// Get all non-critical extension values, by oid /// /// IDictionary with string (OID) keys and Asn1OctetString values - ISet GetNonCriticalExtensionOids(); - - - Asn1OctetString GetExtensionValue(string oid); + ISet GetNonCriticalExtensionOids(); Asn1OctetString GetExtensionValue(DerObjectIdentifier oid); } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/PEMParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/PEMParser.cs index 7d41b69..493a5da 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/PEMParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/PEMParser.cs @@ -62,7 +62,7 @@ internal Asn1Sequence ReadPemObject( while ((line = ReadLine(inStream)) != null) { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(line, _header1) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(line, _header2)) + if (Org.BouncyCastle.Utilities.Platform.StartsWith(line, _header1) || Org.BouncyCastle.Utilities.Platform.StartsWith(line, _header2)) { break; } @@ -70,7 +70,7 @@ internal Asn1Sequence ReadPemObject( while ((line = ReadLine(inStream)) != null) { - if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(line, _footer1) || BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.StartsWith(line, _footer2)) + if (Org.BouncyCastle.Utilities.Platform.StartsWith(line, _footer1) || Org.BouncyCastle.Utilities.Platform.StartsWith(line, _footer2)) { break; } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/SubjectPublicKeyInfoFactory.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/SubjectPublicKeyInfoFactory.cs index 2e515d3..21be1ff 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/SubjectPublicKeyInfoFactory.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/SubjectPublicKeyInfoFactory.cs @@ -2,7 +2,6 @@ #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; @@ -12,22 +11,18 @@ 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.Math.EC; using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities; -using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Encoders; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509 { /// /// A factory to produce Public Key Info Objects. /// - public sealed class SubjectPublicKeyInfoFactory + public static class SubjectPublicKeyInfoFactory { - private SubjectPublicKeyInfoFactory() - { - } - /// /// Create a Subject Public Key Info object for a given public key. /// @@ -146,7 +141,7 @@ public static SubjectPublicKeyInfo CreateSubjectPublicKeyInfo( if (_key.AlgorithmName == "ECGOST3410") { if (_key.PublicKeyParamSet == null) - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); + throw new NotImplementedException("Not a CryptoPro parameter set"); ECPoint q = _key.Q.Normalize(); BigInteger bX = q.AffineXCoord.ToBigInteger(); @@ -171,7 +166,8 @@ public static SubjectPublicKeyInfo CreateSubjectPublicKeyInfo( if (_key.PublicKeyParamSet == null) { ECDomainParameters kp = _key.Parameters; - X9ECParameters ecP = new X9ECParameters(kp.Curve, kp.G, kp.N, kp.H, kp.GetSeed()); + X9ECParameters ecP = new X9ECParameters(kp.Curve, new X9ECPoint(kp.G, false), kp.N, kp.H, + kp.GetSeed()); x962 = new X962Parameters(ecP); } @@ -194,7 +190,7 @@ public static SubjectPublicKeyInfo CreateSubjectPublicKeyInfo( Gost3410PublicKeyParameters _key = (Gost3410PublicKeyParameters) publicKey; if (_key.PublicKeyParamSet == null) - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("Not a CryptoPro parameter set"); + throw new NotImplementedException("Not a CryptoPro parameter set"); byte[] keyEnc = _key.Y.ToByteArrayUnsigned(); byte[] keyBytes = new byte[keyEnc.Length]; @@ -242,7 +238,7 @@ public static SubjectPublicKeyInfo CreateSubjectPublicKeyInfo( 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)); + throw new ArgumentException("Class provided no convertible: " + Org.BouncyCastle.Utilities.Platform.GetTypeName(publicKey)); } private static void ExtractBytes( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509AttrCertParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509AttrCertParser.cs index 380789f..2517cca 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509AttrCertParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509AttrCertParser.cs @@ -1,14 +1,13 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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 @@ -21,7 +20,7 @@ public class X509AttrCertParser private int sDataObjectCount; private Stream currentStream; - private IX509AttributeCertificate ReadDerCertificate( + private X509V2AttributeCertificate ReadDerCertificate( Asn1InputStream dIn) { Asn1Sequence seq = (Asn1Sequence)dIn.ReadObject(); @@ -37,25 +36,21 @@ private IX509AttributeCertificate ReadDerCertificate( } } -// return new X509V2AttributeCertificate(seq.getEncoded()); return new X509V2AttributeCertificate(AttributeCertificate.GetInstance(seq)); } - private IX509AttributeCertificate GetCertificate() + private X509V2AttributeCertificate GetCertificate() { if (sData != null) { while (sDataObjectCount < sData.Count) { - object obj = sData[sDataObjectCount++]; + Asn1Encodable ae = sData[sDataObjectCount++]; - if (obj is Asn1TaggedObject && ((Asn1TaggedObject)obj).TagNo == 2) + if (ae.ToAsn1Object() is Asn1TaggedObject t && t.TagNo == 2) { - //return new X509V2AttributeCertificate( - // Asn1Sequence.GetInstance((Asn1TaggedObject)obj, false).GetEncoded()); return new X509V2AttributeCertificate( - AttributeCertificate.GetInstance( - Asn1Sequence.GetInstance((Asn1TaggedObject)obj, false))); + AttributeCertificate.GetInstance(Asn1Sequence.GetInstance(t, false))); } } } @@ -63,14 +58,13 @@ private IX509AttributeCertificate GetCertificate() return null; } - private IX509AttributeCertificate ReadPemCertificate( + private X509V2AttributeCertificate ReadPemCertificate( Stream inStream) { Asn1Sequence seq = PemAttrCertParser.ReadPemObject(inStream); return seq == null ? null - //: new X509V2AttributeCertificate(seq.getEncoded()); : new X509V2AttributeCertificate(AttributeCertificate.GetInstance(seq)); } @@ -78,8 +72,7 @@ private IX509AttributeCertificate ReadPemCertificate( /// Create loading data from byte array. /// /// - public IX509AttributeCertificate ReadAttrCert( - byte[] input) + public X509V2AttributeCertificate ReadAttrCert(byte[] input) { return ReadAttrCert(new MemoryStream(input, false)); } @@ -88,8 +81,7 @@ public IX509AttributeCertificate ReadAttrCert( /// Create loading data from byte array. /// /// - public ICollection ReadAttrCerts( - byte[] input) + public IList ReadAttrCerts(byte[] input) { return ReadAttrCerts(new MemoryStream(input, false)); } @@ -98,7 +90,7 @@ public ICollection ReadAttrCerts( * Generates a certificate object and initializes it with the data * read from the input stream inStream. */ - public IX509AttributeCertificate ReadAttrCert( + public X509V2AttributeCertificate ReadAttrCert( Stream inStream) { if (inStream == null) @@ -133,20 +125,27 @@ public IX509AttributeCertificate ReadAttrCert( 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. + int tag = inStream.ReadByte(); + if (tag < 0) + return null; + + if (inStream.CanSeek) + { + inStream.Seek(-1L, SeekOrigin.Current); + } + else + { + PushbackStream pis = new PushbackStream(inStream); + pis.Unread(tag); + inStream = pis; + } + + if (tag != 0x30) // assume ascii PEM encoded. { - return ReadPemCertificate(pis); + return ReadPemCertificate(inStream); } - return ReadDerCertificate(new Asn1InputStream(pis)); + return ReadDerCertificate(new Asn1InputStream(inStream)); } catch (Exception e) { @@ -158,12 +157,11 @@ public IX509AttributeCertificate ReadAttrCert( * Returns a (possibly empty) collection view of the certificates * read from the given input stream inStream. */ - public ICollection ReadAttrCerts( - Stream inStream) + public IList ReadAttrCerts(Stream inStream) { - IX509AttributeCertificate attrCert; - IList attrCerts = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var attrCerts = new List(); + X509V2AttributeCertificate attrCert; while ((attrCert = ReadAttrCert(inStream)) != null) { attrCerts.Add(attrCert); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CertPairParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CertPairParser.cs index a73c108..6fbdde0 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CertPairParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CertPairParser.cs @@ -1,13 +1,12 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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 @@ -29,8 +28,7 @@ private X509CertificatePair ReadDerCrossCertificatePair( /// Create loading data from byte array. /// /// - public X509CertificatePair ReadCertPair( - byte[] input) + public X509CertificatePair ReadCertPair(byte[] input) { return ReadCertPair(new MemoryStream(input, false)); } @@ -39,14 +37,12 @@ public X509CertificatePair ReadCertPair( /// Create loading data from byte array. /// /// - public ICollection ReadCertPairs( - byte[] input) + public IList ReadCertPairs(byte[] input) { return ReadCertPairs(new MemoryStream(input, false)); } - public X509CertificatePair ReadCertPair( - Stream inStream) + public X509CertificatePair ReadCertPair(Stream inStream) { if (inStream == null) throw new ArgumentNullException("inStream"); @@ -64,15 +60,22 @@ public X509CertificatePair ReadCertPair( try { - PushbackStream pis = new PushbackStream(inStream); - int tag = pis.ReadByte(); - - if (tag < 0) - return null; + int tag = inStream.ReadByte(); + if (tag < 0) + return null; - pis.Unread(tag); + if (inStream.CanSeek) + { + inStream.Seek(-1L, SeekOrigin.Current); + } + else + { + PushbackStream pis = new PushbackStream(inStream); + pis.Unread(tag); + inStream = pis; + } - return ReadDerCrossCertificatePair(pis); + return ReadDerCrossCertificatePair(inStream); } catch (Exception e) { @@ -80,12 +83,11 @@ public X509CertificatePair ReadCertPair( } } - public ICollection ReadCertPairs( - Stream inStream) + public IList ReadCertPairs(Stream inStream) { - X509CertificatePair certPair; - IList certPairs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var certPairs = new List(); + X509CertificatePair certPair; while ((certPair = ReadCertPair(inStream)) != null) { certPairs.Add(certPair); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509Certificate.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509Certificate.cs index 0ef93fc..1d1acbe 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509Certificate.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509Certificate.cs @@ -1,8 +1,9 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; +using System.Net; using System.Text; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; @@ -57,8 +58,8 @@ internal byte[] GetEncoded() } private readonly X509CertificateStructure c; - //private Hashtable pkcs12Attributes = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateHashtable(); - //private ArrayList pkcs12Ordering = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + //private Dictionary<> pkcs12Attributes = new Dictionary<>(); + //private List<> pkcs12Ordering = new List<>(); private readonly string sigAlgName; private readonly byte[] sigAlgParams; private readonly BasicConstraints basicConstraints; @@ -98,12 +99,10 @@ public X509Certificate(X509CertificateStructure c) try { - Asn1OctetString str = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.19")); - + Asn1OctetString str = GetExtensionValue(X509Extensions.BasicConstraints); if (str != null) { - basicConstraints = BasicConstraints.GetInstance( - X509ExtensionUtilities.FromExtensionValue(str)); + basicConstraints = BasicConstraints.GetInstance(X509ExtensionUtilities.FromExtensionValue(str)); } } catch (Exception e) @@ -113,12 +112,10 @@ public X509Certificate(X509CertificateStructure c) try { - Asn1OctetString str = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.15")); - + Asn1OctetString str = GetExtensionValue(X509Extensions.KeyUsage); if (str != null) { - DerBitString bits = DerBitString.GetInstance( - X509ExtensionUtilities.FromExtensionValue(str)); + DerBitString bits = DerBitString.GetInstance(X509ExtensionUtilities.FromExtensionValue(str)); byte[] bytes = bits.GetBytes(); int length = (bytes.Length * 8) - bits.PadBits; @@ -210,9 +207,9 @@ public virtual void CheckValidity( DateTime time) { if (time.CompareTo(NotAfter) > 0) - throw new CertificateExpiredException("certificate expired on " + c.EndDate.GetTime()); + throw new CertificateExpiredException("certificate expired on " + c.EndDate); if (time.CompareTo(NotBefore) < 0) - throw new CertificateNotYetValidException("certificate not valid until " + c.StartDate.GetTime()); + throw new CertificateNotYetValidException("certificate not valid until " + c.StartDate); } /// @@ -345,26 +342,23 @@ public virtual bool[] GetKeyUsage() } // TODO Replace with something that returns a list of DerObjectIdentifier - public virtual IList GetExtendedKeyUsage() + public virtual IList GetExtendedKeyUsage() { - Asn1OctetString str = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.37")); + Asn1OctetString str = GetExtensionValue(X509Extensions.ExtendedKeyUsage); if (str == null) return null; try { - Asn1Sequence seq = Asn1Sequence.GetInstance( - X509ExtensionUtilities.FromExtensionValue(str)); - - IList list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + Asn1Sequence seq = Asn1Sequence.GetInstance(X509ExtensionUtilities.FromExtensionValue(str)); + var result = new List(); foreach (DerObjectIdentifier oid in seq) { - list.Add(oid.Id); + result.Add(oid); } - - return list; + return result; } catch (Exception e) { @@ -387,34 +381,80 @@ public virtual int GetBasicConstraints() return -1; } - public virtual ICollection GetSubjectAlternativeNames() + public virtual GeneralNames GetIssuerAlternativeNameExtension() { - return GetAlternativeNames("2.5.29.17"); + return GetAlternativeNameExtension(X509Extensions.IssuerAlternativeName); } - public virtual ICollection GetIssuerAlternativeNames() + public virtual GeneralNames GetSubjectAlternativeNameExtension() { - return GetAlternativeNames("2.5.29.18"); + return GetAlternativeNameExtension(X509Extensions.SubjectAlternativeName); } - protected virtual ICollection GetAlternativeNames( - string oid) + public virtual IList> GetIssuerAlternativeNames() { - Asn1OctetString altNames = GetExtensionValue(new DerObjectIdentifier(oid)); + return GetAlternativeNames(X509Extensions.IssuerAlternativeName); + } + public virtual IList> GetSubjectAlternativeNames() + { + return GetAlternativeNames(X509Extensions.SubjectAlternativeName); + } + + protected virtual GeneralNames GetAlternativeNameExtension(DerObjectIdentifier oid) + { + Asn1OctetString altNames = GetExtensionValue(oid); if (altNames == null) return null; Asn1Object asn1Object = X509ExtensionUtilities.FromExtensionValue(altNames); - GeneralNames gns = GeneralNames.GetInstance(asn1Object); + return GeneralNames.GetInstance(asn1Object); + } + + protected virtual IList> GetAlternativeNames(DerObjectIdentifier oid) + { + var generalNames = GetAlternativeNameExtension(oid); + if (generalNames == null) + return null; - IList result = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); - foreach (GeneralName gn in gns.GetNames()) + var gns = generalNames.GetNames(); + + var result = new List>(gns.Length); + foreach (GeneralName gn in gns) { - IList entry = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var entry = new List(2); entry.Add(gn.TagNo); - entry.Add(gn.Name.ToString()); + + switch (gn.TagNo) + { + case GeneralName.EdiPartyName: + case GeneralName.X400Address: + case GeneralName.OtherName: + entry.Add(gn.GetEncoded()); + break; + case GeneralName.DirectoryName: + // TODO Styles + //entry.Add(X509Name.GetInstance(Rfc4519Style.Instance, gn.Name).ToString()); + entry.Add(X509Name.GetInstance(gn.Name).ToString()); + break; + case GeneralName.DnsName: + case GeneralName.Rfc822Name: + case GeneralName.UniformResourceIdentifier: + entry.Add(((IAsn1String)gn.Name).GetString()); + break; + case GeneralName.RegisteredID: + entry.Add(DerObjectIdentifier.GetInstance(gn.Name).Id); + break; + case GeneralName.IPAddress: + byte[] addrBytes = Asn1OctetString.GetInstance(gn.Name).GetOctets(); + IPAddress ipAddress = new IPAddress(addrBytes); + entry.Add(ipAddress.ToString()); + break; + default: + throw new IOException("Bad tag number: " + gn.TagNo); + } + result.Add(entry); } return result; @@ -527,31 +567,30 @@ public override int GetHashCode() 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); + buf.Append(" [0] Version: ").Append(this.Version).AppendLine(); + buf.Append(" SerialNumber: ").Append(this.SerialNumber).AppendLine(); + buf.Append(" IssuerDN: ").Append(this.IssuerDN).AppendLine(); + buf.Append(" Start Date: ").Append(this.NotBefore).AppendLine(); + buf.Append(" Final Date: ").Append(this.NotAfter).AppendLine(); + buf.Append(" SubjectDN: ").Append(this.SubjectDN).AppendLine(); + buf.Append(" Public Key: ").Append(this.GetPublicKey()).AppendLine(); + buf.Append(" Signature Algorithm: ").Append(this.SigAlgName).AppendLine(); byte[] sig = this.GetSignature(); - buf.Append(" Signature: ").Append(Hex.ToHexString(sig, 0, 20)).Append(nl); + buf.Append(" Signature: ").Append(Hex.ToHexString(sig, 0, 20)).AppendLine(); 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); + buf.Append(" ").Append(Hex.ToHexString(sig, i, len)).AppendLine(); } X509Extensions extensions = c.TbsCertificate.Extensions; if (extensions != null) { - IEnumerator e = extensions.ExtensionOids.GetEnumerator(); + var e = extensions.ExtensionOids.GetEnumerator(); if (e.MoveNext()) { @@ -560,7 +599,7 @@ public override string ToString() do { - DerObjectIdentifier oid = (DerObjectIdentifier)e.Current; + DerObjectIdentifier oid = e.Current; X509Extension ext = extensions.GetExtension(oid); if (ext.Value != null) @@ -594,18 +633,18 @@ public override string ToString() { buf.Append(oid.Id); buf.Append(" value = ").Append(Asn1Dump.DumpAsString(obj)); - //buf.Append(" value = ").Append("*****").Append(nl); + //buf.Append(" value = ").Append("*****").AppendLine(); } } catch (Exception) { buf.Append(oid.Id); - //buf.Append(" value = ").Append(new string(Hex.encode(ext.getValue().getOctets()))).Append(nl); + //buf.Append(" value = ").Append(new string(Hex.encode(ext.getValue().getOctets()))).AppendLine(); buf.Append(" value = ").Append("*****"); } } - buf.Append(nl); + buf.AppendLine(); } while (e.MoveNext()); } @@ -643,20 +682,16 @@ protected virtual void CheckSignature( 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 = GetTbsCertificate(); - 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())) + IStreamCalculator streamCalculator = verifier.CreateCalculator(); + using (var stream = streamCalculator.Stream) { - throw new InvalidKeyException("Public key presented not for certificate signature"); + stream.Write(b, 0, b.Length); } + + if (!streamCalculator.GetResult().IsVerified(this.GetSignature())) + throw new InvalidKeyException("Public key presented not for certificate signature"); } private CachedEncoding GetCachedEncoding() @@ -700,7 +735,7 @@ private static bool IsAlgIDEqual(AlgorithmIdentifier id1, AlgorithmIdentifier id Asn1Encodable p2 = id2.Parameters; if ((p1 == null) == (p2 == null)) - return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Equals(p1, p2); + return Org.BouncyCastle.Utilities.Platform.Equals(p1, p2); // Exactly one of p1, p2 is null at this point return p1 == null diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CertificatePair.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CertificatePair.cs index 23c5b3c..b64a45d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CertificatePair.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CertificatePair.cs @@ -103,8 +103,8 @@ public override bool Equals( 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); + return Org.BouncyCastle.Utilities.Platform.Equals(this.forward, other.forward) + && Org.BouncyCastle.Utilities.Platform.Equals(this.reverse, other.reverse); } public override int GetHashCode() diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CertificateParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CertificateParser.cs index 4863e70..524e7d2 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CertificateParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CertificateParser.cs @@ -1,16 +1,13 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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 @@ -26,12 +23,11 @@ public class X509CertificateParser { private static readonly PemParser PemCertParser = new PemParser("CERTIFICATE"); - private Asn1Set sData; - private int sDataObjectCount; - private Stream currentStream; + private Asn1Set sData; + private int sDataObjectCount; + private Stream currentStream; - private X509Certificate ReadDerCertificate( - Asn1InputStream dIn) + private X509Certificate ReadDerCertificate(Asn1InputStream dIn) { Asn1Sequence seq = (Asn1Sequence)dIn.ReadObject(); @@ -46,7 +42,14 @@ private X509Certificate ReadDerCertificate( } } - return CreateX509Certificate(X509CertificateStructure.GetInstance(seq)); + return new X509Certificate(X509CertificateStructure.GetInstance(seq)); + } + + private X509Certificate ReadPemCertificate(Stream inStream) + { + Asn1Sequence seq = PemCertParser.ReadPemObject(inStream); + + return seq == null ? null : new X509Certificate(X509CertificateStructure.GetInstance(seq)); } private X509Certificate GetCertificate() @@ -58,38 +61,18 @@ private X509Certificate GetCertificate() object obj = sData[sDataObjectCount++]; if (obj is Asn1Sequence) - { - return CreateX509Certificate( - X509CertificateStructure.GetInstance(obj)); - } + return new X509Certificate(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) + public X509Certificate ReadCertificate(byte[] input) { return ReadCertificate(new MemoryStream(input, false)); } @@ -98,8 +81,7 @@ public X509Certificate ReadCertificate( /// Create loading data from byte array. /// /// - public ICollection ReadCertificates( - byte[] input) + public IList ReadCertificates(byte[] input) { return ReadCertificates(new MemoryStream(input, false)); } @@ -108,8 +90,7 @@ public ICollection ReadCertificates( * Generates a certificate object and initializes it with the data * read from the input stream inStream. */ - public X509Certificate ReadCertificate( - Stream inStream) + public X509Certificate ReadCertificate(Stream inStream) { if (inStream == null) throw new ArgumentNullException("inStream"); @@ -134,29 +115,32 @@ public X509Certificate ReadCertificate( 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)); + int tag = inStream.ReadByte(); + if (tag < 0) + return null; + + if (inStream.CanSeek) + { + inStream.Seek(-1L, SeekOrigin.Current); + } + else + { + PushbackStream pis = new PushbackStream(inStream); + pis.Unread(tag); + inStream = pis; + } + + if (tag != 0x30) // assume ascii PEM encoded. + return ReadPemCertificate(inStream); + + return ReadDerCertificate(new Asn1InputStream(inStream)); } catch (Exception e) { @@ -168,18 +152,18 @@ public X509Certificate ReadCertificate( * Returns a (possibly empty) collection view of the certificates * read from the given input stream inStream. */ - public ICollection ReadCertificates( - Stream inStream) + public IList ReadCertificates(Stream inStream) { - X509Certificate cert; - IList certs = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + return new List(ParseCertificates(inStream)); + } + public IEnumerable ParseCertificates(Stream inStream) + { + X509Certificate cert; while ((cert = ReadCertificate(inStream)) != null) { - certs.Add(cert); + yield return cert; } - - return certs; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509Crl.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509Crl.cs index b1aff2d..203f671 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509Crl.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509Crl.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using System.Text; @@ -14,8 +14,6 @@ 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; @@ -130,25 +128,20 @@ public virtual void Verify( protected virtual void CheckSignature( IVerifierFactory verifier) { + // TODO Compare IsAlgIDEqual in X509Certificate.CheckSignature 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); + byte[] b = GetTbsCertList(); - BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.Dispose(streamCalculator.Stream); + IStreamCalculator streamCalculator = verifier.CreateCalculator(); + using (var stream = streamCalculator.Stream) + { + stream.Write(b, 0, b.Length); + } - if (!((IVerifier)streamCalculator.GetResult()).IsVerified(this.GetSignature())) - { + if (!streamCalculator.GetResult().IsVerified(GetSignature())) throw new InvalidKeyException("CRL does not verify with supplied public key."); - } } public virtual int Version @@ -166,23 +159,15 @@ public virtual DateTime ThisUpdate get { return c.ThisUpdate.ToDateTime(); } } - public virtual DateTimeObject NextUpdate - { - get - { - return c.NextUpdate == null - ? null - : new DateTimeObject(c.NextUpdate.ToDateTime()); - } - } + public virtual DateTime? NextUpdate => c.NextUpdate?.ToDateTime(); - private ISet LoadCrlEntries() + private ISet LoadCrlEntries() { - ISet entrySet = new HashSet(); - IEnumerable certs = c.GetRevokedCertificateEnumeration(); + var entrySet = new HashSet(); + var revoked = c.GetRevokedCertificateEnumeration(); X509Name previousCertificateIssuer = IssuerDN; - foreach (CrlEntry entry in certs) + foreach (CrlEntry entry in revoked) { X509CrlEntry crlEntry = new X509CrlEntry(entry, isIndirect, previousCertificateIssuer); entrySet.Add(crlEntry); @@ -195,7 +180,7 @@ private ISet LoadCrlEntries() public virtual X509CrlEntry GetRevokedCertificate( BigInteger serialNumber) { - IEnumerable certs = c.GetRevokedCertificateEnumeration(); + var certs = c.GetRevokedCertificateEnumeration(); X509Name previousCertificateIssuer = IssuerDN; foreach (CrlEntry entry in certs) @@ -213,14 +198,12 @@ public virtual X509CrlEntry GetRevokedCertificate( return null; } - public virtual ISet GetRevokedCertificates() + public virtual ISet GetRevokedCertificates() { - ISet entrySet = LoadCrlEntries(); + var entrySet = LoadCrlEntries(); if (entrySet.Count > 0) - { - return entrySet; // TODO? Collections.unmodifiableSet(entrySet); - } + return entrySet; return null; } @@ -317,40 +300,39 @@ public override int GetHashCode() 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); + buf.Append(" Version: ").Append(this.Version).AppendLine(); + buf.Append(" IssuerDN: ").Append(this.IssuerDN).AppendLine(); + buf.Append(" This update: ").Append(this.ThisUpdate).AppendLine(); + buf.Append(" Next update: ").Append(this.NextUpdate).AppendLine(); + buf.Append(" Signature Algorithm: ").Append(this.SigAlgName).AppendLine(); byte[] sig = this.GetSignature(); buf.Append(" Signature: "); - buf.Append(Hex.ToHexString(sig, 0, 20)).Append(nl); + buf.Append(Hex.ToHexString(sig, 0, 20)).AppendLine(); 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); + buf.Append(Hex.ToHexString(sig, i, count)).AppendLine(); } X509Extensions extensions = c.TbsCertList.Extensions; if (extensions != null) { - IEnumerator e = extensions.ExtensionOids.GetEnumerator(); + var e = extensions.ExtensionOids.GetEnumerator(); if (e.MoveNext()) { - buf.Append(" Extensions: ").Append(nl); + buf.Append(" Extensions: ").AppendLine(); } do { - DerObjectIdentifier oid = (DerObjectIdentifier) e.Current; + DerObjectIdentifier oid = e.Current; X509Extension ext = extensions.GetExtension(oid); if (ext.Value != null) @@ -362,7 +344,7 @@ public override string ToString() { if (oid.Equals(X509Extensions.CrlNumber)) { - buf.Append(new CrlNumber(DerInteger.GetInstance(asn1Value).PositiveValue)).Append(nl); + buf.Append(new CrlNumber(DerInteger.GetInstance(asn1Value).PositiveValue)).AppendLine(); } else if (oid.Equals(X509Extensions.DeltaCrlIndicator)) { @@ -370,49 +352,49 @@ public override string ToString() "Base CRL: " + new CrlNumber(DerInteger.GetInstance( asn1Value).PositiveValue)) - .Append(nl); + .AppendLine(); } else if (oid.Equals(X509Extensions.IssuingDistributionPoint)) { - buf.Append(IssuingDistributionPoint.GetInstance((Asn1Sequence) asn1Value)).Append(nl); + buf.Append(IssuingDistributionPoint.GetInstance((Asn1Sequence) asn1Value)).AppendLine(); } else if (oid.Equals(X509Extensions.CrlDistributionPoints)) { - buf.Append(CrlDistPoint.GetInstance((Asn1Sequence) asn1Value)).Append(nl); + buf.Append(CrlDistPoint.GetInstance((Asn1Sequence) asn1Value)).AppendLine(); } else if (oid.Equals(X509Extensions.FreshestCrl)) { - buf.Append(CrlDistPoint.GetInstance((Asn1Sequence) asn1Value)).Append(nl); + buf.Append(CrlDistPoint.GetInstance((Asn1Sequence) asn1Value)).AppendLine(); } else { buf.Append(oid.Id); buf.Append(" value = ").Append( Asn1Dump.DumpAsString(asn1Value)) - .Append(nl); + .AppendLine(); } } catch (Exception) { buf.Append(oid.Id); - buf.Append(" value = ").Append("*****").Append(nl); + buf.Append(" value = ").Append("*****").AppendLine(); } } else { - buf.Append(nl); + buf.AppendLine(); } } while (e.MoveNext()); } - ISet certSet = GetRevokedCertificates(); + var certSet = GetRevokedCertificates(); if (certSet != null) { foreach (X509CrlEntry entry in certSet) { buf.Append(entry); - buf.Append(nl); + buf.AppendLine(); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CrlEntry.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CrlEntry.cs index d5c58ad..866dc09 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CrlEntry.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CrlEntry.cs @@ -1,7 +1,6 @@ #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; @@ -168,24 +167,23 @@ public override int GetHashCode() 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); + buf.Append(" userCertificate: ").Append(this.SerialNumber).AppendLine(); + buf.Append(" revocationDate: ").Append(this.RevocationDate).AppendLine(); + buf.Append(" certificateIssuer: ").Append(this.GetCertificateIssuer()).AppendLine(); X509Extensions extensions = c.Extensions; if (extensions != null) { - IEnumerator e = extensions.ExtensionOids.GetEnumerator(); + var e = extensions.ExtensionOids.GetEnumerator(); if (e.MoveNext()) { - buf.Append(" crlEntryExtensions:").Append(nl); + buf.Append(" crlEntryExtensions:").AppendLine(); do { - DerObjectIdentifier oid = (DerObjectIdentifier)e.Current; + DerObjectIdentifier oid = e.Current; X509Extension ext = extensions.GetExtension(oid); if (ext.Value != null) @@ -211,17 +209,17 @@ public override string ToString() buf.Append(oid.Id); buf.Append(" value = ").Append(Asn1Dump.DumpAsString(obj)); } - buf.Append(nl); + buf.AppendLine(); } catch (Exception) { buf.Append(oid.Id); - buf.Append(" value = ").Append("*****").Append(nl); + buf.Append(" value = ").Append("*****").AppendLine(); } } else { - buf.Append(nl); + buf.AppendLine(); } } while (e.MoveNext()); diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CrlParser.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CrlParser.cs index 0121cdd..aab05bd 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CrlParser.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509CrlParser.cs @@ -1,16 +1,13 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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 @@ -21,33 +18,16 @@ public class X509CrlParser private readonly bool lazyAsn1; - private Asn1Set sCrlData; - private int sCrlDataObjectCount; - private Stream currentCrlStream; + private Asn1Set sCrlData; + private int sCrlDataObjectCount; + private Stream currentCrlStream; - public X509CrlParser() - : this(false) - { - } - - public X509CrlParser( - bool lazyAsn1) + public X509CrlParser(bool lazyAsn1 = false) { 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) + private X509Crl ReadDerCrl(Asn1InputStream dIn) { Asn1Sequence seq = (Asn1Sequence)dIn.ReadObject(); @@ -62,33 +42,29 @@ private X509Crl ReadDerCrl( } } - return CreateX509Crl(CertificateList.GetInstance(seq)); + return new X509Crl(CertificateList.GetInstance(seq)); } - private X509Crl GetCrl() + private X509Crl ReadPemCrl(Stream inStream) { - if (sCrlData == null || sCrlDataObjectCount >= sCrlData.Count) - { - return null; - } + Asn1Sequence seq = PemCrlParser.ReadPemObject(inStream); - return CreateX509Crl( - CertificateList.GetInstance( - sCrlData[sCrlDataObjectCount++])); + return seq == null ? null : new X509Crl(CertificateList.GetInstance(seq)); } - protected virtual X509Crl CreateX509Crl( - CertificateList c) + private X509Crl GetCrl() { - return new X509Crl(c); + if (sCrlData == null || sCrlDataObjectCount >= sCrlData.Count) + return null; + + return new X509Crl(CertificateList.GetInstance(sCrlData[sCrlDataObjectCount++])); } /// /// Create loading data from byte array. /// /// - public X509Crl ReadCrl( - byte[] input) + public X509Crl ReadCrl(byte[] input) { return ReadCrl(new MemoryStream(input, false)); } @@ -97,8 +73,7 @@ public X509Crl ReadCrl( /// Create loading data from byte array. /// /// - public ICollection ReadCrls( - byte[] input) + public IList ReadCrls(byte[] input) { return ReadCrls(new MemoryStream(input, false)); } @@ -107,8 +82,7 @@ public ICollection ReadCrls( * Generates a certificate revocation list (CRL) object and initializes * it with the data read from the input stream inStream. */ - public X509Crl ReadCrl( - Stream inStream) + public X509Crl ReadCrl(Stream inStream) { if (inStream == null) throw new ArgumentNullException("inStream"); @@ -133,31 +107,34 @@ public X509Crl ReadCrl( if (sCrlData != null) { if (sCrlDataObjectCount != sCrlData.Count) - { return GetCrl(); - } sCrlData = null; sCrlDataObjectCount = 0; return null; } - PushbackStream pis = new PushbackStream(inStream); - int tag = pis.ReadByte(); + int tag = inStream.ReadByte(); + if (tag < 0) + return null; - if (tag < 0) - return null; + if (inStream.CanSeek) + { + inStream.Seek(-1L, SeekOrigin.Current); + } + else + { + PushbackStream pis = new PushbackStream(inStream); + pis.Unread(tag); + inStream = pis; + } - pis.Unread(tag); - - if (tag != 0x30) // assume ascii PEM encoded. - { - return ReadPemCrl(pis); - } + if (tag != 0x30) // assume ascii PEM encoded. + return ReadPemCrl(inStream); Asn1InputStream asn1 = lazyAsn1 - ? new LazyAsn1InputStream(pis) - : new Asn1InputStream(pis); + ? new LazyAsn1InputStream(inStream) + : new Asn1InputStream(inStream); return ReadDerCrl(asn1); } @@ -180,18 +157,18 @@ public X509Crl ReadCrl( * only significant field being crls. In particular the signature * and the contents are ignored. */ - public ICollection ReadCrls( - Stream inStream) + public IList ReadCrls(Stream inStream) { - X509Crl crl; - IList crls = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + return new List(ParseCrls(inStream)); + } + public IEnumerable ParseCrls(Stream inStream) + { + X509Crl crl; while ((crl = ReadCrl(inStream)) != null) { - crls.Add(crl); + yield return crl; } - - return crls; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509ExtensionBase.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509ExtensionBase.cs index 3cd3a5a..9bc1672 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509ExtensionBase.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509ExtensionBase.cs @@ -1,10 +1,10 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Collections.Generic; 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 { @@ -13,33 +13,29 @@ public abstract class X509ExtensionBase { protected abstract X509Extensions GetX509Extensions(); - protected virtual ISet GetExtensionOids( - bool critical) + protected virtual ISet GetExtensionOids(bool critical) { X509Extensions extensions = GetX509Extensions(); - if (extensions != null) + if (extensions == null) + return null; + + var set = new HashSet(); + foreach (DerObjectIdentifier oid in extensions.ExtensionOids) { - HashSet set = new HashSet(); - foreach (DerObjectIdentifier oid in extensions.ExtensionOids) + X509Extension ext = extensions.GetExtension(oid); + if (ext.IsCritical == critical) { - X509Extension ext = extensions.GetExtension(oid); - if (ext.IsCritical == critical) - { - set.Add(oid.Id); - } + set.Add(oid.Id); } - - return set; } - - return null; + return set; } /// /// Get non critical extensions. /// /// A set of non critical extension oids. - public virtual ISet GetNonCriticalExtensionOids() + public virtual ISet GetNonCriticalExtensionOids() { return GetExtensionOids(false); } @@ -48,37 +44,14 @@ public virtual ISet GetNonCriticalExtensionOids() /// Get any critical extensions. /// /// A sorted list of critical entension. - public virtual ISet GetCriticalExtensionOids() + 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. - - public Asn1OctetString GetExtensionValue( - string oid) - { - return GetExtensionValue(new DerObjectIdentifier(oid)); - } - - public virtual Asn1OctetString GetExtensionValue( - 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; + return GetX509Extensions()?.GetExtension(oid)?.Value; } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509SignatureUtil.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509SignatureUtil.cs index 48bbd24..a7e432b 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509SignatureUtil.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509SignatureUtil.cs @@ -37,7 +37,7 @@ internal static void SetSignatureParameters( // throw new SignatureException("IOException decoding parameters: " + e.Message); // } // -// if (BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.EndsWith(signature.getAlgorithm(), "MGF1")) +// if (Org.BouncyCastle.Utilities.Platform.EndsWith(signature.getAlgorithm(), "MGF1")) // { // try // { diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509Utilities.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509Utilities.cs index 753da78..e45cf04 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509Utilities.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509Utilities.cs @@ -1,8 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; -using System.IO; +using System.Collections.Generic; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1.CryptoPro; @@ -12,122 +11,120 @@ 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(); + private static readonly Dictionary m_algorithms = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly Dictionary m_exParams = + new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly HashSet m_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("SHA-1WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha1WithRsaEncryption); - algorithms.Add("SHA1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption); - algorithms.Add("SHA-1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption); - algorithms.Add("SHA224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption); - algorithms.Add("SHA-224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption); - algorithms.Add("SHA224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption); - algorithms.Add("SHA-224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption); - algorithms.Add("SHA256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption); - algorithms.Add("SHA-256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption); - algorithms.Add("SHA256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption); - algorithms.Add("SHA-256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption); - algorithms.Add("SHA384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption); - algorithms.Add("SHA-384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption); - algorithms.Add("SHA384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption); - algorithms.Add("SHA-384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption); - algorithms.Add("SHA512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption); - algorithms.Add("SHA-512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption); - algorithms.Add("SHA512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption); - algorithms.Add("SHA-512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption); - algorithms.Add("SHA512(224)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); - algorithms.Add("SHA-512(224)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); - algorithms.Add("SHA512(224)WITHRSA", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); - algorithms.Add("SHA-512(224)WITHRSA", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); - algorithms.Add("SHA512(256)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); - algorithms.Add("SHA-512(256)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); - algorithms.Add("SHA512(256)WITHRSA", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); - algorithms.Add("SHA-512(256)WITHRSA", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); - 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); + m_algorithms.Add("MD2WITHRSAENCRYPTION", PkcsObjectIdentifiers.MD2WithRsaEncryption); + m_algorithms.Add("MD2WITHRSA", PkcsObjectIdentifiers.MD2WithRsaEncryption); + m_algorithms.Add("MD5WITHRSAENCRYPTION", PkcsObjectIdentifiers.MD5WithRsaEncryption); + m_algorithms.Add("MD5WITHRSA", PkcsObjectIdentifiers.MD5WithRsaEncryption); + m_algorithms.Add("SHA1WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha1WithRsaEncryption); + m_algorithms.Add("SHA-1WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha1WithRsaEncryption); + m_algorithms.Add("SHA1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption); + m_algorithms.Add("SHA-1WITHRSA", PkcsObjectIdentifiers.Sha1WithRsaEncryption); + m_algorithms.Add("SHA224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption); + m_algorithms.Add("SHA-224WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha224WithRsaEncryption); + m_algorithms.Add("SHA224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption); + m_algorithms.Add("SHA-224WITHRSA", PkcsObjectIdentifiers.Sha224WithRsaEncryption); + m_algorithms.Add("SHA256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption); + m_algorithms.Add("SHA-256WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha256WithRsaEncryption); + m_algorithms.Add("SHA256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption); + m_algorithms.Add("SHA-256WITHRSA", PkcsObjectIdentifiers.Sha256WithRsaEncryption); + m_algorithms.Add("SHA384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption); + m_algorithms.Add("SHA-384WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha384WithRsaEncryption); + m_algorithms.Add("SHA384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption); + m_algorithms.Add("SHA-384WITHRSA", PkcsObjectIdentifiers.Sha384WithRsaEncryption); + m_algorithms.Add("SHA512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption); + m_algorithms.Add("SHA-512WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512WithRsaEncryption); + m_algorithms.Add("SHA512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption); + m_algorithms.Add("SHA-512WITHRSA", PkcsObjectIdentifiers.Sha512WithRsaEncryption); + m_algorithms.Add("SHA512(224)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); + m_algorithms.Add("SHA-512(224)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); + m_algorithms.Add("SHA512(224)WITHRSA", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); + m_algorithms.Add("SHA-512(224)WITHRSA", PkcsObjectIdentifiers.Sha512_224WithRSAEncryption); + m_algorithms.Add("SHA512(256)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); + m_algorithms.Add("SHA-512(256)WITHRSAENCRYPTION", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); + m_algorithms.Add("SHA512(256)WITHRSA", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); + m_algorithms.Add("SHA-512(256)WITHRSA", PkcsObjectIdentifiers.Sha512_256WithRSAEncryption); + m_algorithms.Add("SHA1WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss); + m_algorithms.Add("SHA224WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss); + m_algorithms.Add("SHA256WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss); + m_algorithms.Add("SHA384WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss); + m_algorithms.Add("SHA512WITHRSAANDMGF1", PkcsObjectIdentifiers.IdRsassaPss); + m_algorithms.Add("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160); + m_algorithms.Add("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD160); + m_algorithms.Add("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128); + m_algorithms.Add("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD128); + m_algorithms.Add("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256); + m_algorithms.Add("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.RsaSignatureWithRipeMD256); + m_algorithms.Add("SHA1WITHDSA", X9ObjectIdentifiers.IdDsaWithSha1); + m_algorithms.Add("DSAWITHSHA1", X9ObjectIdentifiers.IdDsaWithSha1); + m_algorithms.Add("SHA224WITHDSA", NistObjectIdentifiers.DsaWithSha224); + m_algorithms.Add("SHA256WITHDSA", NistObjectIdentifiers.DsaWithSha256); + m_algorithms.Add("SHA384WITHDSA", NistObjectIdentifiers.DsaWithSha384); + m_algorithms.Add("SHA512WITHDSA", NistObjectIdentifiers.DsaWithSha512); + m_algorithms.Add("SHA1WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha1); + m_algorithms.Add("ECDSAWITHSHA1", X9ObjectIdentifiers.ECDsaWithSha1); + m_algorithms.Add("SHA224WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha224); + m_algorithms.Add("SHA256WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha256); + m_algorithms.Add("SHA384WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha384); + m_algorithms.Add("SHA512WITHECDSA", X9ObjectIdentifiers.ECDsaWithSha512); + m_algorithms.Add("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94); + m_algorithms.Add("GOST3411WITHGOST3410-94", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94); + m_algorithms.Add("GOST3411WITHECGOST3410", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001); + m_algorithms.Add("GOST3411WITHECGOST3410-2001", CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001); + m_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(OiwObjectIdentifiers.DsaWithSha1); - noParams.Add(NistObjectIdentifiers.DsaWithSha224); - noParams.Add(NistObjectIdentifiers.DsaWithSha256); - noParams.Add(NistObjectIdentifiers.DsaWithSha384); - noParams.Add(NistObjectIdentifiers.DsaWithSha512); + m_noParams.Add(X9ObjectIdentifiers.ECDsaWithSha1); + m_noParams.Add(X9ObjectIdentifiers.ECDsaWithSha224); + m_noParams.Add(X9ObjectIdentifiers.ECDsaWithSha256); + m_noParams.Add(X9ObjectIdentifiers.ECDsaWithSha384); + m_noParams.Add(X9ObjectIdentifiers.ECDsaWithSha512); + m_noParams.Add(X9ObjectIdentifiers.IdDsaWithSha1); + m_noParams.Add(OiwObjectIdentifiers.DsaWithSha1); + m_noParams.Add(NistObjectIdentifiers.DsaWithSha224); + m_noParams.Add(NistObjectIdentifiers.DsaWithSha256); + m_noParams.Add(NistObjectIdentifiers.DsaWithSha384); + m_noParams.Add(NistObjectIdentifiers.DsaWithSha512); // // RFC 4491 // - noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94); - noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001); + m_noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x94); + m_noParams.Add(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001); // // explicit params // AlgorithmIdentifier sha1AlgId = new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance); - exParams.Add("SHA1WITHRSAANDMGF1", CreatePssParams(sha1AlgId, 20)); + m_exParams.Add("SHA1WITHRSAANDMGF1", CreatePssParams(sha1AlgId, 20)); AlgorithmIdentifier sha224AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha224, DerNull.Instance); - exParams.Add("SHA224WITHRSAANDMGF1", CreatePssParams(sha224AlgId, 28)); + m_exParams.Add("SHA224WITHRSAANDMGF1", CreatePssParams(sha224AlgId, 28)); AlgorithmIdentifier sha256AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256, DerNull.Instance); - exParams.Add("SHA256WITHRSAANDMGF1", CreatePssParams(sha256AlgId, 32)); + m_exParams.Add("SHA256WITHRSAANDMGF1", CreatePssParams(sha256AlgId, 32)); AlgorithmIdentifier sha384AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha384, DerNull.Instance); - exParams.Add("SHA384WITHRSAANDMGF1", CreatePssParams(sha384AlgId, 48)); + m_exParams.Add("SHA384WITHRSAANDMGF1", CreatePssParams(sha384AlgId, 48)); AlgorithmIdentifier sha512AlgId = new AlgorithmIdentifier(NistObjectIdentifiers.IdSha512, DerNull.Instance); - exParams.Add("SHA512WITHRSAANDMGF1", CreatePssParams(sha512AlgId, 64)); + m_exParams.Add("SHA512WITHRSAANDMGF1", CreatePssParams(sha512AlgId, 64)); } private static RsassaPssParameters CreatePssParams( @@ -141,68 +138,28 @@ private static RsassaPssParameters CreatePssParams( new DerInteger(1)); } - internal static DerObjectIdentifier GetAlgorithmOid( - string algorithmName) + internal static DerObjectIdentifier GetAlgorithmOid(string algorithmName) { - algorithmName = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.ToUpperInvariant(algorithmName); - - if (algorithms.Contains(algorithmName)) - { - return (DerObjectIdentifier) algorithms[algorithmName]; - } + if (m_algorithms.TryGetValue(algorithmName, out var oid)) + return oid; return new DerObjectIdentifier(algorithmName); } - internal static AlgorithmIdentifier GetSigAlgID( - DerObjectIdentifier sigOid, - string algorithmName) + internal static AlgorithmIdentifier GetSigAlgID(DerObjectIdentifier sigOid, string algorithmName) { - if (noParams.Contains(sigOid)) - { + if (m_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]); - } + if (m_exParams.TryGetValue(algorithmName, out var explicitParameters)) + return new AlgorithmIdentifier(sigOid, explicitParameters); 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) + internal static IEnumerable GetAlgNames() { - 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(); + return CollectionUtilities.Proxy(m_algorithms.Keys); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V1CertificateGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V1CertificateGenerator.cs index 0c62ca0..c8e2a80 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V1CertificateGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V1CertificateGenerator.cs @@ -1,17 +1,13 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; +using System.Collections.Generic; 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 @@ -21,10 +17,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509 /// public class X509V1CertificateGenerator { - private V1TbsCertificateGenerator tbsGen; - private DerObjectIdentifier sigOID; - private AlgorithmIdentifier sigAlgId; - private string signatureAlgorithm; + private V1TbsCertificateGenerator tbsGen; /// /// Default Constructor. @@ -120,91 +113,35 @@ public void SetPublicKey( } /// - /// 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. + /// Generate a new using the provided . /// - /// string representation of the algorithm name - - 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. - - 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. - - public X509Certificate Generate( - AsymmetricKeyParameter privateKey, - SecureRandom random) + /// A signature factory with the necessary + /// algorithm details. + /// An . + public X509Certificate Generate(ISignatureFactory signatureFactory) { - return Generate(new Asn1SignatureFactory(signatureAlgorithm, privateKey, random)); - } + var sigAlgID = (AlgorithmIdentifier)signatureFactory.AlgorithmDetails; - /// - /// 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); + tbsGen.SetSignature(sigAlgID); 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); + IStreamCalculator streamCalculator = signatureFactory.CreateCalculator(); + using (Stream sigStream = streamCalculator.Stream) + { + tbsCert.EncodeTo(sigStream, Asn1Encodable.Der); + } - return GenerateJcaObject(tbsCert, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect()); - } + var signature = streamCalculator.GetResult().Collect(); - private X509Certificate GenerateJcaObject( - TbsCertificateStructure tbsCert, - AlgorithmIdentifier sigAlg, - byte[] signature) - { return new X509Certificate( - new X509CertificateStructure(tbsCert, sigAlg, new DerBitString(signature))); + new X509CertificateStructure(tbsCert, sigAlgID, new DerBitString(signature))); } /// /// Allows enumeration of the signature names supported by the generator. /// - public IEnumerable SignatureAlgNames + public IEnumerable SignatureAlgNames { get { return X509Utilities.GetAlgNames(); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V2AttributeCertificate.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V2AttributeCertificate.cs index 13a5d4c..e045bb5 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V2AttributeCertificate.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V2AttributeCertificate.cs @@ -1,7 +1,7 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; using System.IO; using BestHTTP.SecureProtocol.Org.BouncyCastle.Asn1; @@ -17,7 +17,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509 { /// An implementation of a version 2 X.509 Attribute Certificate. public class X509V2AttributeCertificate - : X509ExtensionBase, IX509AttributeCertificate + : X509ExtensionBase { private readonly AttributeCertificate cert; private readonly DateTime notBefore; @@ -51,8 +51,7 @@ public X509V2AttributeCertificate( { } - internal X509V2AttributeCertificate( - AttributeCertificate cert) + public X509V2AttributeCertificate(AttributeCertificate cert) { this.cert = cert; @@ -67,6 +66,11 @@ internal X509V2AttributeCertificate( } } + public virtual AttributeCertificate AttributeCertificate + { + get { return cert; } + } + public virtual int Version { get { return cert.ACInfo.Version.IntValueExact + 1; } @@ -180,30 +184,28 @@ public virtual void Verify( protected virtual void CheckSignature( IVerifierFactory verifier) { + // TODO Compare IsAlgIDEqual in X509Certificate.CheckSignature if (!cert.SignatureAlgorithm.Equals(cert.ACInfo.Signature)) - { throw new CertificateException("Signature algorithm in certificate info not same as outer certificate"); - } - IStreamCalculator streamCalculator = verifier.CreateCalculator(); + 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); + using (var stream = streamCalculator.Stream) + { + stream.Write(b, 0, b.Length); + } } catch (IOException e) { throw new SignatureException("Exception encoding certificate info object", e); } - if (!((IVerifier)streamCalculator.GetResult()).IsVerified(this.GetSignature())) - { + if (!streamCalculator.GetResult().IsVerified(this.GetSignature())) throw new InvalidKeyException("Public key presented not for certificate signature"); - } } public virtual byte[] GetEncoded() @@ -233,7 +235,7 @@ public virtual X509Attribute[] GetAttributes( string oid) { Asn1Sequence seq = cert.ACInfo.Attributes; - IList list = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(); + var list = new List(); for (int i = 0; i != seq.Count; i++) { @@ -249,16 +251,10 @@ public virtual X509Attribute[] GetAttributes( return null; } - X509Attribute[] result = new X509Attribute[list.Count]; - for (int i = 0; i < list.Count; ++i) - { - result[i] = (X509Attribute)list[i]; - } - return result; + return list.ToArray(); } - public override bool Equals( - object obj) + public override bool Equals(object obj) { if (obj == this) return true; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V2AttributeCertificateGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V2AttributeCertificateGenerator.cs index a9d2f59..7796f0d 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V2AttributeCertificateGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V2AttributeCertificateGenerator.cs @@ -1,15 +1,13 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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; @@ -20,10 +18,7 @@ public class X509V2AttributeCertificateGenerator { private readonly X509ExtensionsGenerator extGenerator = new X509ExtensionsGenerator(); - private V2AttributeCertificateInfoGenerator acInfoGen; - private DerObjectIdentifier sigOID; - private AlgorithmIdentifier sigAlgId; - private string signatureAlgorithm; + private V2AttributeCertificateInfoGenerator acInfoGen; public X509V2AttributeCertificateGenerator() { @@ -61,38 +56,13 @@ public void SetSerialNumber( public void SetNotBefore( DateTime date) { - acInfoGen.SetStartDate(new DerGeneralizedTime(date)); + acInfoGen.SetStartDate(new Asn1GeneralizedTime(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. - - 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); + acInfoGen.SetEndDate(new Asn1GeneralizedTime(date)); } /// Add an attribute. @@ -107,7 +77,7 @@ public void SetIssuerUniqueId( { // TODO convert bool array to bit string //acInfoGen.SetIssuerUniqueID(iui); - throw BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateNotImplementedException("SetIssuerUniqueId()"); + throw new NotImplementedException("SetIssuerUniqueId()"); } /// Add a given extension field for the standard extensions tag. @@ -132,72 +102,41 @@ public void AddExtension( extGenerator.AddExtension(new DerObjectIdentifier(oid), critical, extensionValue); } - /// - /// Generate an X509 certificate, based on the current issuer and subject. - /// - - public IX509AttributeCertificate Generate( - AsymmetricKeyParameter privateKey) - { - return Generate(privateKey, null); - } + /// + /// Generate a new using the provided . + /// + /// A signature factory with the necessary + /// algorithm details. + /// An . + public X509V2AttributeCertificate Generate(ISignatureFactory signatureFactory) + { + var sigAlgID = (AlgorithmIdentifier)signatureFactory.AlgorithmDetails; - /// - /// Generate an X509 certificate, based on the current issuer and subject, - /// using the supplied source of randomness, if required. - /// + acInfoGen.SetSignature(sigAlgID); - 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) + 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 + IStreamCalculator streamCalculator = signatureFactory.CreateCalculator(); + using (Stream sigStream = streamCalculator.Stream) { - 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); + acInfo.EncodeTo(sigStream, Asn1Encodable.Der); } + + var signature = streamCalculator.GetResult().Collect(); + + return new X509V2AttributeCertificate( + new AttributeCertificate(acInfo, sigAlgID, new DerBitString(signature))); } /// /// Allows enumeration of the signature names supported by the generator. /// - public IEnumerable SignatureAlgNames + public IEnumerable SignatureAlgNames { get { return X509Utilities.GetAlgNames(); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V2CRLGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V2CRLGenerator.cs index d119e20..24372cb 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V2CRLGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V2CRLGenerator.cs @@ -1,19 +1,15 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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 { @@ -24,10 +20,7 @@ public class X509V2CrlGenerator { private readonly X509ExtensionsGenerator extGenerator = new X509ExtensionsGenerator(); - private V2TbsCertListGenerator tbsGen; - private DerObjectIdentifier sigOID; - private AlgorithmIdentifier sigAlgId; - private string signatureAlgorithm; + private V2TbsCertListGenerator tbsGen; public X509V2CrlGenerator() { @@ -88,7 +81,8 @@ public void AddCrlEntry( int reason, DateTime invalidityDate) { - tbsGen.AddCrlEntry(new DerInteger(userCertificate), new Time(revocationDate), reason, new DerGeneralizedTime(invalidityDate)); + tbsGen.AddCrlEntry(new DerInteger(userCertificate), new Time(revocationDate), reason, + new Asn1GeneralizedTime(invalidityDate)); } /** @@ -107,13 +101,12 @@ public void AddCrlEntry( * * @param other the X509Crl to source the other entries from. */ - public void AddCrl( - X509Crl other) + public void AddCrl(X509Crl other) { if (other == null) throw new ArgumentNullException("other"); - ISet revocations = other.GetRevokedCertificates(); + var revocations = other.GetRevokedCertificates(); if (revocations != null) { @@ -133,30 +126,6 @@ public void AddCrl( } } - /// - /// Set the signature algorithm that will be used to sign this CRL. - /// - /// - - 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) */ @@ -201,78 +170,41 @@ public void AddExtension( 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. - - 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. - - 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) + /// + /// Generate a new using the provided . + /// + /// A signature factory with the necessary + /// algorithm details. + /// An . + public X509Crl Generate(ISignatureFactory signatureFactory) { - 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); + var sigAlgID = (AlgorithmIdentifier)signatureFactory.AlgorithmDetails; - return GenerateJcaObject(tbsCertList, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect()); - } + tbsGen.SetSignature(sigAlgID); - private TbsCertificateList GenerateCertList() - { if (!extGenerator.IsEmpty) { tbsGen.SetExtensions(extGenerator.Generate()); } - return tbsGen.GenerateTbsCertList(); - } + TbsCertificateList tbsCertList = tbsGen.GenerateTbsCertList(); + + IStreamCalculator streamCalculator = signatureFactory.CreateCalculator(); + using (Stream sigStream = streamCalculator.Stream) + { + tbsCertList.EncodeTo(sigStream, Asn1Encodable.Der); + } + + var signature = streamCalculator.GetResult().Collect(); - private X509Crl GenerateJcaObject( - TbsCertificateList tbsCrl, - AlgorithmIdentifier algId, - byte[] signature) - { return new X509Crl( - CertificateList.GetInstance( - new DerSequence(tbsCrl, algId, new DerBitString(signature)))); + CertificateList.GetInstance(new DerSequence(tbsCertList, sigAlgID, new DerBitString(signature)))); } /// /// Allows enumeration of the signature names supported by the generator. /// - public IEnumerable SignatureAlgNames + public IEnumerable SignatureAlgNames { get { return X509Utilities.GetAlgNames(); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V3CertificateGenerator.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V3CertificateGenerator.cs index 20ea19a..6a51b65 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V3CertificateGenerator.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/X509V3CertificateGenerator.cs @@ -1,14 +1,13 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; +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; using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Extension; @@ -22,10 +21,7 @@ public class X509V3CertificateGenerator { private readonly X509ExtensionsGenerator extGenerator = new X509ExtensionsGenerator(); - private V3TbsCertificateGenerator tbsGen; - private DerObjectIdentifier sigOid; - private AlgorithmIdentifier sigAlgId; - private string signatureAlgorithm; + private V3TbsCertificateGenerator tbsGen; public X509V3CertificateGenerator() { @@ -109,30 +105,6 @@ public void SetPublicKey( tbsGen.SetSubjectPublicKeyInfo(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey)); } - /// - /// Set the signature algorithm that will be used to sign this certificate. - /// - /// - - 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. /// @@ -255,11 +227,8 @@ public void CopyAndAddExtension( X509Certificate cert) { Asn1OctetString extValue = cert.GetExtensionValue(oid); - if (extValue == null) - { throw new CertificateParsingException("extension " + oid + " not present"); - } try { @@ -274,39 +243,16 @@ public void CopyAndAddExtension( } /// - /// Generate an X509Certificate. - /// - /// The private key of the issuer that is signing this certificate. - /// An X509Certificate. - - public X509Certificate Generate( - AsymmetricKeyParameter privateKey) - { - return Generate(privateKey, null); - } - - /// - /// Generate an X509Certificate using your own SecureRandom. + /// Generate a new using the provided . /// - /// The private key of the issuer that is signing this certificate. - /// You Secure Random instance. - /// An X509Certificate. - - public X509Certificate Generate( - AsymmetricKeyParameter privateKey, - SecureRandom random) + /// A signature factory with the necessary + /// algorithm details. + /// An . + public X509Certificate Generate(ISignatureFactory signatureFactory) { - return Generate(new Asn1SignatureFactory(signatureAlgorithm, privateKey, random)); - } + var sigAlgID = (AlgorithmIdentifier)signatureFactory.AlgorithmDetails; - /// - /// 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); + tbsGen.SetSignature(sigAlgID); if (!extGenerator.IsEmpty) { @@ -315,30 +261,21 @@ public X509Certificate Generate(ISignatureFactory signatureCalculatorFactory) 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); + IStreamCalculator streamCalculator = signatureFactory.CreateCalculator(); + using (Stream sigStream = streamCalculator.Stream) + { + tbsCert.EncodeTo(sigStream, Asn1Encodable.Der); + } - return GenerateJcaObject(tbsCert, (AlgorithmIdentifier)signatureCalculatorFactory.AlgorithmDetails, ((IBlockResult)streamCalculator.GetResult()).Collect()); - } + var signature = streamCalculator.GetResult().Collect(); - private X509Certificate GenerateJcaObject( - TbsCertificateStructure tbsCert, - AlgorithmIdentifier sigAlg, - byte[] signature) - { - return new X509Certificate( - new X509CertificateStructure(tbsCert, sigAlg, new DerBitString(signature))); + return new X509Certificate(new X509CertificateStructure(tbsCert, sigAlgID, new DerBitString(signature))); } /// /// Allows enumeration of the signature names supported by the generator. /// - public IEnumerable SignatureAlgNames + public IEnumerable SignatureAlgNames { get { return X509Utilities.GetAlgNames(); } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/extension/X509ExtensionUtil.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/extension/X509ExtensionUtil.cs index de059e7..8d254e6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/extension/X509ExtensionUtil.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/extension/X509ExtensionUtil.cs @@ -1,93 +1,29 @@ #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) + public static Asn1Object FromExtensionValue(Asn1OctetString extensionValue) { return Asn1Object.FromByteArray(extensionValue.GetOctets()); } - public static ICollection GetIssuerAlternativeNames( - X509Certificate cert) + /// + /// Extract the value of the given extension, if it exists. + /// + /// The extensions object. + /// The object identifier to obtain. + /// Asn1Object + /// if the extension cannot be read. + public static Asn1Object FromExtensionValue(IX509Extension extensions, DerObjectIdentifier oid) { - 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; + Asn1OctetString extensionValue = extensions.GetExtensionValue(oid); + return extensionValue == null ? null : FromExtensionValue(extensionValue); } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509AttrCertStoreSelector.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509AttrCertStoreSelector.cs index 66d6eba..96983e6 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509AttrCertStoreSelector.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509AttrCertStoreSelector.cs @@ -1,14 +1,12 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; -using System.IO; +using System.Collections.Generic; 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 @@ -21,17 +19,17 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store * @see org.bouncycastle.x509.X509Store */ public class X509AttrCertStoreSelector - : IX509Selector + : ISelector { // TODO: name constraints??? - private IX509AttributeCertificate attributeCert; - private DateTimeObject attributeCertificateValid; + private X509V2AttributeCertificate attributeCert; + private DateTime? attributeCertificateValid; private AttributeCertificateHolder holder; private AttributeCertificateIssuer issuer; private BigInteger serialNumber; - private ISet targetNames = new HashSet(); - private ISet targetGroups = new HashSet(); + private ISet targetNames = new HashSet(); + private ISet targetGroups = new HashSet(); public X509AttrCertStoreSelector() { @@ -45,23 +43,17 @@ private X509AttrCertStoreSelector( this.holder = o.holder; this.issuer = o.issuer; this.serialNumber = o.serialNumber; - this.targetGroups = new HashSet(o.targetGroups); - this.targetNames = new HashSet(o.targetNames); + 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. + /// The attribute certificate to be checked. /// true if the object matches this selector. - public bool Match( - object obj) + public bool Match(X509V2AttributeCertificate attrCert) { - if (obj == null) - throw new ArgumentNullException("obj"); - - IX509AttributeCertificate attrCert = obj as IX509AttributeCertificate; - if (attrCert == null) return false; @@ -163,22 +155,15 @@ public object Clone() /// The attribute certificate which must be matched. /// If null is given, any will do. - public IX509AttributeCertificate AttributeCert + public X509V2AttributeCertificate AttributeCert { get { return attributeCert; } set { this.attributeCert = value; } } - - public DateTimeObject AttribueCertificateValid - { - get { return attributeCertificateValid; } - set { this.attributeCertificateValid = value; } - } - /// The criteria for validity /// If null is given any will do. - public DateTimeObject AttributeCertificateValid + public DateTime? AttributeCertificateValid { get { return attributeCertificateValid; } set { this.attributeCertificateValid = value; } @@ -241,8 +226,7 @@ public void AddTargetName( * @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) + public void AddTargetName(byte[] name) { AddTargetName(GeneralName.GetInstance(Asn1Object.FromByteArray(name))); } @@ -260,8 +244,7 @@ public void AddTargetName( * @see #AddTargetName(byte[]) * @see #AddTargetName(GeneralName) */ - public void SetTargetNames( - IEnumerable names) + public void SetTargetNames(IEnumerable names) { targetNames = ExtractGeneralNames(names); } @@ -275,9 +258,9 @@ public void SetTargetNames( * @return The collection of target names * @see #setTargetNames(Collection) */ - public IEnumerable GetTargetNames() + public IEnumerable GetTargetNames() { - return new EnumerableProxy(targetNames); + return CollectionUtilities.Proxy(targetNames); } /** @@ -293,8 +276,7 @@ public IEnumerable GetTargetNames() * * @param group The group as GeneralName form (not null) */ - public void AddTargetGroup( - GeneralName group) + public void AddTargetGroup(GeneralName group) { targetGroups.Add(group); } @@ -313,8 +295,7 @@ public void AddTargetGroup( * @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) + public void AddTargetGroup(byte[] name) { AddTargetGroup(GeneralName.GetInstance(Asn1Object.FromByteArray(name))); } @@ -332,8 +313,7 @@ public void AddTargetGroup( * @see #AddTargetGroup(byte[]) * @see #AddTargetGroup(GeneralName) */ - public void SetTargetGroups( - IEnumerable names) + public void SetTargetGroups(IEnumerable names) { targetGroups = ExtractGeneralNames(names); } @@ -347,28 +327,31 @@ public void SetTargetGroups( * @return The collection of target groups. * @see #setTargetGroups(Collection) */ - public IEnumerable GetTargetGroups() + public IEnumerable GetTargetGroups() { - return new EnumerableProxy(targetGroups); + return CollectionUtilities.Proxy(targetGroups); } - private ISet ExtractGeneralNames( - IEnumerable names) + private ISet ExtractGeneralNames(IEnumerable names) { - ISet result = new HashSet(); + var result = new HashSet(); if (names != null) { foreach (object o in names) { - if (o is GeneralName) + if (o is GeneralName gn) { - result.Add(o); + result.Add(gn); } - else + else if (o is byte[] bs) { - result.Add(GeneralName.GetInstance(Asn1Object.FromByteArray((byte[]) o))); + result.Add(GeneralName.GetInstance(Asn1Object.FromByteArray(bs))); } + else + { + throw new InvalidOperationException(); + } } } diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CertPairStoreSelector.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CertPairStoreSelector.cs index f2a2687..546a381 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CertPairStoreSelector.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CertPairStoreSelector.cs @@ -2,6 +2,8 @@ #pragma warning disable using System; +using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Collections; + namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store { /// @@ -11,7 +13,7 @@ namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store /// each of which, if present, must match the respective component of a pair. /// public class X509CertPairStoreSelector - : IX509Selector + : ISelector { private static X509CertStoreSelector CloneSelector( X509CertStoreSelector s) @@ -61,16 +63,10 @@ public X509CertStoreSelector ReverseSelector /// obj is not a X509CertificatePair, this method /// returns false. /// - /// The X509CertificatePair to be tested. + /// The X509CertificatePair to be tested. /// true if the object matches this selector. - public bool Match( - object obj) + public bool Match(X509CertificatePair pair) { - if (obj == null) - throw new ArgumentNullException("obj"); - - X509CertificatePair pair = obj as X509CertificatePair; - if (pair == null) return false; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CertStoreSelector.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CertStoreSelector.cs index 49db195..4379e81 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CertStoreSelector.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CertStoreSelector.cs @@ -1,33 +1,32 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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 + : ISelector { // TODO Missing criteria? private byte[] authorityKeyIdentifier; private int basicConstraints = -1; private X509Certificate certificate; - private DateTimeObject certificateValid; - private ISet extendedKeyUsage; + private DateTime? certificateValid; + private ISet extendedKeyUsage; private bool ignoreX509NameOrdering; private X509Name issuer; private bool[] keyUsage; - private ISet policy; - private DateTimeObject privateKeyValid; + private ISet policy; + private DateTime? privateKeyValid; private BigInteger serialNumber; private X509Name subject; private byte[] subjectKeyIdentifier; @@ -87,13 +86,13 @@ public X509Certificate Certificate set { this.certificate = value; } } - public DateTimeObject CertificateValid + public DateTime? CertificateValid { get { return certificateValid; } set { certificateValid = value; } } - public ISet ExtendedKeyUsage + public ISet ExtendedKeyUsage { get { return CopySet(extendedKeyUsage); } set { extendedKeyUsage = CopySet(value); } @@ -111,12 +110,6 @@ public X509Name Issuer set { issuer = value; } } - - public string IssuerAsString - { - get { return issuer != null ? issuer.ToString() : null; } - } - public bool[] KeyUsage { get { return CopyBoolArray(keyUsage); } @@ -126,13 +119,13 @@ public bool[] KeyUsage /// /// An ISet of DerObjectIdentifier objects. /// - public ISet Policy + public ISet Policy { get { return CopySet(policy); } set { policy = CopySet(value); } } - public DateTimeObject PrivateKeyValid + public DateTime? PrivateKeyValid { get { return privateKeyValid; } set { privateKeyValid = value; } @@ -150,12 +143,6 @@ public X509Name Subject set { subject = value; } } - - public string SubjectAsString - { - get { return subject != null ? subject.ToString() : null; } - } - public byte[] SubjectKeyIdentifier { get { return Arrays.Clone(subjectKeyIdentifier); } @@ -174,11 +161,8 @@ public DerObjectIdentifier SubjectPublicKeyAlgID set { subjectPublicKeyAlgID = value; } } - public virtual bool Match( - object obj) + public virtual bool Match(X509Certificate c) { - X509Certificate c = obj as X509Certificate; - if (c == null) return false; @@ -209,7 +193,7 @@ public virtual bool Match( if (extendedKeyUsage != null) { - IList eku = c.GetExtendedKeyUsage(); + var eku = c.GetExtendedKeyUsage(); // Note: if no extended key usage set, all key purposes are implicitly allowed @@ -217,7 +201,7 @@ public virtual bool Match( { foreach (DerObjectIdentifier oid in extendedKeyUsage) { - if (!eku.Contains(oid.Id)) + if (!eku.Contains(oid)) return false; } } @@ -317,10 +301,9 @@ private static bool[] CopyBoolArray( return b == null ? null : (bool[]) b.Clone(); } - private static ISet CopySet( - ISet s) + private static ISet CopySet(ISet s) { - return s == null ? null : new HashSet(s); + return s == null ? null : new HashSet(s); } private static SubjectPublicKeyInfo GetSubjectPublicKey( diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CollectionStore.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CollectionStore.cs index 79d680f..0454b34 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CollectionStore.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CollectionStore.cs @@ -1,55 +1,3 @@ #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/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CollectionStore.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CollectionStore.cs.meta index e5def69..340f047 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CollectionStore.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CollectionStore.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: c62d23a23e8e043429d9fdb60117aee8 +guid: c44ab57be880acf4083d7227de673914 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CollectionStoreParameters.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CollectionStoreParameters.cs index 16d7abf..0454b34 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CollectionStoreParameters.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CollectionStoreParameters.cs @@ -1,64 +1,3 @@ #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/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CollectionStoreParameters.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CollectionStoreParameters.cs.meta index d48c033..dba4f59 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CollectionStoreParameters.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CollectionStoreParameters.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: e09969b5dbb57ba4f89c0de6827cd0e3 +guid: c065ab63ea9da2a4dbca3a45cf5cf943 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CrlStoreSelector.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CrlStoreSelector.cs index 725967b..c3de478 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CrlStoreSelector.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509CrlStoreSelector.cs @@ -1,30 +1,29 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) #pragma warning disable using System; -using System.Collections; +using System.Collections.Generic; 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.Utilities.Collections; using BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Extension; namespace BestHTTP.SecureProtocol.Org.BouncyCastle.X509.Store { public class X509CrlStoreSelector - : IX509Selector + : ISelector { // TODO Missing criteria? private X509Certificate certificateChecking; - private DateTimeObject dateAndTime; - private ICollection issuers; + private DateTime? dateAndTime; + private IList issuers; private BigInteger maxCrlNumber; private BigInteger minCrlNumber; - private IX509AttributeCertificate attrCertChecking; + private X509V2AttributeCertificate attrCertChecking; private bool completeCrlEnabled; private bool deltaCrlIndicatorEnabled; private byte[] issuingDistributionPoint; @@ -63,7 +62,7 @@ public X509Certificate CertificateChecking set { certificateChecking = value; } } - public DateTimeObject DateAndTime + public DateTime? DateAndTime { get { return dateAndTime; } set { dateAndTime = value; } @@ -72,10 +71,10 @@ public DateTimeObject DateAndTime /// /// An ICollection of X509Name objects /// - public ICollection Issuers + public IList Issuers { - get { return BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(issuers); } - set { issuers = BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.CreateArrayList(value); } + get { return new List(issuers); } + set { issuers = new List(value); } } public BigInteger MaxCrlNumber @@ -101,7 +100,7 @@ public BigInteger MinCrlNumber * null) * @see #getAttrCertificateChecking() */ - public IX509AttributeCertificate AttrCertChecking + public X509V2AttributeCertificate AttrCertChecking { get { return attrCertChecking; } set { this.attrCertChecking = value; } @@ -183,11 +182,8 @@ public BigInteger MaxBaseCrlNumber set { this.maxBaseCrlNumber = value; } } - public virtual bool Match( - object obj) + public virtual bool Match(X509Crl c) { - X509Crl c = obj as X509Crl; - if (c == null) return false; @@ -195,7 +191,7 @@ public virtual bool Match( { DateTime dt = dateAndTime.Value; DateTime tu = c.ThisUpdate; - DateTimeObject nu = c.NextUpdate; + DateTime? nu = c.NextUpdate; if (dt.CompareTo(tu) < 0 || nu == null || dt.CompareTo(nu.Value) >= 0) return false; diff --git a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509StoreFactory.cs b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509StoreFactory.cs index 2336f4e..0454b34 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509StoreFactory.cs +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509StoreFactory.cs @@ -1,69 +1,3 @@ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) -#pragma warning disable -using System; -using System.Collections; -#if UNITY_WSA && !UNITY_EDITOR && !ENABLE_IL2CPP -using System.TypeFix; -#endif - -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/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509StoreFactory.cs.meta b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509StoreFactory.cs.meta index f60d949..ef6de67 100644 --- a/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509StoreFactory.cs.meta +++ b/Assets/URS/Best HTTP/Source/SecureProtocol/x509/store/X509StoreFactory.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 7fe5a804c6168c344a5147f544de5a2f +guid: 2756db2be5ed60c4a9f25ba9608ae2d0 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Assets/URS/Best HTTP/Source/ServerSentEvents/EventSource.cs b/Assets/URS/Best HTTP/Source/ServerSentEvents/EventSource.cs index e451a97..8572db1 100644 --- a/Assets/URS/Best HTTP/Source/ServerSentEvents/EventSource.cs +++ b/Assets/URS/Best HTTP/Source/ServerSentEvents/EventSource.cs @@ -104,6 +104,7 @@ private set public HostConnectionKey ConnectionKey { get; private set; } public bool IsClosed { get { return this.State == States.Closed; } } + public LoggingContext LoggingContext { get; private set; } #if !UNITY_WEBGL || UNITY_EDITOR @@ -213,7 +214,7 @@ public EventSource(Uri uri, int readBufferSizeOverride = 0) this.ReconnectionTime = TimeSpan.FromMilliseconds(2000); this.ConnectionKey = new HostConnectionKey(this.Uri.Host, HostDefinition.GetKeyFor(this.Uri -#if !BESTHTTP_DISABLE_PROXY +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) , HTTPManager.Proxy #endif )); diff --git a/Assets/URS/Best HTTP/Source/SignalR/Connection.cs b/Assets/URS/Best HTTP/Source/SignalR/Connection.cs index fb59b70..d278fba 100644 --- a/Assets/URS/Best HTTP/Source/SignalR/Connection.cs +++ b/Assets/URS/Best HTTP/Source/SignalR/Connection.cs @@ -1,4 +1,4 @@ -#if !BESTHTTP_DISABLE_SIGNALR +#if !BESTHTTP_DISABLE_SIGNALR using System; using System.Text; @@ -13,6 +13,7 @@ using PlatformSupport.Collections.ObjectModel; using BestHTTP.Connections; +using BestHTTP.PlatformSupport.Text; #if !NETFX_CORE using PlatformSupport.Collections.Specialized; @@ -367,7 +368,7 @@ private string QueryParams if (!string.IsNullOrEmpty(BuiltQueryParams)) return BuiltQueryParams; - StringBuilder sb = new StringBuilder(AdditionalQueryParams.Count * 4); + StringBuilder sb = StringBuilderPool.Get(AdditionalQueryParams.Count * 4); //new StringBuilder(AdditionalQueryParams.Count * 4); foreach (var kvp in AdditionalQueryParams) { @@ -381,7 +382,7 @@ private string QueryParams } } - return BuiltQueryParams = sb.ToString(); + return BuiltQueryParams = StringBuilderPool.ReleaseAndGrab(sb); } } @@ -1295,4 +1296,4 @@ void OnPingRequestFinished(HTTPRequest req, HTTPResponse resp) } } -#endif \ No newline at end of file +#endif diff --git a/Assets/URS/Best HTTP/Source/SignalRCore/HelperClasses.cs b/Assets/URS/Best HTTP/Source/SignalRCore/HelperClasses.cs index cfc2ee2..0d13337 100644 --- a/Assets/URS/Best HTTP/Source/SignalRCore/HelperClasses.cs +++ b/Assets/URS/Best HTTP/Source/SignalRCore/HelperClasses.cs @@ -136,6 +136,20 @@ public CallbackDescriptor(Type[] paramTypes, Action callback) } } + struct FunctionCallbackDescriptor + { + public readonly Type ReturnType; + public readonly Type[] ParamTypes; + public readonly Func Callback; + + public FunctionCallbackDescriptor(Type returnType, Type[] paramTypes, Func callback) + { + this.ReturnType = returnType; + this.ParamTypes = paramTypes; + this.Callback = callback; + } + } + internal struct InvocationDefinition { public Action callback; @@ -145,24 +159,31 @@ internal struct InvocationDefinition internal sealed class Subscription { public List callbacks = new List(1); + public List functionCallbacks; public void Add(Type[] paramTypes, Action callback) { this.callbacks.Add(new CallbackDescriptor(paramTypes, callback)); } - public void Remove(Action callback) + public void AddFunc(Type resultType, Type[] paramTypes, Func callback) { - int idx = -1; - for (int i = 0; i < this.callbacks.Count && idx == -1; ++i) - if (this.callbacks[i].Callback == callback) - idx = i; + if (this.functionCallbacks == null) + this.functionCallbacks = new List(1); - if (idx != -1) - this.callbacks.RemoveAt(idx); + this.functionCallbacks.Add(new FunctionCallbackDescriptor(resultType, paramTypes, callback)); } } + public sealed class WebsocketOptions + { +#if !BESTHTTP_DISABLE_WEBSOCKET && (!UNITY_WEBGL || UNITY_EDITOR) + public Func ExtensionsFactory { get; set; } = WebSocket.WebSocket.GetDefaultExtensions; + + public TimeSpan? PingIntervalOverride { get; set; } = TimeSpan.Zero; +#endif + } + public sealed class HubOptions { /// @@ -195,6 +216,11 @@ public sealed class HubOptions /// public TimeSpan ConnectTimeout { get; set; } + /// + /// Customization options for the websocket transport. + /// + public WebsocketOptions WebsocketOptions { get; set; } = new WebsocketOptions(); + public HubOptions() { this.SkipNegotiation = false; diff --git a/Assets/URS/Best HTTP/Source/SignalRCore/HubConnection.cs b/Assets/URS/Best HTTP/Source/SignalRCore/HubConnection.cs index bc3a6fc..3b449bc 100644 --- a/Assets/URS/Best HTTP/Source/SignalRCore/HubConnection.cs +++ b/Assets/URS/Best HTTP/Source/SignalRCore/HubConnection.cs @@ -153,6 +153,8 @@ private set { private ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); + private bool pausedInLastFrame; + public HubConnection(Uri hubUri, IProtocol protocol) : this(hubUri, protocol, new HubOptions()) { @@ -192,7 +194,7 @@ public void StartConnect() { HTTPManager.Logger.Information("HubConnection", "StartConnect - Authenticating", this.Context); - SetState(ConnectionStates.Authenticating); + SetState(ConnectionStates.Authenticating, null, this.defaultReconnect); this.AuthenticationProvider.OnAuthenticationSucceded += OnAuthenticationSucceded; this.AuthenticationProvider.OnAuthenticationFailed += OnAuthenticationFailed; @@ -263,7 +265,7 @@ private void OnAuthenticationFailed(IAuthenticationProvider provider, string rea this.AuthenticationProvider.OnAuthenticationSucceded -= OnAuthenticationSucceded; this.AuthenticationProvider.OnAuthenticationFailed -= OnAuthenticationFailed; - SetState(ConnectionStates.Closed, reason); + SetState(ConnectionStates.Closed, reason, this.defaultReconnect); } private void StartNegotiation() @@ -272,7 +274,7 @@ private void StartNegotiation() if (this.State == ConnectionStates.CloseInitiated) { - SetState(ConnectionStates.Closed); + SetState(ConnectionStates.Closed, null, this.defaultReconnect); return; } @@ -286,7 +288,7 @@ private void StartNegotiation() } #endif - SetState(ConnectionStates.Negotiating); + SetState(ConnectionStates.Negotiating, null, this.defaultReconnect); // https://github.com/dotnet/aspnetcore/blob/master/src/SignalR/docs/specs/TransportProtocols.md#post-endpoint-basenegotiate-request // Send out a negotiation request. While we could skip it and connect right with the websocket transport @@ -325,7 +327,7 @@ private void ConnectImpl(TransportTypes transport) case TransportTypes.WebSocket: if (this.NegotiationResult != null && !IsTransportSupported("WebSockets")) { - SetState(ConnectionStates.Closed, "Couldn't use preferred transport, as the 'WebSockets' transport isn't supported by the server!"); + SetState(ConnectionStates.Closed, "Couldn't use preferred transport, as the 'WebSockets' transport isn't supported by the server!", this.defaultReconnect); return; } @@ -337,7 +339,7 @@ private void ConnectImpl(TransportTypes transport) case TransportTypes.LongPolling: if (this.NegotiationResult != null && !IsTransportSupported("LongPolling")) { - SetState(ConnectionStates.Closed, "Couldn't use preferred transport, as the 'LongPolling' transport isn't supported by the server!"); + SetState(ConnectionStates.Closed, "Couldn't use preferred transport, as the 'LongPolling' transport isn't supported by the server!", this.defaultReconnect); return; } @@ -346,7 +348,7 @@ private void ConnectImpl(TransportTypes transport) break; default: - SetState(ConnectionStates.Closed, "Unsupported transport: " + transport); + SetState(ConnectionStates.Closed, "Unsupported transport: " + transport, this.defaultReconnect); break; } @@ -384,7 +386,7 @@ private void OnNegotiationRequestFinished(HTTPRequest req, HTTPResponse resp) if (this.State == ConnectionStates.CloseInitiated) { - SetState(ConnectionStates.Closed); + SetState(ConnectionStates.Closed, null, this.defaultReconnect); return; } @@ -409,7 +411,7 @@ private void OnNegotiationRequestFinished(HTTPRequest req, HTTPResponse resp) { if (this.NegotiationResult.Url != null) { - this.SetState(ConnectionStates.Redirected); + this.SetState(ConnectionStates.Redirected, null, this.defaultReconnect); if (++this.RedirectCount >= this.Options.MaxRedirects) errorReason = string.Format("MaxRedirects ({0:N0}) reached!", this.Options.MaxRedirects); @@ -470,29 +472,30 @@ private void OnNegotiationRequestFinished(HTTPRequest req, HTTPResponse resp) this.NegotiationResult = new NegotiationResult(); this.NegotiationResult.NegotiationResponse = resp; - SetState(ConnectionStates.Closed, errorReason); + SetState(ConnectionStates.Closed, errorReason, this.defaultReconnect); } } public void StartClose() { HTTPManager.Logger.Verbose("HubConnection", "StartClose", this.Context); + this.defaultReconnect = false; switch(this.State) { case ConnectionStates.Initial: - SetState(ConnectionStates.Closed); + SetState(ConnectionStates.Closed, null, this.defaultReconnect); break; case ConnectionStates.Authenticating: this.AuthenticationProvider.OnAuthenticationSucceded -= OnAuthenticationSucceded; this.AuthenticationProvider.OnAuthenticationFailed -= OnAuthenticationFailed; this.AuthenticationProvider.Cancel(); - SetState(ConnectionStates.Closed); + SetState(ConnectionStates.Closed, null, this.defaultReconnect); break; case ConnectionStates.Reconnecting: - SetState(ConnectionStates.Closed); + SetState(ConnectionStates.Closed, null, this.defaultReconnect); break; case ConnectionStates.CloseInitiated: @@ -501,10 +504,17 @@ public void StartClose() break; default: - SetState(ConnectionStates.CloseInitiated); + if (HTTPManager.IsQuitting) + { + SetState(ConnectionStates.Closed, null, this.defaultReconnect); + } + else + { + SetState(ConnectionStates.CloseInitiated, null, this.defaultReconnect); - if (this.Transport != null) - this.Transport.StartClose(); + if (this.Transport != null) + this.Transport.StartClose(); + } break; } } @@ -696,13 +706,17 @@ private long InvokeImp(string target, object[] args, Action callback, T if (!blockingInvocation) if (!this.invocations.TryAdd(invocationId, new InvocationDefinition { callback = callback, returnType = itemType })) - HTTPManager.Logger.Warning("HubConnection", "InvokeImp - invocations already contains id: " + invocationId); + HTTPManager.Logger.Warning("HubConnection", "InvokeImp - invocations already contains id: " + invocationId, this.Context); return invocationId; } internal void SendMessage(Message message) { + // https://github.com/Benedicht/BestHTTP-Issues/issues/146 + if (this.State == ConnectionStates.Closed) + return; + if (HTTPManager.Logger.Level == Logger.Loglevels.All) HTTPManager.Logger.Verbose("HubConnection", "SendMessage: " + message.ToString(), this.Context); @@ -784,7 +798,7 @@ public DownStreamItemController GetDownStreamController(string tar if (callback != null) if (!this.invocations.TryAdd(invocationId, new InvocationDefinition { callback = callback, returnType = typeof(TDown) })) - HTTPManager.Logger.Warning("HubConnection", "GetDownStreamController - invocations already contains id: " + invocationId); + HTTPManager.Logger.Warning("HubConnection", "GetDownStreamController - invocations already contains id: " + invocationId, this.Context); return controller; } @@ -855,7 +869,7 @@ public UpStreamItemController GetUpStreamController(string tar SendMessage(messageToSend); if (!this.invocations.TryAdd(invocationId, new InvocationDefinition { callback = callback, returnType = typeof(TResult) })) - HTTPManager.Logger.Warning("HubConnection", "GetUpStreamController - invocations already contains id: " + invocationId); + HTTPManager.Logger.Warning("HubConnection", "GetUpStreamController - invocations already contains id: " + invocationId, this.Context); return controller; } @@ -900,6 +914,38 @@ private void On(string methodName, Type[] paramTypes, Action callback) .Add(paramTypes, callback); } + public void On(string methodName, Func callback) + { + OnFunc(methodName, null, (args) => callback()); + } + + public void On(string methodName, Func callback) + { + OnFunc(methodName, new Type[] { typeof(T1) }, (args) => callback((T1)args[0])); + } + + public void On(string methodName, Func callback) + { + OnFunc(methodName, new Type[] { typeof(T1), typeof(T2) }, (args) => callback((T1)args[0], (T2)args[1])); + } + + public void On(string methodName, Func callback) + { + OnFunc(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, Func callback) + { + OnFunc(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])); + } + + // https://github.com/dotnet/aspnetcore/issues/5280 + private void OnFunc(string methodName, Type[] paramTypes, Func callback) + { + this.subscriptions.GetOrAdd(methodName, _ => new Subscription()) + .AddFunc(typeof(Result), paramTypes, callback); + } + /// /// Remove all event handlers for that subscribed with an On call. /// @@ -926,9 +972,21 @@ internal Type GetItemType(long invocationId) return def.returnType; } + List delayedMessages; internal void OnMessages(List messages) { this.lastMessageReceivedAt = DateTime.Now; + + if (pausedInLastFrame) + { + if (this.delayedMessages == null) + this.delayedMessages = new List(messages.Count); + foreach(var msg in messages) + delayedMessages.Add(msg); + + messages.Clear(); + } + for (int messageIdx = 0; messageIdx < messages.Count; ++messageIdx) { var message = messages[messageIdx]; @@ -948,11 +1006,17 @@ internal void OnMessages(List messages) switch (message.type) { + case MessageTypes.Handshake: + break; + case MessageTypes.Invocation: { Subscription subscribtion = null; if (this.subscriptions.TryGetValue(message.target, out subscribtion)) { + if (subscribtion.callbacks?.Count == 0) + HTTPManager.Logger.Warning("HubConnection", $"No callback for invocation '{message.ToString()}'", this.Context); + for (int i = 0; i < subscribtion.callbacks.Count; ++i) { var callbackDesc = subscribtion.callbacks[i]; @@ -976,7 +1040,53 @@ internal void OnMessages(List messages) HTTPManager.Logger.Exception("HubConnection", "OnMessages - Invocation - Invoke", ex, this.Context); } } + + if (subscribtion.functionCallbacks?.Count == 0) + HTTPManager.Logger.Warning("HubConnection", $"No function callback for invocation '{message.ToString()}'", this.Context); + + if (subscribtion.functionCallbacks != null) + { + for (int i = 0; i < subscribtion.functionCallbacks.Count; ++i) + { + var callbackDesc = subscribtion.functionCallbacks[i]; + + object[] realArgs = null; + try + { + realArgs = this.Protocol.GetRealArguments(callbackDesc.ParamTypes, message.arguments); + } + catch (Exception ex) + { + HTTPManager.Logger.Exception("HubConnection", "OnMessages - Function Invocation - GetRealArguments", ex, this.Context); + } + + try + { + var result = callbackDesc.Callback(realArgs); + + SendMessage(new Message + { + type = MessageTypes.Completion, + invocationId = message.invocationId, + result = result + }); + } + catch (Exception ex) + { + HTTPManager.Logger.Exception("HubConnection", "OnMessages - Function Invocation - Invoke", ex, this.Context); + + SendMessage(new Message + { + type = MessageTypes.Completion, + invocationId = message.invocationId, + error = ex.Message + }); + } + } + } } + else + HTTPManager.Logger.Warning("HubConnection", $"No subscription could be found for invocation '{message.ToString()}'", this.Context); break; } @@ -1060,7 +1170,7 @@ private void Transport_OnStateChanged(TransportStates oldState, TransportStates HTTPManager.Logger.Exception("HubConnection", "Exception in OnTransportEvent user code!", ex, this.Context); } - SetState(ConnectionStates.Connected); + SetState(ConnectionStates.Connected, null, this.defaultReconnect); break; case TransportStates.Failed: @@ -1080,7 +1190,12 @@ private void Transport_OnStateChanged(TransportStates oldState, TransportStates var nextTransport = GetNextTransportToTry(); if (nextTransport == null) - SetState(ConnectionStates.Closed, this.Transport.ErrorReason); + { + var reason = this.Transport.ErrorReason; + this.Transport = null; + + SetState(ConnectionStates.Closed, reason, this.defaultReconnect); + } else ConnectImpl(nextTransport.Value); } @@ -1096,7 +1211,10 @@ private void Transport_OnStateChanged(TransportStates oldState, TransportStates HTTPManager.Logger.Exception("HubConnection", "Exception in OnTransportEvent user code!", ex, this.Context); } - SetState(ConnectionStates.Closed, HTTPManager.IsQuitting ? null : this.Transport.ErrorReason); + var reason = this.Transport.ErrorReason; + this.Transport = null; + + SetState(ConnectionStates.Closed, HTTPManager.IsQuitting ? null : reason, this.defaultReconnect); } break; @@ -1112,7 +1230,9 @@ private void Transport_OnStateChanged(TransportStates oldState, TransportStates HTTPManager.Logger.Exception("HubConnection", "Exception in OnTransportEvent user code!", ex, this.Context); } - SetState(ConnectionStates.Closed); + // Check wheter we have any delayed message and a Close message among them. If there's one, delay the SetState(Close) too. + if (this.delayedMessages == null || this.delayedMessages.FindLast(dm => dm.type == MessageTypes.Close).type != MessageTypes.Close) + SetState(ConnectionStates.Closed, null, this.defaultReconnect); } break; } @@ -1127,12 +1247,10 @@ private void Transport_OnStateChanged(TransportStates oldState, TransportStates return null; } - private void SetState(ConnectionStates state, string errorReason = null, bool allowReconnect = true) + bool defaultReconnect = true; + private void SetState(ConnectionStates state, string errorReason, bool allowReconnect) { - if (string.IsNullOrEmpty(errorReason)) - HTTPManager.Logger.Information("HubConnection", string.Format("SetState - from State: '{0}' to State: '{1}', allowReconnect: {2}", this.State, state, allowReconnect), this.Context); - else - HTTPManager.Logger.Information("HubConnection", string.Format("SetState - from State: '{0}' to State: '{1}', errorReason: '{2}', allowReconnect: {3}", this.State, state, errorReason, allowReconnect), this.Context); + HTTPManager.Logger.Information("HubConnection", string.Format("SetState - from State: '{0}' to State: '{1}', errorReason: '{2}', allowReconnect: {3}, isQuitting: {4}", this.State, state, errorReason, allowReconnect, HTTPManager.IsQuitting), this.Context); if (this.State == state) return; @@ -1187,6 +1305,9 @@ private void SetState(ConnectionStates state, string errorReason = null, bool al this.reconnectStartTime = DateTime.MinValue; this.reconnectAt = DateTime.MinValue; + HTTPUpdateDelegator.OnApplicationForegroundStateChanged -= this.OnApplicationForegroundStateChanged; + HTTPUpdateDelegator.OnApplicationForegroundStateChanged += this.OnApplicationForegroundStateChanged; + break; case ConnectionStates.Closed: @@ -1208,7 +1329,7 @@ private void SetState(ConnectionStates state, string errorReason = null, bool al this.invocations.Clear(); // No errorReason? It's an expected closure. - if (errorReason == null) + if (errorReason == null && (!allowReconnect || HTTPManager.IsQuitting)) { if (this.OnClosed != null) { @@ -1263,7 +1384,7 @@ private void SetState(ConnectionStates state, string errorReason = null, bool al // No more reconnect attempt, we are closing if (nextAttempt == null) { - HTTPManager.Logger.Warning("HubConnecction", "No more reconnect attempt!", this.Context); + HTTPManager.Logger.Warning("HubConnection", "No more reconnect attempt!", this.Context); // Clean up everything this.currentContext = new RetryContext(); @@ -1272,14 +1393,14 @@ private void SetState(ConnectionStates state, string errorReason = null, bool al } else { - HTTPManager.Logger.Information("HubConnecction", "Next reconnect attempt after " + nextAttempt.Value.ToString(), this.Context); + HTTPManager.Logger.Information("HubConnection", "Next reconnect attempt after " + nextAttempt.Value.ToString(), this.Context); this.currentContext = context; this.currentContext.PreviousRetryCount += 1; this.reconnectAt = DateTime.Now + nextAttempt.Value; - this.SetState(ConnectionStates.Reconnecting); + this.SetState(ConnectionStates.Reconnecting, null, this.defaultReconnect); return; } @@ -1297,14 +1418,17 @@ private void SetState(ConnectionStates state, string errorReason = null, bool al } } } - - HTTPManager.Heartbeats.Unsubscribe(this); - this.rwLock.Dispose(); - this.rwLock = null; break; } } + private void OnApplicationForegroundStateChanged(bool isPaused) + { + pausedInLastFrame = !isPaused; + + HTTPManager.Logger.Information("HubConnection", $"OnApplicationForegroundStateChanged isPaused: {isPaused} pausedInLastFrame: {pausedInLastFrame}", this.Context); + } + void BestHTTP.Extensions.IHeartbeat.OnHeartbeatUpdate(TimeSpan dif) { switch (this.State) @@ -1335,37 +1459,78 @@ void BestHTTP.Extensions.IHeartbeat.OnHeartbeatUpdate(TimeSpan dif) this.Transport.StartClose(); } - SetState(ConnectionStates.Closed, string.Format("Couldn't connect in the given time({0})!", this.Options.ConnectTimeout)); + SetState(ConnectionStates.Closed, string.Format("Couldn't connect in the given time({0})!", this.Options.ConnectTimeout), this.defaultReconnect); } break; case ConnectionStates.Connected: - if (this.Options.PingInterval != TimeSpan.Zero && DateTime.Now - this.lastMessageReceivedAt >= this.Options.PingTimeoutInterval) + if (this.delayedMessages?.Count > 0) { - // The transport itself can be in a failure state or in a completely valid one, so while we do not want to receive anything from it, we have to try to close it - if (this.Transport != null) + pausedInLastFrame = false; + try { - this.Transport.OnStateChanged -= Transport_OnStateChanged; - this.Transport.StartClose(); + // if there's any Close message clear any other one. + int idx = this.delayedMessages.FindLastIndex(dm => dm.type == MessageTypes.Close); + if (idx > 0) + this.delayedMessages.RemoveRange(0, idx); + + OnMessages(this.delayedMessages); + } + finally + { + this.delayedMessages.Clear(); } + } - SetState(ConnectionStates.Closed, string.Format("PingInterval set to '{0}' and no message is received since '{1}'. PingTimeoutInterval: '{2}'", this.Options.PingInterval, this.lastMessageReceivedAt, this.Options.PingTimeoutInterval)); + // Still connected? Check pinging. + if (this.State == ConnectionStates.Connected) + { + if (this.Options.PingInterval != TimeSpan.Zero && DateTime.Now - this.lastMessageReceivedAt >= this.Options.PingTimeoutInterval) + { + // The transport itself can be in a failure state or in a completely valid one, so while we do not want to receive anything from it, we have to try to close it + if (this.Transport != null) + { + this.Transport.OnStateChanged -= Transport_OnStateChanged; + this.Transport.StartClose(); + } + + SetState(ConnectionStates.Closed, + string.Format("PingInterval set to '{0}' and no message is received since '{1}'. PingTimeoutInterval: '{2}'", this.Options.PingInterval, this.lastMessageReceivedAt, this.Options.PingTimeoutInterval), + this.defaultReconnect); + } + else if (this.Options.PingInterval != TimeSpan.Zero && DateTime.Now - this.lastMessageSentAt >= this.Options.PingInterval) + SendMessage(new Message() { type = MessageTypes.Ping }); } - else if (this.Options.PingInterval != TimeSpan.Zero && DateTime.Now - this.lastMessageSentAt >= this.Options.PingInterval) - SendMessage(new Message() { type = MessageTypes.Ping }); break; case ConnectionStates.Reconnecting: if (this.reconnectAt != DateTime.MinValue && DateTime.Now >= this.reconnectAt) { + this.delayedMessages?.Clear(); this.connectionStartedAt = DateTime.Now; this.reconnectAt = DateTime.MinValue; this.triedoutTransports.Clear(); this.StartConnect(); } break; + + case ConnectionStates.Closed: + CleanUp(); + break; } } + + private void CleanUp() + { + HTTPManager.Logger.Information("HubConnection", "CleanUp", this.Context); + + this.delayedMessages?.Clear(); + HTTPManager.Heartbeats.Unsubscribe(this); + HTTPUpdateDelegator.OnApplicationForegroundStateChanged -= this.OnApplicationForegroundStateChanged; + + this.rwLock?.Dispose(); + this.rwLock = null; + } } } diff --git a/Assets/URS/Best HTTP/Source/SignalRCore/JsonProtocol.cs b/Assets/URS/Best HTTP/Source/SignalRCore/JsonProtocol.cs index 9d0ec3e..8d6370e 100644 --- a/Assets/URS/Best HTTP/Source/SignalRCore/JsonProtocol.cs +++ b/Assets/URS/Best HTTP/Source/SignalRCore/JsonProtocol.cs @@ -163,14 +163,22 @@ public BufferSegment EncodeMessage(Message message) break; case MessageTypes.Ping: - result = this.Encoder.Encode(new PingMessage()); + //result = this.Encoder.Encode(new PingMessage()); + // fast path to encode a well-known json string + result = EncodeKnown("{\"type\":6}"); break; case MessageTypes.Close: if (!string.IsNullOrEmpty(message.error)) + { result = this.Encoder.Encode(new CloseWithErrorMessage() { error = message.error }); + } else - result = this.Encoder.Encode(new CloseMessage()); + { + //result = this.Encoder.Encode(new CloseMessage()); + // fast path to encode a well-known json string + result = EncodeKnown("{\"type\":7}"); + } break; } @@ -180,6 +188,15 @@ public BufferSegment EncodeMessage(Message message) return result; } + private BufferSegment EncodeKnown(string json) + { + int len = System.Text.Encoding.UTF8.GetByteCount(json); + byte[] buffer = BufferPool.Get(len + 1, true); + System.Text.Encoding.UTF8.GetBytes(json, 0, json.Length, buffer, 0); + buffer[len] = (byte)JsonProtocol.Separator; + return new BufferSegment(buffer, 0, len + 1); + } + public object[] GetRealArguments(Type[] argTypes, object[] arguments) { if (arguments == null || arguments.Length == 0) diff --git a/Assets/URS/Best HTTP/Source/SignalRCore/Messages/Invocation.cs b/Assets/URS/Best HTTP/Source/SignalRCore/Messages/Invocation.cs index be0146b..04f129a 100644 --- a/Assets/URS/Best HTTP/Source/SignalRCore/Messages/Invocation.cs +++ b/Assets/URS/Best HTTP/Source/SignalRCore/Messages/Invocation.cs @@ -3,72 +3,82 @@ namespace BestHTTP.SignalRCore.Messages { + [PlatformSupport.IL2CPP.Preserve] public struct Completion { - public MessageTypes type; - public string invocationId; + [PlatformSupport.IL2CPP.Preserve] public MessageTypes type; + [PlatformSupport.IL2CPP.Preserve] public string invocationId; } + [PlatformSupport.IL2CPP.Preserve] public struct CompletionWithResult { - public MessageTypes type; - public string invocationId; - public object result; + [PlatformSupport.IL2CPP.Preserve] public MessageTypes type; + [PlatformSupport.IL2CPP.Preserve] public string invocationId; + [PlatformSupport.IL2CPP.Preserve] public object result; } + [PlatformSupport.IL2CPP.Preserve] public struct CompletionWithError { - public MessageTypes type; - public string invocationId; - public string error; + [PlatformSupport.IL2CPP.Preserve] public MessageTypes type; + [PlatformSupport.IL2CPP.Preserve] public string invocationId; + [PlatformSupport.IL2CPP.Preserve] public string error; } + [PlatformSupport.IL2CPP.Preserve] public struct StreamItemMessage { - public MessageTypes type; - public string invocationId; - public object item; + [PlatformSupport.IL2CPP.Preserve] public MessageTypes type; + [PlatformSupport.IL2CPP.Preserve] public string invocationId; + [PlatformSupport.IL2CPP.Preserve] public object item; } + [PlatformSupport.IL2CPP.Preserve] public struct InvocationMessage { - public MessageTypes type; - public string invocationId; - public bool nonblocking; - public string target; - public object[] arguments; + [PlatformSupport.IL2CPP.Preserve] public MessageTypes type; + [PlatformSupport.IL2CPP.Preserve] public string invocationId; + [PlatformSupport.IL2CPP.Preserve] public bool nonblocking; + [PlatformSupport.IL2CPP.Preserve] public string target; + [PlatformSupport.IL2CPP.Preserve] public object[] arguments; } + [PlatformSupport.IL2CPP.Preserve] public struct UploadInvocationMessage { - public MessageTypes type; - public string invocationId; - public bool nonblocking; - public string target; - public object[] arguments; - public string[] streamIds; + [PlatformSupport.IL2CPP.Preserve] public MessageTypes type; + [PlatformSupport.IL2CPP.Preserve] public string invocationId; + [PlatformSupport.IL2CPP.Preserve] public bool nonblocking; + [PlatformSupport.IL2CPP.Preserve] public string target; + [PlatformSupport.IL2CPP.Preserve] public object[] arguments; + [PlatformSupport.IL2CPP.Preserve] public string[] streamIds; } + [PlatformSupport.IL2CPP.Preserve] public struct CancelInvocationMessage { - public MessageTypes type { get { return MessageTypes.CancelInvocation; } } - public string invocationId; + [PlatformSupport.IL2CPP.Preserve] public MessageTypes type { get { return MessageTypes.CancelInvocation; } } + [PlatformSupport.IL2CPP.Preserve] public string invocationId; } + [PlatformSupport.IL2CPP.Preserve] public struct PingMessage { - public MessageTypes type { get { return MessageTypes.Ping; } } + [PlatformSupport.IL2CPP.Preserve] public MessageTypes type { get { return MessageTypes.Ping; } } } + [PlatformSupport.IL2CPP.Preserve] public struct CloseMessage { - public MessageTypes type { get { return MessageTypes.Close; } } + [PlatformSupport.IL2CPP.Preserve] public MessageTypes type { get { return MessageTypes.Close; } } } + [PlatformSupport.IL2CPP.Preserve] public struct CloseWithErrorMessage { - public MessageTypes type { get { return MessageTypes.Close; } } - public string error; + [PlatformSupport.IL2CPP.Preserve] public MessageTypes type { get { return MessageTypes.Close; } } + [PlatformSupport.IL2CPP.Preserve] public string error; } } #endif diff --git a/Assets/URS/Best HTTP/Source/SignalRCore/Messages/Message.cs b/Assets/URS/Best HTTP/Source/SignalRCore/Messages/Message.cs index 7488286..aaff446 100644 --- a/Assets/URS/Best HTTP/Source/SignalRCore/Messages/Message.cs +++ b/Assets/URS/Best HTTP/Source/SignalRCore/Messages/Message.cs @@ -64,6 +64,8 @@ public override string ToString() { switch (this.type) { + case MessageTypes.Handshake: + return string.Format("[Handshake Error: '{0}'", this.error); case MessageTypes.Invocation: return string.Format("[Invocation Id: {0}, Target: '{1}', Argument count: {2}, Stream Ids: {3}]", this.invocationId, this.target, this.arguments != null ? this.arguments.Length : 0, this.streamIds != null ? this.streamIds.Length : 0); case MessageTypes.StreamItem: diff --git a/Assets/URS/Best HTTP/Source/SignalRCore/Transports/LongPollingTransport.cs b/Assets/URS/Best HTTP/Source/SignalRCore/Transports/LongPollingTransport.cs index 68277c0..a9caaa5 100644 --- a/Assets/URS/Best HTTP/Source/SignalRCore/Transports/LongPollingTransport.cs +++ b/Assets/URS/Best HTTP/Source/SignalRCore/Transports/LongPollingTransport.cs @@ -240,7 +240,14 @@ private void OnSendMessagesFinished(HTTPRequest req, HTTPResponse resp) // The connections is OK, call OnMessages with an empty list to update HubConnection's lastMessageReceivedAt. this.messages.Clear(); - this.connection.OnMessages(this.messages); + try + { + this.connection.OnMessages(this.messages); + } + finally + { + this.messages.Clear(); + } SendMessages(); @@ -301,7 +308,7 @@ private void OnPollRequestFinished(HTTPRequest req, HTTPResponse resp) // Parse and dispatch messages only if the transport is still in connected state if (this.State == TransportStates.Connecting) { - int idx = Array.IndexOf(resp.Data, (byte)JsonProtocol.Separator, 0); + int idx = resp.Data != null ? Array.IndexOf(resp.Data, (byte)JsonProtocol.Separator, 0) : -1; if (idx > 0) { base.HandleHandshakeResponse(System.Text.Encoding.UTF8.GetString(resp.Data, 0, idx)); diff --git a/Assets/URS/Best HTTP/Source/SignalRCore/Transports/TransportBase.cs b/Assets/URS/Best HTTP/Source/SignalRCore/Transports/TransportBase.cs index d4204cb..1920e96 100644 --- a/Assets/URS/Best HTTP/Source/SignalRCore/Transports/TransportBase.cs +++ b/Assets/URS/Best HTTP/Source/SignalRCore/Transports/TransportBase.cs @@ -4,6 +4,7 @@ using System.Text; using BestHTTP.Logger; using BestHTTP.PlatformSupport.Memory; +using BestHTTP.PlatformSupport.Text; namespace BestHTTP.SignalRCore.Transports { @@ -104,7 +105,7 @@ protected void HandleHandshakeResponse(string data) this.State = string.IsNullOrEmpty(this.ErrorReason) ? TransportStates.Connected : TransportStates.Failed; } - StringBuilder queryBuilder = new StringBuilder(3); + //StringBuilder queryBuilder = new StringBuilder(3); protected Uri BuildUri(Uri baseUri) { if (this.connection.NegotiationResult == null) @@ -112,7 +113,7 @@ protected Uri BuildUri(Uri baseUri) UriBuilder builder = new UriBuilder(baseUri); - queryBuilder.Length = 0; + var queryBuilder = StringBuilderPool.Get(3); queryBuilder.Append(baseUri.Query); if (!string.IsNullOrEmpty(this.connection.NegotiationResult.ConnectionToken)) @@ -120,7 +121,7 @@ protected Uri BuildUri(Uri baseUri) else if (!string.IsNullOrEmpty(this.connection.NegotiationResult.ConnectionId)) queryBuilder.Append("&id=").Append(this.connection.NegotiationResult.ConnectionId); - builder.Query = queryBuilder.ToString(); + builder.Query = StringBuilderPool.ReleaseAndGrab(queryBuilder); if (builder.Query.StartsWith("??")) builder.Query = builder.Query.Substring(2); diff --git a/Assets/URS/Best HTTP/Source/SignalRCore/Transports/WebsocketTransport.cs b/Assets/URS/Best HTTP/Source/SignalRCore/Transports/WebsocketTransport.cs index 5f94690..73d41c7 100644 --- a/Assets/URS/Best HTTP/Source/SignalRCore/Transports/WebsocketTransport.cs +++ b/Assets/URS/Best HTTP/Source/SignalRCore/Transports/WebsocketTransport.cs @@ -45,18 +45,36 @@ public override void StartConnect() HTTPManager.Logger.Verbose("WebSocketTransport", "StartConnect connecting to Uri: " + uri.ToString(), this.Context); - this.webSocket = new WebSocket.WebSocket(uri); + this.webSocket = new WebSocket.WebSocket(uri, string.Empty, string.Empty +#if !UNITY_WEBGL || UNITY_EDITOR + , (this.connection.Options.WebsocketOptions?.ExtensionsFactory ?? WebSocket.WebSocket.GetDefaultExtensions)?.Invoke() +#endif + ); + this.webSocket.Context.Add("Transport", this.Context); } #if !UNITY_WEBGL || UNITY_EDITOR + if (this.connection.Options.WebsocketOptions?.PingIntervalOverride is TimeSpan ping) + { + if (ping > TimeSpan.Zero) + { + this.webSocket.StartPingThread = true; + this.webSocket.PingFrequency = (int)ping.TotalMilliseconds; + } + else + this.webSocket.StartPingThread = false; + } + else + this.webSocket.StartPingThread = true; + // prepare the internal http request if (this.connection.AuthenticationProvider != null) webSocket.OnInternalRequestCreated = (ws, internalRequest) => this.connection.AuthenticationProvider.PrepareRequest(internalRequest); #endif this.webSocket.OnOpen += OnOpen; this.webSocket.OnMessage += OnMessage; - this.webSocket.OnBinary += OnBinary; + this.webSocket.OnBinaryNoAlloc += OnBinaryNoAlloc; this.webSocket.OnError += OnError; this.webSocket.OnClosed += OnClosed; @@ -71,13 +89,13 @@ public override void Send(BufferSegment msg) { BufferPool.Release(msg.Data); - this.OnError(this.webSocket, "Send called while the websocket is null or isn't open! Transport's State: " + this.State); + //this.OnError(this.webSocket, "Send called while the websocket is null or isn't open! Transport's State: " + this.State); return; } - this.webSocket.Send(msg.Data, (ulong)msg.Offset, (ulong)msg.Count); - - BufferPool.Release(msg.Data); + if (HTTPManager.Logger.Level == Logger.Loglevels.All) + HTTPManager.Logger.Verbose("WebSocketTransport", "Send: " + msg.ToString(), this.Context); + this.webSocket.SendAsBinary(msg); } // The websocket connection is open @@ -95,13 +113,6 @@ private void OnMessage(WebSocket.WebSocket webSocket, string data) if (this.State == TransportStates.Closing) return; - if (this.State == TransportStates.Connecting) - { - HandleHandshakeResponse(data); - - return; - } - this.messages.Clear(); try { @@ -110,11 +121,34 @@ private void OnMessage(WebSocket.WebSocket webSocket, string data) byte[] buffer = BufferPool.Get(len, true); try { + // Clear the buffer, it might have previous messages in it with the record separator somewhere it doesn't gets overwritten by the new data Array.Clear(buffer, 0, buffer.Length); - System.Text.Encoding.UTF8.GetBytes(data, 0, data.Length, buffer, 0); this.connection.Protocol.ParseMessages(new BufferSegment(buffer, 0, len), ref this.messages); + + if (this.State == TransportStates.Connecting) + { + // we expect a handshake response in this case + + if (this.messages.Count == 0) + { + this.ErrorReason = $"Expecting handshake response, but message({data}) couldn't be parsed!"; + this.State = TransportStates.Failed; + return; + } + + var message = this.messages[0]; + if (message.type != MessageTypes.Handshake) + { + this.ErrorReason = $"Expecting handshake response, but the first message is {message.type}!"; + this.State = TransportStates.Failed; + return; + } + + this.ErrorReason = message.error; + this.State = string.IsNullOrEmpty(message.error) ? TransportStates.Connected : TransportStates.Failed; + } } finally { @@ -133,22 +167,64 @@ private void OnMessage(WebSocket.WebSocket webSocket, string data) } } - private void OnBinary(WebSocket.WebSocket webSocket, byte[] data) + private void OnBinaryNoAlloc(WebSocket.WebSocket webSocket, BufferSegment data) { if (this.State == TransportStates.Closing) return; if (this.State == TransportStates.Connecting) { - HandleHandshakeResponse(System.Text.Encoding.UTF8.GetString(data, 0, data.Length)); + int recordSeparatorIdx = Array.FindIndex(data.Data, data.Offset, data.Count, (b) => b == JsonProtocol.Separator); - return; + if (recordSeparatorIdx == -1) + { + this.ErrorReason = $"Expecting handshake response, but message({data}) has no record separator(0x1E)!"; + this.State = TransportStates.Failed; + return; + } + else + { + HandleHandshakeResponse(System.Text.Encoding.UTF8.GetString(data.Data, data.Offset, recordSeparatorIdx - data.Offset)); + + // Skip any other messages sent if handshake is failed + if (this.State != TransportStates.Connected) + return; + + recordSeparatorIdx++; + if (recordSeparatorIdx == data.Offset + data.Count) + return; + + data = new BufferSegment(data.Data, data.Offset + recordSeparatorIdx, data.Count - recordSeparatorIdx); + } } this.messages.Clear(); try { - this.connection.Protocol.ParseMessages(new BufferSegment(data, 0, data.Length), ref this.messages); + this.connection.Protocol.ParseMessages(data, ref this.messages); + + if (this.State == TransportStates.Connecting) + { + // we expect a handshake response in this case + + if (this.messages.Count == 0) + { + this.ErrorReason = $"Expecting handshake response, but message({data}) couldn't be parsed!"; + this.State = TransportStates.Failed; + return; + } + + var message = this.messages[0]; + if (message.type != MessageTypes.Handshake) + { + this.ErrorReason = $"Expecting handshake response, but the first message is {message.type}!"; + this.State = TransportStates.Failed; + return; + } + + this.ErrorReason = message.error; + this.State = string.IsNullOrEmpty(message.error) ? TransportStates.Connected : TransportStates.Failed; + } this.connection.OnMessages(this.messages); } @@ -159,8 +235,6 @@ private void OnBinary(WebSocket.WebSocket webSocket, byte[] data) finally { this.messages.Clear(); - - BufferPool.Release(data); } } @@ -192,7 +266,7 @@ public override void StartClose() { HTTPManager.Logger.Verbose("WebSocketTransport", "StartClose", this.Context); - if (this.webSocket != null) + if (this.webSocket != null && this.webSocket.IsOpen) { this.State = TransportStates.Closing; this.webSocket.Close(); diff --git a/Assets/URS/Best HTTP/Source/SocketIO.3/HandshakeData.cs b/Assets/URS/Best HTTP/Source/SocketIO.3/HandshakeData.cs index 1f9248e..1d21753 100644 --- a/Assets/URS/Best HTTP/Source/SocketIO.3/HandshakeData.cs +++ b/Assets/URS/Best HTTP/Source/SocketIO.3/HandshakeData.cs @@ -33,6 +33,11 @@ public sealed class HandshakeData /// [PlatformSupport.IL2CPP.Preserve] public int PingTimeout { get; private set; } + + /// + /// This defines how many bytes a single message can be, before the server closes the socket. + /// + public int MaxPayload { get; private set; } } } diff --git a/Assets/URS/Best HTTP/Source/SocketIO.3/Parsers/DefaultJsonParser.cs b/Assets/URS/Best HTTP/Source/SocketIO.3/Parsers/DefaultJsonParser.cs index 57456c3..76b4c5e 100644 --- a/Assets/URS/Best HTTP/Source/SocketIO.3/Parsers/DefaultJsonParser.cs +++ b/Assets/URS/Best HTTP/Source/SocketIO.3/Parsers/DefaultJsonParser.cs @@ -118,6 +118,12 @@ public IncomingPacket Parse(SocketManager manager, string from) (eventName, args) = ReadData(manager, packet, payload); break; + case SocketIOEventTypes.BinaryAck: + // Save payload until all attachments arrive + if (packet.AttachementCount > 0) + packet.DecodedArg = payload; + break; + default: // Array (eventName, args) = ReadData(manager, packet, payload); @@ -218,6 +224,7 @@ public IncomingPacket MergeAttachements(SocketManager manager, IncomingPacket pa break; case SocketIOEventTypes.Ack: + case SocketIOEventTypes.BinaryAck: eventName = IncomingPacket.GenerateAcknowledgementNameFromId(packet.Id); subscription = socket.GetSubscription(eventName); diff --git a/Assets/URS/Best HTTP/Source/SocketIO.3/SocketManager.cs b/Assets/URS/Best HTTP/Source/SocketIO.3/SocketManager.cs index f113dfc..7d0d7f8 100644 --- a/Assets/URS/Best HTTP/Source/SocketIO.3/SocketManager.cs +++ b/Assets/URS/Best HTTP/Source/SocketIO.3/SocketManager.cs @@ -8,6 +8,7 @@ using BestHTTP.SocketIO3.Parsers; using BestHTTP.SocketIO3.Events; using BestHTTP.Logger; +using BestHTTP.PlatformSupport.Memory; namespace BestHTTP.SocketIO3 { @@ -207,9 +208,6 @@ public SocketManager(Uri uri, IParser parser, SocketOptions options) { this.Context = new LoggingContext(this); - if (uri.Scheme.StartsWith("ws")) - options.ConnectWith = TransportTypes.WebSocket; - string path = uri.PathAndQuery; if (path.Length <= 1) { @@ -227,6 +225,11 @@ public SocketManager(Uri uri, IParser parser, SocketOptions options) this.State = States.Initial; this.PreviousState = States.Initial; this.Parser = parser ?? new DefaultJsonParser(); + +#if !BESTHTTP_DISABLE_WEBSOCKET + if (uri.Scheme.StartsWith("ws")) + options.ConnectWith = TransportTypes.WebSocket; +#endif } #endregion @@ -355,7 +358,11 @@ void IManager.Close(bool removeSockets) lastPingReceived = DateTime.MinValue; if (removeSockets && OfflinePackets != null) + { + foreach (var packet in OfflinePackets) + BufferPool.Release(packet.PayloadData); OfflinePackets.Clear(); + } // Remove the references from the dictionary too. if (removeSockets) @@ -523,7 +530,8 @@ private void SendOfflinePackets() /// void IManager.SendPacket(OutgoingPacket packet) { - HTTPManager.Logger.Information("SocketManager", "SendPacket " + packet.ToString(), this.Context); + if (HTTPManager.Logger.Level <= Loglevels.Information) + HTTPManager.Logger.Information("SocketManager", "SendPacket " + packet.ToString(), this.Context); ITransport trans = SelectTransport(); @@ -541,7 +549,10 @@ void IManager.SendPacket(OutgoingPacket packet) else { if (packet.IsVolatile) + { + BufferPool.Release(packet.PayloadData); return; + } HTTPManager.Logger.Information("SocketManager", "SendPacket - Offline stashing packet", this.Context); diff --git a/Assets/URS/Best HTTP/Source/SocketIO.3/SocketOptions.cs b/Assets/URS/Best HTTP/Source/SocketIO.3/SocketOptions.cs index f4c49cb..65bf308 100644 --- a/Assets/URS/Best HTTP/Source/SocketIO.3/SocketOptions.cs +++ b/Assets/URS/Best HTTP/Source/SocketIO.3/SocketOptions.cs @@ -3,6 +3,8 @@ using System; using System.Text; +using BestHTTP.PlatformSupport.Text; + using PlatformSupport.Collections.ObjectModel; #if !NETFX_CORE @@ -15,6 +17,15 @@ namespace BestHTTP.SocketIO3 { public delegate void HTTPRequestCallbackDelegate(SocketManager manager, HTTPRequest request); + public sealed class WebsocketOptions + { +#if !BESTHTTP_DISABLE_WEBSOCKET && (!UNITY_WEBGL || UNITY_EDITOR) + public Func ExtensionsFactory { get; set; } = WebSocket.WebSocket.GetDefaultExtensions; + + public TimeSpan? PingIntervalOverride { get; set; } = TimeSpan.Zero; +#endif + } + public sealed class SocketOptions { #region Properties @@ -102,6 +113,11 @@ public ObservableDictionary AdditionalQueryParams /// public Func Auth; + /// + /// Customization options for the websocket transport. + /// + public WebsocketOptions WebsocketOptions { get; set; } = new WebsocketOptions(); + #endregion /// @@ -138,7 +154,7 @@ internal string BuildQueryParams() if (!string.IsNullOrEmpty(BuiltQueryParams)) return BuiltQueryParams; - StringBuilder sb = new StringBuilder(AdditionalQueryParams.Count * 4); + StringBuilder sb = StringBuilderPool.Get(AdditionalQueryParams.Count * 4); //new StringBuilder(AdditionalQueryParams.Count * 4); foreach(var kvp in AdditionalQueryParams) { @@ -152,7 +168,7 @@ internal string BuildQueryParams() } } - return BuiltQueryParams = sb.ToString(); + return BuiltQueryParams = StringBuilderPool.ReleaseAndGrab(sb); } /// diff --git a/Assets/URS/Best HTTP/Source/SocketIO.3/Transports/PollingTransport.cs b/Assets/URS/Best HTTP/Source/SocketIO.3/Transports/PollingTransport.cs index 889c052..ce82798 100644 --- a/Assets/URS/Best HTTP/Source/SocketIO.3/Transports/PollingTransport.cs +++ b/Assets/URS/Best HTTP/Source/SocketIO.3/Transports/PollingTransport.cs @@ -163,6 +163,8 @@ private void EncodePackets(System.Collections.Generic.List packe if (i < packets.Count - 1) sendBuilder.Append((char)0x1E); + + BufferPool.Release(packet.PayloadData); } string result = sendBuilder.ToString(); diff --git a/Assets/URS/Best HTTP/Source/SocketIO.3/Transports/WebSocketTransport.cs b/Assets/URS/Best HTTP/Source/SocketIO.3/Transports/WebSocketTransport.cs index c2576cd..d936aed 100644 --- a/Assets/URS/Best HTTP/Source/SocketIO.3/Transports/WebSocketTransport.cs +++ b/Assets/URS/Best HTTP/Source/SocketIO.3/Transports/WebSocketTransport.cs @@ -14,7 +14,7 @@ namespace BestHTTP.SocketIO3.Transports /// /// A transport implementation that can communicate with a SocketIO server. /// - internal sealed class WebSocketTransport : ITransport + public sealed class WebSocketTransport : ITransport { public TransportTypes Type { get { return TransportTypes.WebSocket; } } public TransportStates State { get; private set; } @@ -53,16 +53,33 @@ public void Open() Manager.Handshake != null ? Manager.Handshake.Sid : string.Empty, sendAdditionalQueryParams ? Manager.Options.BuildQueryParams() : string.Empty)); - Implementation = new WebSocket(uri); + Implementation = new WebSocket(uri, string.Empty, string.Empty +#if !UNITY_WEBGL || UNITY_EDITOR + , (Manager.Options.WebsocketOptions?.ExtensionsFactory ?? WebSocket.GetDefaultExtensions)?.Invoke() +#endif + ); #if !UNITY_WEBGL || UNITY_EDITOR + if (this.Manager.Options.WebsocketOptions?.PingIntervalOverride is TimeSpan ping) + { + if (ping > TimeSpan.Zero) + { + Implementation.StartPingThread = true; + Implementation.PingFrequency = (int)ping.TotalMilliseconds; + } + else + Implementation.StartPingThread = false; + } + else + Implementation.StartPingThread = true; + if (this.Manager.Options.HTTPRequestCustomizationCallback != null) Implementation.OnInternalRequestCreated = (ws, internalRequest) => this.Manager.Options.HTTPRequestCustomizationCallback(this.Manager, internalRequest); #endif Implementation.OnOpen = OnOpen; Implementation.OnMessage = OnMessage; - Implementation.OnBinary = OnBinary; + Implementation.OnBinaryNoAlloc = OnBinaryNoAlloc; Implementation.OnError = OnError; Implementation.OnClosed = OnClosed; @@ -153,27 +170,29 @@ private void OnMessage(WebSocket ws, string message) HTTPManager.Logger.Exception("WebSocketTransport", "OnMessage OnPacket", ex, this.Manager.Context); } } + else if (HTTPManager.Logger.Level == Logger.Loglevels.All) + HTTPManager.Logger.Verbose("WebSocketTransport", "OnMessage: skipping message " + message, this.Manager.Context); } /// /// WebSocket implementation OnBinary event handler. /// - private void OnBinary(WebSocket ws, byte[] data) + private void OnBinaryNoAlloc(WebSocket ws, BufferSegment data) { if (ws != Implementation) return; if (HTTPManager.Logger.Level <= BestHTTP.Logger.Loglevels.All) - HTTPManager.Logger.Verbose("WebSocketTransport", "OnBinary", this.Manager.Context); + HTTPManager.Logger.Verbose("WebSocketTransport", $"OnBinaryNoAlloc({data})", this.Manager.Context); IncomingPacket packet = IncomingPacket.Empty; try { - packet = this.Manager.Parser.Parse(this.Manager, new BufferSegment(data, 0, data.Length)); + packet = this.Manager.Parser.Parse(this.Manager, data); } catch (Exception ex) { - HTTPManager.Logger.Exception("WebSocketTransport", "OnBinary Packet parsing", ex, this.Manager.Context); + HTTPManager.Logger.Exception("WebSocketTransport", $"OnBinaryNoAlloc({data}) Packet parsing", ex, this.Manager.Context); } if (!packet.Equals(IncomingPacket.Empty)) @@ -184,9 +203,11 @@ private void OnBinary(WebSocket ws, byte[] data) } catch (Exception ex) { - HTTPManager.Logger.Exception("WebSocketTransport", "OnBinary OnPacket", ex, this.Manager.Context); + HTTPManager.Logger.Exception("WebSocketTransport", $"OnBinaryNoAlloc({data}) OnPacket", ex, this.Manager.Context); } } + else if (HTTPManager.Logger.Level == Logger.Loglevels.All) + HTTPManager.Logger.Verbose("WebSocketTransport", "OnBinaryNoAlloc skipping message", this.Manager.Context); } /// @@ -277,9 +298,11 @@ public void Send(OutgoingPacket packet) } if (packet.IsBinary) - Implementation.Send(packet.PayloadData.Data, (ulong)packet.PayloadData.Offset, (ulong)packet.PayloadData.Count); + Implementation.SendAsBinary(packet.PayloadData); else + { Implementation.Send(packet.Payload); + } if (packet.Attachements != null) for (int i = 0; i < packet.Attachements.Count; ++i) diff --git a/Assets/URS/Best HTTP/Source/SocketIO/SocketOptions.cs b/Assets/URS/Best HTTP/Source/SocketIO/SocketOptions.cs index f6cf60f..db4ea10 100644 --- a/Assets/URS/Best HTTP/Source/SocketIO/SocketOptions.cs +++ b/Assets/URS/Best HTTP/Source/SocketIO/SocketOptions.cs @@ -3,6 +3,8 @@ using System; using System.Text; +using BestHTTP.PlatformSupport.Text; + using PlatformSupport.Collections.ObjectModel; #if !NETFX_CORE @@ -150,9 +152,9 @@ internal string BuildQueryParams() if (!string.IsNullOrEmpty(BuiltQueryParams)) return BuiltQueryParams; - StringBuilder sb = new StringBuilder(AdditionalQueryParams.Count * 4); + StringBuilder sb = StringBuilderPool.Get(AdditionalQueryParams.Count * 4); //new StringBuilder(AdditionalQueryParams.Count * 4); - foreach(var kvp in AdditionalQueryParams) + foreach (var kvp in AdditionalQueryParams) { sb.Append("&"); sb.Append(kvp.Key); @@ -164,7 +166,7 @@ internal string BuildQueryParams() } } - return BuiltQueryParams = sb.ToString(); + return BuiltQueryParams = StringBuilderPool.ReleaseAndGrab(sb); } /// diff --git a/Assets/URS/Best HTTP/Source/SocketIO/Transports/WebSocketTransport.cs b/Assets/URS/Best HTTP/Source/SocketIO/Transports/WebSocketTransport.cs index 713da59..5f17c34 100644 --- a/Assets/URS/Best HTTP/Source/SocketIO/Transports/WebSocketTransport.cs +++ b/Assets/URS/Best HTTP/Source/SocketIO/Transports/WebSocketTransport.cs @@ -58,6 +58,8 @@ public void Open() Implementation = new WebSocket(uri); #if !UNITY_WEBGL || UNITY_EDITOR + Implementation.StartPingThread = true; + if (this.Manager.Options.HTTPRequestCustomizationCallback != null) Implementation.OnInternalRequestCreated = (ws, internalRequest) => this.Manager.Options.HTTPRequestCustomizationCallback(this.Manager, internalRequest); #endif diff --git a/Assets/URS/Best HTTP/Source/WebSocket/Extensions/IExtension.cs b/Assets/URS/Best HTTP/Source/WebSocket/Extensions/IExtension.cs index 082c2fd..324a96f 100644 --- a/Assets/URS/Best HTTP/Source/WebSocket/Extensions/IExtension.cs +++ b/Assets/URS/Best HTTP/Source/WebSocket/Extensions/IExtension.cs @@ -1,5 +1,6 @@ -#if !BESTHTTP_DISABLE_WEBSOCKET && (!UNITY_WEBGL || UNITY_EDITOR) +#if !BESTHTTP_DISABLE_WEBSOCKET && (!UNITY_WEBGL || UNITY_EDITOR) +using BestHTTP.PlatformSupport.Memory; using BestHTTP.WebSocket.Frames; namespace BestHTTP.WebSocket.Extensions @@ -16,7 +17,7 @@ public interface IExtension /// If the websocket upgrade succeded it will call this function to be able to parse the server's negotiation /// response. Inside this function the IsEnabled should be set. /// - bool ParseNegotiation(WebSocketResponse resp); + bool ParseNegotiation(HTTPResponse resp); /// /// This function should return a new header flag based on the inFlag parameter. The extension should set only the @@ -29,13 +30,13 @@ public interface IExtension /// /// /// - byte[] Encode(WebSocketFrame writer); + BufferSegment Encode(WebSocketFrame writer); /// /// This function can be used the decode the server-sent data. /// - byte[] Decode(byte header, byte[] data, int length); + BufferSegment Decode(byte header, BufferSegment data); } } -#endif \ No newline at end of file +#endif diff --git a/Assets/URS/Best HTTP/Source/WebSocket/Extensions/PerMessageCompression.cs b/Assets/URS/Best HTTP/Source/WebSocket/Extensions/PerMessageCompression.cs index b5806e6..922cbb3 100644 --- a/Assets/URS/Best HTTP/Source/WebSocket/Extensions/PerMessageCompression.cs +++ b/Assets/URS/Best HTTP/Source/WebSocket/Extensions/PerMessageCompression.cs @@ -148,7 +148,7 @@ public void AddNegotiation(HTTPRequest request) request.AddHeader("Sec-WebSocket-Extensions", headerValue); } - public bool ParseNegotiation(WebSocketResponse resp) + public bool ParseNegotiation(HTTPResponse resp) { // Search for any returned neogitation offer var headerValues = resp.GetHeaderValues("Sec-WebSocket-Extensions"); @@ -208,7 +208,7 @@ public byte GetFrameHeader(WebSocketFrame writer, byte inFlag) // http://tools.ietf.org/html/rfc7692#section-7.2.3.1 // the RSV1 bit is set only on the first frame. if ((writer.Type == WebSocketFrameTypes.Binary || writer.Type == WebSocketFrameTypes.Text) && - writer.Data != null && writer.DataLength >= this.MinimumDataLegthToCompress) + writer.Data != null && writer.Data.Count >= this.MinimumDataLegthToCompress) return (byte)(inFlag | 0x40); else return inFlag; @@ -217,14 +217,14 @@ public byte GetFrameHeader(WebSocketFrame writer, byte inFlag) /// /// IExtension implementation to be able to compress the data hold in the writer. /// - public byte[] Encode(WebSocketFrame writer) + public BufferSegment Encode(WebSocketFrame writer) { if (writer.Data == null) - return BufferPool.NoData; + return BufferSegment.Empty; // Is compressing enabled for this frame? If so, compress it. if ((writer.Header & 0x40) != 0) - return Compress(writer.Data, writer.DataLength); + return Compress(writer.Data); else return writer.Data; } @@ -232,11 +232,11 @@ public byte[] Encode(WebSocketFrame writer) /// /// IExtension implementation to possible decompress the data. /// - public byte[] Decode(byte header, byte[] data, int length) + public BufferSegment Decode(byte header, BufferSegment data) { // Is the server compressed the data? If so, decompress it. if ((header & 0x40) != 0) - return Decompress(data, length); + return Decompress(data); else return data; } @@ -248,7 +248,7 @@ public byte[] Decode(byte header, byte[] data, int length) /// /// A function to compress and return the data parameter with possible context takeover support (reusing the DeflateStream). /// - private byte[] Compress(byte[] data, int length) + private BufferSegment Compress(BufferSegment data) { if (compressorOutputStream == null) compressorOutputStream = new BufferPoolMemoryStream(); @@ -260,10 +260,10 @@ private byte[] Compress(byte[] data, int length) compressorDeflateStream.FlushMode = FlushType.Sync; } - byte[] result = null; + BufferSegment result = BufferSegment.Empty; try { - compressorDeflateStream.Write(data, 0, length); + compressorDeflateStream.Write(data.Data, data.Offset, data.Count); compressorDeflateStream.Flush(); compressorOutputStream.Position = 0; @@ -272,7 +272,7 @@ private byte[] Compress(byte[] data, int length) // Remove 4 octets (that are 0x00 0x00 0xff 0xff) from the tail end. After this step, the last octet of the compressed data contains (possibly part of) the DEFLATE header bits with the "BTYPE" bits set to 00. compressorOutputStream.SetLength(compressorOutputStream.Length - 4); - result = compressorOutputStream.ToArray(); + result = compressorOutputStream.ToBufferSegment(); } finally { @@ -289,12 +289,12 @@ private byte[] Compress(byte[] data, int length) /// /// A function to decompress and return the data parameter with possible context takeover support (reusing the DeflateStream). /// - private byte[] Decompress(byte[] data, int length) + private BufferSegment Decompress(BufferSegment data) { if (decompressorInputStream == null) - decompressorInputStream = new BufferPoolMemoryStream(length + 4); + decompressorInputStream = new BufferPoolMemoryStream(data.Count + 4); - decompressorInputStream.Write(data, 0, length); + decompressorInputStream.Write(data.Data, data.Offset, data.Count); // http://tools.ietf.org/html/rfc7692#section-7.2.2 // Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the payload of the message. @@ -321,7 +321,7 @@ private byte[] Decompress(byte[] data, int length) decompressorDeflateStream.SetLength(0); - byte[] result = decompressorOutputStream.ToArray(); + var result = decompressorOutputStream.ToBufferSegment(); if (this.ServerNoContextTakeover) { diff --git a/Assets/URS/Best HTTP/Source/WebSocket/Frames/WebSocketFrame.cs b/Assets/URS/Best HTTP/Source/WebSocket/Frames/WebSocketFrame.cs index 01e31cc..109bb04 100644 --- a/Assets/URS/Best HTTP/Source/WebSocket/Frames/WebSocketFrame.cs +++ b/Assets/URS/Best HTTP/Source/WebSocket/Frames/WebSocketFrame.cs @@ -1,240 +1,355 @@ #if !BESTHTTP_DISABLE_WEBSOCKET && (!UNITY_WEBGL || UNITY_EDITOR) +using System; using BestHTTP.Extensions; using BestHTTP.PlatformSupport.Memory; -using System; -using System.IO; +using System.Runtime.CompilerServices; +using BestHTTP.PlatformSupport.IL2CPP; +using BestHTTP.Logger; + +#if BESTHTTP_WITH_BURST +using Unity.Burst; +using Unity.Burst.Intrinsics; +using static Unity.Burst.Intrinsics.X86.Avx2; +using static Unity.Burst.Intrinsics.X86.Sse2; +using static Unity.Burst.Intrinsics.Arm.Neon; +#endif namespace BestHTTP.WebSocket.Frames { - public struct RawFrameData : IDisposable - { - public byte[] Data; - public int Length; - - public RawFrameData(byte[] data, int length) - { - Data = data; - Length = length; - } - - public void Dispose() - { - BufferPool.Release(Data); - Data = null; - } - } /// /// Denotes a binary frame. The "Payload data" is arbitrary binary data whose interpretation is solely up to the application layer. /// This is the base class of all other frame writers, as all frame can be represented as a byte array. /// - [BestHTTP.PlatformSupport.IL2CPP.Il2CppEagerStaticClassConstructionAttribute] - public sealed class WebSocketFrame +#if BESTHTTP_WITH_BURST + [BurstCompile] +#endif + [Il2CppEagerStaticClassConstruction] + public struct WebSocketFrame { public WebSocketFrameTypes Type { get; private set; } + public bool IsFinal { get; private set; } + public byte Header { get; private set; } - public byte[] Data { get; private set; } - public int DataLength { get; private set; } - public bool UseExtensions { get; private set; } + public BufferSegment Data { get; private set; } - public override string ToString() - { - return string.Format("[WebSocketFrame Type: {0}, IsFinal: {1}, Header: {2:X2}, DataLength: {3}, UseExtensions: {4}]", - this.Type, this.IsFinal, this.Header, this.DataLength, this.UseExtensions); - } + public WebSocket Websocket { get; private set; } - #region Constructors + public bool UseExtensions { get; private set; } - public WebSocketFrame(WebSocket webSocket, WebSocketFrameTypes type, byte[] data) + public WebSocketFrame(WebSocket webSocket, WebSocketFrameTypes type, BufferSegment data) :this(webSocket, type, data, true) { } - public WebSocketFrame(WebSocket webSocket, WebSocketFrameTypes type, byte[] data, bool useExtensions) - : this(webSocket, type, data, 0, data != null ? (UInt64)data.Length : 0, true, useExtensions) + public WebSocketFrame(WebSocket webSocket, WebSocketFrameTypes type, BufferSegment data, bool useExtensions) + : this(webSocket, type, data, true, useExtensions) { } - public WebSocketFrame(WebSocket webSocket, WebSocketFrameTypes type, byte[] data, bool isFinal, bool useExtensions) - : this(webSocket, type, data, 0, data != null ? (UInt64)data.Length : 0, isFinal, useExtensions) + public WebSocketFrame(WebSocket webSocket, WebSocketFrameTypes type, BufferSegment data, bool isFinal, bool useExtensions) + :this(webSocket, type, data, isFinal, useExtensions, copyData: true) { + } - public WebSocketFrame(WebSocket webSocket, WebSocketFrameTypes type, byte[] data, UInt64 pos, UInt64 length, bool isFinal, bool useExtensions) + public WebSocketFrame(WebSocket webSocket, WebSocketFrameTypes type, BufferSegment data, bool isFinal, bool useExtensions, bool copyData) { this.Type = type; this.IsFinal = isFinal; + this.Websocket = webSocket; this.UseExtensions = useExtensions; - this.DataLength = (int)length; - if (data != null) + this.Data = data; + + if (this.Data.Data != null) { - this.Data = BufferPool.Get(this.DataLength, true); - Array.Copy(data, (int)pos, this.Data, 0, this.DataLength); + if (copyData) + { + var from = this.Data; + + var buffer = BufferPool.Get(this.Data.Count, true); + this.Data = new BufferSegment(buffer, 0, this.Data.Count); + + Array.Copy(from.Data, (int)from.Offset, this.Data.Data, this.Data.Offset, this.Data.Count); + } } else - data = BufferPool.NoData; + this.Data = BufferSegment.Empty; // First byte: Final Bit + Rsv flags + OpCode byte finalBit = (byte)(IsFinal ? 0x80 : 0x0); this.Header = (byte)(finalBit | (byte)Type); + } + + public override string ToString() + { + return string.Format("[WebSocketFrame Type: {0}, IsFinal: {1}, Header: {2:X2}, Data: {3}, UseExtensions: {4}]", + this.Type, this.IsFinal, this.Header, this.Data, this.UseExtensions); + } + + public void WriteTo(Action callback, uint maxFragmentSize, bool mask, LoggingContext context) + { + DoExtensions(); + + if (HTTPManager.Logger.Level <= Logger.Loglevels.All) + HTTPManager.Logger.Verbose("WebSocketFrame", "WriteTo - Frame: " + ToString(), context); + + if ((this.Type == WebSocketFrameTypes.Binary || this.Type == WebSocketFrameTypes.Text) && this.Data.Count > maxFragmentSize) + { + FragmentAndSend(callback, maxFragmentSize, mask, context); + } + else + { + WriteFragment(callback, this.Type, this.Header, this.Data, mask, context); + } + } - if (this.UseExtensions && webSocket != null && webSocket.Extensions != null) + private void DoExtensions() + { + if (this.UseExtensions && this.Websocket != null && this.Websocket.Extensions != null) { - for (int i = 0; i < webSocket.Extensions.Length; ++i) + for (int i = 0; i < this.Websocket.Extensions.Length; ++i) { - var ext = webSocket.Extensions[i]; + var ext = this.Websocket.Extensions[i]; if (ext != null) { this.Header |= ext.GetFrameHeader(this, this.Header); - byte[] newData = ext.Encode(this); + BufferSegment newData = ext.Encode(this); if (newData != this.Data) { BufferPool.Release(this.Data); this.Data = newData; - this.DataLength = newData.Length; } } } } } - #endregion + private void FragmentAndSend(Action callback, uint maxFragmentSize, bool mask, LoggingContext context) + { + int pos = this.Data.Offset; + int endPos = this.Data.Offset + this.Data.Count; + + while (pos < endPos) + { + int chunkLength = Math.Min((int)maxFragmentSize, endPos - pos); + + WriteFragment(callback: callback, + Type: pos == this.Data.Offset ? this.Type : WebSocketFrameTypes.Continuation, + IsFinal: pos + chunkLength >= this.Data.Count, + Data: this.Data.Slice((int)pos, (int)chunkLength), + mask: mask, + context: context); - #region Public Functions + pos += chunkLength; + } + } - public unsafe RawFrameData Get() + private static void WriteFragment(Action callback, WebSocketFrameTypes Type, bool IsFinal, BufferSegment Data, bool mask, LoggingContext context) { - if (Data == null) - Data = BufferPool.NoData; + // First byte: Final Bit + Rsv flags + OpCode + byte finalBit = (byte)(IsFinal ? 0x80 : 0x0); + byte Header = (byte)(finalBit | (byte)Type); - using (var ms = new BufferPoolMemoryStream(this.DataLength + 9)) - { - // For the complete documentation for this section see: - // http://tools.ietf.org/html/rfc6455#section-5.2 - - // Write the header - ms.WriteByte(this.Header); - - // The length of the "Payload data", in bytes: if 0-125, that is the payload length. If 126, the following 2 bytes interpreted as a - // 16-bit unsigned integer are the payload length. If 127, the following 8 bytes interpreted as a 64-bit unsigned integer (the - // most significant bit MUST be 0) are the payload length. Multibyte length quantities are expressed in network byte order. - if (this.DataLength < 126) - ms.WriteByte((byte)(0x80 | (byte)this.DataLength)); - else if (this.DataLength < UInt16.MaxValue) - { - ms.WriteByte((byte)(0x80 | 126)); - byte[] len = BitConverter.GetBytes((UInt16)this.DataLength); - if (BitConverter.IsLittleEndian) - Array.Reverse(len, 0, len.Length); + WriteFragment(callback, Type, Header, Data, mask, context); + } - ms.Write(len, 0, len.Length); - } - else - { - ms.WriteByte((byte)(0x80 | 127)); - byte[] len = BitConverter.GetBytes((UInt64)this.DataLength); - if (BitConverter.IsLittleEndian) - Array.Reverse(len, 0, len.Length); + private static unsafe void WriteFragment(Action callback, WebSocketFrameTypes Type, byte Header, BufferSegment Data, bool mask, LoggingContext context) + { + // For the complete documentation for this section see: + // http://tools.ietf.org/html/rfc6455#section-5.2 - ms.Write(len, 0, len.Length); - } + // Header(1) + Len(8) + Mask (4) + byte[] wsHeader = BufferPool.Get(13, true); + int pos = 0; + + // Write the header + wsHeader[pos++] = Header; + + // The length of the "Payload data", in bytes: if 0-125, that is the payload length. If 126, the following 2 bytes interpreted as a + // 16-bit unsigned integer are the payload length. If 127, the following 8 bytes interpreted as a 64-bit unsigned integer (the + // most significant bit MUST be 0) are the payload length. Multibyte length quantities are expressed in network byte order. + if (Data.Count < 126) + { + wsHeader[pos++] = (byte)(0x80 | (byte)Data.Count); + } + else if (Data.Count < UInt16.MaxValue) + { + wsHeader[pos++] = (byte)(0x80 | 126); + var count = (UInt16)Data.Count; + wsHeader[pos++] = (byte)(count >> 8); + wsHeader[pos++] = (byte)(count); + } + else + { + wsHeader[pos++] = (byte)(0x80 | 127); + + var count = (UInt64)Data.Count; + wsHeader[pos++] = (byte)(count >> 56); + wsHeader[pos++] = (byte)(count >> 48); + wsHeader[pos++] = (byte)(count >> 40); + wsHeader[pos++] = (byte)(count >> 32); + wsHeader[pos++] = (byte)(count >> 24); + wsHeader[pos++] = (byte)(count >> 16); + wsHeader[pos++] = (byte)(count >> 8); + wsHeader[pos++] = (byte)(count); + } + if (Data != BufferSegment.Empty) + { // All frames sent from the client to the server are masked by a 32-bit value that is contained within the frame. This field is // present if the mask bit is set to 1 and is absent if the mask bit is set to 0. // If the data is being sent by the client, the frame(s) MUST be masked. - byte[] mask = BufferPool.Get(4, true); - - int hash = this.GetHashCode(); - mask[0] = (byte)((hash >> 24) & 0xFF); - mask[1] = (byte)((hash >> 16) & 0xFF); - mask[2] = (byte)((hash >> 8) & 0xFF); - mask[3] = (byte)(hash & 0xFF); + uint hash = mask ? (uint)wsHeader.GetHashCode() : 0; - ms.Write(mask, 0, 4); + wsHeader[pos++] = (byte)(hash >> 24); + wsHeader[pos++] = (byte)(hash >> 16); + wsHeader[pos++] = (byte)(hash >> 8); + wsHeader[pos++] = (byte)(hash); // Do the masking. - fixed (byte* pData = Data, pmask = mask) + if (mask) { - // Here, instead of byte by byte, we reinterpret cast the data as uints and apply the masking so. - // This way, we can mask 4 bytes in one cycle, instead of just 1 - int localLength = this.DataLength / 4; - if (localLength > 0) + fixed (byte* pData = Data.Data/*, pmask = &wsHeader[pos - 4]*/) { - uint* upData = (uint*)pData; - uint umask = *(uint*)pmask; + byte* alignedMask = stackalloc byte[4]; + alignedMask[0] = wsHeader[pos - 4]; + alignedMask[1] = wsHeader[pos - 3]; + alignedMask[2] = wsHeader[pos - 2]; + alignedMask[3] = wsHeader[pos - 1]; - unchecked - { - for (int i = 0; i < localLength; ++i) - upData[i] = upData[i] ^ umask; - } + ApplyMask(pData, Data.Offset, Data.Count, alignedMask); } - - // Because data might not be exactly dividable by 4, we have to mask the remaining 0..3 too. - int from = localLength * 4; - localLength = from + this.DataLength % 4; - for (int i = from; i < localLength; ++i) - pData[i] = (byte)(pData[i] ^ pmask[i % 4]); } + } + else + { + wsHeader[pos++] = 0; + wsHeader[pos++] = 0; + wsHeader[pos++] = 0; + wsHeader[pos++] = 0; + } - BufferPool.Release(mask); + var header = wsHeader.AsBuffer(pos); - ms.Write(Data, 0, DataLength); + if (HTTPManager.Logger.Level <= Logger.Loglevels.All) + HTTPManager.Logger.Verbose("WebSocketFrame", string.Format("WriteFragment - Header: {0}, data chunk: {1}", header.ToString(), Data.ToString()), context); - return new RawFrameData(ms.ToArray(true), (int)ms.Length); - } + callback(header, Data); } - - public WebSocketFrame[] Fragment(uint maxFragmentSize) + [MethodImpl(MethodImplOptions.AggressiveInlining)] +#if BESTHTTP_WITH_BURST + [BurstCompile(CompileSynchronously = true)] +#endif + public unsafe static void ApplyMask( +#if BESTHTTP_WITH_BURST + [NoAlias] +#endif + byte* pData, + int DataOffset, + int DataCount, +#if BESTHTTP_WITH_BURST + [NoAlias] +#endif + byte* pmask + ) { - if (this.Data == null) - return null; + int targetOffset = DataOffset + DataCount; + uint umask = *(uint*)pmask; + +#if BESTHTTP_WITH_BURST + if (targetOffset - DataOffset >= 32) + { + if (IsAvx2Supported) + { + v256 mask = new v256(umask); + v256 ldstrMask = new v256((byte)0xFF); + + while (targetOffset - DataOffset >= 32) + { + // load data + v256 data = mm256_maskload_epi32(pData + DataOffset, ldstrMask); - // All control frames MUST have a payload length of 125 bytes or less and MUST NOT be fragmented. - if (this.Type != WebSocketFrameTypes.Binary && this.Type != WebSocketFrameTypes.Text) - return null; + // xor + v256 result = mm256_xor_si256(data, mask); - if (this.DataLength <= maxFragmentSize) - return null; + // store + mm256_maskstore_epi32(pData + DataOffset, ldstrMask, result); - this.IsFinal = false; + // advance + DataOffset += 32; + } + } + } - // Clear final bit from the header flags - this.Header &= 0x7F; + if (targetOffset - DataOffset >= 16) + { + v128 mask = new v128(umask); - // One chunk will remain in this fragment, so we have to allocate one less - int count = (int)((this.DataLength / maxFragmentSize) + (this.DataLength % maxFragmentSize == 0 ? -1 : 0)); + if (IsSse2Supported) + { + while (targetOffset - DataOffset >= 16) + { + // load data + v128 data = loadu_si128(pData + DataOffset); - WebSocketFrame[] fragments = new WebSocketFrame[count]; + // xor + var result = xor_si128(data, mask); - // Skip one chunk, for the current one - UInt64 pos = maxFragmentSize; - while (pos < (UInt64)this.DataLength) - { - UInt64 chunkLength = Math.Min(maxFragmentSize, (UInt64)this.DataLength - pos); + // store + storeu_si128(pData + DataOffset, result); - fragments[fragments.Length - count--] = new WebSocketFrame(null, WebSocketFrameTypes.Continuation, this.Data, pos, chunkLength, pos + chunkLength >= (UInt64)this.DataLength, false); + // advance + DataOffset += 16; + } + } + else if (IsNeonSupported) + { + while (targetOffset - DataOffset >= 16) + { + // load data + v128 data = vld1q_u8(pData + DataOffset); - pos += chunkLength; + // xor + v128 result = veorq_u8(data, mask); + + // store + vst1q_u8(pData + DataOffset, result); + + // advance + DataOffset += 16; + } + } } +#endif - //byte[] newData = VariableSizedBufferPool.Get(maxFragmentSize, true); - //Array.Copy(this.Data, 0, newData, 0, maxFragmentSize); - //VariableSizedBufferPool.Release(this.Data); + // fallback to calculate by reinterpret-casting to ulong + if (targetOffset - DataOffset >= 8) + { + ulong* ulpData = (ulong*)(pData + DataOffset); - //this.Data = newData; - this.DataLength = (int)maxFragmentSize; + // duplicate the mask to fill up a whole ulong. + ulong ulmask = (((ulong)umask << 32) | umask); - return fragments; - } + while (targetOffset - DataOffset >= 8) + { + *ulpData = *ulpData ^ ulmask; + + ulpData++; + DataOffset += 8; + } + } - #endregion + // process remaining bytes (0..7) + for (int i = DataOffset; i < targetOffset; ++i) + pData[i] = (byte)(pData[i] ^ pmask[(i - DataOffset) % 4]); + } } } diff --git a/Assets/URS/Best HTTP/Source/WebSocket/Frames/WebSocketFrameReader.cs b/Assets/URS/Best HTTP/Source/WebSocket/Frames/WebSocketFrameReader.cs index b9b6d21..550ce95 100644 --- a/Assets/URS/Best HTTP/Source/WebSocket/Frames/WebSocketFrameReader.cs +++ b/Assets/URS/Best HTTP/Source/WebSocket/Frames/WebSocketFrameReader.cs @@ -28,20 +28,10 @@ public struct WebSocketFrameReader /// public WebSocketFrameTypes Type { get; private set; } - /// - /// Indicates if there are any mask sent to decode the data. - /// - public bool HasMask { get; private set; } - - /// - /// The length of the Data. - /// - public UInt64 Length { get; private set; } - /// /// The decoded array of bytes. /// - public byte[] Data { get; private set; } + public BufferSegment Data { get; private set; } /// /// Textual representation of the received Data. @@ -66,13 +56,14 @@ internal unsafe void Read(Stream stream) byte maskAndLength = ReadByte(stream); // The second byte is the Mask Bit and the length of the payload data - HasMask = (maskAndLength & 0x80) != 0; + if ((maskAndLength & 0x80) != 0) + throw new NotImplementedException($"Payload from the server is masked!"); // if 0-125, that is the payload length. - Length = (UInt64)(maskAndLength & 127); + var length = (UInt64)(maskAndLength & 127); // If 126, the following 2 bytes interpreted as a 16-bit unsigned integer are the payload length. - if (Length == 126) + if (length == 126) { byte[] rawLen = BufferPool.Get(2, true); @@ -81,11 +72,11 @@ internal unsafe void Read(Stream stream) if (BitConverter.IsLittleEndian) Array.Reverse(rawLen, 0, 2); - Length = (UInt64)BitConverter.ToUInt16(rawLen, 0); + length = (UInt64)BitConverter.ToUInt16(rawLen, 0); BufferPool.Release(rawLen); } - else if (Length == 127) + else if (length == 127) { // If 127, the following 8 bytes interpreted as a 64-bit unsigned integer (the // most significant bit MUST be 0) are the payload length. @@ -97,74 +88,39 @@ internal unsafe void Read(Stream stream) if (BitConverter.IsLittleEndian) Array.Reverse(rawLen, 0, 8); - Length = (UInt64)BitConverter.ToUInt64(rawLen, 0); + length = (UInt64)BitConverter.ToUInt64(rawLen, 0); BufferPool.Release(rawLen); } - // The sent byte array as a mask to decode the data. - byte[] mask = null; - - // Read the Mask, if has any - if (HasMask) + if (length == 0L) { - mask = BufferPool.Get(4, true); - if (stream.Read(mask, 0, 4) < mask.Length) - throw ExceptionHelper.ServerClosedTCPStream(); + Data = BufferSegment.Empty; + return; } - if (Type == WebSocketFrameTypes.Text || Type == WebSocketFrameTypes.Continuation) - Data = BufferPool.Get((long)Length, true); - else - if (Length == 0) - Data = BufferPool.NoData; - else - Data = new byte[Length]; - //Data = Type == WebSocketFrameTypes.Text ? VariableSizedBufferPool.Get((long)Length, true) : new byte[Length]; - - if (Length == 0L) - return; + var buffer = BufferPool.Get((long)length, true); uint readLength = 0; - do - { - int read = stream.Read(Data, (int)readLength, (int)(Length - readLength)); - - if (read <= 0) - throw ExceptionHelper.ServerClosedTCPStream(); - - readLength += (uint)read; - } while (readLength < Length); - - if (HasMask) + try { - fixed (byte* pData = Data, pmask = mask) + do { - // Here, instead of byte by byte, we reinterpret cast the data as uints and apply the masking so. - // This way, we can mask 4 bytes in one cycle, instead of just 1 - ulong localLength = this.Length / 4; - if (localLength > 0) - { - uint* upData = (uint*)pData; - uint umask = *(uint*)pmask; + int read = stream.Read(buffer, (int)readLength, (int)(length - readLength)); - unchecked - { - for (ulong i = 0; i < localLength; ++i) - upData[i] = upData[i] ^ umask; - } - } - - // Because data might not be exactly dividable by 4, we have to mask the remaining 0..3 too. - ulong from = localLength * 4; - localLength = from + this.Length % 4; - for (ulong i = from; i < localLength; ++i) - pData[i] = (byte)(pData[i] ^ pmask[i % 4]); - } + if (read <= 0) + throw ExceptionHelper.ServerClosedTCPStream(); - BufferPool.Release(mask); + readLength += (uint)read; + } while (readLength < length); + } + catch + { + BufferPool.Release(buffer); + throw; } + this.Data = new BufferSegment(buffer, 0, (int)length); } private byte ReadByte(Stream stream) @@ -192,16 +148,17 @@ public void Assemble(List fragments) UInt64 finalLength = 0; for (int i = 0; i < fragments.Count; ++i) - finalLength += fragments[i].Length; + finalLength += (UInt64)fragments[i].Data.Count; - byte[] buffer = fragments[0].Type == WebSocketFrameTypes.Text ? BufferPool.Get((long)finalLength, true) : new byte[finalLength]; + byte[] buffer = BufferPool.Get((long)finalLength, true); UInt64 pos = 0; for (int i = 0; i < fragments.Count; ++i) { - Array.Copy(fragments[i].Data, 0, buffer, (int)pos, (int)fragments[i].Length); + if (fragments[i].Data.Count > 0) + Array.Copy(fragments[i].Data.Data, fragments[i].Data.Offset, buffer, (int)pos, (int)fragments[i].Data.Count); fragments[i].ReleaseData(); - pos += fragments[i].Length; + pos += (UInt64)fragments[i].Data.Count; } // All fragments of a message are of the same type, as set by the first fragment's opcode. @@ -210,8 +167,7 @@ public void Assemble(List fragments) // Reserver flags may be contained only in the first fragment this.Header = fragments[0].Header; - this.Length = finalLength; - this.Data = buffer; + this.Data = new BufferSegment(buffer, 0, (int)finalLength); } /// @@ -225,30 +181,36 @@ public void DecodeWithExtensions(WebSocket webSocket) var ext = webSocket.Extensions[i]; if (ext != null) { - var newData = ext.Decode(this.Header, this.Data, (int)this.Length); + var newData = ext.Decode(this.Header, this.Data); if (this.Data != newData) { this.ReleaseData(); this.Data = newData; - this.Length = (ulong)newData.Length; } } } - if (this.Type == WebSocketFrameTypes.Text && this.Data != null) + if (this.Type == WebSocketFrameTypes.Text) { - this.DataAsText = System.Text.Encoding.UTF8.GetString(this.Data, 0, (int)this.Length); - this.ReleaseData(); + if (this.Data != BufferSegment.Empty) + { + this.DataAsText = System.Text.Encoding.UTF8.GetString(this.Data.Data, this.Data.Offset, this.Data.Count); + this.ReleaseData(); + } + else + HTTPManager.Logger.Warning("WebSocketFrameReader", "Empty Text frame received!"); } } public void ReleaseData() { - if (this.Data != null) - { - BufferPool.Release(this.Data); - this.Data = null; - } + BufferPool.Release(this.Data); + this.Data = BufferSegment.Empty; + } + + public override string ToString() + { + return string.Format("[{0} Header: {1:X2}, IsFinal: {2}, Data: {3}]", this.Type.ToString(), this.Header, this.IsFinal, this.Data); } #endregion diff --git a/Assets/URS/Best HTTP/Source/WebSocket/Implementations/OverHTTP1.cs b/Assets/URS/Best HTTP/Source/WebSocket/Implementations/OverHTTP1.cs index fae2bfa..db3b861 100644 --- a/Assets/URS/Best HTTP/Source/WebSocket/Implementations/OverHTTP1.cs +++ b/Assets/URS/Best HTTP/Source/WebSocket/Implementations/OverHTTP1.cs @@ -3,6 +3,7 @@ using BestHTTP.Connections; using BestHTTP.Extensions; +using BestHTTP.PlatformSupport.Memory; using BestHTTP.WebSocket.Frames; namespace BestHTTP.WebSocket @@ -80,7 +81,7 @@ protected override void CreateInternalRequest() this._internalRequest.DisableCache = true; #endif -#if !BESTHTTP_DISABLE_PROXY +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) this._internalRequest.Proxy = this.Parent.GetProxy(this.Uri); #endif @@ -283,10 +284,17 @@ private void OnInternalRequestUpgraded(HTTPRequest req, HTTPResponse resp) this.Parent.OnMessage(this.Parent, msg); }; - webSocket.OnBinary = (ws, bin) => + webSocket.OnBinaryNoAlloc = (ws, frame) => { if (this.Parent.OnBinary != null) + { + var bin = new byte[frame.Count]; + Array.Copy(frame.Data, 0, bin, 0, frame.Count); this.Parent.OnBinary(this.Parent, bin); + } + + if (this.Parent.OnBinaryNoAlloc != null) + this.Parent.OnBinaryNoAlloc(this.Parent, frame); }; webSocket.OnClosed = (ws, code, msg) => @@ -325,6 +333,16 @@ public override void Send(byte[] buffer, ulong offset, ulong count) webSocket.Send(buffer, offset, count); } + public override void SendAsBinary(BufferSegment data) + { + webSocket.Send(WebSocketFrameTypes.Binary, data); + } + + public override void SendAsText(BufferSegment data) + { + webSocket.Send(WebSocketFrameTypes.Text, data); + } + public override void Send(WebSocketFrame frame) { webSocket.Send(frame); diff --git a/Assets/URS/Best HTTP/Source/WebSocket/Implementations/OverHTTP2.cs b/Assets/URS/Best HTTP/Source/WebSocket/Implementations/OverHTTP2.cs index 76423a3..7174eaa 100644 --- a/Assets/URS/Best HTTP/Source/WebSocket/Implementations/OverHTTP2.cs +++ b/Assets/URS/Best HTTP/Source/WebSocket/Implementations/OverHTTP2.cs @@ -1,13 +1,15 @@ #if (!UNITY_WEBGL || UNITY_EDITOR) && !BESTHTTP_DISABLE_ALTERNATE_SSL && !BESTHTTP_DISABLE_HTTP2 && !BESTHTTP_DISABLE_WEBSOCKET using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; +using System.Text; using BestHTTP.Connections.HTTP2; using BestHTTP.Extensions; +using BestHTTP.Logger; using BestHTTP.PlatformSupport.Memory; using BestHTTP.WebSocket.Frames; -using BestHTTP.WebSocket.Implementations.Utils; namespace BestHTTP.WebSocket { @@ -16,18 +18,20 @@ namespace BestHTTP.WebSocket /// public sealed class OverHTTP2 : WebSocketBaseImplementation, IHeartbeat { - public override int BufferedAmount { get => (int)this.upStream.Length; } + public override int BufferedAmount { get => this._bufferedAmount; } + internal volatile int _bufferedAmount; + public override bool IsOpen => this.State == WebSocketStates.Open; + public override int Latency { get { return this.Parent.StartPingThread ? base.Latency : (int)this.http2Handler.Latency; } } private List IncompleteFrames = new List(); private HTTP2Handler http2Handler; - private LockedBufferSegmenStream upStream; /// /// True if we sent out a Close message to the server /// - private volatile bool closeSent; + internal volatile bool closeSent; /// /// When we sent out the last ping. @@ -42,19 +46,25 @@ public sealed class OverHTTP2 : WebSocketBaseImplementation, IHeartbeat private CircularBuffer rtts = new CircularBuffer(WebSocketResponse.RTTBufferCapacity); private PeekableIncomingSegmentStream incomingSegmentStream = new PeekableIncomingSegmentStream(); + private ConcurrentQueue CompletedFrames = new ConcurrentQueue(); + internal ConcurrentQueue frames = new ConcurrentQueue(); - public OverHTTP2(WebSocket parent, HTTP2Handler handler, Uri uri, string origin, string protocol) : base(parent, uri, origin, protocol) + public OverHTTP2(WebSocket parent, Uri uri, string origin, string protocol) : base(parent, uri, origin, protocol) { - this.http2Handler = handler; - + // use https scheme so it will be served over HTTP/2. Thre request's Tag will be set to this class' instance so HTTP2Handler will know it has to create a HTTP2WebSocketStream instance to + // process the request. string scheme = "https"; int port = uri.Port != -1 ? uri.Port : 443; base.Uri = new Uri(scheme + "://" + uri.Host + ":" + port + uri.GetRequestPathAndQueryURL()); } + internal void SetHTTP2Handler(HTTP2Handler handler) => this.http2Handler = handler; + protected override void CreateInternalRequest() { + HTTPManager.Logger.Verbose("OverHTTP2", "CreateInternalRequest", this.Parent.Context); + base._internalRequest = new HTTPRequest(base.Uri, HTTPMethods.Connect, OnInternalRequestCallback); base._internalRequest.Context.Add("WebSocket", this.Parent.Context); @@ -84,14 +94,16 @@ protected override void CreateInternalRequest() base._internalRequest.DisableCache = true; #endif - base._internalRequest.OnHeadersReceived += OnHeadersReceived; - base._internalRequest.OnStreamingData += OnFrame; - base._internalRequest.StreamChunksImmediately = true; + base._internalRequest.OnHeadersReceived += OnHeadersReceived; - base._internalRequest.UploadStream = this.upStream = new LockedBufferSegmenStream(); + // set a fake upload stream, so HPACKEncoder will not set the END_STREAM flag + base._internalRequest.UploadStream = new MemoryStream(0); base._internalRequest.UseUploadStreamLength = false; + this.LastMessageReceived = DateTime.Now; + base._internalRequest.Tag = this; + if (this.Parent.OnInternalRequestCreated != null) { try @@ -107,8 +119,31 @@ protected override void CreateInternalRequest() private void OnHeadersReceived(HTTPRequest req, HTTPResponse resp, Dictionary> newHeaders) { + HTTPManager.Logger.Verbose("OverHTTP2", $"OnHeadersReceived - StatusCode: {resp?.StatusCode}", this.Parent.Context); + if (resp != null && resp.StatusCode == 200) { + if (this.Parent.Extensions != null) + { + for (int i = 0; i < this.Parent.Extensions.Length; ++i) + { + var ext = this.Parent.Extensions[i]; + + try + { + if (ext != null && !ext.ParseNegotiation(resp)) + this.Parent.Extensions[i] = null; // Keep extensions only that successfully negotiated + } + catch (Exception ex) + { + HTTPManager.Logger.Exception("OverHTTP2", "ParseNegotiation", ex, this.Parent.Context); + + // Do not try to use a defective extension in the future + this.Parent.Extensions[i] = null; + } + } + } + this.State = WebSocketStates.Open; if (this.Parent.OnOpen != null) @@ -208,11 +243,11 @@ private static bool CanReadFullFrame(PeekableIncomingSegmentStream stream) return stream.Length >= (long)Length; } - private bool OnFrame(HTTPRequest request, HTTPResponse response, byte[] dataFragment, int dataFragmentLength) + internal void OnReadThread(BufferSegment buffer) { - base.LastMessageReceived = DateTime.Now; + this.LastMessageReceived = DateTime.Now; - this.incomingSegmentStream.Write(dataFragment, 0, dataFragmentLength); + this.incomingSegmentStream.Write(buffer); while (CanReadFullFrame(this.incomingSegmentStream)) { @@ -220,24 +255,15 @@ private bool OnFrame(HTTPRequest request, HTTPResponse response, byte[] dataFrag frame.Read(this.incomingSegmentStream); if (HTTPManager.Logger.Level == Logger.Loglevels.All) - HTTPManager.Logger.Verbose("OverHTTP2", "Frame received: " + frame.Type, this.Parent.Context); + HTTPManager.Logger.Verbose("OverHTTP2", "Frame received: " + frame.ToString(), this.Parent.Context); if (!frame.IsFinal) { if (this.Parent.OnIncompleteFrame == null) IncompleteFrames.Add(frame); - else if (this.Parent.OnIncompleteFrame != null) - { - try - { - this.Parent.OnIncompleteFrame(this.Parent, frame); - } - catch (Exception ex) - { - HTTPManager.Logger.Exception("OverHTTP2", "OnIncompleteFrame", ex, this.Parent.Context); - } - } - return false; + else + CompletedFrames.Enqueue(frame); + continue; } switch (frame.Type) @@ -254,146 +280,67 @@ private bool OnFrame(HTTPRequest request, HTTPResponse response, byte[] dataFrag IncompleteFrames.Clear(); // Control frames themselves MUST NOT be fragmented. So, its a normal text or binary frame. Go, handle it as usual. - //goto case WebSocketFrameTypes.Binary; - if (frame.Type == WebSocketFrameTypes.Text) - goto case WebSocketFrameTypes.Text; - else if (frame.Type == WebSocketFrameTypes.Binary) - goto case WebSocketFrameTypes.Binary; + goto case WebSocketFrameTypes.Binary; } else { - if (this.Parent.OnIncompleteFrame != null) - { - try - { - this.Parent.OnIncompleteFrame(this.Parent, frame); - } - catch (Exception ex) - { - HTTPManager.Logger.Exception("OverHTTP2", "OnIncompleteFrame", ex, this.Parent.Context); - } - } + CompletedFrames.Enqueue(frame); } break; case WebSocketFrameTypes.Text: - frame.DecodeWithExtensions(this.Parent); - if (this.Parent.OnMessage != null) - { - try - { - this.Parent.OnMessage(this.Parent, frame.DataAsText); - } - catch (Exception ex) - { - HTTPManager.Logger.Exception("OverHTTP2", "OnMessage", ex, this.Parent.Context); - } - } - break; - case WebSocketFrameTypes.Binary: frame.DecodeWithExtensions(this.Parent); - if (this.Parent.OnBinary != null) - { - try - { - this.Parent.OnBinary(this.Parent, frame.Data); - } - catch (Exception ex) - { - HTTPManager.Logger.Exception("OverHTTP2", "OnBinary", ex, this.Parent.Context); - } - } + CompletedFrames.Enqueue(frame); break; // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in response, unless it already received a Close frame. case WebSocketFrameTypes.Ping: - if (!closeSent && !this.upStream.IsClosed) - Send(new WebSocketFrame(this.Parent, WebSocketFrameTypes.Pong, frame.Data)); + if (!closeSent && this.State != WebSocketStates.Closed) + { + // copy data set to true here, as the frame's data is released back to the pool after the switch + Send(new WebSocketFrame(this.Parent, WebSocketFrameTypes.Pong, frame.Data, true, true, true)); + } break; case WebSocketFrameTypes.Pong: - waitingForPong = false; - - try - { - // Get the ticks from the frame's payload - long ticksSent = BitConverter.ToInt64(frame.Data, 0); + // https://tools.ietf.org/html/rfc6455#section-5.5 + // A Pong frame MAY be sent unsolicited. This serves as a + // unidirectional heartbeat. A response to an unsolicited Pong frame is + // not expected. + if (!waitingForPong) + break; - // the difference between the current time and the time when the ping message is sent - TimeSpan diff = TimeSpan.FromTicks(this.LastMessageReceived.Ticks - ticksSent); + waitingForPong = false; + // the difference between the current time and the time when the ping message is sent + TimeSpan diff = DateTime.Now - lastPing; - // add it to the buffer - this.rtts.Add((int)diff.TotalMilliseconds); - - // and calculate the new latency - base.Latency = CalculateLatency(); - } - catch - { - // https://tools.ietf.org/html/rfc6455#section-5.5 - // A Pong frame MAY be sent unsolicited. This serves as a - // unidirectional heartbeat. A response to an unsolicited Pong frame is - // not expected. - } + // add it to the buffer + this.rtts.Add((int)diff.TotalMilliseconds); + // and calculate the new latency + base.Latency = CalculateLatency(); break; // If an endpoint receives a Close frame and did not previously send a Close frame, the endpoint MUST send a Close frame in response. case WebSocketFrameTypes.ConnectionClose: HTTPManager.Logger.Information("OverHTTP2", "ConnectionClose packet received!", this.Parent.Context); - //CloseFrame = frame; - if (!closeSent) - Send(new WebSocketFrame(this.Parent, WebSocketFrameTypes.ConnectionClose, null)); - this.upStream.Close(); - - UInt16 statusCode = 0; - string msg = string.Empty; - try - { - // If we received any data, we will get the status code and the message from it - if (frame.Data != null && frame.Length >= 2) - { - if (BitConverter.IsLittleEndian) - Array.Reverse(frame.Data, 0, 2); - statusCode = BitConverter.ToUInt16(frame.Data, 0); - - if (frame.Data.Length > 2) - msg = System.Text.Encoding.UTF8.GetString(frame.Data, 2, (int)frame.Length - 2); - - frame.ReleaseData(); - } - } - catch (Exception ex) - { - HTTPManager.Logger.Exception("OverHTTP2", "OnFrame - parsing ConnectionClose data", ex, this.Parent.Context); - } - - if (this.Parent.OnClosed != null) - { - try - { - this.Parent.OnClosed(this.Parent, statusCode, msg); - } - catch (Exception ex) - { - HTTPManager.Logger.Exception("OverHTTP2", "OnClosed", ex, this.Parent.Context); - } - this.Parent.OnClosed = null; - } + CompletedFrames.Enqueue(frame); + if (!closeSent) + Send(new WebSocketFrame(this.Parent, WebSocketFrameTypes.ConnectionClose, BufferSegment.Empty)); + this.State = WebSocketStates.Closed; - break; } } - - return false; } private void OnInternalRequestCallback(HTTPRequest req, HTTPResponse resp) { + HTTPManager.Logger.Verbose("OverHTTP2", $"OnInternalRequestCallback - this.State: {this.State}", this.Parent.Context); + // If it's already closed, all events are called too. if (this.State == WebSocketStates.Closed) return; @@ -480,6 +427,8 @@ private void OnInternalRequestCallback(HTTPRequest req, HTTPResponse resp) public override void StartOpen() { + HTTPManager.Logger.Verbose("OverHTTP2", "StartOpen", this.Parent.Context); + if (this.Parent.Extensions != null) { try @@ -499,13 +448,14 @@ public override void StartOpen() base.InternalRequest.Send(); HTTPManager.Heartbeats.Subscribe(this); - HTTPUpdateDelegator.OnApplicationForegroundStateChanged += OnApplicationForegroundStateChanged; this.State = WebSocketStates.Connecting; } public override void StartClose(ushort code, string message) { + HTTPManager.Logger.Verbose("OverHTTP2", "StartClose", this.Parent.Context); + if (this.State == WebSocketStates.Connecting) { if (this.InternalRequest != null) @@ -517,7 +467,7 @@ public override void StartClose(ushort code, string message) } else { - Send(new WebSocketFrame(this.Parent, WebSocketFrameTypes.ConnectionClose, WebSocket.EncodeCloseData(code, message))); + Send(new WebSocketFrame(this.Parent, WebSocketFrameTypes.ConnectionClose, WebSocket.EncodeCloseData(code, message), true, false, false)); this.State = WebSocketStates.Closing; } } @@ -531,22 +481,7 @@ public override void Send(string message) byte[] data = BufferPool.Get(count, true); System.Text.Encoding.UTF8.GetBytes(message, 0, message.Length, data, 0); - var frame = new WebSocketFrame(this.Parent, WebSocketFrameTypes.Text, data, 0, (ulong)count, true, true); - - var maxFrameSize = this.http2Handler.settings.RemoteSettings[HTTP2Settings.MAX_FRAME_SIZE]; - if (frame.Data != null && frame.Data.Length > maxFrameSize) - { - WebSocketFrame[] additionalFrames = frame.Fragment(maxFrameSize); - - Send(frame); - if (additionalFrames != null) - for (int i = 0; i < additionalFrames.Length; ++i) - Send(additionalFrames[i]); - } - else - Send(frame); - - BufferPool.Release(data); + SendAsText(data.AsBuffer(0, count)); } public override void Send(byte[] buffer) @@ -554,20 +489,7 @@ public override void Send(byte[] buffer) if (buffer == null) throw new ArgumentNullException("data must not be null!"); - WebSocketFrame frame = new WebSocketFrame(this.Parent, WebSocketFrameTypes.Binary, buffer); - - var maxFrameSize = this.http2Handler.settings.RemoteSettings[HTTP2Settings.MAX_FRAME_SIZE]; - if (frame.Data != null && frame.Data.Length > maxFrameSize) - { - WebSocketFrame[] additionalFrames = frame.Fragment(maxFrameSize); - - Send(frame); - if (additionalFrames != null) - for (int i = 0; i < additionalFrames.Length; ++i) - Send(additionalFrames[i]); - } - else - Send(frame); + Send(new WebSocketFrame(this.Parent, WebSocketFrameTypes.Binary, new BufferSegment(buffer, 0, buffer.Length))); } public override void Send(byte[] data, ulong offset, ulong count) @@ -577,41 +499,37 @@ public override void Send(byte[] data, ulong offset, ulong count) if (offset + count > (ulong)data.Length) throw new ArgumentOutOfRangeException("offset + count >= data.Length"); - WebSocketFrame frame = new WebSocketFrame(this.Parent, WebSocketFrameTypes.Binary, data, offset, count, true, true); - - var maxFrameSize = this.http2Handler.settings.RemoteSettings[HTTP2Settings.MAX_FRAME_SIZE]; - if (frame.Data != null && frame.Data.Length > maxFrameSize) - { - WebSocketFrame[] additionalFrames = frame.Fragment(maxFrameSize); - - Send(frame); - - if (additionalFrames != null) - for (int i = 0; i < additionalFrames.Length; ++i) - Send(additionalFrames[i]); - } - else - Send(frame); + Send(new WebSocketFrame(this.Parent, WebSocketFrameTypes.Binary, new BufferSegment(data, (int)offset, (int)count), true, true)); } public override void Send(WebSocketFrame frame) { - if (frame == null) - throw new ArgumentNullException("frame is null!"); - - if (this.upStream.IsClosed || closeSent) + if (this.State == WebSocketStates.Closed || closeSent) return; - var frameData = frame.Get(); - this.upStream.Write(new BufferSegment(frameData.Data, 0, frameData.Length)); + this.frames.Enqueue(frame); this.http2Handler.SignalRunnerThread(); - - frameData.Data = null; + this._bufferedAmount += frame.Data.Count; if (frame.Type == WebSocketFrameTypes.ConnectionClose) this.closeSent = true; } + public override void SendAsBinary(BufferSegment data) + { + Send(WebSocketFrameTypes.Binary, data); + } + + public override void SendAsText(BufferSegment data) + { + Send(WebSocketFrameTypes.Text, data); + } + + private void Send(WebSocketFrameTypes type, BufferSegment data) + { + Send(new WebSocketFrame(this.Parent, type, data, true, true, false)); + } + private int CalculateLatency() { if (this.rtts.Count == 0) @@ -624,6 +542,29 @@ private int CalculateLatency() return sumLatency / this.rtts.Count; } + internal void PreReadCallback() + { + if (this.Parent.StartPingThread) + { + DateTime now = DateTime.Now; + + if (!waitingForPong && now - LastMessageReceived >= TimeSpan.FromMilliseconds(this.Parent.PingFrequency)) + SendPing(); + + if (waitingForPong && now - lastPing > this.Parent.CloseAfterNoMessage) + { + if (this.State != WebSocketStates.Closed) + { + HTTPManager.Logger.Warning("OverHTTP2", + string.Format("No message received in the given time! Closing WebSocket. LastPing: {0}, PingFrequency: {1}, Close After: {2}, Now: {3}", + this.lastPing, TimeSpan.FromMilliseconds(this.Parent.PingFrequency), this.Parent.CloseAfterNoMessage, now), this.Parent.Context); + + CloseWithError("No message received in the given time!"); + } + } + } + } + public void OnHeartbeatUpdate(TimeSpan dif) { DateTime now = DateTime.Now; @@ -647,34 +588,109 @@ public void OnHeartbeatUpdate(TimeSpan dif) } break; - case WebSocketStates.Open: - if (this.Parent.StartPingThread) + default: + while (CompletedFrames.TryDequeue(out var frame)) { - if (!waitingForPong && now - LastMessageReceived >= TimeSpan.FromMilliseconds(this.Parent.PingFrequency)) - SendPing(); - - if (waitingForPong && now - lastPing > this.Parent.CloseAfterNoMessage) + // Bugs in the clients shouldn't interrupt the code, so we need to try-catch and ignore any exception occurring here + try { - HTTPManager.Logger.Warning("OverHTTP2", - string.Format("No message received in the given time! Closing WebSocket. LastPing: {0}, PingFrequency: {1}, Close After: {2}, Now: {3}", - this.lastPing, TimeSpan.FromMilliseconds(this.Parent.PingFrequency), this.Parent.CloseAfterNoMessage, now), this.Parent.Context); - - CloseWithError("No message received in the given time!"); + switch (frame.Type) + { + case WebSocketFrameTypes.Continuation: + if (HTTPManager.Logger.Level == Loglevels.All) + HTTPManager.Logger.Verbose("OverHTTP2", "HandleEvents - OnIncompleteFrame", this.Parent.Context); + if (this.Parent.OnIncompleteFrame != null) + this.Parent.OnIncompleteFrame(this.Parent, frame); + break; + + case WebSocketFrameTypes.Text: + // Any not Final frame is handled as a fragment + if (!frame.IsFinal) + goto case WebSocketFrameTypes.Continuation; + + if (HTTPManager.Logger.Level == Loglevels.All) + HTTPManager.Logger.Verbose("OverHTTP2", $"HandleEvents - OnText(\"{frame.DataAsText}\")", this.Parent.Context); + + if (this.Parent.OnMessage != null) + this.Parent.OnMessage(this.Parent, frame.DataAsText); + break; + + case WebSocketFrameTypes.Binary: + // Any not Final frame is handled as a fragment + if (!frame.IsFinal) + goto case WebSocketFrameTypes.Continuation; + + if (HTTPManager.Logger.Level == Loglevels.All) + HTTPManager.Logger.Verbose("OverHTTP2", $"HandleEvents - OnBinary({frame.Data})", this.Parent.Context); + + if (this.Parent.OnBinary != null) + { + var data = new byte[frame.Data.Count]; + Array.Copy(frame.Data.Data, frame.Data.Offset, data, 0, frame.Data.Count); + this.Parent.OnBinary(this.Parent, data); + } + + if (this.Parent.OnBinaryNoAlloc != null) + this.Parent.OnBinaryNoAlloc(this.Parent, frame.Data); + break; + + case WebSocketFrameTypes.ConnectionClose: + HTTPManager.Logger.Verbose("OverHTTP2", "HandleEvents - Calling OnClosed", this.Parent.Context); + if (this.Parent.OnClosed != null) + { + try + { + UInt16 statusCode = 0; + string msg = string.Empty; + + // If we received any data, we will get the status code and the message from it + if (/*CloseFrame != null && */ frame.Data != BufferSegment.Empty && frame.Data.Count >= 2) + { + if (BitConverter.IsLittleEndian) + Array.Reverse(frame.Data.Data, frame.Data.Offset, 2); + statusCode = BitConverter.ToUInt16(frame.Data.Data, frame.Data.Offset); + + if (frame.Data.Count > 2) + msg = Encoding.UTF8.GetString(frame.Data.Data, frame.Data.Offset + 2, frame.Data.Count - 2); + + frame.ReleaseData(); + } + + this.Parent.OnClosed(this.Parent, statusCode, msg); + this.Parent.OnClosed = null; + } + catch (Exception ex) + { + HTTPManager.Logger.Exception("OverHTTP2", "HandleEvents - OnClosed", ex, this.Parent.Context); + } + } + + HTTPManager.Heartbeats.Unsubscribe(this); + break; + } + } + catch (Exception ex) + { + HTTPManager.Logger.Exception("OverHTTP2", string.Format("HandleEvents({0})", frame.ToString()), ex, this.Parent.Context); + } + finally + { + frame.ReleaseData(); } } break; - - case WebSocketStates.Closed: - HTTPManager.Heartbeats.Unsubscribe(this); - HTTPUpdateDelegator.OnApplicationForegroundStateChanged -= OnApplicationForegroundStateChanged; - break; } } - private void OnApplicationForegroundStateChanged(bool isPaused) + /// + /// Next interaction relative to *now*. + /// + public TimeSpan GetNextInteraction() { - if (!isPaused) - base.LastMessageReceived = DateTime.Now; + if (waitingForPong) + return TimeSpan.MaxValue; + + return (LastMessageReceived + TimeSpan.FromMilliseconds(this.Parent.PingFrequency)) - DateTime.Now; } private void SendPing() @@ -684,18 +700,14 @@ private void SendPing() lastPing = DateTime.Now; waitingForPong = true; - long ticks = DateTime.Now.Ticks; - var ticksBytes = BitConverter.GetBytes(ticks); - - var pingFrame = new WebSocketFrame(this.Parent, WebSocketFrameTypes.Ping, ticksBytes); - - Send(pingFrame); + Send(new WebSocketFrame(this.Parent, WebSocketFrameTypes.Ping, BufferSegment.Empty)); } private void CloseWithError(string message) { + HTTPManager.Logger.Verbose("OverHTTP2", $"CloseWithError(\"{message}\")", this.Parent.Context); + this.State = WebSocketStates.Closed; - this.upStream.Close(); if (this.Parent.OnError != null) { diff --git a/Assets/URS/Best HTTP/Source/WebSocket/Implementations/WebGLBrowser.cs b/Assets/URS/Best HTTP/Source/WebSocket/Implementations/WebGLBrowser.cs index f5e2e35..531a47e 100644 --- a/Assets/URS/Best HTTP/Source/WebSocket/Implementations/WebGLBrowser.cs +++ b/Assets/URS/Best HTTP/Source/WebSocket/Implementations/WebGLBrowser.cs @@ -68,6 +68,18 @@ public override void Send(byte[] buffer, ulong offset, ulong count) WS_Send_Binary(this.ImplementationId, buffer, (int)offset, (int)count); } + public override void SendAsBinary(BufferSegment data) + { + WS_Send_Binary(this.ImplementationId, data.Data, data.Offset, data.Count); + BufferPool.Release(data); + } + + public override void SendAsText(BufferSegment data) + { + WS_Send_String(this.ImplementationId, data.Data, data.Offset, data.Count); + BufferPool.Release(data); + } + [DllImport("__Internal")] static extern uint WS_Create(string url, string protocol, OnWebGLWebSocketOpenDelegate onOpen, OnWebGLWebSocketTextDelegate onText, OnWebGLWebSocketBinaryDelegate onBinary, OnWebGLWebSocketErrorDelegate onError, OnWebGLWebSocketCloseDelegate onClose); @@ -155,6 +167,26 @@ static void OnBinaryCallback(uint id, IntPtr pBuffer, int length) HTTPManager.Logger.Exception("WebSocket", "OnBinary", ex, ws.Context); } } + + if (ws.OnBinaryNoAlloc != null) + { + try + { + byte[] buffer = BufferPool.Get(length, true); + + // We still have to do a copy here, but at least the buffer will be released back to the pool. + // Copy data from the 'unmanaged' memory to managed memory. Buffer will be reclaimed by the GC. + Marshal.Copy(pBuffer, buffer, 0, length); + + ws.OnBinaryNoAlloc(ws, new BufferSegment(buffer, 0, length)); + + BufferPool.Release(buffer); + } + catch (Exception ex) + { + HTTPManager.Logger.Exception("WebSocket", "OnBinary", ex, ws.Context); + } + } } else HTTPManager.Logger.Warning("WebSocket", "OnBinaryCallback - No WebSocket found for id: " + id.ToString()); diff --git a/Assets/URS/Best HTTP/Source/WebSocket/Implementations/WebSocketBaseImplementation.cs b/Assets/URS/Best HTTP/Source/WebSocket/Implementations/WebSocketBaseImplementation.cs index 0b25d18..2df6f57 100644 --- a/Assets/URS/Best HTTP/Source/WebSocket/Implementations/WebSocketBaseImplementation.cs +++ b/Assets/URS/Best HTTP/Source/WebSocket/Implementations/WebSocketBaseImplementation.cs @@ -1,6 +1,8 @@ #if !BESTHTTP_DISABLE_WEBSOCKET using System; +using BestHTTP.PlatformSupport.Memory; + #if !UNITY_WEBGL || UNITY_EDITOR using BestHTTP.WebSocket.Frames; #endif @@ -22,6 +24,7 @@ public enum WebSocketStates : byte public delegate void OnWebSocketOpenDelegate(WebSocket webSocket); public delegate void OnWebSocketMessageDelegate(WebSocket webSocket, string message); public delegate void OnWebSocketBinaryDelegate(WebSocket webSocket, byte[] data); + public delegate void OnWebSocketBinaryNoAllocDelegate(WebSocket webSocket, BufferSegment data); public delegate void OnWebSocketClosedDelegate(WebSocket webSocket, UInt16 code, string message); public delegate void OnWebSocketErrorDelegate(WebSocket webSocket, string reason); @@ -68,7 +71,7 @@ public WebSocketBaseImplementation(WebSocket parent, Uri uri, string origin, str this.LastMessageReceived = DateTime.MinValue; // Set up some default values. - this.Parent.PingFrequency = 1000; + this.Parent.PingFrequency = 10_000; this.Parent.CloseAfterNoMessage = TimeSpan.FromSeconds(2); #endif } @@ -79,6 +82,8 @@ public WebSocketBaseImplementation(WebSocket parent, Uri uri, string origin, str public abstract void Send(string message); public abstract void Send(byte[] buffer); public abstract void Send(byte[] buffer, ulong offset, ulong count); + public abstract void SendAsBinary(BufferSegment data); + public abstract void SendAsText(BufferSegment data); #if !UNITY_WEBGL || UNITY_EDITOR protected abstract void CreateInternalRequest(); diff --git a/Assets/URS/Best HTTP/Source/WebSocket/WebSocket.cs b/Assets/URS/Best HTTP/Source/WebSocket/WebSocket.cs index c8875a9..152c1c2 100644 --- a/Assets/URS/Best HTTP/Source/WebSocket/WebSocket.cs +++ b/Assets/URS/Best HTTP/Source/WebSocket/WebSocket.cs @@ -21,6 +21,22 @@ public sealed class WebSocket /// public static uint MaxFragmentSize = UInt16.MaxValue / 2; +#if !UNITY_WEBGL || UNITY_EDITOR + public static IExtension[] GetDefaultExtensions() + { +#if !BESTHTTP_DISABLE_GZIP + return new IExtension[] { new PerMessageCompression(/*compression level: */ Decompression.Zlib.CompressionLevel.Default, + /*clientNoContextTakeover: */ false, + /*serverNoContextTakeover: */ false, + /*clientMaxWindowBits: */ Decompression.Zlib.ZlibConstants.WindowBitsMax, + /*desiredServerMaxWindowBits: */ Decompression.Zlib.ZlibConstants.WindowBitsMax, + /*minDatalengthToCompress: */ PerMessageCompression.MinDataLengthToCompressDefault) }; +#else + return null; +#endif + } +#endif + public WebSocketStates State { get { return this.implementation.State; } } /// @@ -41,7 +57,7 @@ public sealed class WebSocket public bool StartPingThread { get; set; } /// - /// The delay between two Pings in milliseconds. Minimum value is 100, default is 1000. + /// The delay between two Pings in milliseconds. Minimum value is 100ms, default is 10 seconds. /// public int PingFrequency { get; set; } @@ -93,6 +109,11 @@ public sealed class WebSocket /// public OnWebSocketBinaryDelegate OnBinary; + /// + /// Called when a Binary message received. It's a more performant version than the OnBinary event, as the memory will be reused. + /// + public OnWebSocketBinaryNoAllocDelegate OnBinaryNoAlloc; + /// /// Called when the WebSocket connection is closed. /// @@ -127,13 +148,8 @@ public sealed class WebSocket public WebSocket(Uri uri) :this(uri, string.Empty, string.Empty) { -#if (!UNITY_WEBGL || UNITY_EDITOR) && !BESTHTTP_DISABLE_GZIP - this.Extensions = new IExtension[] { new PerMessageCompression(/*compression level: */ Decompression.Zlib.CompressionLevel.Default, - /*clientNoContextTakeover: */ false, - /*serverNoContextTakeover: */ false, - /*clientMaxWindowBits: */ Decompression.Zlib.ZlibConstants.WindowBitsMax, - /*desiredServerMaxWindowBits: */ Decompression.Zlib.ZlibConstants.WindowBitsMax, - /*minDatalengthToCompress: */ PerMessageCompression.MinDataLengthToCompressDefault) }; +#if (!UNITY_WEBGL || UNITY_EDITOR) + this.Extensions = WebSocket.GetDefaultExtensions(); #endif } @@ -141,13 +157,8 @@ public WebSocket(Uri uri) public WebSocket(Uri uri, string origin, string protocol) :this(uri, origin, protocol, null) { -#if !BESTHTTP_DISABLE_GZIP - this.Extensions = new IExtension[] { new PerMessageCompression(/*compression level: */ Decompression.Zlib.CompressionLevel.Default, - /*clientNoContextTakeover: */ false, - /*serverNoContextTakeover: */ false, - /*clientMaxWindowBits: */ Decompression.Zlib.ZlibConstants.WindowBitsMax, - /*desiredServerMaxWindowBits: */ Decompression.Zlib.ZlibConstants.WindowBitsMax, - /*minDatalengthToCompress: */ PerMessageCompression.MinDataLengthToCompressDefault) }; +#if (!UNITY_WEBGL || UNITY_EDITOR) + this.Extensions = WebSocket.GetDefaultExtensions(); #endif } #endif @@ -176,11 +187,13 @@ public WebSocket(Uri uri, string origin, string protocol if (HTTPManager.HTTP2Settings.WebSocketOverHTTP2Settings.EnableWebSocketOverHTTP2 && HTTPProtocolFactory.IsSecureProtocol(uri)) { // Try to find a HTTP/2 connection that supports the connect protocol. - var con = BestHTTP.Core.HostManager.GetHost(uri.Host).GetHostDefinition(Core.HostDefinition.GetKeyFor(new UriBuilder("https", uri.Host, uri.Port).Uri -#if !BESTHTTP_DISABLE_PROXY + var connectionKey = Core.HostDefinition.GetKeyFor(new UriBuilder("https", uri.Host, uri.Port).Uri +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) , GetProxy(uri) #endif - )).Find(c => { + ); + + var con = BestHTTP.Core.HostManager.GetHost(uri.Host).GetHostDefinition(connectionKey).Find(c => { var httpConnection = c as HTTPConnection; var http2Handler = httpConnection?.requestHandler as Connections.HTTP2.HTTP2Handler; @@ -194,7 +207,7 @@ public WebSocket(Uri uri, string origin, string protocol var httpConnection = con as HTTPConnection; var http2Handler = httpConnection?.requestHandler as Connections.HTTP2.HTTP2Handler; - this.implementation = new OverHTTP2(this, http2Handler, uri, origin, protocol); + this.implementation = new OverHTTP2(this, uri, origin, protocol); } } #endif @@ -212,6 +225,8 @@ public WebSocket(Uri uri, string origin, string protocol #if !UNITY_WEBGL || UNITY_EDITOR internal void FallbackToHTTP1() { + HTTPManager.Logger.Verbose("WebSocket", "FallbackToHTTP1", this.Context); + if (this.implementation == null) return; @@ -261,6 +276,34 @@ public void Send(byte[] buffer, ulong offset, ulong count) this.implementation.Send(buffer, offset, count); } + /// + /// Will send the data in one or more binary frame and takes ownership over it calling BufferPool.Release when sent. + /// + public void SendAsBinary(BufferSegment data) + { + if (!IsOpen) + { + BufferPool.Release(data); + return; + } + + this.implementation.SendAsBinary(data); + } + + /// + /// Will send data as a text frame and takes owenership over the memory region releasing it to the BufferPool as soon as possible. + /// + public void SendAsText(BufferSegment data) + { + if (!IsOpen) + { + BufferPool.Release(data); + return; + } + + this.implementation.SendAsText(data); + } + #if !UNITY_WEBGL || UNITY_EDITOR /// /// It will send the given frame to the server. @@ -296,7 +339,7 @@ public void Close(UInt16 code, string message) this.implementation.StartClose(code, message); } -#if !BESTHTTP_DISABLE_PROXY +#if !BESTHTTP_DISABLE_PROXY && (!UNITY_WEBGL || UNITY_EDITOR) internal Proxy GetProxy(Uri uri) { // WebSocket is not a request-response based protocol, so we need a 'tunnel' through the proxy @@ -314,7 +357,7 @@ internal Proxy GetProxy(Uri uri) #if !UNITY_WEBGL || UNITY_EDITOR - public static byte[] EncodeCloseData(UInt16 code, string message) + public static BufferSegment EncodeCloseData(UInt16 code, string message) { //If there is a body, the first two bytes of the body MUST be a 2-byte unsigned integer // (in network byte order) representing a status code with value /code/ defined in Section 7.4 (http://tools.ietf.org/html/rfc6455#section-7.4). Following the 2-byte integer, @@ -332,7 +375,9 @@ public static byte[] EncodeCloseData(UInt16 code, string message) buff = Encoding.UTF8.GetBytes(message); ms.Write(buff, 0, buff.Length); - return ms.ToArray(); + buff = ms.ToArray(); + + return buff.AsBuffer(buff.Length); } } diff --git a/Assets/URS/Best HTTP/Source/WebSocket/WebSocketResponse.cs b/Assets/URS/Best HTTP/Source/WebSocket/WebSocketResponse.cs index a1de669..59fb28d 100644 --- a/Assets/URS/Best HTTP/Source/WebSocket/WebSocketResponse.cs +++ b/Assets/URS/Best HTTP/Source/WebSocket/WebSocketResponse.cs @@ -12,10 +12,11 @@ using BestHTTP.Core; using BestHTTP.PlatformSupport.Memory; using BestHTTP.Logger; +using BestHTTP.Connections; namespace BestHTTP.WebSocket { - public sealed class WebSocketResponse : HTTPResponse, IHeartbeat, IProtocol + public sealed class WebSocketResponse : HTTPResponse, IProtocol { /// /// Capacity of the RTT buffer where the latencies are kept. @@ -39,6 +40,11 @@ public sealed class WebSocketResponse : HTTPResponse, IHeartbeat, IProtocol /// public Action OnBinary; + /// + /// Called when a Binary message received. It's a more performant version than the OnBinary event, as the memory will be reused. + /// + public Action OnBinaryNoAlloc; + /// /// Called when an incomplete frame received. No attempt will be made to reassemble these fragments. /// @@ -118,7 +124,10 @@ public sealed class WebSocketResponse : HTTPResponse, IHeartbeat, IProtocol /// private DateTime lastPing = DateTime.MinValue; - private bool waitingForPong = false; + /// + /// True if waiting for an answer to our ping request. Ping timeout is used only why waitingForPong is true. + /// + private volatile bool waitingForPong = false; /// /// A circular buffer to store the last N rtt times calculated by the pong messages. @@ -170,21 +179,7 @@ public void Send(string message) byte[] data = BufferPool.Get(count, true); System.Text.Encoding.UTF8.GetBytes(message, 0, message.Length, data, 0); - var frame = new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.Text, data, 0, (ulong)count, true, true); - - if (frame.Data != null && frame.Data.Length > this.MaxFragmentSize) - { - WebSocketFrame[] additionalFrames = frame.Fragment(this.MaxFragmentSize); - - Send(frame); - if (additionalFrames != null) - for (int i = 0; i < additionalFrames.Length; ++i) - Send(additionalFrames[i]); - } - else - Send(frame); - - BufferPool.Release(data); + Send(WebSocketFrameTypes.Text, data.AsBuffer(count)); } /// @@ -195,19 +190,8 @@ public void Send(byte[] data) if (data == null) throw new ArgumentNullException("data must not be null!"); - WebSocketFrame frame = new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.Binary, data); - - if (frame.Data != null && frame.Data.Length > this.MaxFragmentSize) - { - WebSocketFrame[] additionalFrames = frame.Fragment(this.MaxFragmentSize); - - Send(frame); - if (additionalFrames != null) - for (int i = 0; i < additionalFrames.Length; ++i) - Send(additionalFrames[i]); - } - else - Send(frame); + WebSocketFrame frame = new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.Binary, new BufferSegment(data, 0, data.Length)); + Send(frame); } /// @@ -220,20 +204,14 @@ public void Send(byte[] data, ulong offset, ulong count) if (offset + count > (ulong)data.Length) throw new ArgumentOutOfRangeException("offset + count >= data.Length"); - WebSocketFrame frame = new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.Binary, data, offset, count, true, true); - - if (frame.Data != null && frame.Data.Length > this.MaxFragmentSize) - { - WebSocketFrame[] additionalFrames = frame.Fragment(this.MaxFragmentSize); - - Send(frame); + WebSocketFrame frame = new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.Binary, new BufferSegment(data, (int)offset, (int)count), true, true); + Send(frame); + } - if (additionalFrames != null) - for (int i = 0; i < additionalFrames.Length; ++i) - Send(additionalFrames[i]); - } - else - Send(frame); + public void Send(WebSocketFrameTypes type, BufferSegment data) + { + WebSocketFrame frame = new WebSocketFrame(this.WebSocket, type, data, true, true, false); + Send(frame); } /// @@ -241,9 +219,6 @@ public void Send(byte[] data, ulong offset, ulong count) /// public void Send(WebSocketFrame frame) { - if (frame == null) - throw new ArgumentNullException("frame is null!"); - if (closed || closeSent) return; @@ -256,7 +231,7 @@ public void Send(WebSocketFrame frame) BestHTTP.PlatformSupport.Threading.ThreadedRunner.RunLongLiving(SendThreadFunc); } - Interlocked.Add(ref this._bufferedAmount, frame.Data != null ? frame.DataLength : 0); + Interlocked.Add(ref this._bufferedAmount, frame.Data.Count); //if (HTTPManager.Logger.Level <= Logger.Loglevels.All) // HTTPManager.Logger.Information("WebSocketResponse", "Signaling SendThread!", this.Context); @@ -284,10 +259,13 @@ public void Close(UInt16 code, string msg) WebSocketFrame frame; while (this.unsentFrames.TryDequeue(out frame)) - ; - //this.unsentFrames.Clear(); - - Interlocked.Exchange(ref this._bufferedAmount, 0); + { + if (frame.Data.Data != null) + { + BufferPool.Release(frame.Data); + Interlocked.Add(ref this._bufferedAmount, -frame.Data.Count); + } + } Send(new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.ConnectionClose, WebSocket.EncodeCloseData(code, msg))); } @@ -301,9 +279,6 @@ public void StartPinging(int frequency) lastMessage = DateTime.UtcNow; SendPing(); - - HTTPManager.Heartbeats.Subscribe(this); - HTTPUpdateDelegator.OnApplicationForegroundStateChanged += OnApplicationForegroundStateChanged; } #endregion @@ -312,15 +287,48 @@ public void StartPinging(int frequency) private void SendThreadFunc() { + PlatformSupport.Threading.ThreadedRunner.SetThreadName("BestHTTP.WebSocket Send"); + try { + bool mask = !HTTPProtocolFactory.IsSecureProtocol(this.baseRequest.CurrentUri); using (WriteOnlyBufferedStream bufferedStream = new WriteOnlyBufferedStream(this.Stream, 16 * 1024)) { while (!closed && !closeSent) { //if (HTTPManager.Logger.Level <= Logger.Loglevels.All) // HTTPManager.Logger.Information("WebSocketResponse", "SendThread - Waiting...", this.Context); - newFrameSignal.WaitOne(); + + TimeSpan waitTime = TimeSpan.FromMilliseconds(int.MaxValue); + + if (this.PingFrequnecy != TimeSpan.Zero) + { + DateTime now = DateTime.UtcNow; + waitTime = lastMessage + PingFrequnecy - now; + + if (waitTime <= TimeSpan.Zero) + { + if (!waitingForPong && now - lastMessage >= PingFrequnecy) + { + if (!SendPing()) + continue; + } + + waitTime = PingFrequnecy; + } + + if (waitingForPong && now - lastPing > this.WebSocket.CloseAfterNoMessage) + { + HTTPManager.Logger.Warning("WebSocketResponse", + string.Format("No message received in the given time! Closing WebSocket. LastPing: {0}, PingFrequency: {1}, Close After: {2}, Now: {3}", + this.lastPing, this.PingFrequnecy, this.WebSocket.CloseAfterNoMessage, now), this.Context); + + CloseWithError(HTTPRequestStates.Error, "No message received in the given time!"); + continue; + } + } + + newFrameSignal.WaitOne(waitTime); try { @@ -330,18 +338,26 @@ private void SendThreadFunc() WebSocketFrame frame; while (this.unsentFrames.TryDequeue(out frame)) { + // save data count as per-message deflate can compress, and it would be different after calling WriteTo + int originalFrameDataLength = frame.Data.Count; + if (!closeSent) { - using (var rawData = frame.Get()) - bufferedStream.Write(rawData.Data, 0, rawData.Length); - + frame.WriteTo((header, chunk) => + { + bufferedStream.Write(header.Data, header.Offset, header.Count); + BufferPool.Release(header); + + if (chunk != BufferSegment.Empty) + bufferedStream.Write(chunk.Data, chunk.Offset, chunk.Count); + }, MaxFragmentSize, mask, this.Context); BufferPool.Release(frame.Data); if (frame.Type == WebSocketFrameTypes.ConnectionClose) closeSent = true; } - Interlocked.Add(ref this._bufferedAmount, -frame.DataLength); + Interlocked.Add(ref this._bufferedAmount, -originalFrameDataLength); } bufferedStream.Flush(); @@ -363,6 +379,11 @@ private void SendThreadFunc() HTTPManager.Logger.Information("WebSocketResponse", string.Format("Ending Send thread. Closed: {0}, closeSent: {1}", closed, closeSent), this.Context); } } + catch (Exception ex) + { + if (HTTPManager.Logger.Level == Loglevels.All) + HTTPManager.Logger.Exception("WebSocketResponse", "SendThread", ex); + } finally { Interlocked.Exchange(ref sendThreadCreated, 0); @@ -375,6 +396,8 @@ private void SendThreadFunc() private void ReceiveThreadFunc() { + PlatformSupport.Threading.ThreadedRunner.SetThreadName("BestHTTP.WebSocket Receive"); + try { while (!closed) @@ -385,20 +408,10 @@ private void ReceiveThreadFunc() frame.Read(this.Stream); if (HTTPManager.Logger.Level == Logger.Loglevels.All) - HTTPManager.Logger.Information("WebSocketResponse", "Frame received: " + frame.Type, this.Context); + HTTPManager.Logger.Information("WebSocketResponse", "Frame received: " + frame.ToString(), this.Context); lastMessage = DateTime.UtcNow; - // A server MUST NOT mask any frames that it sends to the client. A client MUST close a connection if it detects a masked frame. - // In this case, it MAY use the status code 1002 (protocol error) - // (These rules might be relaxed in a future specification.) - if (frame.HasMask) - { - HTTPManager.Logger.Warning("WebSocketResponse", "Protocol Error: masked frame received from server!", this.Context); - Close(1002, "Protocol Error: masked frame received from server!"); - continue; - } - if (!frame.IsFinal) { if (OnIncompleteFrame == null) @@ -441,19 +454,14 @@ private void ReceiveThreadFunc() // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in response, unless it already received a Close frame. case WebSocketFrameTypes.Ping: if (!closeSent && !closed) - Send(new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.Pong, frame.Data)); + Send(new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.Pong, frame.Data, true, true)); break; case WebSocketFrameTypes.Pong: - waitingForPong = false; - try { - // Get the ticks from the frame's payload - long ticksSent = BitConverter.ToInt64(frame.Data, 0); - // the difference between the current time and the time when the ping message is sent - TimeSpan diff = TimeSpan.FromTicks(lastMessage.Ticks - ticksSent); + TimeSpan diff = TimeSpan.FromTicks(this.lastMessage.Ticks - this.lastPing.Ticks); // add it to the buffer this.rtts.Add((int)diff.TotalMilliseconds); @@ -468,6 +476,10 @@ private void ReceiveThreadFunc() // unidirectional heartbeat. A response to an unsolicited Pong frame is // not expected. } + finally + { + waitingForPong = false; + } break; @@ -477,7 +489,7 @@ private void ReceiveThreadFunc() CloseFrame = frame; if (!closeSent) - Send(new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.ConnectionClose, null)); + Send(new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.ConnectionClose, BufferSegment.Empty)); closed = true; break; } @@ -501,9 +513,6 @@ private void ReceiveThreadFunc() } finally { - HTTPManager.Heartbeats.Unsubscribe(this); - HTTPUpdateDelegator.OnApplicationForegroundStateChanged -= OnApplicationForegroundStateChanged; - HTTPManager.Logger.Information("WebSocketResponse", "ReceiveThread - Closed!", this.Context); TryToCleanup(); @@ -528,7 +537,9 @@ void IProtocol.HandleEvents() switch (frame.Type) { case WebSocketFrameTypes.Continuation: - HTTPManager.Logger.Verbose("WebSocketResponse", "HandleEvents - OnIncompleteFrame", this.Context); + if (HTTPManager.Logger.Level == Loglevels.All) + HTTPManager.Logger.Verbose("WebSocketResponse", "HandleEvents - OnIncompleteFrame: " + frame.ToString(), this.Context); + if (OnIncompleteFrame != null) OnIncompleteFrame(this, frame); break; @@ -538,7 +549,9 @@ void IProtocol.HandleEvents() if (!frame.IsFinal) goto case WebSocketFrameTypes.Continuation; - HTTPManager.Logger.Verbose("WebSocketResponse", "HandleEvents - OnText", this.Context); + if (HTTPManager.Logger.Level == Loglevels.All) + HTTPManager.Logger.Verbose("WebSocketResponse", "HandleEvents - OnText: " + frame.DataAsText, this.Context); + if (OnText != null) OnText(this, frame.DataAsText); break; @@ -548,15 +561,28 @@ void IProtocol.HandleEvents() if (!frame.IsFinal) goto case WebSocketFrameTypes.Continuation; - HTTPManager.Logger.Verbose("WebSocketResponse", "HandleEvents - OnBinary", this.Context); + if (HTTPManager.Logger.Level == Loglevels.All) + HTTPManager.Logger.Verbose("WebSocketResponse", "HandleEvents - OnBinary: " + frame.ToString(), this.Context); + if (OnBinary != null) - OnBinary(this, frame.Data); + { + var data = new byte[frame.Data.Count]; + Array.Copy(frame.Data.Data, frame.Data.Offset, data, 0, frame.Data.Count); + OnBinary(this, data); + } + + if (OnBinaryNoAlloc != null) + OnBinaryNoAlloc(this, frame.Data); break; } } catch (Exception ex) { - HTTPManager.Logger.Exception("WebSocketResponse", "HandleEvents", ex, this.Context); + HTTPManager.Logger.Exception("WebSocketResponse", string.Format("HandleEvents({0})", frame.ToString()), ex, this.Context); + } + finally + { + frame.ReleaseData(); } } @@ -572,14 +598,14 @@ void IProtocol.HandleEvents() string msg = string.Empty; // If we received any data, we will get the status code and the message from it - if (/*CloseFrame != null && */CloseFrame.Data != null && CloseFrame.Data.Length >= 2) + if (/*CloseFrame != null && */CloseFrame.Data != BufferSegment.Empty && CloseFrame.Data.Count >= 2) { if (BitConverter.IsLittleEndian) - Array.Reverse(CloseFrame.Data, 0, 2); - statusCode = BitConverter.ToUInt16(CloseFrame.Data, 0); + Array.Reverse(CloseFrame.Data.Data, CloseFrame.Data.Offset, 2); + statusCode = BitConverter.ToUInt16(CloseFrame.Data.Data, CloseFrame.Data.Offset); - if (CloseFrame.Data.Length > 2) - msg = Encoding.UTF8.GetString(CloseFrame.Data, 2, CloseFrame.Data.Length - 2); + if (CloseFrame.Data.Count > 2) + msg = Encoding.UTF8.GetString(CloseFrame.Data.Data, CloseFrame.Data.Offset + 2, CloseFrame.Data.Count - 2); CloseFrame.ReleaseData(); } @@ -596,34 +622,7 @@ void IProtocol.HandleEvents() #endregion - #region IHeartbeat Implementation - - void IHeartbeat.OnHeartbeatUpdate(TimeSpan dif) - { - DateTime now = DateTime.UtcNow; - - if (!waitingForPong && now - lastMessage >= PingFrequnecy) - SendPing(); - - if (waitingForPong && now - lastPing > this.WebSocket.CloseAfterNoMessage) - { - HTTPManager.Logger.Warning("WebSocketResponse", - string.Format("No message received in the given time! Closing WebSocket. LastPing: {0}, PingFrequency: {1}, Close After: {2}, Now: {3}", - this.lastPing, this.PingFrequnecy, this.WebSocket.CloseAfterNoMessage, now), this.Context); - - CloseWithError(HTTPRequestStates.Error, "No message received in the given time!"); - } - } - - #endregion - - private void OnApplicationForegroundStateChanged(bool isPaused) - { - if (!isPaused) - lastMessage = DateTime.UtcNow; - } - - private void SendPing() + private bool SendPing() { HTTPManager.Logger.Information("WebSocketResponse", "Sending Ping frame, waiting for a pong...", this.Context); @@ -632,10 +631,7 @@ private void SendPing() try { - long ticks = DateTime.UtcNow.Ticks; - var ticksBytes = BitConverter.GetBytes(ticks); - - var pingFrame = new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.Ping, ticksBytes); + var pingFrame = new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.Ping, BufferSegment.Empty); Send(pingFrame); } @@ -643,7 +639,11 @@ private void SendPing() { HTTPManager.Logger.Information("WebSocketResponse", "Error while sending PING message! Closing WebSocket.", this.Context); CloseWithError(HTTPRequestStates.Error, "Error while sending PING message!"); + + return false; } + + return true; } private void CloseWithError(HTTPRequestStates state, string message) @@ -654,9 +654,6 @@ private void CloseWithError(HTTPRequestStates state, string message) this.closed = true; - HTTPManager.Heartbeats.Unsubscribe(this); - HTTPUpdateDelegator.OnApplicationForegroundStateChanged -= OnApplicationForegroundStateChanged; - CloseStream(); ProtocolEventHelper.EnqueueProtocolEvent(new ProtocolEventInfo(this)); } @@ -687,6 +684,8 @@ private void TryToCleanup() newFrameSignal = null; CloseStream(); + + HTTPManager.Logger.Information("WebSocketResponse", "TryToCleanup - finished!", this.Context); } } @@ -694,6 +693,15 @@ public override string ToString() { return this.ConnectionKey.ToString(); } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + + IncompleteFrames.Clear(); + CompletedFrames.Clear(); + unsentFrames.Clear(); + } } } diff --git a/Assets/URS/Setting/Editor/Settings/ScriptableObjectSettingsProvider.cs b/Assets/URS/Setting/Editor/Settings/ScriptableObjectSettingsProvider.cs deleted file mode 100644 index e4877cf..0000000 --- a/Assets/URS/Setting/Editor/Settings/ScriptableObjectSettingsProvider.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2021 by Hextant Studios. https://HextantStudios.com -// This work is licensed under CC BY 4.0. http://creativecommons.org/licenses/by/4.0/ -using UnityEditor; -using UnityEngine; - -namespace Hextant.Editor -{ - using Editor = UnityEditor.Editor; - - // SettingsProvider helper used to display settings for a ScriptableObject - // derived class. - public class ScriptableObjectSettingsProvider : SettingsProvider - { - public ScriptableObjectSettingsProvider( ScriptableObject settings, - SettingsScope scope, string displayPath ) : - base( displayPath, scope ) => this.settings = settings; - - // The settings instance being edited. - public readonly ScriptableObject settings; - - // The SerializedObject settings instance. - public SerializedObject serializedSettings => - _serializedSettings != null ? _serializedSettings : - _serializedSettings = new SerializedObject( settings ); - SerializedObject _serializedSettings; - - // Called when the settings are displayed in the UI. - public override void OnActivate( string searchContext, - UnityEngine.UIElements.VisualElement rootElement ) - { - _editor = Editor.CreateEditor( settings ); - base.OnActivate( searchContext, rootElement ); - } - - // Called when the settings are no longer displayed in the UI. - public override void OnDeactivate() - { - Editor.DestroyImmediate( _editor ); - _editor = null; - base.OnDeactivate(); - } - - // Displays the settings. - public override void OnGUI( string searchContext ) - { - if( settings == null || _editor == null ) return; - - // Set label width and indentation to match other settings. - EditorGUIUtility.labelWidth = 250; - GUILayout.BeginHorizontal(); - GUILayout.Space( 10 ); - GUILayout.BeginVertical(); - GUILayout.Space( 10 ); - - // Draw the editor's GUI. - _editor.OnInspectorGUI(); - - // Reset label width and indent. - GUILayout.EndVertical(); - GUILayout.EndHorizontal(); - EditorGUIUtility.labelWidth = 0; - } - - // Build the set of keywords on demand from the settings fields. - public override bool HasSearchInterest( string searchContext ) - { - if( !_keywordsBuilt ) - { - keywords = GetSearchKeywordsFromSerializedObject( - serializedSettings ); - _keywordsBuilt = true; - } - return base.HasSearchInterest( searchContext ); - } - - // True if the keywords set has been built. - bool _keywordsBuilt; - - // Cached editor used to render inspector GUI. - Editor _editor; - } -} diff --git a/Assets/URS/Setting/Editor/Settings/SettingsEditor.cs b/Assets/URS/Setting/Editor/Settings/SettingsEditor.cs deleted file mode 100644 index d1a48ed..0000000 --- a/Assets/URS/Setting/Editor/Settings/SettingsEditor.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2021 by Hextant Studios. https://HextantStudios.com -// This work is licensed under CC BY 4.0. http://creativecommons.org/licenses/by/4.0/ -using UnityEditor; - -namespace Hextant.Editor -{ - // A custom inspector for Settings that does not draw the "Script" field. - [CustomEditor( typeof( Settings<> ), true )] - public class SettingsEditor : UnityEditor.Editor - { - public override void OnInspectorGUI() => DrawDefaultInspector(); - - // Draws the UI for exposed properties *without* the "Script" field. - protected new bool DrawDefaultInspector() - { - if( serializedObject.targetObject == null ) return false; - - EditorGUI.BeginChangeCheck(); - serializedObject.UpdateIfRequiredOrScript(); - - DrawPropertiesExcluding( serializedObject, _excludedFields ); - - serializedObject.ApplyModifiedProperties(); - return EditorGUI.EndChangeCheck(); - } - - static readonly string[] _excludedFields = { "m_Script" }; - } -} diff --git a/Assets/URS/Setting/Editor/Settings/SettingsExtensions.cs b/Assets/URS/Setting/Editor/Settings/SettingsExtensions.cs deleted file mode 100644 index 3b96edf..0000000 --- a/Assets/URS/Setting/Editor/Settings/SettingsExtensions.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2021 by Hextant Studios. https://HextantStudios.com -// This work is licensed under CC BY 4.0. http://creativecommons.org/licenses/by/4.0/ -using UnityEngine; -using UnityEditor; - -namespace Hextant.Editor -{ - public static class SettingsExtensions - { - // The SettingsProvider instance used to display settings in Edit/Preferences - // and Edit/Project Settings. - public static SettingsProvider GetSettingsProvider( - this Settings settings ) where T : Settings - { - Debug.Assert( Settings.attribute.displayPath != null ); - return new ScriptableObjectSettingsProvider( settings, - Settings.attribute.usage == SettingsUsage.EditorUser ? - SettingsScope.User : SettingsScope.Project, - Settings.attribute.displayPath ); - } - } -} diff --git a/Assets/URS/Setting/Resources.meta b/Assets/URS/Setting/Resources.meta new file mode 100644 index 0000000..7a55561 --- /dev/null +++ b/Assets/URS/Setting/Resources.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 882cd3b1bcac26c46840b35cf61e3f34 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Setting/Resources/urs_runtime_setting.txt b/Assets/URS/Setting/Resources/urs_runtime_setting.txt new file mode 100644 index 0000000..2b89a15 --- /dev/null +++ b/Assets/URS/Setting/Resources/urs_runtime_setting.txt @@ -0,0 +1,17 @@ +{ + "FilesVersionIndexFileName": "files_version_index.txt", + "PatchDirectory": "patch", + "PatchTempDirectory": "patch_temp", + "AssetBundleFileVariant": ".bundle", + "RawFileVariant": "rawfile", + "FileManifestFileName": "file_manifest.txt", + "BundleManifestFileRelativePath": "bundles/bundle_manifest.txt", + "BundleManifestFileName": "bundle_manifest.txt", + "ChannelFileName": "channel.txt", + "ForceDownloadDirectory": "", + "PlayMode": 0, + "RemoteChannelRootUrl": "https://staticninja.happyelements.cn", + "RemoteAppVersionRouterFileName": "app_version_router.txt", + "DefaultTag": "default", + "BuildinTag": "buildin" +} \ No newline at end of file diff --git a/Assets/URS/Setting/Resources/urs_runtime_setting.txt.meta b/Assets/URS/Setting/Resources/urs_runtime_setting.txt.meta new file mode 100644 index 0000000..9cf63d0 --- /dev/null +++ b/Assets/URS/Setting/Resources/urs_runtime_setting.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: f5443add870c21d47a5ab2933371e928 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Setting/Runtime.meta b/Assets/URS/Setting/Runtime.meta deleted file mode 100644 index fa54d3e..0000000 --- a/Assets/URS/Setting/Runtime.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: aa2dc517c217fa84e886068609fb15ca -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/URS/Setting/Runtime/Settings.meta b/Assets/URS/Setting/Runtime/Settings.meta deleted file mode 100644 index 5438221..0000000 --- a/Assets/URS/Setting/Runtime/Settings.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 27a0965380972a34e9b6bfdad8763a17 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/URS/Setting/Runtime/Settings/Settings.cs b/Assets/URS/Setting/Runtime/Settings/Settings.cs deleted file mode 100644 index 857f58f..0000000 --- a/Assets/URS/Setting/Runtime/Settings/Settings.cs +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright 2021 by Hextant Studios. https://HextantStudios.com -// This work is licensed under CC BY 4.0. http://creativecommons.org/licenses/by/4.0/ -using System; -using System.IO; -using System.Collections.Generic; -using System.Reflection; -using UnityEditor; -using UnityEngine; - -namespace Hextant -{ - // Base class for project/users settings. Use the [Settings] attribute to - // specify its usage, display path, and filename. - // * Settings are stored in Assets/Settings/ folder. - // * Important! The user settings folder Assets/Settings/Editor/User/ must be - // excluded from source control. - // * User settings will be placed in a subdirectory named the same as - // the current project folder so that shallow cloning (symbolic links to - // the Assets/ folder) can be used when testing multiplayer games. - // See: https://HextantStudios.com/unity-custom-settings/ - public abstract class Settings : ScriptableObject where T : Settings - { - // The singleton instance. (Not thread safe but fine for ScriptableObjects.) - public static T instance => _instance != null ? _instance : Initialize(); - static T _instance; - - // Loads or creates the settings instance and stores it in _instance. - protected static T Initialize() - { - // If the instance is already valid, return it. Needed if called from a - // derived class that wishes to ensure the settings are initialized. - if( _instance != null ) return _instance; - - // Verify there was a [Settings] attribute. - if( attribute == null ) - { - Debug.LogError( "[Settings] attribute missing for type: " + - typeof( T ).Name ); - return null; - } - - // Attempt to load the settings asset. - var filename = attribute.filename ?? typeof( T ).Name; - var path = GetSettingsPath() + filename + ".asset"; - - if( attribute.usage == SettingsUsage.RuntimeProject ) - _instance = Resources.Load( filename ); -#if UNITY_EDITOR - else - _instance = AssetDatabase.LoadAssetAtPath( path ); - - // Return the instance if it was the load was successful. - if( _instance != null ) return _instance; - - // Move settings if its path changed (type renamed or attribute changed) - // while the editor was running. This must be done manually if the - // change was made outside the editor. - var instances = Resources.FindObjectsOfTypeAll(); - if( instances.Length > 0 ) - { - var oldPath = AssetDatabase.GetAssetPath( instances[ 0 ] ); - var result = AssetDatabase.MoveAsset( oldPath, path ); - if( string.IsNullOrEmpty( result ) ) - return _instance = instances[ 0 ]; - else - Debug.LogWarning( $"Failed to move previous settings asset " + - $"'{oldPath}' to '{path}'. " + - $"A new settings asset will be created.", _instance ); - } -#endif - // Create the settings instance if it was not loaded or found. - if( _instance != null ) return _instance; - _instance = CreateInstance(); - -#if UNITY_EDITOR - // Create a new settings instance if it was not found. - // Create the directory as Unity does not do this itself. - Directory.CreateDirectory( Path.Combine( - Directory.GetCurrentDirectory(), - Path.GetDirectoryName( path ) ) ); - - // Create the asset only in the editor. - AssetDatabase.CreateAsset( _instance, path ); -#endif - return _instance; - } - - // Returns the full asset path to the settings file. - static string GetSettingsPath() - { - var path = "Assets/Settings/"; - - switch( attribute.usage ) - { - case SettingsUsage.RuntimeProject: - path += "Resources/"; break; -#if UNITY_EDITOR - case SettingsUsage.EditorProject: - path += "Editor/"; break; - case SettingsUsage.EditorUser: - path += "Editor/User/"; break; -#endif - default: throw new System.InvalidOperationException(); - } - return path; - } - - // The derived type's [Settings] attribute. - public static SettingsAttribute attribute => - _attribute != null ? _attribute : _attribute = - typeof( T ).GetCustomAttribute( true ); - static SettingsAttribute _attribute; - - // Called to validate settings changes. - protected virtual void OnValidate() { } - -#if UNITY_EDITOR - // Sets the specified setting to the desired value and marks the settings - // so that it will be saved. - protected void Set( ref S setting, S value ) - { - if( EqualityComparer.Default.Equals( setting, value ) ) return; - setting = value; - OnValidate(); - SetDirty(); - } - - // Marks the settings dirty so that it will be saved. - protected new void SetDirty() => EditorUtility.SetDirty( this ); - - // The directory name of the current project folder. - static string GetProjectFolderName() - { - var path = Application.dataPath.Split( '/' ); - return path[ path.Length - 2 ]; - } -#endif - - // Base class for settings contained by a Settings instance. - [Serializable] - public abstract class SubSettings - { - // Called when a setting is modified. - protected virtual void OnValidate() { } - -#if UNITY_EDITOR - // Sets the specified setting to the desired value and marks the settings - // instance so that it will be saved. - protected void Set( ref S setting, S value ) - { - if( EqualityComparer.Default.Equals( setting, value ) ) return; - setting = value; - OnValidate(); - instance.SetDirty(); - } -#endif - } - } -} \ No newline at end of file diff --git a/Assets/URS/Setting/Runtime/Settings/SettingsAttribute.cs b/Assets/URS/Setting/Runtime/Settings/SettingsAttribute.cs deleted file mode 100644 index c65dff7..0000000 --- a/Assets/URS/Setting/Runtime/Settings/SettingsAttribute.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2021 by Hextant Studios. https://HextantStudios.com -// This work is licensed under CC BY 4.0. http://creativecommons.org/licenses/by/4.0/ -using System; - -namespace Hextant -{ - // Specifies the settings type, path in the settings UI, and optionally its - // filename. If the filename is not set, the type's name is used. - public sealed class SettingsAttribute : Attribute - { - public SettingsAttribute( SettingsUsage usage, string displayPath = null, - string filename = null ) - { - this.usage = usage; - this.filename = filename; - this.displayPath = displayPath != null ? - ( ( usage == SettingsUsage.EditorUser ? - "Preferences/" : "Project/" ) + displayPath ) : null; - } - - // The type of settings (how and when they are used). - public readonly SettingsUsage usage; - - // The display name and optional path in the settings dialog. - public readonly string displayPath; - - // The filename used to store the settings. If null, the type's name is used. - public readonly string filename; - } -} diff --git a/Assets/URS/Setting/Runtime/Settings/SettingsAttribute.cs.meta b/Assets/URS/Setting/Runtime/Settings/SettingsAttribute.cs.meta deleted file mode 100644 index 8e30d2e..0000000 --- a/Assets/URS/Setting/Runtime/Settings/SettingsAttribute.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 2ab8c8bb8cac93d4b985608a3e273eb5 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/URS/Setting/Runtime/Settings/SettingsUsage.cs b/Assets/URS/Setting/Runtime/Settings/SettingsUsage.cs deleted file mode 100644 index 5eb1275..0000000 --- a/Assets/URS/Setting/Runtime/Settings/SettingsUsage.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2021 by Hextant Studios. https://HextantStudios.com -// This work is licensed under CC BY 4.0. http://creativecommons.org/licenses/by/4.0/ -namespace Hextant -{ - // Specifies how the settings are used and when they are available. - public enum SettingsUsage - { - // Project-wide settings available at runtime. - // Ex: Project Settings/Time - RuntimeProject, - - // Project-wide settings available only in the editor. - // Ex: Project Settings/Version Control - EditorProject, - - // User-specific settings available only in the editor. - // Ex: Preferences/Scene View - EditorUser - } -} diff --git a/Assets/URS/Setting/Runtime/Settings/SettingsUsage.cs.meta b/Assets/URS/Setting/Runtime/Settings/SettingsUsage.cs.meta deleted file mode 100644 index fd0f303..0000000 --- a/Assets/URS/Setting/Runtime/Settings/SettingsUsage.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 43e8b492742be3744b0f33f46dd024c1 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/URS/Setting/URSRuntimeSetting.cs b/Assets/URS/Setting/URSRuntimeSetting.cs new file mode 100644 index 0000000..1a57ade --- /dev/null +++ b/Assets/URS/Setting/URSRuntimeSetting.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Rendering; +using YooAsset; + +[Serializable] +public class URSRuntimeSetting +{ + public const string SAVE_RESOUCE_PATH = "urs_runtime_setting.txt"; + + public const string SAVE_RESOUCE_PATH_NO_EXTENSION = "urs_runtime_setting"; + + [SerializeField] + public string FilesVersionIndexFileName = "files_version_index.txt"; + + [SerializeField] + public string PatchDirectory = "patch"; + + [SerializeField] + public string PatchTempDirectory = "patch_temp"; + /// + /// AssetBundle文件的后缀名 + /// + [SerializeField] + public string AssetBundleFileVariant = ".bundle"; + + /// + /// 原生文件的后缀名 + /// + [SerializeField] + public string RawFileVariant = "rawfile"; + + /// + /// 构建输出的文件清单文件名称 + /// + [SerializeField] + public string FileManifestFileName = "file_manifest.txt"; + + /// + /// 构建输出的文件清单文件名称 + /// + [SerializeField] + public string BundleManifestFileRelativePath = "bundles/bundle_manifest.txt"; + + /// + /// 构建输出的文件清单文件名称 + /// + [SerializeField] + public string BundleManifestFileName = "bundle_manifest.txt"; + + /// + /// 表示app的id文件名称,放在stream asset的 urs_buildin_resource 里面 + /// + [SerializeField] + public string ChannelFileName = "channel.txt"; + + /// + /// 默认的沙盒目录是 persistent 目录,你可以强制指定这个目录,到本地某个版本的时候 + /// + [SerializeField] + public string ForceDownloadDirectory = string.Empty; + + [SerializeField] + public YooAssets.EPlayMode PlayMode = YooAssets.EPlayMode.EditorPlayMode; + + [SerializeField] + public string RemoteChannelRootUrl = @"https://staticninja.happyelements.cn"; + + [SerializeField] + public string RemoteAppVersionRouterFileName = "app_version_router.txt"; + //public string FallbackHostServer = ""; + + [SerializeField] + public string DefaultTag = "default"; + + [SerializeField] + public string BuildinTag = "buildin"; + + public static URSRuntimeSetting instance + { + get + { + if (_instance == null) + { + var textAsset = Resources.Load(SAVE_RESOUCE_PATH_NO_EXTENSION); + if (textAsset != null) + { + _instance = UnityEngine.JsonUtility.FromJson(textAsset.text); + } + else + { + _instance = new URSRuntimeSetting(); + } + } + return _instance; + } + } + private static URSRuntimeSetting _instance = null; +} + + diff --git a/Assets/URS/Setting/URSSetting/Runtime/URSRuntimeSetting.cs.meta b/Assets/URS/Setting/URSRuntimeSetting.cs.meta similarity index 100% rename from Assets/URS/Setting/URSSetting/Runtime/URSRuntimeSetting.cs.meta rename to Assets/URS/Setting/URSRuntimeSetting.cs.meta diff --git a/Assets/URS/Setting/URSSetting.meta b/Assets/URS/Setting/URSSetting.meta deleted file mode 100644 index 0f041b8..0000000 --- a/Assets/URS/Setting/URSSetting.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: 6cadc5721b0f7d84d9f0f570850fd023 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/URS/Setting/URSSetting/Editor/EditorSetting.cs b/Assets/URS/Setting/URSSetting/Editor/EditorSetting.cs deleted file mode 100644 index ac0d147..0000000 --- a/Assets/URS/Setting/URSSetting/Editor/EditorSetting.cs +++ /dev/null @@ -1,49 +0,0 @@ -using Hextant; -using Hextant.Editor; -using UnityEditor; -using UnityEngine; - -/* -[Settings(SettingsUsage.EditorProject, "URSEditorProjectSettings")] -public sealed class URSEditorProjectSettings : Settings -{ - public int integerValue => _integerValue; - [SerializeField, Range(0, 10)] int _integerValue = 5; - - public float floatValue => _floatValue; - [SerializeField, Range(0, 100)] float _floatValue = 25.0f; - - public string stringValue => _stringValue; - [SerializeField, Tooltip("A string value.")] string _stringValue = "Hello"; - - [SettingsProvider] - static SettingsProvider GetSettingsProvider() => - instance.GetSettingsProvider(); -} -*/ -[Settings(SettingsUsage.EditorUser, "URSEditorUserSettings")] -public sealed class URSEditorUserSettings : Settings -{ - // 本次构建的资源版本号(资源的版本号,不是包的版本号) - [SerializeField, Tooltip("CurrentBuildVersionCode")] - public string BuildVersionCode = "1.0.0"; - - // 本次进包的资源版本号(这个资源版本号必须有效,例如本次资源版本号或者之前打过的资源版本号) - [SerializeField, Tooltip("CopyToStreamTargetVersion")] - public string CopyToStreamTargetVersion = "1.0.0"; - - - [SerializeField, Tooltip("CurrentBuildChanel")] - public string BuildChannel = "default_channel"; - - - [SerializeField, Tooltip("CurrentBuildAppId")] - public string AppId = "AppId"; - - - [SerializeField, Tooltip("AppToChannelRouter")] - public AppToChannelRouter AppToChannelRouter = new AppToChannelRouter(); - [SettingsProvider] - static SettingsProvider GetSettingsProvider() => - instance.GetSettingsProvider(); -} \ No newline at end of file diff --git a/Assets/URS/Setting/URSSetting/Editor/EditorSetting.cs.meta b/Assets/URS/Setting/URSSetting/Editor/EditorSetting.cs.meta deleted file mode 100644 index b068a41..0000000 --- a/Assets/URS/Setting/URSSetting/Editor/EditorSetting.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 52a87961cb20165429cd6d7494969ad1 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/URS/Setting/URSSetting/Runtime.meta b/Assets/URS/Setting/URSSetting/Runtime.meta deleted file mode 100644 index e02d8c3..0000000 --- a/Assets/URS/Setting/URSSetting/Runtime.meta +++ /dev/null @@ -1,8 +0,0 @@ -fileFormatVersion: 2 -guid: fdba2152e47e28c428448a795c4e85f2 -folderAsset: yes -DefaultImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/URS/Setting/URSSetting/Runtime/URSRuntimeSetting.cs b/Assets/URS/Setting/URSSetting/Runtime/URSRuntimeSetting.cs deleted file mode 100644 index 8d9990e..0000000 --- a/Assets/URS/Setting/URSSetting/Runtime/URSRuntimeSetting.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System.Collections; -using System.Collections.Generic; -using UnityEngine; -using Hextant; -using YooAsset; -#if UNITY_EDITOR - using UnityEditor; -#endif -[Settings(SettingsUsage.RuntimeProject)] -public class URSRuntimeSetting : Hextant.Settings -{ - public string FilesVersionIndexFileName = "files_version_index.txt"; - public string PatchDirectory = "patch"; - public string PatchTempDirectory = "patch_temp"; - /// - /// AssetBundleļĺ׺ - /// - public string AssetBundleFileVariant = ".bundle"; - - /// - /// ԭļĺ׺ - /// - public string RawFileVariant = "rawfile"; - - /// - /// ļ嵥ļ - /// - public string FileManifestFileName = "file_manifest.txt"; - - /// - /// ļ嵥ļ - /// - public string BundleManifestFileName = "bundle_manifest.txt"; - - /// - /// ʾappidļƣstream asset sandbox - /// - public string AppIdFileName = "app_id.txt"; - - /// - /// ĬϵɳĿ¼ persistent Ŀ¼ǿָĿ¼ij汾ʱ - /// - public string ForceSandboxDirectory = string.Empty; - - public YooAssets.EPlayMode PlayMode = YooAssets.EPlayMode.EditorPlayMode; - - public string RemoteChannelRootUrl = "http://127.0.0.1:8000"; - - public string RemoteAppToChannelRouterFileName = "channel_router.txt"; - //public string FallbackHostServer = ""; - - public string DefaultTag = "default"; - - public string BuildinTag = "buildin"; -} -#if UNITY_EDITOR -[InitializeOnLoad] - static class ProjectOpenURSRuntimeSetting -{ - static ProjectOpenURSRuntimeSetting() - { - var instance= URSRuntimeSetting.instance; - } -} -#endif \ No newline at end of file diff --git a/Assets/URS/SmartLibrary/Editor/Data/Collections/LibraryCollection.cs b/Assets/URS/SmartLibrary/Editor/Data/Collections/LibraryCollection.cs index 145f40d..1c3fdb6 100644 --- a/Assets/URS/SmartLibrary/Editor/Data/Collections/LibraryCollection.cs +++ b/Assets/URS/SmartLibrary/Editor/Data/Collections/LibraryCollection.cs @@ -27,7 +27,7 @@ public abstract class LibraryCollection : ScriptableObject, IEnumerable @@ -117,8 +118,15 @@ public UniqueID ID get { if (_id == UniqueID.Empty) - _id = UniqueID.NewUniqueId(); - + { + if (this.GetType() == typeof(RootLibraryCollection)) + { + _id = UniqueID.ROOT_UNIQUE_ID; + } + else { + _id = UniqueID.NewUniqueId(); + } + } return _id; } } @@ -157,7 +165,7 @@ public RuleSet Rules /// public int Count { - get { return _items.Count; } + get { return GetGUIDHashSet().Count; } } public float ItemDisplaySize @@ -218,8 +226,15 @@ public static LibraryCollection CreateCollection(Type collectionType) return null; var collection = (LibraryCollection)CreateInstance(collectionType); - - collection._id = UniqueID.NewUniqueId(); + if (collectionType == typeof(RootLibraryCollection)) + { + collection._id = UniqueID.ROOT_UNIQUE_ID; + } + else + { + collection._id = UniqueID.NewUniqueId(); + } + collection.CollectionName = ObjectNames.NicifyVariableName(collectionType.Name); collection.hideFlags = HideFlags.DontSave; @@ -264,7 +279,7 @@ public virtual bool IsAddable(LibraryItem item) /// true if the contains ; otherwise, false. public bool Contains(LibraryItem item) { - return _items.Contains(item.GUID); + return GetGUIDHashSet().Contains(item.GUID); } public abstract void UpdateItems(bool syn= false); @@ -278,7 +293,7 @@ public bool Contains(LibraryItem item) /// true if is added to the ; otherwise, false if is aldreay present. protected bool AddItem(LibraryItem item, bool notifyChange = true) { - bool added = _items.Add(item.GUID); + bool added = GetGUIDHashSet().Add(item.GUID); if (added) { LibraryDatabase.RootCollection.RegisterWithCollection(item, ID); @@ -297,7 +312,7 @@ protected bool AddItem(LibraryItem item, bool notifyChange = true) /// true if is successfully found and removed; otherwise, false. Also returns false if is not found. protected internal bool RemoveItem(LibraryItem item, bool notifyChange = true) { - bool removed = _items.Remove(item.GUID); + bool removed = GetGUIDHashSet().Remove(item.GUID); if (removed) { LibraryDatabase.RootCollection.UnregisterWithCollection(item, ID); @@ -318,11 +333,11 @@ protected void ClearItems(bool notifyChange = true) if (notifyChange) itemsCopy = new List(this); - foreach (var item in _items) + foreach (var item in GetGUIDHashSet()) { LibraryDatabase.RootCollection.UnregisterWithCollection(LibraryItem.GetItemInstance(item), ID); } - _items.Clear(); + GetGUIDHashSet().Clear(); if (notifyChange) NotifyItemsChanged(itemsCopy, LibraryItemsChangeType.Removed); @@ -332,12 +347,12 @@ protected void ClearItems(bool notifyChange = true) /// Adds the specified as a subcollection to the . Removes it from it's previus parent if it has one. /// /// The to add as a subcollection. - public void AddSubcollection(LibraryCollection collection) + public void AddSubcollection(LibraryCollection collection,bool silence=false) { - InsertSubcollection(_subcollections.Count, collection); + InsertSubcollection(_subcollections.Count, collection, silence); } - public void InsertSubcollection(int index, LibraryCollection collection) + public void InsertSubcollection(int index, LibraryCollection collection, bool silence = false) { if (collection == null || !collection.IsValidReparenting(this)) return; @@ -370,11 +385,15 @@ public void InsertSubcollection(int index, LibraryCollection collection) //TODO: Replace //LibraryData.DequeCollectionDestruction(collection); + FinishChange(undoGroup); - if (collection.Count > 0) - LibraryDatabase.HandleLibraryItemsChanged(new LibraryItemsChangedEventArgs(collection, collection, LibraryItemsChangeType.Added)); - + if (!silence) + { + if (collection.Count > 0) + LibraryDatabase.HandleLibraryItemsChanged(new LibraryItemsChangedEventArgs(collection, collection, LibraryItemsChangeType.Added)); + } + NotifySubcollectionsChanged(collection, index, HierarchyChangeType.Added); } @@ -562,7 +581,7 @@ public void FinishChange(int undoGroup = -1) public IEnumerator GetEnumerator() { - var enumerator = _items.GetEnumerator(); + var enumerator = GetGUIDHashSet().GetEnumerator(); while (enumerator.MoveNext()) { yield return LibraryItem.GetItemInstance(enumerator.Current); diff --git a/Assets/URS/SmartLibrary/Editor/Data/Collections/RootLibraryCollection.cs b/Assets/URS/SmartLibrary/Editor/Data/Collections/RootLibraryCollection.cs index 717915c..c937712 100644 --- a/Assets/URS/SmartLibrary/Editor/Data/Collections/RootLibraryCollection.cs +++ b/Assets/URS/SmartLibrary/Editor/Data/Collections/RootLibraryCollection.cs @@ -19,7 +19,11 @@ private struct CollectionsContainingItemPair //[SerializeField] private List _allCollections = new List(); [SerializeField] private List _allCollections = new List(); [SerializeField] private List _itemCollectionIdPairs = new List(); - + [SerializeField] public AssetGUIDHashSet _items = new AssetGUIDHashSet(); + public override AssetGUIDHashSet GetGUIDHashSet() + { + return _items; + } public Dictionary> CollectionsContainingItems { get; @@ -28,6 +32,7 @@ public Dictionary> CollectionsContainingItems public Dictionary AssetGuidToItem { get; } = new Dictionary(); + /* private Dictionary _legacyIdMap = new Dictionary(); public Dictionary LegacyIDToCollectionMap { @@ -47,7 +52,7 @@ public Dictionary LegacyIDToCollectionMap return _legacyIdMap; } } - + */ public RootLibraryCollection() { Root = this; @@ -172,6 +177,20 @@ public void RemoveInvailidItem() } } } + public void ValidateSubCollection() + { + var collections = SessionData.instance.IDToCollectionMap; + this.SubcollectionsInternal.Clear(); + this.SubcollectionIDs.Clear(); + foreach (var collection in collections) + { + if (collection.Value is RootLibraryCollection) { + continue; + } + this.SubcollectionsInternal.Add(collection.Value); + this.SubcollectionIDs.Add(collection.Key); + } + } void ISerializationCallbackReceiver.OnBeforeSerialize() { // // Clear serialized data. @@ -189,6 +208,8 @@ void ISerializationCallbackReceiver.OnBeforeSerialize() { _itemCollectionIdPairs.Add(new CollectionsContainingItemPair() { item = pair.Key, collectionIds = pair.Value}); } + + _itemCollectionIdPairs.Sort((x, y) => string.CompareOrdinal(x.item.GUID, y.item.GUID)); } void ISerializationCallbackReceiver.OnAfterDeserialize() diff --git a/Assets/URS/SmartLibrary/Editor/Data/Collections/SmartCollection.cs b/Assets/URS/SmartLibrary/Editor/Data/Collections/SmartCollection.cs index 46e77a8..79f4b44 100644 --- a/Assets/URS/SmartLibrary/Editor/Data/Collections/SmartCollection.cs +++ b/Assets/URS/SmartLibrary/Editor/Data/Collections/SmartCollection.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using UnityEngine; using UnityEditor.Search; +using System; namespace Bewildered.SmartLibrary { @@ -13,7 +14,13 @@ public class SmartCollection : LibraryCollection private bool _isSearching; [SerializeField] private List _folders = new List(); - + + [NonSerialized] + public AssetGUIDHashSet _items = new AssetGUIDHashSet(); + public override AssetGUIDHashSet GetGUIDHashSet() + { + return _items; + } /// /// Folders to search in for valid assets to add to the , or to exclude. /// @@ -100,17 +107,21 @@ private void OnSearchComplete(HashSet paths) foreach (var path in paths) { - //Object obj = item.ToObject(); + if (path.Contains(".DS_Store")) + continue; + //Object obj = item.ToObject(); // QuickSearch does not remove entries of deleted assets right away. // So we need to handle when the SearchItem may not have an asset associated with it any more. //if (obj == null) - // continue; - - LibraryItem libraryItem = LibraryItem.GetItemInstanceByPath(path); + // continue; + var path2= path.Replace('\\', '/'); + + LibraryItem libraryItem = LibraryItem.GetItemInstanceByPath(path2); // Item is added to this second list to be used when sending the items changed notification. addedItems.Add(libraryItem); + //Debug.LogError("path " + path2 + " cc name " + this.CollectionName+" null"+ (libraryItem==null)); // Now that the item has been fully validated it can be added to the collection. AddItem(libraryItem, false); } @@ -125,7 +136,7 @@ private void OnSearchComplete(SearchContext context, IList items) foreach (SearchItem item in items) { - Object obj = item.ToObject(); + UnityEngine.Object obj = item.ToObject(); // QuickSearch does not remove entries of deleted assets right away. // So we need to handle when the SearchItem may not have an asset associated with it any more. @@ -145,6 +156,18 @@ private void OnSearchComplete(SearchContext context, IList items) public HashSet GetAssetPaths() { HashSet paths = new HashSet(); + string excludeNameContains = ""; + foreach (var rule in Rules) + { + if (rule is TagRule tagRule) { + if (tagRule.TagType == TagRule.TagRuleType.ExcludeFileNameContains) + { + excludeNameContains = tagRule.Text; + break; + } + } + } + bool checkExcludeName = !string.IsNullOrEmpty(excludeNameContains); for (int i = 0; i < _folders.Count; i++) { var folderConfig = _folders[i]; @@ -170,6 +193,12 @@ public HashSet GetAssetPaths() foreach (var file in files) { var path = file.path; + if (checkExcludeName) { + var fileName = System.IO.Path.GetFileName(path); + if (fileName.Contains(excludeNameContains)) { + continue; + } + } if (!paths.Contains(path)) { paths.Add(path); diff --git a/Assets/URS/SmartLibrary/Editor/Data/Collections/StandardCollection.cs b/Assets/URS/SmartLibrary/Editor/Data/Collections/StandardCollection.cs index 6936d7b..2aaf0dd 100644 --- a/Assets/URS/SmartLibrary/Editor/Data/Collections/StandardCollection.cs +++ b/Assets/URS/SmartLibrary/Editor/Data/Collections/StandardCollection.cs @@ -11,6 +11,12 @@ namespace Bewildered.SmartLibrary [System.Serializable] public class StandardCollection : LibraryCollection, ILibrarySet { + [SerializeField] public AssetGUIDHashSet _items = new AssetGUIDHashSet(); + + public override AssetGUIDHashSet GetGUIDHashSet() + { + return _items; + } /// public override void UpdateItems(bool syn= false) { diff --git a/Assets/URS/SmartLibrary/Editor/Data/LibraryData.cs b/Assets/URS/SmartLibrary/Editor/Data/LibraryData.cs index fd5dd45..75b891e 100644 --- a/Assets/URS/SmartLibrary/Editor/Data/LibraryData.cs +++ b/Assets/URS/SmartLibrary/Editor/Data/LibraryData.cs @@ -92,6 +92,7 @@ private static void SetInstance() } } + /* internal static void ConvertToNewSave() { // If the folder already exists that means that we must have already converted. @@ -141,7 +142,7 @@ internal static void ConvertToNewSave() AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(Instance)); } - + */ void ISerializationCallbackReceiver.OnBeforeSerialize() { _serializedEntries.Clear(); diff --git a/Assets/URS/SmartLibrary/Editor/Data/LibraryDatabase.cs b/Assets/URS/SmartLibrary/Editor/Data/LibraryDatabase.cs index 802ca5b..58056bd 100644 --- a/Assets/URS/SmartLibrary/Editor/Data/LibraryDatabase.cs +++ b/Assets/URS/SmartLibrary/Editor/Data/LibraryDatabase.cs @@ -120,7 +120,7 @@ internal static void RemoveItemFromLibrary(LibraryItem item) // Iterate in reverse because the RemoveItem method removes the collection id from the list. for (int i = collectionIds.Count - 1; i >= 0; i--) { - FindCollectionByID(collectionIds[i]).RemoveItem(item); + FindCollectionByID(collectionIds[i])?.RemoveItem(item); } } } diff --git a/Assets/URS/SmartLibrary/Editor/SessionData.cs b/Assets/URS/SmartLibrary/Editor/SessionData.cs index 4173be9..55aa15f 100644 --- a/Assets/URS/SmartLibrary/Editor/SessionData.cs +++ b/Assets/URS/SmartLibrary/Editor/SessionData.cs @@ -23,10 +23,10 @@ internal RootLibraryCollection RootCollection { get { - if (!Directory.Exists(LibraryConstants.CollectionsPath) && _rootCollection == null) - { - LibraryData.ConvertToNewSave(); - } + // if (!Directory.Exists(LibraryConstants.CollectionsPath) && _rootCollection == null) + // { + // LibraryData.ConvertToNewSave(); + // } if (_rootCollection == null) { diff --git a/Assets/URS/SmartLibrary/Editor/Utility/LibraryUtility.cs b/Assets/URS/SmartLibrary/Editor/Utility/LibraryUtility.cs index 92cce74..33b943f 100644 --- a/Assets/URS/SmartLibrary/Editor/Utility/LibraryUtility.cs +++ b/Assets/URS/SmartLibrary/Editor/Utility/LibraryUtility.cs @@ -178,7 +178,8 @@ internal static void SaveCollection(LibraryCollection collection) { Directory.CreateDirectory(LibraryConstants.CollectionsPath); - string path = GetCollectionPath(collection); + bool isRoot = collection is RootLibraryCollection; + string path = GetCollectionPath(collection, isRoot); InternalEditorUtility.SaveToSerializedFileAndForget(new Object[] {collection}, path, true); } @@ -208,9 +209,17 @@ internal static void RenameCollectionFile(LibraryCollection collection, string n File.Move(path, newPath); } - internal static string GetCollectionPath(LibraryCollection collection) + internal static string GetCollectionPath(LibraryCollection collection, bool isRoot = false) { - string filename = $"{collection.CollectionName}_{collection.ID}"; + string filename = null; + if (isRoot) + { + filename = $"{collection.CollectionName}"; + } + else + { + filename = $"{collection.CollectionName}_{collection.ID}"; + } filename = GetSafeFilename(filename); return $"{LibraryConstants.CollectionsPath}/{filename}{LibraryConstants.CollectionFileExtension}"; } @@ -231,8 +240,13 @@ internal static void LoadAllCollections() Directory.CreateDirectory(LibraryConstants.CollectionsPath); foreach (string collectionPath in Directory.EnumerateFiles(LibraryConstants.CollectionsPath)) { + var fileName= Path.GetFileName(collectionPath); + if (fileName == ".DS_Store") + { + continue; + } var collection = LoadCollection(collectionPath); - + collection.savePath = collectionPath; // This is required since in 2.0.0 the HideAndDontSave flag was used. So this is used to update it. if (collection.hideFlags != HideFlags.DontSave) collection.hideFlags = HideFlags.DontSave; @@ -276,15 +290,29 @@ internal static void LoadAllCollections() if (collection.Parent == null) { collection.Parent = rootCollection; - Debug.LogWarning($"Could not find parent with id {parentId}. Collection '{collection}' was added as a base collection."); + rootCollection.AddSubcollection(collection, true); + SaveCollection(collection); + Debug.LogWarning($"Could not find parent with id {parentId}. Collection name '{collection.CollectionName}' was added as a base collection. savePath {collection.savePath} "); + } + else + { + int index = collection.Parent.SubcollectionIDs.IndexOf(collection.ID); + if (index >= 0) + { + collection.Parent.SubcollectionsInternal[index] = collection; + } + else + { + collection.Parent = rootCollection; + rootCollection.AddSubcollection(collection, true); + SaveCollection(collection); + Debug.LogWarning($"Could not find parent with id {parentId}. Collection name '{collection.CollectionName}' was added as a base collection. savePath {collection.savePath} "); + } } - - int index = collection.Parent.SubcollectionIDs.IndexOf(collection.ID); - collection.Parent.SubcollectionsInternal[index] = collection; - SessionData.CacheCollectionData(collection, false); } LibraryDatabase.RootCollection.RemoveInvailidItem(); + LibraryDatabase.RootCollection.ValidateSubCollection(); } /// diff --git a/Assets/URS/SmartLibrary/Editor/View/LibraryCollectionsView.cs b/Assets/URS/SmartLibrary/Editor/View/LibraryCollectionsView.cs index 58dc191..c1770c3 100644 --- a/Assets/URS/SmartLibrary/Editor/View/LibraryCollectionsView.cs +++ b/Assets/URS/SmartLibrary/Editor/View/LibraryCollectionsView.cs @@ -115,8 +115,19 @@ public void SetCollectionSelection(LibraryCollection collection) /// The action to take to add an item. For baseCollections should add item to rootItems; otherwise add as a child to the current item. private void CreateTreeItems(IEnumerable collections, System.Action add) { + bool isFirst = true; foreach (LibraryCollection collection in collections) { + if (collection == null) + { + var s = "你的SmartLibrary错了,如果你不知道SmartLibrary是什么,那就\n1. 把Unity关闭\n2. 然后把Git里面多出来的SmartLibrarySetting***********.collect删除\n3. 修改过的SmartLibrarySetting***********.collect恢复\n4. 再重新启动unity"; + Debug.LogError(s); + if (isFirst) + { + isFirst = false; + EditorUtility.DisplayDialog("123", s, "ok"); + } + } var item = new CollectionTreeViewItem(collection, NextId()); add(item); _collectionItemMap.Add(collection, item); diff --git a/Assets/URS/SmartLibrary/Runtime/UniqueID.cs b/Assets/URS/SmartLibrary/Runtime/UniqueID.cs index 191d6ae..5e53ac2 100644 --- a/Assets/URS/SmartLibrary/Runtime/UniqueID.cs +++ b/Assets/URS/SmartLibrary/Runtime/UniqueID.cs @@ -9,6 +9,9 @@ namespace Bewildered.SmartLibrary [Serializable] public struct UniqueID : ISerializationCallbackReceiver { + + public static UniqueID ROOT_UNIQUE_ID = new UniqueID("de0dede7-af86-40d4-a625-dd41b111e7e7"); + private Guid _guid; // Use bytes because strings allocate memory and is twice as slow. diff --git a/Assets/URS/SocoShaderVariant.meta b/Assets/URS/SocoShaderVariant.meta new file mode 100644 index 0000000..0d41ffa --- /dev/null +++ b/Assets/URS/SocoShaderVariant.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 65f315ff3acb51e4c8e76cbac90ed645 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/..Associate/README.md b/Assets/URS/SocoShaderVariant/..Associate/README.md new file mode 100644 index 0000000..c624778 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/..Associate/README.md @@ -0,0 +1,6 @@ +# 联动组件 + +  这个文件夹内,存放多个SocoTools工具的联动功能,如果只使用了部分工具,可能会导致这里的脚本报错,请添加被引用的工具,或删除这个脚本。
+  当前联动组件包括: +> 1. SocoVariantStripAssociate: 变体收集与剔除工具的联动脚本,可在收集工具中运行变体剔除判断。 + diff --git a/Assets/URS/SocoShaderVariant/..Associate/SocoVariantStripAssociate.cs b/Assets/URS/SocoShaderVariant/..Associate/SocoVariantStripAssociate.cs new file mode 100644 index 0000000..1329b4b --- /dev/null +++ b/Assets/URS/SocoShaderVariant/..Associate/SocoVariantStripAssociate.cs @@ -0,0 +1,56 @@ +using System.Linq; +using System.Reflection; +using Soco.ShaderVariantsCollection; +using UnityEditor; +using UnityEditor.Rendering; +using UnityEngine.Rendering; + +// 用于联动变体收集 和 变体剔除工具 +// 如果没有使用Soco变体剔除工具,此执行器应删除 +public class SocoVariantStripAssociate : Soco.ShaderVariantsCollection.IExecutable +{ + public override void Execute(ShaderVariantCollectionMapper mapper) + { + var m_ShaderType = typeof(ShaderSnippetData).GetField("m_ShaderType", BindingFlags.Instance | BindingFlags.NonPublic); + var m_PassType = typeof(ShaderSnippetData).GetField("m_PassType", BindingFlags.Instance | BindingFlags.NonPublic); + var m_PassName = typeof(ShaderSnippetData).GetField("m_PassName", BindingFlags.Instance | BindingFlags.NonPublic); + + var stripConfigs = + com.cyou.soco.ShaderVariantsStripper.ShaderVariantsStripperCode.LoadConfigs(); + + foreach (var shader in mapper.shaders) + { + int variantIndex = 0; + var variants = mapper.GetShaderVariants(shader).ToArray(); + foreach (var variant in variants) + { + EditorUtility.DisplayProgressBar("变体剔除", $"正在处理{shader.name} {variantIndex}/{variants.Length}变体", + (float)variantIndex / (float)variants.Length); + variantIndex++; + + ShaderSnippetData snipperData = new ShaderSnippetData(); + + //这里没对RayTracing、Mesh Shader的剔除做相关处理,默认所有Shader Pass都有VertexShader + m_ShaderType.SetValueDirect(__makeref(snipperData), ShaderType.Vertex); + m_PassType.SetValueDirect(__makeref(snipperData), variant.passType); + m_PassName.SetValueDirect(__makeref(snipperData), ""); + + ShaderCompilerData data = new ShaderCompilerData(); + data.shaderKeywordSet = new ShaderKeywordSet(); + + foreach (var keyword in variant.keywords) + { + data.shaderKeywordSet.Enable(new ShaderKeyword(keyword)); + } + + if (com.cyou.soco.ShaderVariantsStripper.ShaderVariantsStripperCode.IsVariantStrip( + shader, snipperData, data, stripConfigs)) + { + mapper.RemoveVariant(variant); + } + } + } + + EditorUtility.ClearProgressBar(); + } +} diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection.meta new file mode 100644 index 0000000..77a1360 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 49a70c8e9336f3a478da70912489e607 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git "a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/1.\345\274\200\345\220\257\347\225\214\351\235\242.png" "b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/1.\345\274\200\345\220\257\347\225\214\351\235\242.png" new file mode 100644 index 0000000..abe6231 Binary files /dev/null and "b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/1.\345\274\200\345\220\257\347\225\214\351\235\242.png" differ diff --git "a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/2.\345\212\237\350\203\275\351\200\211\346\213\251.png" "b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/2.\345\212\237\350\203\275\351\200\211\346\213\251.png" new file mode 100644 index 0000000..098a036 Binary files /dev/null and "b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/2.\345\212\237\350\203\275\351\200\211\346\213\251.png" differ diff --git "a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/3.\345\277\253\351\200\237\346\265\217\350\247\210.png" "b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/3.\345\277\253\351\200\237\346\265\217\350\247\210.png" new file mode 100644 index 0000000..ca03f2d Binary files /dev/null and "b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/3.\345\277\253\351\200\237\346\265\217\350\247\210.png" differ diff --git "a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/4.\346\235\220\350\264\250\346\224\266\351\233\206\345\231\250\345\210\227\350\241\250.png" "b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/4.\346\235\220\350\264\250\346\224\266\351\233\206\345\231\250\345\210\227\350\241\250.png" new file mode 100644 index 0000000..fd73906 Binary files /dev/null and "b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/4.\346\235\220\350\264\250\346\224\266\351\233\206\345\231\250\345\210\227\350\241\250.png" differ diff --git "a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/5.\345\217\230\344\275\223\350\277\207\346\273\244\345\231\250\345\210\227\350\241\250.png" "b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/5.\345\217\230\344\275\223\350\277\207\346\273\244\345\231\250\345\210\227\350\241\250.png" new file mode 100644 index 0000000..918e651 Binary files /dev/null and "b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/5.\345\217\230\344\275\223\350\277\207\346\273\244\345\231\250\345\210\227\350\241\250.png" differ diff --git "a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/6.\345\220\210\345\271\266\346\226\207\344\273\266.png" "b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/6.\345\220\210\345\271\266\346\226\207\344\273\266.png" new file mode 100644 index 0000000..7bb8966 Binary files /dev/null and "b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/6.\345\220\210\345\271\266\346\226\207\344\273\266.png" differ diff --git "a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/7.\346\211\247\350\241\214\345\231\250\345\210\227\350\241\250.png" "b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/7.\346\211\247\350\241\214\345\231\250\345\210\227\350\241\250.png" new file mode 100644 index 0000000..a256de8 Binary files /dev/null and "b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/7.\346\211\247\350\241\214\345\231\250\345\210\227\350\241\250.png" differ diff --git "a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/8.\345\217\230\344\275\223\345\243\260\346\230\216\347\273\204\345\220\210.png" "b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/8.\345\217\230\344\275\223\345\243\260\346\230\216\347\273\204\345\220\210.png" new file mode 100644 index 0000000..739d4d5 Binary files /dev/null and "b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/8.\345\217\230\344\275\223\345\243\260\346\230\216\347\273\204\345\220\210.png" differ diff --git "a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/9.\345\210\206\345\211\262\346\226\207\344\273\266.png" "b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/9.\345\210\206\345\211\262\346\226\207\344\273\266.png" new file mode 100644 index 0000000..70a5f11 Binary files /dev/null and "b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/..Images/9.\345\210\206\345\211\262\346\226\207\344\273\266.png" differ diff --git a/Assets/Settings/Editor.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor.meta similarity index 77% rename from Assets/Settings/Editor.meta rename to Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor.meta index d2500ff..ea5a7df 100644 --- a/Assets/Settings/Editor.meta +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 5f2d21f583b3cb34aa7eed1358d0afff +guid: ac0cd9d26cc1c694187d194b295dd359 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Default ShaderVariantCollection Tool Config.asset b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Default ShaderVariantCollection Tool Config.asset new file mode 100644 index 0000000..2f854dd --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Default ShaderVariantCollection Tool Config.asset @@ -0,0 +1,19 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &11400000 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: d22892cb17f31f84cb4c273d63a7e13f, type: 3} + m_Name: Default ShaderVariantCollection Tool Config + m_EditorClassIdentifier: + mKeys: + - Soco.ShaderVariantsCollection.IExecutable, Assembly-CSharp-Editor, Version=0.0.0.0, + Culture=neutral, PublicKeyToken=null + mValues: + - list: [] diff --git a/Assets/UniversalRenderPipelineGlobalSettings.asset.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Default ShaderVariantCollection Tool Config.asset.meta similarity index 79% rename from Assets/UniversalRenderPipelineGlobalSettings.asset.meta rename to Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Default ShaderVariantCollection Tool Config.asset.meta index 69224c2..48e50f6 100644 --- a/Assets/UniversalRenderPipelineGlobalSettings.asset.meta +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Default ShaderVariantCollection Tool Config.asset.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: c67d1f707925d91498ee0a7fc1b385de +guid: a78e199f87bb9db47a3c17d1a07308fb NativeFormatImporter: externalObjects: {} mainObjectFileID: 11400000 diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable.meta new file mode 100644 index 0000000..b1e63eb --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: eebe44c5492ebee4e8b8226043a41fa0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable/IExecutable.cs b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable/IExecutable.cs new file mode 100644 index 0000000..2a182bb --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable/IExecutable.cs @@ -0,0 +1,11 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace Soco.ShaderVariantsCollection +{ + public abstract class IExecutable : ScriptableObject + { + public abstract void Execute(ShaderVariantCollectionMapper mapper); + } +} \ No newline at end of file diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable/IExecutable.cs.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable/IExecutable.cs.meta new file mode 100644 index 0000000..ebed66c --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable/IExecutable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 753aebac5bd30034fb12ad7c2591a6ba +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable/InvalidVariantStrip.cs b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable/InvalidVariantStrip.cs new file mode 100644 index 0000000..af0827c --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable/InvalidVariantStrip.cs @@ -0,0 +1,59 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +namespace Soco.ShaderVariantsCollection +{ + public class InvalidVariantStrip : IExecutable + { + public override void Execute(ShaderVariantCollectionMapper mapper) + { + var collection = mapper.mCollection; + + SerializedObject serializedObject = new UnityEditor.SerializedObject(collection); + //serializedObject.Update(); + SerializedProperty m_Shaders = serializedObject.FindProperty("m_Shaders"); + + for (int i = 0; i < m_Shaders.arraySize; ++i) + { + SerializedProperty pair = m_Shaders.GetArrayElementAtIndex(i); + + SerializedProperty first = pair.FindPropertyRelative("first"); + SerializedProperty second = pair.FindPropertyRelative("second");//ShaderInfo + + Shader shader = first.objectReferenceValue as Shader; + + if (shader == null) + continue; + + SerializedProperty variants = second.FindPropertyRelative("variants"); + for (var vi = variants.arraySize - 1; vi >= 0 ; --vi) + { + SerializedProperty variantInfo = variants.GetArrayElementAtIndex(vi); + ShaderVariantCollection.ShaderVariant variant = ShaderVariantCollectionMapper.PropToVariantObject(shader, variantInfo); + + if (!IsValid(variant)) + variants.DeleteArrayElementAtIndex(vi); + } + } + + serializedObject.ApplyModifiedProperties(); + mapper.Refresh(); + + } + + private bool IsValid(ShaderVariantCollection.ShaderVariant variant) + { + try + { + new ShaderVariantCollection.ShaderVariant(variant.shader, variant.passType, variant.keywords); + return true; + } + catch + { + return false; + } + } + } +} \ No newline at end of file diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable/InvalidVariantStrip.cs.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable/InvalidVariantStrip.cs.meta new file mode 100644 index 0000000..c54d1e5 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable/InvalidVariantStrip.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1601ff25e5bda3b48b0eecdd090006fc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable/VariantKeywordCombination.cs b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable/VariantKeywordCombination.cs new file mode 100644 index 0000000..bb9b7d5 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable/VariantKeywordCombination.cs @@ -0,0 +1,448 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text.RegularExpressions; +using UnityEditor; +using UnityEngine; +using UnityEngine.Rendering; + +namespace Soco.ShaderVariantsCollection +{ + [System.Serializable] + public struct KeywordDeclareGroup + { + public List keywords; + } + + public class VariantKeywordCombination : IExecutable + { + public Shader mShader; + public List mKeywordDeclareGroups = new List(); + + public override void Execute(ShaderVariantCollectionMapper mapper) + { + if (mShader == null ) + { + Debug.LogWarning($"执行器{name}无法执行,原因是成员参数不符合规格,可能shader{mShader}为null)"); + return; + } + var shaderVariants = mapper.GetShaderVariants(mShader); + if (shaderVariants.Count > 0&& mKeywordDeclareGroups.Count == 0) + { + Debug.LogWarning($"执行器{name}无法执行,keyword声明组长度为0(当前长度为{mKeywordDeclareGroups.Count})"); + } + if (!mapper.HasShader(mShader)) + { + Debug.LogError($"执行器{name}无法执行,原因是收集文件中不包含当前shader{mShader}"); + return; + } + + + var combinationList = GetCombine(new List(mKeywordDeclareGroups)); + + for (int i = combinationList.Count - 1; i >= 0; i--) + { + var list = combinationList[i]; + for (int index = list.Count - 1; index >= 0; index--) + { + if (list[index] == "_") + { + list.RemoveAt(index); + } + } + } + if (combinationList.Count == 0) + { + combinationList.Add(new List()); + } + + + if (shaderVariants.Count > 0) + { + foreach (ShaderVariantCollection.ShaderVariant variant in shaderVariants.ToArray()) + { + //去除已有变体中包含的multi_compile声明 + var removeMultiCompileKeywordList = variant.keywords.Where((string k) => + { + foreach (KeywordDeclareGroup declareGroup in mKeywordDeclareGroups) + { + foreach (var keyword in declareGroup.keywords) + { + if (k == keyword) + return false; + } + } + + return true; + }); + + foreach (var combination in combinationList) + { + try + { + + ShaderVariantCollection.ShaderVariant newVariant = + new ShaderVariantCollection.ShaderVariant(variant.shader, variant.passType, + removeMultiCompileKeywordList.Concat(combination).ToArray()); + + mapper.AddVariant(newVariant); + } + catch (Exception e) + { + continue; + } + } + } + } + else + { + foreach (var combination in combinationList) + { + for (PassType passType = (PassType)Enum.GetValues(typeof(PassType)).Cast().Min(); + passType <= (PassType)Enum.GetValues(typeof(PassType)).Cast().Max(); + ++passType) + { + + var success = GetShaderVariant(mShader, passType, combination.ToArray(), out var variant); + if (success) + { + mapper.AddVariant(variant); + } + } + } + } + + } + bool GetShaderVariant(Shader shader,PassType passType,string[] keywords, out ShaderVariantCollection.ShaderVariant result) + { + result = default(ShaderVariantCollection.ShaderVariant); + try + { + result = new ShaderVariantCollection.ShaderVariant(shader, passType, keywords); + return true; + } + catch + { + return false; + } + } + public List> GetCombine(List declareGroup) + { + List> result = new List>(); + if (declareGroup.Count > 0) + { + var current = declareGroup[0]; + var currentKeywords= current.keywords; + declareGroup.RemoveAt(0); + var leftKeywords = GetCombine(declareGroup); + if (leftKeywords.Count > 0) + { + foreach (var left in leftKeywords) + { + foreach (var currentKeyword in currentKeywords) + { + var temp = new List(); + temp.Add(currentKeyword); + temp.AddRange(left); + temp.Distinct(); + result.Add(temp); + } + } + } + else + { + foreach (var currentKeyword in currentKeywords) + { + var temp = new List(); + temp.Add(currentKeyword); + result.Add(temp); + } + } + } + + + return result; + } + } + + + + [ShaderVariantCollectionToolEditor(typeof(VariantKeywordCombination))] + class VariantKeywordCombinationEditor : ShaderVariantCollectionToolEditor + { + private static MethodInfo _GetShaderGlobalKeywordsMethod = null; + private static MethodInfo _GetShaderLocalKeywordsMethod = null; + + private static MethodInfo GetShaderGlobalKeywordsMethod + { + get + { + if(_GetShaderGlobalKeywordsMethod == null) + _GetShaderGlobalKeywordsMethod = typeof(ShaderUtil).GetMethod("GetShaderGlobalKeywords", + BindingFlags.NonPublic | BindingFlags.Static); + + return _GetShaderGlobalKeywordsMethod; + } + } + + private static MethodInfo GetShaderLocalKeywordsMethod + { + get + { + if(_GetShaderLocalKeywordsMethod == null) + _GetShaderLocalKeywordsMethod = typeof(ShaderUtil).GetMethod("GetShaderLocalKeywords", + BindingFlags.NonPublic | BindingFlags.Static); + + return _GetShaderLocalKeywordsMethod; + } + } + + private string[] mShaderKeywords = new string[0]; + private int mSelectedKeywordIndex = 0; + + private enum KeywordMode + { + CustomKeyword, + DefaultKeyword, + DeclareStatement + } + + private KeywordMode mKeywordMode = KeywordMode.CustomKeyword; + private string mDeclareStatement = ""; + + private const string cDeclarePattern = @"#pragma\s+(multi_compile(?:_\w+)?)+(?:\s+(\w+))*"; + + public void OnEnable() + { + VariantKeywordCombination obj = target as VariantKeywordCombination; + + if (obj.mShader != null) + { + string[] globalKeywords = GetShaderGlobalKeywordsMethod.Invoke(null, new object[] { obj.mShader }) as string[]; + string[] localKeywords = GetShaderLocalKeywordsMethod.Invoke(null, new object[] { obj.mShader }) as string[]; + mShaderKeywords = globalKeywords.Concat(localKeywords).ToArray(); + Array.Sort(mShaderKeywords); + mSelectedKeywordIndex = 0; + } + } + + public override void OnInspectorGUI() + { + VariantKeywordCombination obj = target as VariantKeywordCombination; + + EditorGUILayout.BeginVertical(); + + EditorGUILayout.BeginHorizontal(); + EditorGUI.BeginChangeCheck(); + Shader newShader = EditorGUILayout.ObjectField("Shader", obj.mShader, typeof(Shader)) as Shader; + if (EditorGUI.EndChangeCheck() && newShader != obj.mShader) + { + Undo.RecordObject(obj, $"{obj.GetType().Name} change shader"); + + obj.mShader = newShader; + if (obj.mShader == null) + mShaderKeywords = new string[0]; + else + { + string[] globalKeywords = GetShaderGlobalKeywordsMethod.Invoke(null, new object[] { obj.mShader }) as string[]; + string[] localKeywords = GetShaderLocalKeywordsMethod.Invoke(null, new object[] { obj.mShader }) as string[]; + mShaderKeywords = globalKeywords.Concat(localKeywords).ToArray(); + Array.Sort(mShaderKeywords); + } + obj.mKeywordDeclareGroups.Clear(); + + mSelectedKeywordIndex = 0; + } + + if (obj.mShader != null && GUILayout.Button("尝试收集声明组")) + { + Undo.RecordObject(obj, $"{obj.GetType().Name} add keyword throw declare statement"); + obj.mKeywordDeclareGroups.Clear(); + TryParseShader(obj.mShader, obj.mKeywordDeclareGroups); + + } + EditorGUILayout.EndHorizontal(); + + EditorGUILayout.BeginHorizontal(); + mKeywordMode = (KeywordMode)EditorGUILayout.EnumPopup("选择模式", mKeywordMode); + if (mKeywordMode == KeywordMode.CustomKeyword) + { + mSelectedKeywordIndex = EditorGUILayout.Popup(mSelectedKeywordIndex, mShaderKeywords); + } + else if (mKeywordMode == KeywordMode.DeclareStatement) + { + mDeclareStatement = EditorGUILayout.TextField("声明语句", mDeclareStatement); + } + EditorGUILayout.EndHorizontal(); + + for (int i = 0; i < obj.mKeywordDeclareGroups.Count; ++i) + { + EditorGUILayout.BeginHorizontal(); + + for (int j = 0; j < obj.mKeywordDeclareGroups[i].keywords.Count; ++j) + { + string keyword = obj.mKeywordDeclareGroups[i].keywords[j]; + if (GUILayout.Button(new GUIContent(keyword, keyword))) + { + Undo.RecordObject(obj, $"{obj.GetType().Name} delete declareGroup's keyword"); + obj.mKeywordDeclareGroups[i].keywords.RemoveAt(j); + } + } + + if (GUILayout.Button(new GUIContent("+", "将keyword添加到当前组合中"), GUILayout.Width(20))) + { + if (mKeywordMode == KeywordMode.CustomKeyword) + { + if (!obj.mKeywordDeclareGroups[i].keywords.Contains(mShaderKeywords[mSelectedKeywordIndex])) + { + Undo.RecordObject(obj, $"{obj.GetType().Name} add keyword to declareGroup"); + obj.mKeywordDeclareGroups[i].keywords.Add(mShaderKeywords[mSelectedKeywordIndex]); + } + } + else if(mKeywordMode == KeywordMode.DefaultKeyword) + { + if (!obj.mKeywordDeclareGroups[i].keywords.Contains("_")) + { + Undo.RecordObject(obj, $"{obj.GetType().Name} add default keyword to declareGroup"); + obj.mKeywordDeclareGroups[i].keywords.Add("_"); + } + } + else if (mKeywordMode == KeywordMode.DeclareStatement) + { + Undo.RecordObject(obj, $"{obj.GetType().Name} add keyword throw declare statement"); + foreach (string keyword in ParseDeclareStatement(mDeclareStatement)) + { + if (!obj.mKeywordDeclareGroups[i].keywords.Contains(keyword)) + obj.mKeywordDeclareGroups[i].keywords.Add(keyword); + } + } + } + + if (GUILayout.Button(new GUIContent("-", "将当前变体组删除"), GUILayout.Width(20))) + { + Undo.RecordObject(obj, $"{obj.GetType().Name} delete declareGroup"); + obj.mKeywordDeclareGroups.RemoveAt(i); + EditorGUILayout.EndHorizontal(); + break; + } + + EditorGUILayout.EndHorizontal(); + } + + if (GUILayout.Button(new GUIContent("+", "添加变体声明组"), GUILayout.Width(20))) + { + Undo.RecordObject(obj, $"{obj.GetType().Name} add keywords"); + if (mKeywordMode == KeywordMode.DeclareStatement) + { + obj.mKeywordDeclareGroups.Add(new KeywordDeclareGroup(){keywords = ParseDeclareStatement(mDeclareStatement).ToList()}); + } + else + { + obj.mKeywordDeclareGroups.Add(new KeywordDeclareGroup(){keywords = new List()}); + } + } + + EditorGUILayout.EndVertical(); + } + + public static void TryParseShader(Shader shader, List targetList) + { + string path = AssetDatabase.GetAssetPath(shader); + + if (!File.Exists(path)) + { + Debug.LogError($"{shader}所在路径{path}不存在,可能Shader是Unity内置Shader"); + return; + } + + using (var sr = new StreamReader(path)) + { + string content = sr.ReadToEnd(); + //正则前加行首和空字符,这样去除注释的声明 + MatchCollection matches = Regex.Matches(content, @"^\s+"+cDeclarePattern, RegexOptions.Multiline); + + foreach (Match match in matches) + { + string[] declareGroup = ParseDeclareStatement(match.Groups[0].Value); + if (declareGroup.Length == 0) + continue; + + bool hasDeclared = targetList.FindIndex( + kdg => kdg.keywords.OrderBy(k => k).SequenceEqual(declareGroup.OrderBy(k => k))) > 0; + + if (!hasDeclared) + targetList.Add(new KeywordDeclareGroup(){keywords = declareGroup.ToList()}); + } + } + } + + public static string[] ParseDeclareStatement(string statement) + { + MatchCollection matches = Regex.Matches(statement, cDeclarePattern); + + if (matches.Count == 0) + { + Debug.LogError($"当前声明语句{statement}无法匹配出字段"); + return new string[0]; + } + else + { + string multiCompileDeclare = matches[0].Groups[1].Value; + multiCompileDeclare = multiCompileDeclare.Replace("_vertex", ""); + multiCompileDeclare = multiCompileDeclare.Replace("_fragment", ""); + multiCompileDeclare = multiCompileDeclare.Replace("_hull", ""); + multiCompileDeclare = multiCompileDeclare.Replace("_domain", ""); + multiCompileDeclare = multiCompileDeclare.Replace("_geometry", ""); + multiCompileDeclare = multiCompileDeclare.Replace("_raytracing", ""); + multiCompileDeclare = multiCompileDeclare.Replace("_local", ""); + + if (multiCompileDeclare == "multi_compile") + { + List keywords = new List(); + foreach (Capture capture in matches[0].Groups[2].Captures) + //如果是全下划线 + if (capture.Value.All(cr=>cr=='_')) + keywords.Add("_"); + else + keywords.Add(capture.Value); + + if (keywords.Count == 1) + { + if (keywords[0] != "_") + { + keywords.Add("_"); + } + else + { + Debug.LogError($"{statement}只声明了一个全下划线变体"); + return new string[0]; + } + } + + return keywords.ToArray(); + } + else if (multiCompileDeclare == "multi_compile_instancing") + { + return new string[] { "_", "INSTANCING_ON" }; + } + else if (multiCompileDeclare == "multi_compile_particles") + { + return new string[] { "_", "SOFTPARTICLES_ON" }; + } + else if (multiCompileDeclare == "multi_compile_fog") + { + return new string[] { "_", "FOG_LINEAR", "FOG_EXP", "FOG_EXP2" }; + } + //TODO: Other BuildIn keyword declare, eg. multi_compile_fwdbase + else + { + Debug.LogError($"未实现当前{multiCompileDeclare}变体声明,请根据需要到VariantKeywordCombination中实现"); + return new string[0]; + } + } + + } + } +} \ No newline at end of file diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable/VariantKeywordCombination.cs.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable/VariantKeywordCombination.cs.meta new file mode 100644 index 0000000..2b3fd16 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/Executable/VariantKeywordCombination.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6b05fedc750c41a4c8cf06d9894f48c3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection.meta new file mode 100644 index 0000000..f234750 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5db002ac54535d94ea8983e37b643ca6 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/IMaterialCollection.cs b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/IMaterialCollection.cs new file mode 100644 index 0000000..57f53af --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/IMaterialCollection.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace Soco.ShaderVariantsCollection +{ + public abstract class IMaterialCollector : ScriptableObject + { + public abstract void AddMaterialBuildDependency(IList buildDependencyList); + } +} \ No newline at end of file diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/IMaterialCollection.cs.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/IMaterialCollection.cs.meta new file mode 100644 index 0000000..348b3ab --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/IMaterialCollection.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b5f254d4a56b54342abf8d436bad8ed9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/MaterialCollection_AssignMaterial.cs b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/MaterialCollection_AssignMaterial.cs new file mode 100644 index 0000000..c700719 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/MaterialCollection_AssignMaterial.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; +using System.Linq; +using UnityEngine; + +namespace Soco.ShaderVariantsCollection +{ + // 这个是指定具体某些材质收集进来 + // 一般用于Debug + public class MaterialCollection_AssignMaterial : IMaterialCollector + { + public Material[] materials = new Material[0]; + + public override void AddMaterialBuildDependency(IList buildDependencyList) + { + materials.ToList().ForEach(buildDependencyList.Add); + } + } +} \ No newline at end of file diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/MaterialCollection_AssignMaterial.cs.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/MaterialCollection_AssignMaterial.cs.meta new file mode 100644 index 0000000..1e33450 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/MaterialCollection_AssignMaterial.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4507a9f4615a5cc498e8e6fb4e331ea8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/MaterialCollection_SceneDependency.cs b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/MaterialCollection_SceneDependency.cs new file mode 100644 index 0000000..eccabb8 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/MaterialCollection_SceneDependency.cs @@ -0,0 +1,26 @@ +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace Soco.ShaderVariantsCollection +{ + //用于收集所有打包场景依赖的材质 + public class MaterialCollection_SceneDependency : IMaterialCollector + { + //是否只收集在EditorBuildSettings中enable的场景 + public bool collectOnlyEnable = true; + public override void AddMaterialBuildDependency(IList buildDependencyList) + { + var sceneDependencyMaterials = EditorBuildSettings.scenes + .Where(scene => !collectOnlyEnable || scene.enabled) + .SelectMany(scene => AssetDatabase.GetDependencies(scene.path)) + .Where(dependencyAsset => dependencyAsset.EndsWith(".mat")) + .Distinct() + .Select(matPath => AssetDatabase.LoadAssetAtPath(matPath)); + + foreach (Material m in sceneDependencyMaterials) + buildDependencyList.Add(m); + } + } +} \ No newline at end of file diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/MaterialCollection_SceneDependency.cs.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/MaterialCollection_SceneDependency.cs.meta new file mode 100644 index 0000000..7c43517 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/MaterialCollection_SceneDependency.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9c92248bdd020784dae23e814f182fb3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/MaterialCollection_TotalMaterial.cs b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/MaterialCollection_TotalMaterial.cs new file mode 100644 index 0000000..e1ae2e4 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/MaterialCollection_TotalMaterial.cs @@ -0,0 +1,38 @@ +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace Soco.ShaderVariantsCollection +{ + //这是一个编写示例 + //将收集目录下所有材质 + //实际项目不建议这样做 + public sealed class MaterialCollection_TotalMaterial : IMaterialCollector + { + public enum PathMode + { + Asset, + String + } + //private readonly string[] cIncludePath = { "Assets", "Packages" }; + [Tooltip("路径选择模式,以文件夹资产的方式,或以字符串路径")] + public PathMode pathMode = PathMode.String; + public string[] mIncludePath = { "Assets", "Packages" }; + public DefaultAsset[] mFolders = new DefaultAsset[0]; + + public override void AddMaterialBuildDependency(IList buildDependencyList) + { + string[] includePath = mFolders.Select(f => AssetDatabase.GetAssetPath(f)).ToArray(); + includePath = pathMode == PathMode.Asset ? includePath : mIncludePath; + var materialsGUID = AssetDatabase.FindAssets("t:Material", includePath); + + foreach (Material m in materialsGUID.Select( + guid => AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid)) + )) + { + buildDependencyList.Add(m); + } + } + } +} \ No newline at end of file diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/MaterialCollection_TotalMaterial.cs.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/MaterialCollection_TotalMaterial.cs.meta new file mode 100644 index 0000000..9c4bedd --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialCollection/MaterialCollection_TotalMaterial.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bc0a1e0c209b59e4b940d4b2ea6ecbad +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialFilter.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialFilter.meta new file mode 100644 index 0000000..0681eb4 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialFilter.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1ce2c909e70872c4c8992cd8bf6cb283 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialFilter/IMaterialFilter.cs b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialFilter/IMaterialFilter.cs new file mode 100644 index 0000000..151dfaf --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialFilter/IMaterialFilter.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace Soco.ShaderVariantsCollection +{ + public abstract class IMaterialFilter : ScriptableObject + { + //return true will save and false will strip + public abstract bool Filter(Material material, List collections); + } +} \ No newline at end of file diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialFilter/IMaterialFilter.cs.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialFilter/IMaterialFilter.cs.meta new file mode 100644 index 0000000..904a68c --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialFilter/IMaterialFilter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3d92a4a987f9c3942bd06190c10c4dd8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialFilter/TestMaterialFilter.cs b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialFilter/TestMaterialFilter.cs new file mode 100644 index 0000000..cca1c40 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialFilter/TestMaterialFilter.cs @@ -0,0 +1,14 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace Soco.ShaderVariantsCollection +{ + public sealed class TestMaterialFilter : IMaterialFilter + { + public override bool Filter(Material material, List collections) + { + //nothing to do + return true; + } + } +} \ No newline at end of file diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialFilter/TestMaterialFilter.cs.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialFilter/TestMaterialFilter.cs.meta new file mode 100644 index 0000000..b518d45 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/MaterialFilter/TestMaterialFilter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c731b06d314c9054195ae05ed900aa3f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/SerializableShaderVariant.cs b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/SerializableShaderVariant.cs new file mode 100644 index 0000000..371a6d9 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/SerializableShaderVariant.cs @@ -0,0 +1,45 @@ +using System; +using UnityEngine; +using UnityEngine.Rendering; + +namespace Soco.ShaderVariantsCollection +{ + [Serializable] + public struct SerializableShaderVariant + { + public Shader shader; + public PassType passType; + public string[] keywords; + + public SerializableShaderVariant(ShaderVariantCollection.ShaderVariant variant) + { + shader = variant.shader; + passType = variant.passType; + keywords = variant.keywords; + } + + public ShaderVariantCollection.ShaderVariant Deserialize() + { + //这样初始化的原因是,假如变体无效不会报错 + return new ShaderVariantCollection.ShaderVariant() + { + shader = shader, + passType = passType, + keywords = keywords + }; + } + + public bool IsValid() + { + try + { + new ShaderVariantCollection.ShaderVariant(shader, passType, keywords);; + return true; + } + catch (Exception e) + { + return false; + } + } + } +} diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/SerializableShaderVariant.cs.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/SerializableShaderVariant.cs.meta new file mode 100644 index 0000000..70a4542 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/SerializableShaderVariant.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0046574c78f805947b36720612bf38b4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionAddVariantWindow.cs b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionAddVariantWindow.cs new file mode 100644 index 0000000..b11f4cc --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionAddVariantWindow.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using UnityEditor; +using UnityEngine; +using UnityEngine.Rendering; + +namespace Soco.ShaderVariantsCollection +{ + public class ShaderVariantCollectionAddVariantWindow : EditorWindow + { + private static ShaderVariantCollectionAddVariantWindow m_window; + public static ShaderVariantCollectionAddVariantWindow Window + { + get + { + if (m_window == null) + { + m_window = EditorWindow.GetWindow("AddVariantWindow"); + m_window.minSize = new Vector2(480, 320); + } + return m_window; + } + } + + private Shader mShader; + private PassType mPassType; + private ShaderVariantCollectionMapper mMapper; + + private static MethodInfo sGetShaderGlobalKeywordsMethod = null; + private static MethodInfo sGetShaderLocalKeywordsMethod = null; + + private string[] mShaderKeywords; + private List mSelectedShaderKeywords = new List(); + private int mSelectedShaderKeywordIndex = 0; + + private enum State + { + None, + Success, + Failure + } + + private State mState; + private string mMessage; + + + private static void InitGetKeywordMethod() + { + if (sGetShaderGlobalKeywordsMethod == null) + sGetShaderGlobalKeywordsMethod = typeof(ShaderUtil).GetMethod("GetShaderGlobalKeywords", + BindingFlags.NonPublic | BindingFlags.Static); + + if (sGetShaderLocalKeywordsMethod == null) + sGetShaderLocalKeywordsMethod = typeof(ShaderUtil).GetMethod("GetShaderLocalKeywords", + BindingFlags.NonPublic | BindingFlags.Static); + } + + public void Setup(Shader shader, PassType passType, ShaderVariantCollectionMapper mapper) + { + mShader = shader; + mPassType = passType; + mMapper = mapper; + + InitGetKeywordMethod(); + + string[] globalKeywords = sGetShaderGlobalKeywordsMethod.Invoke(null, new object[] { shader }) as string[]; + string[] localKeywords = sGetShaderLocalKeywordsMethod.Invoke(null, new object[] { shader }) as string[]; + mShaderKeywords = globalKeywords.Concat(localKeywords).ToArray(); + + mSelectedShaderKeywords.Clear(); + mSelectedShaderKeywordIndex = 0; + mState = State.None; + } + + public void OnGUI() + { + EditorGUILayout.BeginVertical(); + + EditorGUILayout.LabelField($"当前Shader: {mShader}"); + mPassType = (PassType)EditorGUILayout.EnumPopup("PassType", mPassType); + + #region 待添加keyword + EditorGUILayout.LabelField($"待添加Keyword:"); + + EditorGUILayout.BeginHorizontal(); + int i = 0; + foreach (string keyword in mShaderKeywords) + { + if (i != 0 && i % 4 == 0) + { + EditorGUILayout.EndHorizontal(); + EditorGUILayout.BeginHorizontal(); + } + + if (!mSelectedShaderKeywords.Contains(keyword)) + { + if (GUILayout.Button(keyword)) + { + mSelectedShaderKeywords.Add(keyword); + } + i++; + } + } + EditorGUILayout.EndHorizontal(); + #endregion + + #region 当前keyword + EditorGUILayout.LabelField($"当前Keyword:"); + + EditorGUILayout.BeginHorizontal(); + for (int keywordIndex = 0; keywordIndex < mSelectedShaderKeywords.Count; ++keywordIndex) + { + if (keywordIndex != 0 && keywordIndex % 4 == 0) + { + EditorGUILayout.EndHorizontal(); + EditorGUILayout.BeginHorizontal(); + } + + if (GUILayout.Button(mSelectedShaderKeywords[keywordIndex])) + { + mSelectedShaderKeywords.RemoveAt(keywordIndex); + } + } + EditorGUILayout.EndHorizontal(); + #endregion + + if (GUILayout.Button("添加变体")) + { + bool newVariantSuccess = false; + ShaderVariantCollection.ShaderVariant newVariant; + string errorMessage = ""; + + try + { + newVariant = new ShaderVariantCollection.ShaderVariant(mShader, mPassType, + mSelectedShaderKeywords.ToArray()); + newVariantSuccess = true; + } + catch (Exception e) + { + newVariantSuccess = false; + errorMessage = e.Message; + } + + string keywordString = string.Join(", ", mSelectedShaderKeywords); + if (newVariantSuccess) + { + newVariant = new ShaderVariantCollection.ShaderVariant(mShader, mPassType, + mSelectedShaderKeywords.ToArray());//不重新new会因为变量可能没初始化导致编译错误 + if (mMapper.HasVariant(newVariant)) + { + mState = State.Failure; + mMessage = $"变体<{mPassType}>[{keywordString}]已存在"; + } + else + { + ShaderVariantCollectionToolsWindow.Window.UndoShaderVariantCollectionTool(); + if (!mMapper.AddVariant(newVariant)) + { + mState = State.Failure; + mMessage = $"变体<{mPassType}>[{keywordString}]添加失败"; + } + else + { + mState = State.Success; + mMessage = $"变体<{mPassType}>[{keywordString}]添加成功"; + ShaderVariantCollectionToolsWindow.Window.RefreshPassKeywordMap(mShader); + //ShaderVariantCollectionToolsWindow.Window.CollectPassKeywordMap(mMapper.GetShaderVariants(mShader)); + ShaderVariantCollectionToolsWindow.Window.Repaint(); + } + } + } + else + { + mState = State.Failure; + mMessage = $"变体<{mPassType}>[{keywordString}]创建失败,相关报错为:{errorMessage}"; + } + } + + #region 消息显示 + if (mState != State.None) + { + Color oriColor = GUI.color; + GUI.color = mState == State.Success ? Color.green : Color.red; + GUI.color *= 0.5f; + + EditorGUILayout.LabelField(mMessage, EditorStyles.whiteLabel); + + GUI.color = oriColor; + } + #endregion + + EditorGUILayout.EndVertical(); + + + } + } +} \ No newline at end of file diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionAddVariantWindow.cs.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionAddVariantWindow.cs.meta new file mode 100644 index 0000000..777aaee --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionAddVariantWindow.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c3acdd4c88e7fe04b87fedb57c34291a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionMapper.cs b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionMapper.cs new file mode 100644 index 0000000..f9e264b --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionMapper.cs @@ -0,0 +1,341 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using UnityEditor; +using UnityEngine; +using UnityEngine.Rendering; + +namespace Soco.ShaderVariantsCollection +{ + //用于访问ShaderVariantCollection被隐藏的C++部分 + //继承UnityEngine.ScriptableObject, ISerializationCallbackReceiver是为了Undo + public class ShaderVariantCollectionMapper : UnityEngine.ScriptableObject, ISerializationCallbackReceiver + { + [SerializeField] + internal ShaderVariantCollection mCollection; + private Dictionary> mMapper = new Dictionary>(); + + private List mMapperSerializeKeys = new List(); + [System.Serializable] + private struct ListWrapper + { + public List list; + + public ListWrapper(List list) + { + this.list = list; + } + + // public List Deserialize() + // { + // return list.Select(variant => variant.Deserialize()).ToList(); + // } + } + private List mMapperSerializeValues = new List(); + + [NonSerialized] + private bool mSerializedFlag = false; + + + public Dictionary> GetMapper() + { + return mMapper; + } + + private static MethodInfo sAddNewShaderToCollection = null; + + private static void InitShaderUtilMethod() + { + if (sAddNewShaderToCollection == null) + sAddNewShaderToCollection = typeof(ShaderUtil).GetMethod("AddNewShaderToCollection", + BindingFlags.NonPublic | BindingFlags.Static); + } + + //当用CreateInstance时,调用这个方法 + public void Init(ShaderVariantCollection collection) + { + mCollection = collection; + + if (mCollection == null) + { + throw new Exception( + "ShaderVariantCollectionMapper constructor get a null ShaderVariantCollection Object"); + } + + ReadFromFile(); + InitShaderUtilMethod(); + } + + public ShaderVariantCollectionMapper(ShaderVariantCollection collection) + { + Init(collection); + } + + internal static ShaderVariantCollection.ShaderVariant PropToVariantObject(Shader shader, SerializedProperty variantInfo) + { + PassType passType = (PassType)variantInfo.FindPropertyRelative("passType").intValue; + string keywords = variantInfo.FindPropertyRelative("keywords").stringValue; + string[] keywordSet = keywords.Split(' '); + keywordSet = (keywordSet.Length == 1 && keywordSet[0] == "") ? new string[0] : keywordSet; + + ShaderVariantCollection.ShaderVariant newVariant = new ShaderVariantCollection.ShaderVariant() + { + shader = shader, + keywords = keywordSet, + passType = passType + }; + + return newVariant; + } + + private void ReadFromFile() + { + mMapper.Clear(); + + SerializedObject serializedObject = new UnityEditor.SerializedObject(mCollection); + //serializedObject.Update(); + SerializedProperty m_Shaders = serializedObject.FindProperty("m_Shaders"); + + for (int i = 0; i < m_Shaders.arraySize; ++i) + { + SerializedProperty pair = m_Shaders.GetArrayElementAtIndex(i); + + SerializedProperty first = pair.FindPropertyRelative("first"); + SerializedProperty second = pair.FindPropertyRelative("second");//ShaderInfo + + Shader shader = first.objectReferenceValue as Shader; + + if (shader == null) + continue; + + mMapper[shader] = new List(); + + SerializedProperty variants = second.FindPropertyRelative("variants"); + for (var vi = 0; vi < variants.arraySize; ++vi) + { + SerializedProperty variantInfo = variants.GetArrayElementAtIndex(vi); + + ShaderVariantCollection.ShaderVariant variant = PropToVariantObject(shader, variantInfo); + mMapper[shader].Add(new SerializableShaderVariant(variant)); + } + } + } + + public Dictionary>.KeyCollection shaders => mMapper.Keys; + + public ReadOnlyCollection GetShaderVariants(Shader shader) => + mMapper[shader].Select(v=>v.Deserialize()).ToList().AsReadOnly(); + + public bool HasShader(Shader shader) + { + bool collectionHasShader = false; + SerializedObject serializedObject = new UnityEditor.SerializedObject(mCollection); + //serializedObject.Update(); + SerializedProperty m_Shaders = serializedObject.FindProperty("m_Shaders"); + + for (int i = 0; i < m_Shaders.arraySize; ++i) + { + SerializedProperty pair = m_Shaders.GetArrayElementAtIndex(i); + + SerializedProperty first = pair.FindPropertyRelative("first"); + SerializedProperty second = pair.FindPropertyRelative("second"); //ShaderInfo + + Shader currentShader = first.objectReferenceValue as Shader; + + if (currentShader == shader) + { + collectionHasShader = true; + break; + } + } + + bool mapperHasShader = mMapper.ContainsKey(shader); + + Debug.Assert(collectionHasShader == mapperHasShader, "map对象与源文件内容不符"); + return mapperHasShader; + } + + public void AddShader(Shader shader) + { + if (!mMapper.ContainsKey(shader)) + { + mMapper.Add(shader, new List()); + } + + sAddNewShaderToCollection.Invoke(null, new object[] { shader, mCollection }); + } + + public void RemoveShader(Shader shader) + { + if (mMapper.ContainsKey(shader)) + { + mMapper.Remove(shader); + } + + SerializedObject serializedObject = new UnityEditor.SerializedObject(mCollection); + //serializedObject.Update(); + SerializedProperty m_Shaders = serializedObject.FindProperty("m_Shaders"); + + for (int shaderIndex = 0; shaderIndex < m_Shaders.arraySize; ++shaderIndex) + { + SerializedProperty pair = m_Shaders.GetArrayElementAtIndex(shaderIndex); + + SerializedProperty first = pair.FindPropertyRelative("first"); + + Shader currentShader = first.objectReferenceValue as Shader; + + if (currentShader == shader) + { + m_Shaders.DeleteArrayElementAtIndex(shaderIndex); + break; + } + } + + serializedObject.ApplyModifiedProperties(); + } + + private bool VariantCompare(SerializableShaderVariant l, SerializableShaderVariant r) + { + if (l.shader != r.shader) + return false; + + if (l.passType != r.passType) + return false; + + if (l.keywords.Length != r.keywords.Length) + return false; + + return l.keywords.OrderBy(s => s).SequenceEqual(r.keywords.OrderBy(t => t)); + } + + public bool HasVariant(ShaderVariantCollection.ShaderVariant variant) + { + bool collectionHasVariant = mCollection.Contains(variant); + + bool mapperHasVariant = + mMapper.ContainsKey(variant.shader) && mMapper[variant.shader].FindIndex(v=>VariantCompare(new SerializableShaderVariant(variant), v)) != -1; + + Debug.Assert(collectionHasVariant == mapperHasVariant, "map对象与源文件内容不符"); + return collectionHasVariant; + } + + public bool AddVariant(ShaderVariantCollection.ShaderVariant variant) + { + if (!mCollection.Add(variant)) + return false; + + if (!mMapper.ContainsKey(variant.shader)) + mMapper.Add(variant.shader, new List()); + + mMapper[variant.shader].Add(new SerializableShaderVariant(variant)); + + return true; + } + + public bool RemoveVariant(ShaderVariantCollection.ShaderVariant variant) + { + if (!mCollection.Remove(variant)) + return false; + + if (mMapper.TryGetValue(variant.shader, out var variantList)) + { + int index = variantList.FindIndex(v => VariantCompare(new SerializableShaderVariant(variant), v)); + Debug.Assert(index != -1, "map对象与源文件内容不符,无法在map对象中找到变体"); + variantList.RemoveAt(index); + + return true; + } + + Debug.Assert(false, "map对象与源文件内容不符,无法在map对象中找到Shader"); + return false; + } + + private ShaderVariantCollection.ShaderVariant PropToObject(Shader shader, SerializedProperty variantInfo) + { + PassType passType = (PassType)variantInfo.FindPropertyRelative("passType").intValue; + string keywords = variantInfo.FindPropertyRelative("keywords").stringValue; + string[] keywordSet = keywords.Split(' '); + ShaderVariantCollection.ShaderVariant newVariant = new ShaderVariantCollection.ShaderVariant() + { + shader = shader, + keywords = keywordSet, + passType = passType + }; + + return newVariant; + } + + public void Merge(ShaderVariantCollection otherFile) + { + if (otherFile == null) + return; + + SerializedObject serializedOther = new UnityEditor.SerializedObject(otherFile); + SerializedProperty m_Shaders = serializedOther.FindProperty("m_Shaders"); + + for (int i = 0; i < m_Shaders.arraySize; ++i) + { + SerializedProperty pair = m_Shaders.GetArrayElementAtIndex(i); + + SerializedProperty first = pair.FindPropertyRelative("first"); + SerializedProperty second = pair.FindPropertyRelative("second");//ShaderInfo + + Shader shader = first.objectReferenceValue as Shader; + + SerializedProperty variants = second.FindPropertyRelative("variants"); + for (var vi = 0; vi < variants.arraySize; ++vi) + { + SerializedProperty variantInfo = variants.GetArrayElementAtIndex(vi); + + ShaderVariantCollection.ShaderVariant newVariant = PropToObject(shader, variantInfo); + if (!mCollection.Contains(newVariant)) + { + mCollection.Add(newVariant); + } + } + } + + ReadFromFile(); + } + + public void Refresh() => ReadFromFile(); + + public void SetSerializeFlag(bool serialize) => mSerializedFlag = serialize; + + public void OnBeforeSerialize() + { + if (!mSerializedFlag) + { + return; + } + + if (mMapper == null) + mMapper = new Dictionary>(); + + mMapperSerializeKeys.Clear(); + mMapperSerializeValues.Clear(); + + foreach (var kvp in mMapper) + { + mMapperSerializeKeys.Add(kvp.Key); + //序列化与反序列化都需要浅拷贝一层引用,否则对map的value的list操作,依旧会改变序列化中的数值 + mMapperSerializeValues.Add(new ListWrapper(kvp.Value.ToList())); + } + } + + public void OnAfterDeserialize() + { + if (mMapper == null) + mMapper = new Dictionary>(); + + mMapper.Clear(); + for (int i = 0; i < mMapperSerializeKeys.Count; ++i) + { + mMapper.Add(mMapperSerializeKeys[i], mMapperSerializeValues[i].list.ToList()); + } + } + } + +} \ No newline at end of file diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionMapper.cs.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionMapper.cs.meta new file mode 100644 index 0000000..2aebbab --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionMapper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5724dcb96cddd1142888c677d7f16149 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionMaterialVariantConverter.cs b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionMaterialVariantConverter.cs new file mode 100644 index 0000000..40513c1 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionMaterialVariantConverter.cs @@ -0,0 +1,344 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Soco.ShaderVariantsCollection; +using UnityEditor; +using UnityEngine; +using UnityEngine.Rendering; + +public class ShaderVariantCollectionMaterialVariantConverter +{ + //Key-材质 + //Value-材质被哪个收集器采集 + private Dictionary> mMaterials = new Dictionary>(); + + //用于缓存Shader包含哪些keyword + private Dictionary mCachedKeywords = new Dictionary(); + + //存储已经添加的变体 + //列表存放的是,去重、排序后组合成的字符串,当字符串加入到列表中,代表这一keyword序列所有可能的变体都被加入到变体列表中 + private Dictionary> mInsertedVariants = new Dictionary>(); + + private List mVariants = new List(); + + //获取shader keyword方法,需要反射获取 + private static MethodInfo _GetShaderGlobalKeywordsMethod = null; + private static MethodInfo _GetShaderLocalKeywordsMethod = null; + + private static MethodInfo GetShaderGlobalKeywordsMethod + { + get + { + if (_GetShaderGlobalKeywordsMethod == null) + _GetShaderGlobalKeywordsMethod = typeof(ShaderUtil).GetMethod("GetShaderGlobalKeywords", + BindingFlags.NonPublic | BindingFlags.Static); + + return _GetShaderGlobalKeywordsMethod; + } + } + + private static MethodInfo GetShaderLocalKeywordsMethod + { + get + { + if (_GetShaderLocalKeywordsMethod == null) + _GetShaderLocalKeywordsMethod = typeof(ShaderUtil).GetMethod("GetShaderLocalKeywords", + BindingFlags.NonPublic | BindingFlags.Static); + + return _GetShaderLocalKeywordsMethod; + } + } + + public static string[] GetShaderKeywords(Shader shader) + { + string[] globalKeywords = GetShaderGlobalKeywordsMethod.Invoke(null, new object[] { shader }) as string[]; + string[] localKeywords = GetShaderLocalKeywordsMethod.Invoke(null, new object[] { shader }) as string[]; + /* + foreach (var item in globalKeywords) + { + Debug.LogError("global keyword "+ item+" shader name "+shader.name); + } + foreach (var item in localKeywords) + { + Debug.LogError("local keyword " + item + " shader name " + shader.name); + } + */ + return globalKeywords.Concat(localKeywords).ToArray(); + } + + public bool CollectMaterial(IEnumerable collectors) + { + mMaterials.Clear(); + List materials = new List(); + + bool success = false; + + try + { + int collectorIndex = 0; + int collectorListCount = collectors.Count(); + foreach (IMaterialCollector collector in collectors) + { + EditorUtility.DisplayProgressBar("材质收集", $"正在处理第{collectorIndex + 1}/{collectorListCount}个 --{collector.name}", + (float)collectorIndex / (float)collectorListCount); + materials.Clear(); + collector.AddMaterialBuildDependency(materials); + foreach (Material material in materials) + { + if (!mMaterials.TryGetValue(material, out List fromCollect)) + { + fromCollect = new List(); + mMaterials.Add(material, fromCollect); + } + + fromCollect.Add(collector); + } + + collectorIndex++; + } + + Debug.Log($"[材质收集]共收集到{mMaterials}个材质"); + + success = true; + } + finally + { + EditorUtility.ClearProgressBar(); + } + + return success; + } + + public bool FilterMaterial(IEnumerable materialFilters) + { + var deleteList = mMaterials + .Where(kv => materialFilters.Any(mf => !mf.Filter(kv.Key, kv.Value))) + .Select(kv => kv.Key); + + foreach (var deleteMat in deleteList) + mMaterials.Remove(deleteMat); + + return true; + } + + public bool FilterMaterial(IEnumerable variantFilters) + { + mVariants.RemoveAll(variant => variantFilters.Any(vf => !vf.Filter(variant))); + return true; + } + + //查看keyword是否属于shader,用于去除无效keyword + public bool IsKeywordBelongToShader(Shader shader, string keyword) + { + if (!mCachedKeywords.TryGetValue(shader, out string[] keywords)) + { + keywords = GetShaderKeywords(shader); + mCachedKeywords.Add(shader, keywords); + } + + return keywords.Contains(keyword); + } + + private bool AddVariant(ShaderVariantCollection.ShaderVariant variant) + { + int findIndex = mVariants.FindIndex(v => + { + return v.shader == variant.shader + && v.passType == variant.passType + && v.keywords.SequenceEqual(variant.keywords); + }); + + if (findIndex < 0) + { + mVariants.Add(variant); + } + + return findIndex < 0; + } + + private bool IsValidVariant(Shader shader, PassType passType, string[] keywords) + { + try + { + ShaderVariantCollection.ShaderVariant testVariant + = new ShaderVariantCollection.ShaderVariant(shader, passType, keywords); + + return true; + } + catch + { + return false; + } + } + + private readonly string[] mSingleKeywords = new string[1]; + private bool IsKeywordInPass(Shader shader, PassType passType, string keyword) + { + mSingleKeywords[0] = keyword; + return IsValidVariant(shader, passType, mSingleKeywords); + } + + private readonly string[] mEmptyKeywords = new string[0]; + private bool IsPassExist(Shader shader, PassType passType) + { + return IsValidVariant(shader, passType, mEmptyKeywords); + } + + + private List mTempInsertKeywords = new List(); + private List mTempSortedKeywords = new List(); + + private void AddVariantFromKeywords(Shader shader, List validKeywords) + { + //如果keyword为空,直接尝试加入变体 + if (validKeywords.Count == 0) + { + //循环尝试所有Pass是否能加入 + for (PassType passType = (PassType)Enum.GetValues(typeof(PassType)).Cast().Min(); + passType <= (PassType)Enum.GetValues(typeof(PassType)).Cast().Max(); + ++passType) + { + if (!IsPassExist(shader, passType)) + continue; + + AddVariant(new ShaderVariantCollection.ShaderVariant(shader, passType, mEmptyKeywords)); + } + + return; + } + + + foreach (string keyword in validKeywords) + { + for (PassType passType = (PassType)Enum.GetValues(typeof(PassType)).Cast().Min(); + passType <= (PassType)Enum.GetValues(typeof(PassType)).Cast().Max(); + ++passType) + { + //如果当前pass没有这个keyword,跳过 + if (!IsKeywordInPass(shader, passType, keyword)) + continue; + + mTempInsertKeywords.Clear(); + mTempInsertKeywords.Add(keyword); + + //遍历其他keyword,逐个添加进组合,找到对于这个keyword的最长的有效组合 + foreach (string currentKeyword in validKeywords) + { + if (currentKeyword == keyword) + continue; + + mTempInsertKeywords.Add(currentKeyword); + + //需要有序来检查Sequence Equal + mTempSortedKeywords.Clear(); + mTempSortedKeywords.AddRange(mTempInsertKeywords); + mTempSortedKeywords.Sort(); + + //如果加入当前keyword后,变体无效,则将当前keyword去掉 + if (!IsValidVariant(shader, passType, mTempSortedKeywords.ToArray())) + mTempInsertKeywords.RemoveAt(mTempInsertKeywords.Count - 1); + } + + mTempInsertKeywords.Sort(); + AddVariant(new ShaderVariantCollection.ShaderVariant(shader, passType, mTempInsertKeywords.ToArray())); + } + } + } + + public bool CollectVariant() + { + mCachedKeywords.Clear(); + mInsertedVariants.Clear(); + mVariants.Clear(); + + List validKeywords = new List(); + + int materialIndex = 0; + + bool success = false; + + try + { + foreach (Material material in mMaterials.Keys) + { + EditorUtility.DisplayProgressBar("变体收集-材质与变体转换", + $"正在处理第{materialIndex}/{mMaterials.Keys.Count}个材质 --{material.name}", + (float)materialIndex / (float)mMaterials.Keys.Count); + + Shader shader = material.shader; + + validKeywords.Clear(); + validKeywords.AddRange(material.shaderKeywords.Distinct()); //去重 + validKeywords.RemoveAll(keyword => !IsKeywordBelongToShader(shader, keyword)); //去除没有的变体 + validKeywords.Sort(); + + //检查keyword序列是否已添加,如果是则跳过 + string keywordsKey = string.Join(" ", validKeywords); + if (mInsertedVariants.TryGetValue(shader, out List collectedVariant)) + { + if (collectedVariant.Contains(keywordsKey)) + continue; + } + else + { + collectedVariant = new List(); + mInsertedVariants.Add(shader, collectedVariant); + } + + AddVariantFromKeywords(shader, validKeywords); + materialIndex++; + } + foreach (var item in mInsertedVariants) + { + var shader = item.Key; + AddVariantFromKeywords(shader, new List()); + } + + success = true; + } + catch (Exception e) + { + Debug.LogError( + $"[材质变体转换]正在处理第{materialIndex}个材质{mMaterials.ElementAt(materialIndex).Key.name}\n报错信息为:{e.Message}\nStackTrace:{e.StackTrace}"); + } + finally + { + EditorUtility.ClearProgressBar(); + } + + Debug.Log($"[材质变体转换]总共加入{mVariants.Count}个变体"); + return success; + } + + public IEnumerable GetMaterials() + { + return mMaterials.Keys; + } + + public int GetVariantCount() + { + return mVariants.Count; + } + + public IEnumerable GetMaterialFrom(Material material) + { + if (mMaterials.TryGetValue(material, out var fromList)) + { + return fromList; + } + + return new IMaterialCollector[0]; + } + + public void WriteToShaderVariantCollectionFile(ShaderVariantCollection collection) + { + //Debug.LogError("begin WriteToShaderVariantCollectionFile"); + foreach (var variant in mVariants) + { + // Debug.LogError("do WriteToShaderVariantCollectionFile"+ variant.shader.name); + collection.Add(variant); + } + //Debug.LogError("end WriteToShaderVariantCollectionFile"); + } +} diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionMaterialVariantConverter.cs.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionMaterialVariantConverter.cs.meta new file mode 100644 index 0000000..86393f2 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionMaterialVariantConverter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2606055006b6cd242a7b48e333d2b295 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionToolConfig.cs b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionToolConfig.cs new file mode 100644 index 0000000..bbbdac5 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionToolConfig.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +namespace Soco.ShaderVariantsCollection +{ + [System.Serializable] + public class ToggleObject + { + [SerializeReference] + public ScriptableObject obj; + public bool use; + } + + //解决嵌套list序列化问题 + [System.Serializable] + public struct ListWrapper + { + public List list; + public ListWrapper(List list) => this.list = list; + } + + [CreateAssetMenu(menuName = "Soco/ShaderVariantCollectionTools/Create Config")] + public class ShaderVariantCollectionToolConfig : ScriptableObject, ISerializationCallbackReceiver + { + private Dictionary> mToggleObjects = new Dictionary>(); + + [SerializeField] private List mKeys = new List(); + [SerializeField] private List mValues = new List(); + public void OnBeforeSerialize() + { + mKeys.Clear(); + mValues.Clear(); + + foreach (var kvp in mToggleObjects) + { + mKeys.Add(kvp.Key.AssemblyQualifiedName); + mValues.Add(new ListWrapper(kvp.Value)); + } + } + public void OnAfterDeserialize() + { + mToggleObjects.Clear(); + for (int i = 0; i < mKeys.Count; ++i) + { + System.Type type = System.Type.GetType(mKeys[i]); + if (type != null) + { + mToggleObjects.Add(type, mValues[i].list); + } + } + } + + public List GetToggleObjectList(System.Type type) + { + if (!mToggleObjects.TryGetValue(type, out var list)) + { + list = new List(); + mToggleObjects.Add(type, list); + } + + return list; + } + + public void AddToggleObject(ToggleObject obj) + { + GetToggleObjectList(obj.obj.GetType().BaseType).Add(obj); + } + + public void RemoveToggleObject(ToggleObject obj) + { + GetToggleObjectList(obj.obj.GetType().BaseType).Remove(obj); + } + } + + public class ToolDefaultEditor : Editor + { + public override void OnInspectorGUI() + { + base.OnInspectorGUI(); + } + } + + public abstract class ShaderVariantCollectionToolEditor : Editor + { + } + + [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] + public sealed class ShaderVariantCollectionToolEditorAttribute : Attribute + { + public readonly Type componentType; + + public ShaderVariantCollectionToolEditorAttribute(Type componentType) + { + this.componentType = componentType; + } + } +} diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionToolConfig.cs.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionToolConfig.cs.meta new file mode 100644 index 0000000..7cec600 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionToolConfig.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d22892cb17f31f84cb4c273d63a7e13f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionToolWindow.cs b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionToolWindow.cs new file mode 100644 index 0000000..16cbebf --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionToolWindow.cs @@ -0,0 +1,1245 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEngine; +using UnityEngine.Rendering; +using Object = UnityEngine.Object; + +namespace Soco.ShaderVariantsCollection +{ + + public class ShaderVariantCollectionToolsWindow : EditorWindow + { + private enum FeatureViewState + { + None, + ShaderVariantIndex, + CollectionTool, + BatchTool, + } + + private static Vector2 cMinWindowSize = new Vector2(1200, 600); + private static ShaderVariantCollectionToolsWindow mwindow; + public static ShaderVariantCollectionToolsWindow Window + { + get + { + if (mwindow == null) + { + mwindow = EditorWindow.GetWindow("ShaderVariantCollectionTools"); + mwindow.minSize = cMinWindowSize; + } + return mwindow; + } + } + + private ShaderVariantCollection mCollectionFile; + [SerializeField] + private ShaderVariantCollectionMapper mCollectionMapper; + + private ShaderVariantCollectionMapper collectionMapper + { + get + { + if (mCollectionMapper == null || mCollectionMapper.mCollection != mCollectionFile) + { + mCollectionMapper = new ShaderVariantCollectionMapper(mCollectionFile); + if(mShaderViewSelectedShader != null) + CollectPassKeywordMap(collectionMapper.GetShaderVariants(mShaderViewSelectedShader)); + } + + return mCollectionMapper; + } + } + + private ShaderVariantCollectionToolConfig mConfig; + + private FeatureViewState mCurrentFeatureState; + private Vector2 mFeatureViewScrollViewPos = Vector2.zero; + private Vector2 mWorkViewScrollViewPos = Vector2.zero; + + private void ResetFeatureView() + { + mCurrentFeatureState = FeatureViewState.None; + } + + #region ShaderVariantIndex + + private Shader mWillInsertShader; + [SerializeField] + private Shader mShaderViewSelectedShader; + private string mFilterShaderName = ""; + [SerializeField] + private List mFilterShaders = new List(); + + [Serializable] + private class CachePassData + { + public PassType passType; + public List variants; + public bool toggleValue; + } + + [SerializeField] + private List mPassVariantCacheData = new List(); + + private void ResetShaderView() + { + mShaderViewSelectedShader = null; + mFeatureViewScrollViewPos = Vector2.zero; + mWorkViewScrollViewPos = Vector2.zero; + mPassVariantCacheData.Clear(); + } + + private void CollectPassKeywordMap(IEnumerable variants) + { + mPassVariantCacheData.Clear(); + + foreach (var variant in variants) + { + int findRes = mPassVariantCacheData.FindIndex(data => data.passType == variant.passType); + CachePassData pass; + if (findRes < 0) + { + pass = new CachePassData() + { + passType = variant.passType, + variants = new List(), + toggleValue = false + }; + mPassVariantCacheData.Add(pass); + } + else + { + pass = mPassVariantCacheData[findRes]; + } + + pass.variants.Add(new SerializableShaderVariant(variant)); + } + } + + //这个方法不会导致Pass重新折叠 + public void RefreshPassKeywordMap(Shader currentShader) + { + //如果当前Shader已经变了,则不需要操作 + if (currentShader != mShaderViewSelectedShader) + return; + + //否则刷新数据 + Dictionary toggleData = new Dictionary(); + foreach (CachePassData data in mPassVariantCacheData) + { + toggleData.Add(data.passType, data.toggleValue); + } + + CollectPassKeywordMap(collectionMapper.GetShaderVariants(currentShader)); + + foreach (CachePassData data in mPassVariantCacheData) + { + if (toggleData.TryGetValue(data.passType, out bool toggleValue)) + data.toggleValue = toggleValue; + } + } + #endregion + + #region CollectionTool + + private enum CollectionViewState + { + CollectorList, + MaterialFilter, + VariantFilter, + MaterialFrom + } + + private int mSelectedInterfaceImplIndex; + private CollectionViewState mCollectionViewState = CollectionViewState.CollectorList; + private bool mOverrideFile = false; + + private ShaderVariantCollectionMaterialVariantConverter mConverter = + new ShaderVariantCollectionMaterialVariantConverter(); + + private Material mTestMaterial = null; + + #endregion + + #region BatchTool + private enum BatchToolViewState + { + ExecutorList, + MergeFile, + SplitFile, + MaxCount + } + + private static GUIContent[] sBatchToolViewStateStyles = new GUIContent[] + { + new GUIContent("执行器列表", "打开执行器列表"), + new GUIContent("合并文件", "将另一个变体收集文件的内容合并到当前文件"), + new GUIContent("分割文件", "自动将变体收集文件分割为数个文件"), + }; + + private BatchToolViewState mBatchToolViewState = BatchToolViewState.ExecutorList; + private ShaderVariantCollection mOtherCollectionFile; + + private enum SplitMode + { + VariantCount, + FixedFileCount + } + + private SplitMode mSplitMode = SplitMode.VariantCount; + + private static string[] sSplitModeStr = new string[] + { + "按照变体数量切割", + "固定变体收集文件", + }; + + private string mSplitFileOutputPath = ""; + private bool mSplitFileNoSplitShader = true; + private bool mSplitFileNoSplitPass = true; + private int mSplitFileMaxVariantLimit = 50; + private int mSplitFileFixedCount = 10; + #endregion + + private GUIStyle mBlackStyle, mItemStyle; + + private static int cBorderWidth = 10; + private static int cLeftWidth = 400; + private static int cLeftTopHeight = 100; + private static int cLeftMiddleHeight = 100; + private static int cMiddleWidth = 20; + + [MenuItem("Tools/Soco/ShaderVariantCollectionTools/OpenWindow", priority = 200)] + public static void OpenWindow() + { + Window.Show(); + } + + public void OnGUI() + { + EditorGUILayout.Space(cBorderWidth); + GUILayout.BeginHorizontal(GUILayout.ExpandHeight(true), GUILayout.ExpandWidth(true)); + + #region 左半部分 + EditorGUILayout.BeginVertical(GUILayout.Width(cLeftWidth)); + + #region 左上部分 收集文件选择 配置文件选择 + EditorGUILayout.BeginVertical(mBlackStyle, GUILayout.MinHeight(cLeftTopHeight)); + + EditorGUILayout.LabelField("变体收集文件:"); + + Color oriColor = GUI.color; + if (mCollectionFile == null) + GUI.color = Color.red; + ShaderVariantCollection newCollectionFile = EditorGUILayout.ObjectField(mCollectionFile, typeof(ShaderVariantCollection), false) as ShaderVariantCollection; + GUI.color = oriColor; + + if (newCollectionFile != mCollectionFile) + { + SaveObject(mCollectionFile); + mCollectionFile = newCollectionFile; + + ResetShaderView(); + } + + EditorGUILayout.LabelField("工具配置文件:"); + + var newConfig = EditorGUILayout.ObjectField(mConfig, typeof(ShaderVariantCollectionToolConfig), false) as ShaderVariantCollectionToolConfig; + if (newConfig != mConfig) + { + SaveObject(mConfig); + mConfig = newConfig; + + } + + EditorGUILayout.EndVertical(); + #endregion + + EditorGUILayout.Space(cBorderWidth); + + #region 左中部分 功能选择 + EditorGUILayout.BeginVertical(mBlackStyle, GUILayout.MinHeight(cLeftMiddleHeight)); + EditorGUILayout.LabelField("功能选择"); + if (mCollectionFile != null) + { + if (GUILayout.Button(new GUIContent("快速浏览", "快速浏览变体收集文件内容"),GUILayout.ExpandWidth(true))) + { + mCurrentFeatureState = FeatureViewState.ShaderVariantIndex; + ResetShaderView(); + } + + if (GUILayout.Button(new GUIContent("项目收集工具", "自动收集项目打包所需变体"), GUILayout.ExpandWidth(true))) + { + mCurrentFeatureState = FeatureViewState.CollectionTool; + mFeatureViewScrollViewPos = Vector2.zero; + mWorkViewScrollViewPos = Vector2.zero; + mSelectedInterfaceImplIndex = 0; + mCollectionViewState = CollectionViewState.CollectorList; + } + + if (GUILayout.Button(new GUIContent("批处理工具", "批量处理变体收集文件"), GUILayout.ExpandWidth(true))) + { + mCurrentFeatureState = FeatureViewState.BatchTool; + mFeatureViewScrollViewPos = Vector2.zero; + mWorkViewScrollViewPos = Vector2.zero; + } + } + EditorGUILayout.EndVertical(); + #endregion + + EditorGUILayout.Space(cBorderWidth); + + #region 左下部分 次级选项 + EditorGUILayout.BeginVertical(mBlackStyle, GUILayout.MinHeight(position.height - cLeftTopHeight - cLeftMiddleHeight - 4 * cBorderWidth)); + + if (mCollectionFile != null) + { + if (mCurrentFeatureState == FeatureViewState.ShaderVariantIndex) + { + EditorGUILayout.LabelField("Shader View"); + + EditorGUILayout.BeginHorizontal(); + mWillInsertShader = EditorGUILayout.ObjectField(mWillInsertShader, typeof(Shader)) as Shader; + if (GUILayout.Button("添加")) + { + if (!collectionMapper.HasShader(mWillInsertShader)) + { + UndoShaderVariantCollectionTool(); + collectionMapper.AddShader(mWillInsertShader); + //添加Shader后,更新Filter列表 + if (mFilterShaderName != "" && + mWillInsertShader.name.IndexOf(mFilterShaderName, StringComparison.OrdinalIgnoreCase) >= 0 && + !mFilterShaders.Contains(mWillInsertShader)) + { + mFilterShaders.Add(mWillInsertShader); + } + } + else + ShowNotification(new GUIContent($"Shader:{mWillInsertShader}已存在于当前变体收集文件")); + } + EditorGUILayout.EndHorizontal(); + + #region 过滤名称 + string prevFilterShaderName = mFilterShaderName; + mFilterShaderName = EditorGUILayout.TextField("过滤", mFilterShaderName); + if (mFilterShaderName == "") + { + mFilterShaders.Clear(); + } + else if (prevFilterShaderName != mFilterShaderName) + { + FilterShader(); + } + #endregion + + if (collectionMapper.shaders.Count > 0 && GUILayout.Button(new GUIContent("Clear", "清空变体收集文件"), GUILayout.Width(cLeftWidth))) + { + if (EditorUtility.DisplayDialog("确认", "是否确认清空文件", "是", "否")) + { + UndoShaderVariantCollectionTool(); + mCollectionFile.Clear(); + collectionMapper.Refresh(); + mShaderViewSelectedShader = null; + mPassVariantCacheData.Clear(); + mFilterShaders.Clear(); + } + } + + //分割线 + EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); + + mFeatureViewScrollViewPos = EditorGUILayout.BeginScrollView(mFeatureViewScrollViewPos); + + IEnumerable displayList = + (mFilterShaderName == "" ? (collectionMapper.shaders as IEnumerable): mFilterShaders); + + Shader removeShader = null; + + Color oriGUIColor = GUI.color; + foreach (var shader in displayList) + { + EditorGUILayout.BeginHorizontal(GUILayout.Width(cLeftWidth)); + + if (shader == mShaderViewSelectedShader) + GUI.color = Color.green; + + if (GUILayout.Button(new GUIContent(shader.name, shader.name), + GUILayout.Width(cLeftWidth - 30))) + { + if (mShaderViewSelectedShader == shader)//选中状态下再次选择,在项目中定位 + { + Selection.activeObject = shader; + EditorGUIUtility.PingObject(shader); + } + + mShaderViewSelectedShader = shader; + CollectPassKeywordMap(collectionMapper.GetShaderVariants(shader)); + } + GUI.color = oriGUIColor; + + if (GUILayout.Button("-", GUILayout.Width(20))) + { + removeShader = shader; + } + EditorGUILayout.EndHorizontal(); + } + + if (removeShader != null) + { + UndoShaderVariantCollectionTool(); + collectionMapper.RemoveShader(removeShader); + mFilterShaders.Remove(removeShader); + + if (removeShader == mShaderViewSelectedShader) + { + mShaderViewSelectedShader = null; + mPassVariantCacheData.Clear(); + } + + } + + EditorGUILayout.EndScrollView(); + } + + if (mCurrentFeatureState == FeatureViewState.BatchTool) + { + EditorGUILayout.LabelField("Tools View"); + + for (BatchToolViewState state = (BatchToolViewState)0; state < BatchToolViewState.MaxCount; ++state) + { + Color oriStateColor = GUI.color; + if (state == mBatchToolViewState) + GUI.color = Color.green; + + if (GUILayout.Button(sBatchToolViewStateStyles[(int)state], GUILayout.ExpandWidth(true))) + { + mBatchToolViewState = state; + } + + GUI.color = oriStateColor; + } + + // if (GUILayout.Button(, GUILayout.ExpandWidth(true))) + // { + // mBatchToolViewState = BatchToolViewState.ExecutorList; + // } + // + // if (GUILayout.Button(, GUILayout.ExpandWidth(true))) + // { + // mBatchToolViewState = BatchToolViewState.MergeFile; + // } + // + // if (GUILayout.Button(, GUILayout.ExpandWidth(true))) + // { + // mBatchToolViewState = BatchToolViewState.SplitFile; + // } + } + + if (mCurrentFeatureState == FeatureViewState.CollectionTool) + { + EditorGUILayout.LabelField("Collection View"); + + mOverrideFile = EditorGUILayout.Toggle("是否覆盖源文件内容", mOverrideFile); + if (GUILayout.Button(new GUIContent("一键收集变体", "一键收集变体"), GUILayout.ExpandWidth(true))) + { + if (EditorUtility.DisplayDialog("确认", "是否开始一键收集变体", "是", "否") && ConfirmOverride()) + { + var _ = CollectMaterial() + && FilterMaterial() + && mConverter.CollectVariant() + && FilterVariant() + && WriteCollectedVariantToFile(); + } + } + + EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); + + int materialCount = mConverter.GetMaterials().Count(); + string materialCountStr = materialCount > 0 ? $"({materialCount})" : ""; + if (GUILayout.Button(new GUIContent("收集材质" + materialCountStr, "利用有效收集器收集文件"), GUILayout.ExpandWidth(true))) + { + var _ = CollectMaterial() && FilterMaterial(); + } + + int variantCount = mConverter.GetVariantCount(); + string variantCountStr = variantCount > 0 ? $"({variantCount})" : ""; + if (GUILayout.Button(new GUIContent("材质变体收集" + variantCountStr, "将收集到材质的keywords转换为有效变体"), GUILayout.ExpandWidth(true))) + { + var _ = mConverter.CollectVariant() && FilterVariant(); + } + + if (GUILayout.Button(new GUIContent("写入收集文件", "将收集到的变体写入变体收集文件"), GUILayout.ExpandWidth(true))) + { + if (EditorUtility.DisplayDialog("确认", "是否确认写入变体收集文件", "是", "否") && ConfirmOverride()) + { + WriteCollectedVariantToFile(); + } + } + + EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); + + if (GUILayout.Button(new GUIContent("材质收集器列表", "当前配置文件下的材质收集器"), GUILayout.ExpandWidth(true))) + { + mCollectionViewState = CollectionViewState.CollectorList; + mSelectedInterfaceImplIndex = 0; + } + + if (GUILayout.Button(new GUIContent("材质过滤", "根据条件排除收集到的材质"), GUILayout.ExpandWidth(true))) + { + mCollectionViewState = CollectionViewState.MaterialFilter; + mSelectedInterfaceImplIndex = 0; + } + + if (GUILayout.Button(new GUIContent("变体过滤", "根据条件排除收集到的变体"), GUILayout.ExpandWidth(true))) + { + mCollectionViewState = CollectionViewState.VariantFilter; + mSelectedInterfaceImplIndex = 0; + } + + if (GUILayout.Button(new GUIContent("材质来源检查", "查找材质被哪个收集器采集"), GUILayout.ExpandWidth(true))) + { + mCollectionViewState = CollectionViewState.MaterialFrom; + } + + + } + } + + EditorGUILayout.EndVertical(); + #endregion + + EditorGUILayout.EndVertical(); + #endregion + + #region 中间分隔线 + EditorGUILayout.BeginVertical(GUILayout.Width(cMiddleWidth)); + EditorGUILayout.Space(10); + EditorGUILayout.EndVertical(); + #endregion + + #region 右半部分 + int rightWidth = (int)(position.width - cLeftWidth - cMiddleWidth - 10); + EditorGUILayout.BeginVertical(mBlackStyle, GUILayout.MinWidth(rightWidth), GUILayout.MinHeight(position.height - cBorderWidth * 2)); + + if (mCollectionFile != null) + { + #region 变体浏览 + if (mCurrentFeatureState == FeatureViewState.ShaderVariantIndex && mShaderViewSelectedShader != null) + { + if (GUILayout.Button("+")) + { + OpenAddVariantWindow(); + } + + //if (mPassKeywordsMap.Count == 0) + if (mPassVariantCacheData.Count == 0) + { + EditorGUILayout.LabelField("当前Shader没有变体被收集"); + } + + //bool modify = false; + //PassType modifyKey = PassType.Normal; + //(List list, bool toggle) modifyValue = (null, false); + + int keyowrdWidth = rightWidth - 20; + int minusWidth = 20; + + bool removeVariant = false; + // PassType removePassType = PassType.Normal; + // string[] removeKeywords = null; + ShaderVariantCollection.ShaderVariant removedVariant = default; + + mWorkViewScrollViewPos = EditorGUILayout.BeginScrollView(mWorkViewScrollViewPos); + //foreach (KeyValuePair list, bool toggle)> pair in mPassKeywordsMap) + foreach (CachePassData cacheData in mPassVariantCacheData) + { + //var passType = pair.Key; + //var keywordsListTuple = pair.Value; + + cacheData.toggleValue = EditorGUILayout.Foldout(cacheData.toggleValue, $"{cacheData.passType.ToString()}({cacheData.variants.Count})"); + // if (newToggle != keywordsListTuple.toggle) + // { + // modify = true; + // modifyKey = passType; + // modifyValue = (keywordsListTuple.list, newToggle); + // } + + if (cacheData.toggleValue) + { + foreach (SerializableShaderVariant variant in cacheData.variants) + { + EditorGUILayout.BeginHorizontal(GUILayout.Width(rightWidth)); + if(variant.keywords.Length == 0) + EditorGUILayout.LabelField("", GUILayout.Width(keyowrdWidth)); + else + EditorGUILayout.LabelField(string.Join(", ", variant.keywords), GUILayout.Width(keyowrdWidth)); + + if (GUILayout.Button("-", GUILayout.Width(minusWidth))) + { + removeVariant = true; + removedVariant = variant.Deserialize(); + // removePassType = cacheData.passType; + // removeKeywords = variant.keywords; + } + EditorGUILayout.EndHorizontal(); + } + + if (GUILayout.Button("+")) + { + OpenAddVariantWindow(cacheData.passType); + } + } + } + EditorGUILayout.EndScrollView(); + + // if (modify) + // mPassKeywordsMap[modifyKey] = modifyValue; + + if (removeVariant) + { + UndoShaderVariantCollectionTool(); + // collectionMapper.RemoveVariant( + // new ShaderVariantCollection.ShaderVariant(mShaderViewSelectedShader, removePassType, + // removeKeywords)); + collectionMapper.RemoveVariant(removedVariant); + + //CollectPassKeywordMap(collectionMapper.GetShaderVariants(mShaderViewSelectedShader)); + RefreshPassKeywordMap(mShaderViewSelectedShader); + } + + } + #endregion + + #region 项目变体收集工具F + + if (mCurrentFeatureState == FeatureViewState.CollectionTool) + { + + #region 材质收集器列表 + if (mCollectionViewState == CollectionViewState.CollectorList) + { + DrawInterfaceList("材质收集器", rightWidth); + } + #endregion + #region 材质收集过滤 + else if (mCollectionViewState == CollectionViewState.MaterialFilter) + { + DrawInterfaceList("材质过滤器", rightWidth); + } + #endregion + #region 变体收集剔除 + else if (mCollectionViewState == CollectionViewState.VariantFilter) + { + DrawInterfaceList("变体过滤器", rightWidth); + } + #endregion + #region 材质来源 + else if (mCollectionViewState == CollectionViewState.MaterialFrom) + { + mTestMaterial = EditorGUILayout.ObjectField("待检测材质", mTestMaterial, typeof(Material)) as Material; + + if (mConverter.GetMaterials().Count() == 0) + { + EditorGUILayout.LabelField("当前未收集到材质,请收集材质,或检查收集代码后重新收集材质"); + } + else if (mTestMaterial != null) + { + var materialFrom = mConverter.GetMaterialFrom(mTestMaterial); + if(materialFrom.Count() == 0) + EditorGUILayout.LabelField("当前材质没有被收集到"); + else + { + EditorGUILayout.LabelField("来自收集器:"); + foreach (IMaterialCollector collector in materialFrom) + { + if (GUILayout.Button(collector.name)) + { + Selection.activeObject = collector; + EditorGUIUtility.PingObject(collector); + } + } + } + } + } + #endregion + + } + #endregion + + #region 批处理工具 + + if (mCurrentFeatureState == FeatureViewState.BatchTool) + { + #region 执行器列表 + if (mBatchToolViewState == BatchToolViewState.ExecutorList) + { + DrawInterfaceList("批处理执行器", rightWidth); + } + #endregion + #region 合并文件 + else if (mBatchToolViewState == BatchToolViewState.MergeFile) + { + mOtherCollectionFile = EditorGUILayout.ObjectField("需要合并的内容文件", mOtherCollectionFile, typeof(ShaderVariantCollection)) as ShaderVariantCollection; + + if (GUILayout.Button("合并") + && mOtherCollectionFile != null + && mOtherCollectionFile != mCollectionFile + && EditorUtility.DisplayDialog("合并确认", + $"是否确认将{mOtherCollectionFile.name}的内容合并到{mCollectionFile.name}", "确认", "返回")) + { + collectionMapper.Merge(mOtherCollectionFile); + } + } + #endregion + #region 分割文件 + else if (mBatchToolViewState == BatchToolViewState.SplitFile) + { + EditorGUILayout.BeginHorizontal(); + + if (mSplitFileOutputPath == "") + EditorGUILayout.LabelField($"选择输出路径,默认不选为当前变体收集文件路径[{Path.GetDirectoryName(AssetDatabase.GetAssetPath(mCollectionFile))}]"); + else + EditorGUILayout.LabelField($"当前输出路径为[{mSplitFileOutputPath}]"); + + if (GUILayout.Button("选择/改变路径")) + { + string currentPath = string.IsNullOrEmpty(mSplitFileOutputPath) + ? Path.GetDirectoryName(AssetDatabase.GetAssetPath(mCollectionFile)) + : mSplitFileOutputPath; + mSplitFileOutputPath = EditorUtility.OpenFolderPanel("选择输出文件夹", currentPath, "") ?? mSplitFileOutputPath; + + if (!string.IsNullOrEmpty(mSplitFileOutputPath)) + { + string projectPath = + Application.dataPath.Substring(0, Application.dataPath.LastIndexOf("/")); + string relativePath = mSplitFileOutputPath.Substring(projectPath.Length + 1); + mSplitFileOutputPath = relativePath; + } + + } + EditorGUILayout.EndHorizontal(); + + mSplitMode = (SplitMode)EditorGUILayout.Popup("切割模式", (int)mSplitMode, sSplitModeStr); + + if (mSplitMode == SplitMode.VariantCount)//按照每个文件一定变体数分割 + { + mSplitFileMaxVariantLimit = EditorGUILayout.IntField("每个文件最多变体数", mSplitFileMaxVariantLimit); + + EditorGUILayout.BeginHorizontal(); + mSplitFileNoSplitShader = !EditorGUILayout.ToggleLeft(new GUIContent("是否分割同一Shader的变体", + "如不分割,遇到新的Shader的变体数量超标时,会另起一个变体收集文件"), !mSplitFileNoSplitShader); + + //如果可以分割Shader,那么询问是否可以分割Pass + if (!mSplitFileNoSplitShader) + { + mSplitFileNoSplitPass = !EditorGUILayout.ToggleLeft("是否分割Shader下的同一Pass", !mSplitFileNoSplitPass); + } + EditorGUILayout.EndHorizontal(); + } + else if (mSplitMode == SplitMode.FixedFileCount)//按照固定变体收集文件数量分割 + { + mSplitFileFixedCount = EditorGUILayout.IntField("需要分割的文件数", mSplitFileFixedCount); + } + + if (GUILayout.Button("开始分割")) + { + SplitCollectionFile(); + } + } + #endregion + } + + #endregion + } + + EditorGUILayout.EndVertical(); + #endregion + + GUILayout.EndHorizontal(); + } + + private Dictionary mCachedImplements = new Dictionary(); + private Type[] GetInterfaceImplements() where T : ScriptableObject + { + if (!mCachedImplements.TryGetValue(typeof(T), out var impls)) + { + impls = AppDomain.CurrentDomain.GetAssemblies().SelectMany( + assembly => assembly.GetTypes().Where(type => + type.IsSubclassOf(typeof(T)))).ToArray(); + mCachedImplements.Add(typeof(T), impls); + } + + return impls; + } + + private void DrawInterfaceList(string objectName, float uiWidth) where T: ScriptableObject + { + Type[] implements = GetInterfaceImplements(); + if (implements.Length == 0) + { + EditorGUILayout.LabelField($"未找到{typeof(T).Name}的实现类"); + } + else + { + #region 添加对象 + EditorGUILayout.BeginHorizontal(); + mSelectedInterfaceImplIndex = EditorGUILayout.Popup(mSelectedInterfaceImplIndex, implements.Select(i=>i.Name).ToArray(), GUILayout.Width(uiWidth * 0.7f)); + if (GUILayout.Button($"添加{objectName}", GUILayout.Width(uiWidth * 0.3f))) + { + T newObject = CreateInstance(implements[mSelectedInterfaceImplIndex]) as T; + newObject.name = implements[mSelectedInterfaceImplIndex].Name; + Undo.RegisterCreatedObjectUndo(newObject, "Create SCV tool impl object"); + Undo.RecordObject(mConfig, "Impl object list insert"); + mConfig.AddToggleObject(new ToggleObject() + { + obj = newObject, + use = true + }); + AssetDatabase.AddObjectToAsset(newObject, mConfig); + SaveObject(mConfig); + } + EditorGUILayout.EndHorizontal(); + #endregion + + #region 全部执行 + EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); + var objectList = mConfig.GetToggleObjectList(typeof(T)); + bool isExecutor = (typeof(T) == typeof(IExecutable) || typeof(T).IsSubclassOf(typeof(IExecutable))); + + if (objectList.Count > 1 && isExecutor) + { + if (GUILayout.Button(new GUIContent("全部执行", "执行所有执行器")) + && EditorUtility.DisplayDialog("执行确认", "是否执行全部执行器", "确认", "返回")) + { + UndoShaderVariantCollectionTool(); + foreach (ToggleObject to in objectList) + if (to.use) + (to.obj as IExecutable).Execute(collectionMapper); + } + EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); + } + #endregion + + #region 对象列表 + mWorkViewScrollViewPos = EditorGUILayout.BeginScrollView(mWorkViewScrollViewPos); + for (int i = 0; i < objectList.Count; ++i) + { + ToggleObject toggleObject = objectList[i]; + + EditorGUILayout.BeginHorizontal(); + if (GUILayout.Button("删除")) + { + Undo.RecordObject(mConfig, "Impl object remove"); + mConfig.RemoveToggleObject(toggleObject); + AssetDatabase.RemoveObjectFromAsset(toggleObject.obj); + SaveObject(mConfig); + } + + toggleObject.use = EditorGUILayout.ToggleLeft("使用", toggleObject.use); + + EditorGUI.BeginChangeCheck(); + string newName = EditorGUILayout.TextField($"{objectName}名称", toggleObject.obj.name); + if (EditorGUI.EndChangeCheck()) + { + Undo.RecordObject(toggleObject.obj, "Change object name"); + toggleObject.obj.name = newName; + } + + if (isExecutor && GUILayout.Button("执行") && EditorUtility.DisplayDialog("执行确认", "是否执行当前执行器", "确认", "返回")) + { + UndoShaderVariantCollectionTool(); + (toggleObject.obj as IExecutable).Execute(collectionMapper); + } + + if (i != 0 && GUILayout.Button("↑", GUILayout.Width(20))) + { + Undo.RecordObject(mConfig, "Swap object list"); + (objectList[i - 1], objectList[i]) = (objectList[i], objectList[i - 1]); + } + if (i != objectList.Count && GUILayout.Button("↓", GUILayout.Width(20))) + { + Undo.RecordObject(mConfig, "Swap object list"); + (objectList[i], objectList[i + 1]) = (objectList[i + 1], objectList[i]); + } + + EditorGUILayout.EndHorizontal(); + + Editor editor = GetEditor(toggleObject.obj as ScriptableObject); + editor.OnInspectorGUI(); + + EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); + } + EditorGUILayout.EndScrollView(); + #endregion + } + } + + private bool CollectMaterial() + { + return mConverter.CollectMaterial(mConfig.GetToggleObjectList(typeof(IMaterialCollector)) + .Where(co => co.use) + .Select(co => co.obj as IMaterialCollector)); + } + + private bool FilterMaterial() + { + var materialFilters = mConfig.GetToggleObjectList(typeof(IMaterialFilter)) + .Where(mf => mf.use) + .Select(mf => mf.obj as IMaterialFilter); + + return mConverter.FilterMaterial(materialFilters); + } + + private bool FilterVariant() + { + var variantFilters = mConfig.GetToggleObjectList(typeof(IVariantFilter)) + .Where(vf => vf.use) + .Select(vf => vf.obj as IVariantFilter); + + return mConverter.FilterMaterial(variantFilters); + } + + private void OpenAddVariantWindow(PassType passType = PassType.Normal) + { + var window = ShaderVariantCollectionAddVariantWindow.Window; + + window.Setup(mShaderViewSelectedShader, passType, collectionMapper); + window.Show(); + ShowNotification(new GUIContent("已打开添加变体窗口,如未发现请检查窗口是否被当前窗口覆盖")); + } + + private bool ConfirmOverride() + { + if (!mOverrideFile) + return true; + + return EditorUtility.DisplayDialog("覆盖确认", "是否确认覆盖原有收集文件内容", "确认", "返回"); + } + + private void FilterShader() + { + mFilterShaders.Clear(); + + if (mFilterShaderName != "") + { + foreach (var shader in collectionMapper.shaders) + { + if (shader.name.IndexOf(mFilterShaderName, StringComparison.OrdinalIgnoreCase) >= 0) + { + mFilterShaders.Add(shader); + } + } + } + } + + internal void UndoShaderVariantCollectionTool() + { + collectionMapper.SetSerializeFlag(true); + Undo.RecordObject(mCollectionFile, "Change SVC tool"); + Undo.RegisterCompleteObjectUndo(collectionMapper, "Change SVC tool"); + Undo.RegisterCompleteObjectUndo(this, "Change SVC tool"); + collectionMapper.SetSerializeFlag(false); + //Undo.FlushUndoRecordObjects(); + } + + private bool WriteCollectedVariantToFile() + { + try + { + UndoShaderVariantCollectionTool(); + + if (mOverrideFile) + { + mCollectionFile.Clear(); + } + + mConverter.WriteToShaderVariantCollectionFile(mCollectionFile); + collectionMapper.Refresh(); + + //收集完毕写入文件后,更新Filter列表 + FilterShader(); + + return true; + } + catch + { + return false; + } + } + + private Dictionary mCachedEditorTypes = new Dictionary(); + private Type ImplementGetEditor(Type type) + { + if (!mCachedEditorTypes.TryGetValue(type, out var editor)) + { + editor = AppDomain.CurrentDomain.GetAssemblies() + .SelectMany(assembly => assembly.GetTypes() + .Where(t => t.IsSubclassOf(typeof(ShaderVariantCollectionToolEditor)))) + .FirstOrDefault(t => !t.IsAbstract + && t.IsDefined(typeof(ShaderVariantCollectionToolEditorAttribute), false) + && ((ShaderVariantCollectionToolEditorAttribute)t.GetCustomAttributes( + typeof(ShaderVariantCollectionToolEditorAttribute), false)[0]).componentType == + type); + + editor = editor ?? typeof(ToolDefaultEditor); + mCachedEditorTypes.Add(type, editor); + } + + return editor; + } + + private Dictionary mCachedEditor = new Dictionary(); + private Editor GetEditor(ScriptableObject obj) + { + if (!mCachedEditor.TryGetValue(obj, out var editor)) + { + editor = Editor.CreateEditor(obj, ImplementGetEditor(obj.GetType())); + mCachedEditor.Add(obj, editor); + } + + return editor; + } + + private void SaveObject(Object obj) + { + if (obj != null) + { + EditorUtility.SetDirty(obj); + AssetDatabase.SaveAssets(); + AssetDatabase.Refresh(); + } + } + private Texture2D MakeTex(int width, int height, Color col) + { + Color[] pix = new Color[width * height]; + for (int i = 0; i < pix.Length; i++) + pix[i] = col; + Texture2D result = new Texture2D(width, height); + result.SetPixels(pix); + result.Apply(); + return result; + } + private void SetupStyle() + { + if (mBlackStyle == null) + { + Color backColor = EditorGUIUtility.isProSkin ? new Color(0.18f, 0.18f, 0.18f) : new Color(0.7f, 0.7f, 0.7f); + Texture2D _blackTexture; + _blackTexture = MakeTex(4, 4, backColor); + _blackTexture.hideFlags = HideFlags.DontSave; + mBlackStyle = new GUIStyle(); + mBlackStyle.normal.background = _blackTexture; + } + + if (mItemStyle == null) + { + Color itemColor = EditorGUIUtility.isProSkin ? new Color(0.3f, 0.3f, 0.3f) : new Color(0.9f, 0.9f, 0.9f); + Texture2D _itemColorTexture; + _itemColorTexture = MakeTex(4, 4, itemColor); + _itemColorTexture.hideFlags = HideFlags.DontSave; + mItemStyle = new GUIStyle(); + mItemStyle.normal.background = _itemColorTexture; + } + } + + private void CreateIfDefaultConfigIsNull() + { + MonoScript ms = MonoScript.FromScriptableObject(new ShaderVariantCollectionToolConfig()); + string scriptFilePath = AssetDatabase.GetAssetPath(ms); + string scriptDirectoryPath = System.IO.Path.GetDirectoryName(scriptFilePath); + string[] findResultGUID = AssetDatabase.FindAssets("t:ShaderVariantCollectionToolConfig", new string[] { scriptDirectoryPath }); + + if (findResultGUID.Length == 0) + { + ShaderVariantCollectionToolConfig newConfig = ScriptableObject.CreateInstance(); + + AssetDatabase.CreateAsset(newConfig, scriptDirectoryPath +"\\Default ShaderVariantCollection Tool Config.asset"); + AssetDatabase.SaveAssets(); + + mConfig = newConfig; + } + else + { + mConfig = AssetDatabase.LoadAssetAtPath( + AssetDatabase.GUIDToAssetPath(findResultGUID[0])); + } + } + + + private void SplitCollectionFile() + { + List splitItems = + new List(); + + bool splitFileNoSplitShader = mSplitFileNoSplitShader; + bool splitFileNoSplitPass = mSplitFileNoSplitPass; + + //固定输出文件数量下,可以自由切割变体 + if (mSplitMode == SplitMode.FixedFileCount) + { + splitFileNoSplitShader = false; + splitFileNoSplitPass = false; + } + + + //将收集文件拆分成最小的不可分割项 + foreach (Shader shader in collectionMapper.shaders) + { + var variants = collectionMapper.GetShaderVariants(shader); + //如果Shader不可拆分,则Shader作为一个分割整体 + if (splitFileNoSplitShader) + { + splitItems.Add(variants.ToArray()); + } + else + { + var passes = variants.GroupBy(variant => variant.passType); + + foreach (var pass in passes) + { + //如果Pass不可拆分,则Pass作为一个分割整体 + if (splitFileNoSplitPass) + { + splitItems.Add(pass.ToArray()); + } + else + { + foreach (var variant in pass) + { + splitItems.Add(new ShaderVariantCollection.ShaderVariant[1] { variant }); + } + } + } + } + } + + //根据长度排序 + splitItems.Sort((itemX, itemY) => itemX.Length.CompareTo(itemY.Length)); + + int splitFileMaxVariantLimit = mSplitFileMaxVariantLimit; + if (mSplitMode == SplitMode.FixedFileCount) + { + splitFileMaxVariantLimit = Mathf.CeilToInt((float)splitItems.Count / (float)mSplitFileFixedCount); + } + + List outputList = new List(); + ShaderVariantCollection currentCollection = null; + + void CreateCollection() + { + outputList.Add(new ShaderVariantCollection()); + currentCollection = outputList.Last(); + } + + void AddToCollection(ShaderVariantCollection.ShaderVariant[] variants) + { + foreach (var variant in variants) + { + currentCollection.Add(variant); + } + } + + ShaderVariantCollection.ShaderVariant[] PopItem(int index) + { + var item = splitItems[index]; + splitItems.RemoveAt(index); + return item; + } + + while (splitItems.Count > 0) + { + if (outputList.Count == 0) + { + CreateCollection(); + } + + //如果当前收集文件是空的,将最长的不可分割项加入收集文件 + if (outputList.Last().variantCount == 0) + { + //Pop last item + var item = PopItem(splitItems.Count - 1); + AddToCollection(item); + } + else + { + int remainCapacity = splitFileMaxVariantLimit - outputList.Last().variantCount; + + //剩余容量中能装下的最大的Item + int largestItemForRemainCapacity + = splitItems.FindIndex(item => item.Length <= remainCapacity); + + //如果剩余的item中没有能装在当前收集文件中的,则新建收集文件 + if (largestItemForRemainCapacity < 0) + { + CreateCollection(); + var item = PopItem(splitItems.Count - 1); + AddToCollection(item); + } + else + { + var item = PopItem(largestItemForRemainCapacity); + AddToCollection(item); + } + } + } + + string originFilePath = AssetDatabase.GetAssetPath(mCollectionFile); + + string targetDirectory = string.IsNullOrEmpty(mSplitFileOutputPath) + ? Path.GetDirectoryName(originFilePath) + : mSplitFileOutputPath; + string filename = Path.GetFileNameWithoutExtension(originFilePath); + string extension = Path.GetExtension(originFilePath); + + int numberAlign = Mathf.FloorToInt(Mathf.Log10(outputList.Count)) + 1; + string alignStr = $"_{{0:D{numberAlign}}}"; + + int collectionIndex = 0; + foreach (var newCollection in outputList) + { + string number = string.Format(alignStr, collectionIndex++); + string outputPath = targetDirectory + "\\" + filename + number + extension; + + // 保存变体收集文件 + AssetDatabase.CreateAsset(newCollection, outputPath); + } + + //当固定变体文件数量时,不足的文件数量也需要补足 + if (mSplitMode == SplitMode.FixedFileCount) + { + for (; collectionIndex < mSplitFileFixedCount; ++collectionIndex) + { + string number = string.Format(alignStr, collectionIndex); + string outputPath = targetDirectory + "\\" + filename + number + extension; + + AssetDatabase.CreateAsset(new ShaderVariantCollection(), outputPath); + } + } + + AssetDatabase.SaveAssets(); + AssetDatabase.Refresh(); + + if (outputList.Count != 0) + { + Selection.activeObject = outputList.Last(); + EditorGUIUtility.PingObject(outputList.Last()); + } + } + + public void Awake() + { + SetupStyle(); + CreateIfDefaultConfigIsNull(); + } + + public void OnDisable() + { + ShaderVariantCollectionAddVariantWindow.Window.Close(); + SaveObject(mConfig); + } + } +} diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionToolWindow.cs.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionToolWindow.cs.meta new file mode 100644 index 0000000..2874f65 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/ShaderVariantCollectionToolWindow.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 717f7fe01ad147a428358a65d611c15f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter.meta new file mode 100644 index 0000000..b36345c --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f8e0fd4e909759f439c3e4eccdae80e7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter/IVariantFilter.cs b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter/IVariantFilter.cs new file mode 100644 index 0000000..cd0e1e4 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter/IVariantFilter.cs @@ -0,0 +1,10 @@ +using UnityEngine; + +namespace Soco.ShaderVariantsCollection +{ + public abstract class IVariantFilter : ScriptableObject + { + //return true will save and false will strip + public abstract bool Filter(ShaderVariantCollection.ShaderVariant variant); + } +} \ No newline at end of file diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter/IVariantFilter.cs.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter/IVariantFilter.cs.meta new file mode 100644 index 0000000..a995014 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter/IVariantFilter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1635b3b307400b242b251a44fe60acc2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter/VariantFilter_PassStrip.cs b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter/VariantFilter_PassStrip.cs new file mode 100644 index 0000000..3c4f802 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter/VariantFilter_PassStrip.cs @@ -0,0 +1,16 @@ +using UnityEngine; +using System.Linq; +using UnityEngine.Rendering; + +namespace Soco.ShaderVariantsCollection +{ + public class VariantFilter_PassStrip : IVariantFilter + { + public PassType[] mStripPasses = new PassType[0]; + + public override bool Filter(ShaderVariantCollection.ShaderVariant variant) + { + return !mStripPasses.Contains(variant.passType); + } + } +} \ No newline at end of file diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter/VariantFilter_PassStrip.cs.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter/VariantFilter_PassStrip.cs.meta new file mode 100644 index 0000000..d902bb8 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter/VariantFilter_PassStrip.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7ff4f771d4d834c44b94b6941a3bb222 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter/VariantFilter_Shader.cs b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter/VariantFilter_Shader.cs new file mode 100644 index 0000000..59a70eb --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter/VariantFilter_Shader.cs @@ -0,0 +1,92 @@ +using System.Collections.Generic; +using UnityEngine; +using System.Linq; +using UnityEditor; + +namespace Soco.ShaderVariantsCollection +{ + + + public class VariantFilter_Shader : IVariantFilter + { + public enum Mode + { + Strip, + OnlyReserveContains + } + + public Mode mode = Mode.Strip; + public Shader[] mShaders = new Shader[0]; + + public override bool Filter(ShaderVariantCollection.ShaderVariant variant) + { + bool containShader = mShaders.Contains(variant.shader); + return mode == Mode.Strip ? !containShader : containShader; + } + } + + [ShaderVariantCollectionToolEditor(typeof(VariantFilter_Shader))] + class VariantFilter_ShaderEditor : ShaderVariantCollectionToolEditor + { + private bool foldoutValue = false; + private int mOperatorIndex1 = 0; + private int mOperatorIndex2 = 0; + private Shader mOperatorShader = null; + + public override void OnInspectorGUI() + { + base.OnInspectorGUI(); + + foldoutValue = EditorGUILayout.Foldout(foldoutValue, "添加删除交换操作"); + + if (foldoutValue) + { + EditorGUILayout.BeginVertical(); + + EditorGUILayout.BeginHorizontal(); + mOperatorIndex1 = EditorGUILayout.IntField("操作索引1", mOperatorIndex1); + mOperatorIndex2 = EditorGUILayout.IntField("操作索引2", mOperatorIndex2); + EditorGUILayout.EndHorizontal(); + mOperatorShader = EditorGUILayout.ObjectField("添加Shader", mOperatorShader, typeof(Shader)) as Shader; + + var targetObj = target as VariantFilter_Shader; + + EditorGUILayout.BeginHorizontal(); + if (GUILayout.Button("添加至操作索引1")) + { + if (mOperatorIndex1 >= 0 && mOperatorIndex1 <= targetObj.mShaders.Length) + { + Undo.RecordObject(targetObj, "VariantFilter_Shader insert element from list"); + List temp = new List(targetObj.mShaders); + temp.Insert(mOperatorIndex1, mOperatorShader); + targetObj.mShaders = temp.ToArray(); + } + } + + if (GUILayout.Button("删除操作索引1")) + { + if (mOperatorIndex1 >= 0 && mOperatorIndex1 < targetObj.mShaders.Length) + { + Undo.RecordObject(targetObj, "VariantFilter_Shader delete shader from list"); + List temp = new List(targetObj.mShaders); + temp.RemoveAt(mOperatorIndex1); + targetObj.mShaders = temp.ToArray(); + } + } + + if (GUILayout.Button("交换操作索引")) + { + if (mOperatorIndex1 >= 0 && mOperatorIndex1 < targetObj.mShaders.Length + && mOperatorIndex2 >= 0 && mOperatorIndex2 < targetObj.mShaders.Length) + { + Undo.RecordObject(targetObj, "VariantFilter_Shader swap element from list"); + (targetObj.mShaders[mOperatorIndex1], targetObj.mShaders[mOperatorIndex2]) = (targetObj.mShaders[mOperatorIndex2], targetObj.mShaders[mOperatorIndex1]); + } + } + EditorGUILayout.EndHorizontal(); + + EditorGUILayout.EndVertical(); + } + } + } +} \ No newline at end of file diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter/VariantFilter_Shader.cs.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter/VariantFilter_Shader.cs.meta new file mode 100644 index 0000000..53faf2e --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/Editor/VariantFilter/VariantFilter_Shader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6b9930f5f40da9447865cccf0ca449d5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/README.md b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/README.md new file mode 100644 index 0000000..7aa2f58 --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/README.md @@ -0,0 +1,238 @@ +# 变体收集工具 + +### 1. 开启菜单 + +  顶部菜单栏Tools/Soco/ShaderVariantCollectionTools/OpenWindow 开启窗口。 +![](..Images/1.开启界面.png) +  **变体收集文件**:Unity原生的变体收集文件,可以对Shader变体产生引用,使变体打入Bundle,可用于预热变体。在填入当前操作变体收集文件前,将显示红色。
+  **工具配置文件**:当前工具的配置文件,方便保留材质收集、变体材质过滤等工具的参数,不需要每次打开都重新编写。工具打开时会自动寻找,且如果找不到时,会自动在工具目录下生成默认配置文件,并选择添加(上图的Default ShaderVariantCollection Tool Config)。 + +### 2. 功能选择 + +  当变体收集文件不为空时,功能选择菜单启用。
+  当前工具暂时支持三类主要功能:**快速浏览、收集工具、批处理工具**。 + +![](..Images/2.功能选择.png) + +  **快速浏览**:浏览变体收集文件的内容;相比Unity原生的变体收集UI,工具的浏览能更快捷的定位shader、pass所拥有的变体,概览变体个数。
+  **项目收集工具**:利用项目中材质对变体的引用,收集变体,在过程中过滤材质或变体。
+  **批处理工具**:对收集完的变体收集文件批量处理,例如排列组合添加材质不会收集到的multi_compile变体。 + +### 3. 快速浏览 + +  点击快速浏览后,次级功能选项会变成Shader View,可显示当前变体收集文件中包含的Shader。
+  通过选择项目Shader并点击添加,以及点击下方Shader名称后的减号,可以添加或删除Shader。通过“过滤”中的字符串,可以筛选Shader。
+  点击列表中的Shader名称,可以查看收集文件中,Shader拥有哪些变体。变体在右侧浏览窗口,通过PassType分好组。可以通过加号和减少增减变体。 + +![](..Images/3.快速浏览.png) + +### 4. 收集工具 + +#### 4.1 材质收集器 +  点击项目收集工具后,先进入材质收集器列表选项。
+  材质收集器是对象,对象的类需要实现`Soco.ShaderVariantsCollection.IMaterialCollection`接口,并实现`AddMaterialBuildDependency`这个方法,将打包所需要的材质添加到`AddMaterialBuildDependency`传入的`List`中。
+  下面是我所实现的事例`MaterialCollection_SceneDependency`,作用是获取所有打包场景依赖的材质: +```C# +namespace Soco.ShaderVariantsCollection +{ + //用于收集所有打包场景依赖的材质 + public class MaterialCollection_SceneDependency : IMaterialCollection + { + //是否只收集在EditorBuildSettings中enable的场景 + public bool collectOnlyEnable = true; + public override void AddMaterialBuildDependency(IList buildDependencyList) + { + var sceneDependencyMaterials = EditorBuildSettings.scenes //所有场景 + .Where(scene => !collectOnlyEnable || scene.enabled) //是否enable + .SelectMany(scene => AssetDatabase.GetDependencies(scene.path)) //获取场景依赖的所有资源 + .Where(dependencyAsset => dependencyAsset.EndsWith(".mat")) //获取资源中的材质 + .Distinct() //去重 + .Select(matPath => AssetDatabase.LoadAssetAtPath(matPath)); + + buildDependencyList.AddRange(sceneDependencyMaterials); + } + } +} +``` +  不同项目可按照需要实现接口,比如某些项目用资源表决定有哪些材质会打入包中,就可以实现一个类,专门读取资源表获取资源,然后获取资源引用的材质,或资源本身就是材质,下边是我们项目的实现:
+```C# +//用于获取资源表所引用的资源 +//注意,这个类并不在Soco.ShaderVariantsCollection名空间下,因为理想中,这个类是依赖于工程,而非工具的功能,所以继承时用到了类包含namespace的全名 +public sealed class MaterialCollection_DependRes : Soco.ShaderVariantsCollection.IMaterialCollection +{ + public override void AddMaterialBuildDependency(IList buildDependencyList) + { + //获取资源表中所有资源 + List resList = ResConfigFileEnter.GetConfigFile(); + foreach (string res in resList) + { + //如果资源本身是材质,则直接添加到列表中 + if (res.EndsWith(".mat")) + { + Material mat = AssetDatabase.LoadAssetAtPath(res); + if(mat != null) + buildDependencyList.Add(mat); + } + //如果不是材质,则找到资源所引用的材质添加到列表中 + else + { + foreach (string depRes in AssetDatabase.GetDependencies(res)) + { + if (depRes.EndsWith(".mat")) + { + Material mat = AssetDatabase.LoadAssetAtPath(depRes); + if(mat != null) + buildDependencyList.Add(mat); + } + } + } + } + } +} +``` +  工具打开时会获取所有实现`IMaterialCollection`接口的类,可以通过点击“添加收集材质回调”按钮,实例化实现类,对象和对象的参数会保存在工具配置文件中。
+  “**删除**”按钮可以删除收集器对象,**使用**表示下次点击“**收集材质**”时,是否会用到这个收集器对象。
+  下方绘制了实现类的成员,可通过修改数值使对象收集不同的材质,例如我的一个材质收集器实现类,可以收集某些路径下所有材质,成员变量是一个路径,通过修改成员的数值,就可以收集不同路径下的材质。 +![](..Images/4.材质收集器列表.png) + +#### 4.2 收集变体 +  搞定好收集器后,先确认是否要覆盖原有文件,还是在原有文件上添加内容,可通过次级功能选项“**Collection View**”下的复选框修改。
+  收集变体分为三步:**收集材质、材质变体转化、写入收集文件**。在次级功能菜单**Collection View**中可以单步运行,也可以直接点击“一键变体收集”运行三步。
+  **收集材质**是通过4.1描述的材质收集器,在项目中收集材质。
+  **材质变体转化**是将材质存储的shader keyword,转换为一个或多个shader变体。
+  **写入收集文件**是将转换得到的变体写入变体收集文件。 + +#### 4.3 材质、变体过滤 +![](..Images/5.变体过滤器列表.png) +  上述收集器会按照规则收集材质,然后转换变体,但有时会得到我们不希望得到的变体;
+  例如一个URP管线的项目,肯定不希望得到`Standard`这个Shader实例化出来的材质,如果按照引用规则收集,很多模型默认的内嵌材质会导致收集到。
+  或者一个Forward管线也可能收集到`Deferred`或`Meta`这些Pass的变体。
+  理所当然的,可以在收集器的逻辑中,屏蔽掉某个Shader的所有材质,但如果这样,需要在每个收集器的逻辑里添加屏蔽代码,需知材质收集器不止一种,屏蔽需求也不止一个,所以我添加了过滤器这一功能,将收集和过滤分离开来。
+  和收集器一样,需要实现接口来实现过滤器。材质过滤器需要继承`IMaterialFilter`接口,并实现`Filter`方法: +```C# +public abstract class IMaterialFilter : ScriptableObject +{ + //return true will save and false will strip + public abstract bool Filter(Material material, List collections); +} +``` +  方法将传入材质,以及收集到材质的收集器,方法需要返回bool类型参数,返回true这个材质将保留,false则会使材质被剔除。
+  类似的,变体的过滤器需要继承`IVariantFilter`接口,并实现`Filter`方法: +```C# +public abstract class IVariantFilter : ScriptableObject +{ + //return true will save and false will strip + public abstract bool Filter(ShaderVariantCollection.ShaderVariant variant); +} +``` +  工具自带实现了两个变体过滤器:可以剔除或只保留指定Shader的`VariantFilter_Shader`,可以剔除指定Pass的`VariantFilter_PassStrip`。
+  材质过滤器将在材质收集阶段后应用,变体过滤器将在材质-变体转换阶段后应用。 + +  注: 不需要的变体自然能通过Unity的变体剔除来剔除,这里的做法只是为了保证变体收集文件的整洁性。 + +#### 4.4 自带收集器与过滤器使用说明 +材质收集器: + +① `MaterialCollection_SceneDependency`获取所有在BuildSetting中的场景,所引用的材质。
+成员`collectOnlyEnable`指定是否只收集在BuildSetting中打勾的场景。 + +② `MaterialCollection_TotalMaterial`获取指定目录下的所有材质。
+有两种指定文件夹的形式,利用`pathMode`指定;
+其一是Asset,可以拖动文件夹到`mFolders`数组中,这样的缺陷是,`Assets`和`Packages`目录无法拖动;
+其二是String,可以将路径字符串指定到`mIncludePath`数组中,路径的起始从项目根路径开始,也就是类似`Assets\Res`这种形式。 + +③ `MaterialCollection_AssignMaterial`指定收集某几个材质
+将材质拖到materials数组中即可 + +变体过滤器: + +① `VariantFilter_Shaderp`剔除或只保留指定shader。
+将需要操作的Shader指定到`mShaders`数组中,mode指定模式。
+当模式为Strip时,将剔除收集到变体中,shader处于`mShaders`数组中的变体。
+当模式为OnlyReserveContains时,将只保留shader处于`mShaders`数组中的变体。
+只保留模式可以用来只收集某一shader的变体,这样不会减少收集时间,但非覆盖模式下,可以只收集几个Shader,应对需要的场景。 + +② `VariantFilter_PassStrip`剔除指定Pass。
+将需要剔除的PassType指定到`mStripPasses`数组中即可 + +材质过滤器因没有需求,暂时没提供默认实现类。 + +### 5. 批处理工具 +  收集工具将变体收集、写入到变体文件中后,如果有对变体批量处理的需求,则会用到这一功能。
+  通过功能选择的批处理工具按钮会进入到批处理工具页面,当前有三个功能:**批处理执行器列表**、**合并文件** + +#### 5.1 批处理执行器列表 +  当需要自定义批处理功能时,可按照接口实现执行器。
+  这里举例一个使用场景:前面收集器收集到的是所有材质记录的keywords,这个参数是通过Material.EnableKeyword添加,Material.DisableKeyword去除,多数情况下,需要材质来开启关闭的keyword,用shader_feature声明,而雾效、阴影这些全局效果关键字,用multi_compile声明。
+  打包时的规则是,获取引用到的所有变体组合的shader_feature部分(材质和变体收集文件会对变体产生引用),然后和shader的multi_compile keyword排列组合;通过材质获取的keyword组合,能保证打包不会丢变体,但由于没有收集、组合multi_compile keyword,会导致无法正确预热。
+  此时就需要用批处理工具,将multi_compile部分与已经收集的变体排列组合,并添加到变体收集文件中,使变体正确预热。 + +  和材质收集器、材质变体过滤器类似,批处理执行器需要实现`IExecutable`接口,并实现`Execute`方法。 +```C# +public abstract class IExecutable : ScriptableObject +{ + public abstract void Execute(ShaderVariantCollectionMapper mapper); +} +``` +  方法会将当前正在处理的变体收集文件的包装器传入(因为Unity原生的变体收集文件提供的接口太少了),这个包装器类提供了Shader、变体是否存在,以及添加、删除Shader和变体的接口。 +![](..Images/7.执行器列表.png) +  执行器的列表中,会多出“执行”和“全部执行”按钮;执行会执行当前执行器,不管执行器的“使用”选项是否勾选;而全部执行会执行所有勾选“使用”的执行器。 + +#### 5.2 自带执行器使用说明 + +① `VariantKeywordCombination`
+添加keyword声明组,排列组合后,与现有变体再组合,写入到变体收集文件中。
+变体声明组就是Shader中的`#pragma multi_compile _ A B`,这样默认keyword`_`和`A`、`B`就是一个声明组。 +Shader参数指定需要组合的Shader。
+添加keyword声明组可以通过最下面的加号`+`,然后会出现新的一行,包含`+`和`-`,`-`会去掉当前变体声明组,`+`会添加keyword。
+添加的keyword会根据选择模式变化,选择模式共3个`Custom`、`Default`、`DeclareStatement`。
+当模式为`Custom`时,点击`+`会将选择模式右侧选择的变体添加到当前声明组中。
+当模式为`Default`时,点击`+`会将默认keyword`_`(代表全下划线keyword,无论shader中用了几个下划线声明都一样)添加到当前声明组中。
+当模式为`DeclareStatement`时,右侧可以输入声明字符串(类似`#pragma multi_compile _ A B`),点击`+`会解析字符串,并将解析出的声明组添加到当前声明组,这一选项方便直接从shader复制语句。
+声明字符串只支持`multi_compile`,无论是否有local,支持instance(`multi_compile_instancing`)、fog、particle这些build_in声明,暂不支持`multi_compile_fwdbase`等其他build_in声明,如需要可改代码。
+当shader不为空时,可以通过“尝试收集声明组”按钮,读取shader文件尝试解析文件内容,获取声明组,这样能加快设置速度,但需要人工排查是否正确收集,否则很可能收集到不想要的声明组。 +![](..Images/8.变体声明组合.png) + +② `SocoVariantStripAssociate`
+与[Soco变体剔除工具](https://github.com/crossous/SocoTools/tree/main/SocoShaderVariantsStripper)联动,可以利用剔除工具的逻辑,将变体收集文件中,不会打入bundle的变体剔除掉,精简变体收集文件。
+因为依赖于变体剔除工具,所以当变体剔除工具不存在时,可以将这个类去掉。 + +#### 5.3 合并文件 +![](..Images/6.合并文件.png) +  作用是将新放入的文件的内容,合并到左侧的变体收集文件中。 + +#### 5.4 分割文件 +![](..Images/9.分割文件.png) +  有时候会有需求将现有文件分割成多份,比如低端设备初次进入游戏,会在预热时卡住一段时间,希望能在预热时显示进度条,此时就会希望分割文件。
+  首先设置路径,默认是源文件位置。然后设置每个文件最多多少个变体。
+  然后选择切割模式,其一是每个文件固定变体数量。
+  选框可以决定分割的最小单位,如果可以分割Shader也可以分割Pass,则最小单位就是变体;否则如果可以分割Shader但不能分割Shader中的Pass,则最小分割单位是Pass;最后就是不可分割Shader,则不会分割Shader。
+  第二个切割模式是按照固定文件数量切割,变体均匀分布在每个文件中,这样方便配置资源表。 + + +### 6. 自定义编辑器 +  可以发现材质收集器、材质过滤器、变体过滤器、执行器的界面大多相似,因为它们的实现方式都是继承自某个抽象类然后实现抽象方法。
+  界面都是绘制各个对象的成员,如果希望自定义编辑器,工具提供了相关抽象。例如上面的执行器自身的定义是这样: +```C# +public class VariantKeywordCombination : IExecutable +{ + //something +} +``` +  那么自定义编辑器可以这样定义: +```C# +[ShaderVariantCollectionToolEditor(typeof(VariantKeywordCombination))] +class VariantKeywordCombinationEditor : ShaderVariantCollectionToolEditor +{ + public void OnEnable() + { + //something + } + + public override void OnInspectorGUI() + { + //something + } +} +``` +  `ShaderVariantCollectionToolEditor`这个类继承自Unity的`Editor`类,所以相关的事件方法都可以实现,界面打开时会自动寻找有没有实现当前对象类的编辑器,如果没有就绘制类的成员,如果有则按照实现的编辑器代码绘制。 \ No newline at end of file diff --git a/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/README.md.meta b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/README.md.meta new file mode 100644 index 0000000..1abe9dc --- /dev/null +++ b/Assets/URS/SocoShaderVariant/SocoShaderVariantsCollection/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 5fe650f21d3e0164abf7cf7f692544ec +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/UnityShaderStripper/Editor/ShaderStripperEditor.cs b/Assets/URS/UnityShaderStripper/Editor/ShaderStripperEditor.cs index 415d234..7cf956f 100644 --- a/Assets/URS/UnityShaderStripper/Editor/ShaderStripperEditor.cs +++ b/Assets/URS/UnityShaderStripper/Editor/ShaderStripperEditor.cs @@ -10,7 +10,7 @@ using System.Linq; namespace Sigtrap.Editors.ShaderStripper { - [UnityEditor.Build.Pipeline.Utilities.VersionedCallback(2)] + [UnityEditor.Build.Pipeline.Utilities.VersionedCallback(26)] public class ShaderStripperEditor : EditorWindow, IPreprocessShaders{ public const string KEY_LOG = "ShaderStripperLogPath"; public const string KEY_ENABLE = "ShaderStripperGlobalEnable"; diff --git a/Assets/URS/UnityShaderStripper/ShaderForceKeywords.asset b/Assets/URS/UnityShaderStripper/ShaderForceKeywords.asset index f2a2f5f..e5a2563 100644 --- a/Assets/URS/UnityShaderStripper/ShaderForceKeywords.asset +++ b/Assets/URS/UnityShaderStripper/ShaderForceKeywords.asset @@ -13,7 +13,7 @@ MonoBehaviour: m_Name: ShaderForceKeywords m_EditorClassIdentifier: _expanded: 1 - _order: 1 + _order: 2 _active: 1 _notes: _logOutput: 1 @@ -22,4 +22,5 @@ MonoBehaviour: - DYNAMICLIGHTMAP_ON - LOD_FADE_CROSSFADE - _MIXED_LIGHTING_SUBTRACTIVE - - LIGHTMAP_SHADOW_MIXING + - INSTANCING_ON + - PROCEDURAL_INSTANCING_ON diff --git a/Assets/URS/UnityShaderStripper/ShaderStripperBlackShaderVariantCollection.asset b/Assets/URS/UnityShaderStripper/ShaderStripperBlackShaderVariantCollection.asset new file mode 100644 index 0000000..c8e2314 --- /dev/null +++ b/Assets/URS/UnityShaderStripper/ShaderStripperBlackShaderVariantCollection.asset @@ -0,0 +1,19 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &11400000 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: a4bd955c4a652604589fe8b52a87a0db, type: 3} + m_Name: ShaderStripperBlackShaderVariantCollection + m_EditorClassIdentifier: + _expanded: 0 + _order: 0 + _active: 1 + _notes: + _logOutput: 0 diff --git a/Assets/Settings/Editor/User/URSEditorUserSettings.asset.meta b/Assets/URS/UnityShaderStripper/ShaderStripperBlackShaderVariantCollection.asset.meta similarity index 79% rename from Assets/Settings/Editor/User/URSEditorUserSettings.asset.meta rename to Assets/URS/UnityShaderStripper/ShaderStripperBlackShaderVariantCollection.asset.meta index 228c24f..f41a961 100644 --- a/Assets/Settings/Editor/User/URSEditorUserSettings.asset.meta +++ b/Assets/URS/UnityShaderStripper/ShaderStripperBlackShaderVariantCollection.asset.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 0d038d5db632425458f38751b75765ed +guid: 94c85e4a3140bff4db2aaad58f7c2dda NativeFormatImporter: externalObjects: {} mainObjectFileID: 11400000 diff --git a/Assets/URS/UnityShaderStripper/ShaderStripperBlackShaderVariantCollection.cs b/Assets/URS/UnityShaderStripper/ShaderStripperBlackShaderVariantCollection.cs new file mode 100644 index 0000000..feaf76c --- /dev/null +++ b/Assets/URS/UnityShaderStripper/ShaderStripperBlackShaderVariantCollection.cs @@ -0,0 +1,82 @@ +#if UNITY_2018_2_OR_NEWER +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Rendering; +#if UNITY_EDITOR +using UnityEditor; +using UnityEditor.Rendering; +#endif +using System.IO; +using System.Linq; +namespace Sigtrap.Editors.ShaderStripper +{ + /// + /// Strips shaders by shader asset path. + /// + [CreateAssetMenu(menuName = "Sigtrap/Shader Stripper BlackShaderVariantCollection")] + public class ShaderStripperBlackShaderVariantCollection : ShaderStripperBase + { + // public const string BLACK_SHADER_VARIANT_STRIPPER_SAVE_PATH = "Assets/GameResources/ShaderVarians/BlackShaderVariantCollection.shadervariants"; + + private ShaderVariantCollection _blackShaderVariantCollection = null; + +#if UNITY_EDITOR + protected override bool _checkShader { get { return false; } } + protected override bool _checkPass { get { return false; } } + protected override bool _checkVariants { get { return false; } } + protected override bool StripCustom(Shader shader, ShaderSnippetData passData, IList variantData) + { + var c = variantData.Count; + for (int i = variantData.Count - 1; i >= 0; --i) + { + if (IsKeywordMatch(shader, passData, variantData[i])) + { + LogRemoval(this, shader, passData, i, c, variantData[i]); + variantData.RemoveAt(i); + } + } + return true; + } + + public string GetKeywordString(ref ShaderCompilerData variantData) + { + var keywords = variantData.shaderKeywordSet.GetShaderKeywords(); + var result = ""; + foreach (var keyword in keywords) + { + result += keyword.name; + } + return result; + } + public bool IsKeywordMatch(Shader shader, ShaderSnippetData passData, ShaderCompilerData variantData) + { + if (!File.Exists( URS.URSShaderVariantConstant.BLACK_SHADER_VARIANT_STRIPPER_SAVE_PATH)) + { + return false; + } + if (_blackShaderVariantCollection == null || _blackShaderVariantCollection.variantCount == 0 || _blackShaderVariantCollection.shaderCount == 0) + { + Debug.LogError($"load ShaderVariant,shaderName {shader.name} passType {passData.passType} keyword: {GetKeywordString(ref variantData)} "); + _blackShaderVariantCollection =AssetDatabase.LoadAssetAtPath(URS.URSShaderVariantConstant.BLACK_SHADER_VARIANT_STRIPPER_SAVE_PATH); + } + if (_blackShaderVariantCollection != null && _blackShaderVariantCollection.variantCount > 0) + { + ShaderVariantCollection.ShaderVariant shaderVariant = new ShaderVariantCollection.ShaderVariant(); + shaderVariant.shader = shader; + shaderVariant.passType = passData.passType; + shaderVariant.keywords = variantData.shaderKeywordSet.GetShaderKeywords().Select(keyword => keyword.name).ToArray(); + bool remove = _blackShaderVariantCollection.Contains(shaderVariant); + if (remove) + { + Debug.LogError($"success Move ShaderVariant,shaderName {shader.name} passType {passData.passType} keyword: {GetKeywordString(ref variantData)} "); + } + return remove; + } + + return false; + } +#endif + } +} +#endif \ No newline at end of file diff --git a/Assets/URS/UnityShaderStripper/ShaderStripperBlackShaderVariantCollection.cs.meta b/Assets/URS/UnityShaderStripper/ShaderStripperBlackShaderVariantCollection.cs.meta new file mode 100644 index 0000000..f9a600f --- /dev/null +++ b/Assets/URS/UnityShaderStripper/ShaderStripperBlackShaderVariantCollection.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a4bd955c4a652604589fe8b52a87a0db +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/UnityShaderStripper/ShaderStripperSimple.asset b/Assets/URS/UnityShaderStripper/ShaderStripperSimple.asset index 688ba22..e3ff812 100644 --- a/Assets/URS/UnityShaderStripper/ShaderStripperSimple.asset +++ b/Assets/URS/UnityShaderStripper/ShaderStripperSimple.asset @@ -12,8 +12,8 @@ MonoBehaviour: m_Script: {fileID: 11500000, guid: bce01c7e38d77374f90e48cc0061b138, type: 3} m_Name: ShaderStripperSimple m_EditorClassIdentifier: - _expanded: 1 - _order: 0 + _expanded: 0 + _order: 1 _active: 1 _notes: _logOutput: 1 @@ -21,5 +21,5 @@ MonoBehaviour: - matchType: 0 namePattern: Standard caseInsensitive: 0 - _blacklistedPassTypes: + _blacklistedPassTypes: 0b000000 _blacklistedKeywords: [] diff --git a/Assets/URS/YooAsset/Editor/Utils.meta b/Assets/URS/Utils.meta similarity index 77% rename from Assets/URS/YooAsset/Editor/Utils.meta rename to Assets/URS/Utils.meta index 72193b4..022c030 100644 --- a/Assets/URS/YooAsset/Editor/Utils.meta +++ b/Assets/URS/Utils.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 821aadb036350f94c8136c16018c2bf0 +guid: 26443f3f176397148810f29f4c37b87c folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Assets/URS/Setting/URSSetting/Editor.meta b/Assets/URS/Utils/Editor.meta similarity index 77% rename from Assets/URS/Setting/URSSetting/Editor.meta rename to Assets/URS/Utils/Editor.meta index 2b5ee15..9718196 100644 --- a/Assets/URS/Setting/URSSetting/Editor.meta +++ b/Assets/URS/Utils/Editor.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: fd5d56e264ed5bc46aa2292e4420b3d1 +guid: 54f2dd7bbadf97741b86d96c666b9544 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Assets/URS/Utils/Editor/EditorUtils.Reflection.cs b/Assets/URS/Utils/Editor/EditorUtils.Reflection.cs new file mode 100644 index 0000000..1c7cb23 --- /dev/null +++ b/Assets/URS/Utils/Editor/EditorUtils.Reflection.cs @@ -0,0 +1,396 @@ + + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats +{ + + public class AssemblyCache + { + private Assembly m_Assembly; + private Type[] m_Types; + private Type[] m_ExportedTypes; + private Module m_ManifestModule; + + public Assembly Assembly => m_Assembly; + + private string m_FullName; + public string FullName + { + get + { + if (m_FullName == null) + m_FullName = m_Assembly?.FullName; + return m_FullName; + } + } + + public Type[] GetTypes() + { + if (m_Types == null) + m_Types = m_Assembly?.GetTypes(); + return m_Types; + } + + public Type[] GetExportedTypes() + { + if (m_ExportedTypes == null) + m_ExportedTypes = m_Assembly?.GetExportedTypes(); + return m_ExportedTypes; + } + + public Module ManifestModule + { + get + { + if (m_ManifestModule == null) + m_ManifestModule = m_Assembly?.ManifestModule; + return m_ManifestModule; + } + } + + public AssemblyCache(Assembly assembly) + { + m_Assembly = assembly; + } + } + + + public class TypeAttrPairs where T : Attribute + { + public Type type; + public T attr; + + public TypeAttrPairs() + { + type = null; + attr = null; + } + + public TypeAttrPairs(Type type, T attr) + { + this.type = type; + this.attr = attr; + } + } + + public class MethodAttrPair where T : Attribute + { + public MethodInfo method; + public T attr; + + public MethodAttrPair() + { + method = null; + attr = null; + } + + public MethodAttrPair(MethodInfo method, T attr) + { + this.method = method; + this.attr = attr; + } + } + + + public partial class EditorUtils + { + + private static AssemblyCache[] s_Assemblies = null; + public static AssemblyCache[] Assemblies + { + get + { + if (s_Assemblies == null) + { +#if !UNITY_EDITOR + Debug.LogWarning("Init AssemblyCache in runtime"); +#endif + var assemblies = AppDomain.CurrentDomain.GetAssemblies(); + s_Assemblies = new AssemblyCache[assemblies.Length]; + for (int i = 0; i < assemblies.Length; ++i) + s_Assemblies[i] = new(assemblies[i]); + } + + return s_Assemblies; + } + } + + private static Dictionary s_AssemblyByFullName = null; + + public static Dictionary AssemblyByFullName + { + get + { + if (s_AssemblyByFullName == null) + { + s_AssemblyByFullName = new(); + foreach (var a in Assemblies) + s_AssemblyByFullName[a.FullName] = a; + } + + return s_AssemblyByFullName; + } + } + + private static Dictionary s_TypeByFullName = null; + + public static Dictionary TypeByFullName + { + get + { + if (s_TypeByFullName == null) + { + s_TypeByFullName = new(65536); + foreach (var a in Assemblies) + { + foreach (var t in a.GetTypes()) + { + var fullname = t.FullName; + if (!string.IsNullOrWhiteSpace(fullname)) + s_TypeByFullName[fullname] = t; + } + } + } + return s_TypeByFullName; + } + } + + private static Dictionary> s_TypesByNamespace = null; + + public static Dictionary> TypesByNamespace + { + get + { + if (s_TypesByNamespace == null) + { + s_TypesByNamespace = new(2048); + string cacheNamespace = null; + List cacheList = null; + foreach (var a in Assemblies) + { + foreach (var t in a.GetTypes()) + { + var Namespace = t.Namespace; + if (string.IsNullOrWhiteSpace(Namespace)) + continue; + + if (cacheNamespace != Namespace) + { + cacheNamespace = Namespace; + if (!s_TypesByNamespace.TryGetValue(Namespace, out cacheList)) + { + cacheList = new(); + s_TypesByNamespace.Add(Namespace, cacheList); + } + } + + cacheList.Add(t); + } + } + } + + return s_TypesByNamespace; + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static AssemblyCache[] GetAssemblies() => Assemblies; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static AssemblyCache GetAssemblyByFullName(string fullName) + { + if (AssemblyByFullName.TryGetValue(fullName, out var value)) + return value; + return null; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Type GetTypeByFullName(string fullName) + { + if (string.IsNullOrEmpty(fullName)) + return null; + if (TypeByFullName.TryGetValue(fullName, out var value)) + return value; + return null; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static List GetTypesByNamespace(string Namespace) + { + if (TypesByNamespace.TryGetValue(Namespace, out var value)) + return value; + return null; + } + + public static readonly Type typeof_UnityObject = typeof(UnityEngine.Object); + + public static readonly Type typeof_Object = typeof(object); + public static readonly Type typeof_String = typeof(string); + public static readonly Type typeof_Byte = typeof(byte); + public static readonly Type typeof_Char = typeof(char); + public static readonly Type typeof_Int16 = typeof(short); + public static readonly Type typeof_Int32 = typeof(int); + public static readonly Type typeof_Int64 = typeof(long); + public static readonly Type typeof_UInt16 = typeof(ushort); + public static readonly Type typeof_UInt32 = typeof(uint); + public static readonly Type typeof_UInt64 = typeof(ulong); + public static readonly Type typeof_Single = typeof(float); + public static readonly Type typeof_Double = typeof(double); + public static readonly Type typeof_Boolean = typeof(bool); + public static readonly Type typeof_Void = typeof(void); + + private static readonly Dictionary s_InternalTypeNameMap = new() + { + { typeof_Object, "object" }, + { typeof_String, "string" }, + { typeof_Byte, "byte" }, + { typeof_Char, "char" }, + { typeof_Int16, "short" }, + { typeof_Int32, "int" }, + { typeof_Int64, "long" }, + { typeof_UInt16, "ushort" }, + { typeof_UInt32, "uint" }, + { typeof_UInt64, "ulong" }, + { typeof_Single, "float" }, + { typeof_Double, "double" }, + { typeof_Boolean, "bool" }, + { typeof_Void, "void" }, + }; + + private static string GetTypeFullName(this Type type) + { + string fullName = type.Name; + var it = type; + while (it.IsNested) + { + it = it.DeclaringType; + fullName = $"{it.Name}.{fullName}"; + } + if (!string.IsNullOrEmpty(type.Namespace)) + fullName = $"{type.Namespace}.{fullName}"; + return fullName; + } + + public static string GetTypeDisplayName(this Type type, bool flat = false) + { + if (type == null) + return ""; + + if (s_InternalTypeNameMap.TryGetValue(type, out var internalName)) + return internalName; + + string fullName = ""; + if (type.IsArray) + { + var elementTypeName = type.GetElementType().GetTypeDisplayName(flat); + var rank = type.GetArrayRank(); + if (flat) + fullName = $"Array{(rank > 1 ? $"_{rank}" : "")}_{elementTypeName}"; + else + fullName = $"{elementTypeName}[{string.Join(',', Enumerable.Repeat("", rank - 1))}]"; + } + else if (type.IsByRef) + { + fullName = type.GetElementType().GetTypeDisplayName(flat); + } + else if (type.IsGenericParameter) + { + fullName = type.Name; + } + else + { + fullName = type.GetTypeFullName(); + + if (type.IsGenericType) + { + var idx = fullName.IndexOf('`'); + if (idx != -1) + fullName = fullName.Substring(0, idx); + if (type.IsNested) + fullName = fullName.Replace('+', '.'); + + if (!flat) + { + fullName += "<"; + fullName += string.Join(", ", type.GetGenericArguments().Select(x=>x.GetTypeDisplayName(flat))); + fullName += ">"; + } + else + { + fullName += "_"; + fullName += string.Join("_", type.GetGenericArguments().Select(x=>x.GetTypeDisplayName(flat))); + } + } + } + + if (flat) + fullName = fullName.Replace('.', '_'); + return fullName; + } + + public static string GetParameterModifierStr(this ParameterInfo parameter, bool space = true) + { + if (parameter.IsOut) + return space ? "out " : "out"; + if (parameter.IsIn) + return space ? "in " : "in"; + if (parameter.ParameterType.IsByRef) + return space ? "ref " : "ref"; + return ""; + } + + public static List ScanAllMethodsInNamespace(string Namespace, BindingFlags? bindingFlags) + { + List returnList = new List(); + foreach (var pair in TypeByFullName) + { + var t = pair.Value; + if (string.IsNullOrEmpty(Namespace) || Namespace == t.Namespace) + returnList.AddRange(bindingFlags != null + ? t.GetMethods(bindingFlags.Value) + : t.GetMethods()); + } + return returnList; + } + + + public static List> ScanAllTypeWithAttributeMark() where T : Attribute + { + List> returnList = new List>(); + foreach (var type in UnityEditor.TypeCache.GetTypesWithAttribute()) + { + T attribute = type.GetCustomAttribute(true); + if (attribute != null) + { + returnList.Add(new TypeAttrPairs(type, attribute)); + } + } + + return returnList; + } + + public static List> ScanAllMethodsWithAttributeMark(string Namespace, + BindingFlags? bindFlag) where T : Attribute + { + List> returnList = new List>(); + + List methodList = ScanAllMethodsInNamespace(Namespace, bindFlag); + for (int i = 0; i < methodList.Count; i++) + { + MethodInfo method = methodList[i]; + T attribute = method.GetCustomAttribute(true); + if (attribute != null) + { + returnList.Add(new MethodAttrPair(method, attribute)); + } + } + + return returnList; + } + + } +} \ No newline at end of file diff --git a/Assets/URS/Utils/Editor/EditorUtils.Reflection.cs.meta b/Assets/URS/Utils/Editor/EditorUtils.Reflection.cs.meta new file mode 100644 index 0000000..4ef0975 --- /dev/null +++ b/Assets/URS/Utils/Editor/EditorUtils.Reflection.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b7ee0d2e12b21f748901bbcb9f8b896e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/EditorUtils.Scope.cs b/Assets/URS/Utils/Editor/EditorUtils.Scope.cs new file mode 100644 index 0000000..623a5f4 --- /dev/null +++ b/Assets/URS/Utils/Editor/EditorUtils.Scope.cs @@ -0,0 +1,401 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using UnityEngine; +using System.Text; +using System.Text.RegularExpressions; +using UnityEditor; +using UnityEditorInternal; + +namespace NinjaBeats +{ + public partial class EditorUtils + { + public static bool RepaintScene = false; + + public class RepaintSceneScope : IDisposable + { + public RepaintSceneScope() + { + RepaintScene = false; + } + + public void Dispose() + { + if (RepaintScene) + SceneView.RepaintAll(); + } + } + + public struct HandlesColorScope : IDisposable + { + Color color; + + public HandlesColorScope(Color c) + { + color = Handles.color; + Handles.color = c; + } + + public void Dispose() + { + Handles.color = color; + } + } + + public struct GizmosColorScope : IDisposable + { + Color color; + + public GizmosColorScope(Color c) + { + color = Gizmos.color; + Gizmos.color = c; + } + + public void Dispose() + { + Gizmos.color = color; + } + } + + public struct ColorScope : IDisposable + { + Color color; + + public ColorScope(Color c, bool enable = true) + { + if (!enable) + c = GUI.color; + + color = GUI.color; + GUI.color = c; + } + + public void Dispose() + { + GUI.color = color; + } + } + + public struct ContentColorScope : IDisposable + { + Color contentColor; + + public ContentColorScope(Color c, bool enable = true) + { + if (!enable) + c = GUI.contentColor; + + contentColor = GUI.contentColor; + GUI.contentColor = c; + } + + public void Dispose() + { + GUI.contentColor = contentColor; + } + } + + public struct BackgroundColorScope : IDisposable + { + Color color; + + public BackgroundColorScope(Color c) + { + color = GUI.backgroundColor; + GUI.backgroundColor = c; + } + + public void Dispose() + { + GUI.backgroundColor = color; + } + } + + public struct _ErrorGroupScope : IDisposable + { + ColorScope? sub; + + public _ErrorGroupScope(bool error) + { + if (error) + { + sub = new ColorScope(Color.red); + ErrorCheckSetError(); + } + else + { + sub = null; + } + } + + public void Dispose() + { + sub?.Dispose(); + sub = null; + } + } + + public static _ErrorGroupScope ErrorGroupScope(bool error = true) => new _ErrorGroupScope(error); + + + private static List s_ErrorGroupStack = new List(); + + private static void ErrorCheckSetError() + { + for (int i = 0; i < s_ErrorGroupStack.Count; ++i) + s_ErrorGroupStack[i] = true; + } + + public static void BeginErrorCheck() + { + s_ErrorGroupStack.Add(false); + } + + public static bool EndErrorCheck() + { + if (s_ErrorGroupStack.Count == 0) + { + Debug.LogError($"EndErrorCheck Error, s_ErrorGroupStack.Count == 0"); + return true; + } + + var error = s_ErrorGroupStack[s_ErrorGroupStack.Count - 1]; + s_ErrorGroupStack.RemoveAt(s_ErrorGroupStack.Count - 1); + return error; + } + + public struct _ErrorCheckScope : IDisposable + { + private int stackIdx; + + public bool error + { + get + { + if (s_ErrorGroupStack.IdxValid(stackIdx)) + return s_ErrorGroupStack[stackIdx]; + + Debug.LogError($"_ErrorCheckScope Error, s_ErrorGroupStack.Count == 0"); + return true; + } + } + + public _ErrorCheckScope(int stackIdx) + { + this.stackIdx = stackIdx; + } + public void Dispose() + { + EndErrorCheck(); + } + } + + public static _ErrorCheckScope ErrorCheckScope() + { + BeginErrorCheck(); + return new(s_ErrorGroupStack.Count - 1); + } + + public struct _LabelWidthScope : IDisposable + { + float width; + + public _LabelWidthScope(float width) + { + this.width = EditorGUIUtility.labelWidth; + EditorGUIUtility.labelWidth = width; + } + + public void Dispose() + { + EditorGUIUtility.labelWidth = this.width; + } + } + + public static _LabelWidthScope LabelWidthScope(float width) => new _LabelWidthScope(width); + + + public struct GUIContentScope : IDisposable + { + public GUIContent content; + + public GUIContentScope(string text) + { + content = SharedObjectPool.Get(); + content.text = text; + } + + public void Dispose() + { + if (content != null) + { + content.text = ""; + SharedObjectPool.Release(content); + } + } + } + + public struct _ShowMixedValueScopeImpl : IDisposable + { + bool showMixedValue; + + public _ShowMixedValueScopeImpl(bool value) + { + showMixedValue = EditorGUI.showMixedValue; + EditorGUI.showMixedValue = value; + } + + public void Dispose() + { + EditorGUI.showMixedValue = showMixedValue; + } + } + + public static _ShowMixedValueScopeImpl ShowMixedValueScope(bool showMixedValue) => new _ShowMixedValueScopeImpl(showMixedValue); + + public struct _HorizontalScopeImpl : IDisposable + { + public Rect rect; + public void Dispose() => EditorGUILayout.EndHorizontal(); + } + + public static _HorizontalScopeImpl HorizontalScope(params GUILayoutOption[] options) + { + var r = new _HorizontalScopeImpl(); + r.rect = EditorGUILayout.BeginHorizontal(options); + return r; + } + + public static _HorizontalScopeImpl HorizontalScope(GUIStyle style, params GUILayoutOption[] options) + { + var r = new _HorizontalScopeImpl(); + r.rect = EditorGUILayout.BeginHorizontal(style, options); + return r; + } + + public struct _VerticalScopeImpl : IDisposable + { + public Rect rect; + public void Dispose() => EditorGUILayout.EndVertical(); + } + + public static _VerticalScopeImpl VerticalScope(params GUILayoutOption[] options) + { + var r = new _VerticalScopeImpl(); + r.rect = EditorGUILayout.BeginVertical(options); + return r; + } + + public static _VerticalScopeImpl VerticalScope(GUIStyle style, params GUILayoutOption[] options) + { + var r = new _VerticalScopeImpl(); + r.rect = EditorGUILayout.BeginVertical(style, options); + return r; + } + + public struct _ShortLabelScope : IDisposable + { + private bool m_Enable; + public _ShortLabelScope(bool enable) => m_Enable = enable; + + public void Dispose() + { + if (m_Enable) + EndShortLabel(); + } + } + + private static int s_ShortLabelCount = 0; + public static bool IsShortLabel => s_ShortLabelCount > 0; + + public static _ShortLabelScope ShortLabelScope(bool enable = true) + { + if (enable) + BeginShortLabel(); + var r = new _ShortLabelScope(enable); + return r; + } + + public static void BeginShortLabel() => ++s_ShortLabelCount; + public static void EndShortLabel() => --s_ShortLabelCount; + + public static void FlexibleLabel(string label, bool vertical) + { + using (var scope = new EditorUtils.GUIContentScope(label)) + { + if (vertical) + { + using (EditorUtils.VerticalScope( + EditorUtils.GUILayoutOption_Width(GUI.skin.label.CalcSize(scope.content).x))) + { + GUILayout.FlexibleSpace(); + GUILayout.Label(scope.content); + GUILayout.FlexibleSpace(); + } + } + else + { + using (EditorUtils.HorizontalScope()) + { + GUILayout.FlexibleSpace(); + GUILayout.Label(scope.content); + GUILayout.FlexibleSpace(); + } + } + } + } + + public delegate T GUIWithOptionDelegate(T value, params GUILayoutOption[] options); + public delegate T GUIWithOptionDelegate(T0 param0 ,T value, params GUILayoutOption[] options); + public delegate T GUIDelegate(T value); + public delegate T GUIDelegate(T0 param0, T value); + + public static T ShortLabelGUI(GUIWithOptionDelegate func, string label, T value, params GUILayoutOption[] options) + { + using (EditorUtils.HorizontalScope()) + { + EditorUtils.FlexibleLabel(label, true); + return func(value, options); + } + } + public static T ShortLabelGUI(GUIWithOptionDelegate func, string label, T0 param0, T value, params GUILayoutOption[] options) + { + using (EditorUtils.HorizontalScope()) + { + EditorUtils.FlexibleLabel(label, true); + return func(param0, value, options); + } + } + public static T ShortLabelGUI(GUIDelegate func, string label, T value) + { + using (EditorUtils.HorizontalScope()) + { + EditorUtils.FlexibleLabel(label, true); + return func(value); + } + } + public static T ShortLabelGUI(GUIDelegate func, string label, T0 param0, T value) + { + using (EditorUtils.HorizontalScope()) + { + EditorUtils.FlexibleLabel(label, true); + return func(param0, value); + } + } + + public static Type EditingUnityObjectExType = null; + + public struct _EditingUnityObjectExTypeScopeImpl : IDisposable + { + public _EditingUnityObjectExTypeScopeImpl(Type type) => EditingUnityObjectExType = type; + public void Dispose() => EditingUnityObjectExType = null; + } + + public static _EditingUnityObjectExTypeScopeImpl EditingUnityObjectExTypeScope(Type type) => + new _EditingUnityObjectExTypeScopeImpl(type); + + } +} \ No newline at end of file diff --git a/Assets/URS/Utils/Editor/EditorUtils.Scope.cs.meta b/Assets/URS/Utils/Editor/EditorUtils.Scope.cs.meta new file mode 100644 index 0000000..1287944 --- /dev/null +++ b/Assets/URS/Utils/Editor/EditorUtils.Scope.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cc27c10d3ccae7347b69791c4eafb585 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/EditorUtils.Style.cs b/Assets/URS/Utils/Editor/EditorUtils.Style.cs new file mode 100644 index 0000000..2c719c1 --- /dev/null +++ b/Assets/URS/Utils/Editor/EditorUtils.Style.cs @@ -0,0 +1,215 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using UnityEngine; +using System.Text; +using System.Text.RegularExpressions; +using UnityEditor; + +namespace NinjaBeats +{ + public partial class EditorUtils + { + + // Unity Editor Built-in Icons + // https://github.com/halak/unity-editor-icons + + public const float kPrefixPaddingRight = 2; + public const float kLabelW = 80; + public const float kSpacing = 5; + public const float kSpacingSubLabel = 4; + public const float kSliderMinW = 50; + public const float kSliderMaxW = 100; + public const float kSingleLineHeight = 18f; + public const float kSingleSmallLineHeight = 16f; + public const float kStructHeaderLineHeight = 18; + public const float kObjectFieldThumbnailHeight = 64; + public const float kObjectFieldMiniThumbnailHeight = 18f; + public const float kObjectFieldMiniThumbnailWidth = 32f; + public static string kFloatFieldFormatString = "g7"; + public static string kDoubleFieldFormatString = "g15"; + public static string kIntFieldFormatString = "#######0"; + public const float kIndentPerLevel = 15; + public const int kControlVerticalSpacingLegacy = 2; + public const int kDefaultSpacing = 6; + public const int kInspTitlebarIconWidth = 16; + public const int kInspTitlebarFoldoutIconWidth = 13; + public const int kTabButtonHeight = 22; + public const string kEnabledPropertyName = "m_Enabled"; + public const string k_MultiEditValueString = "<>"; + public const float kDropDownArrowMargin = 2; + public const float kDropDownArrowWidth = 12; + public const float kDropDownArrowHeight = 12; + + + private static GUIStyle s_GS_CenteredLabel; + public static GUIStyle GS_CenteredLabel => s_GS_CenteredLabel ??= new GUIStyle("CenteredLabel"); + + private static GUIStyle s_GS_RightLabel; + public static GUIStyle GS_RightLabel => s_GS_RightLabel ??= new GUIStyle("RightLabel"); + + private static GUIStyle _GS_CenteredLabelError; + + public static GUIStyle GS_CenteredLabelError + { + get + { + if (_GS_CenteredLabelError == null) + { + _GS_CenteredLabelError = new GUIStyle("CenteredLabel"); + _GS_CenteredLabelError.normal.textColor = Color.red; + } + + return _GS_CenteredLabelError; + } + } + + private static GUIStyle _GS_ControlLabel; + + public static GUIStyle GS_ControlLabel + { + get + { + if (_GS_ControlLabel == null) + { + _GS_ControlLabel = new GUIStyle("ControlLabel"); + } + + return _GS_ControlLabel; + } + } + + static Dictionary _GUILayoutOption_MaxWidthDict = + new Dictionary(); + + public static GUILayoutOption GUILayoutOption_MaxWidth(float value) + { + if (!_GUILayoutOption_MaxWidthDict.TryGetValue(value, out var r)) + { + r = GUILayout.MaxWidth(value); + _GUILayoutOption_MaxWidthDict.Add(value, r); + } + + return r; + } + + static Dictionary _GUILayoutOption_MaxHeightDict = + new Dictionary(); + + public static GUILayoutOption GUILayoutOption_MaxHeight(float value) + { + if (!_GUILayoutOption_MaxHeightDict.TryGetValue(value, out var r)) + { + r = GUILayout.MaxHeight(value); + _GUILayoutOption_MaxHeightDict.Add(value, r); + } + + return r; + } + + static Dictionary _GUILayoutOption_WidthDict = new Dictionary(); + + public static GUILayoutOption GUILayoutOption_Width(float value) + { + if (!_GUILayoutOption_WidthDict.TryGetValue(value, out var r)) + { + r = GUILayout.Width(value); + _GUILayoutOption_WidthDict.Add(value, r); + } + + return r; + } + + static Dictionary + _GUILayoutOption_HeightDict = new Dictionary(); + + public static GUILayoutOption GUILayoutOption_Height(float value) + { + if (!_GUILayoutOption_HeightDict.TryGetValue(value, out var r)) + { + r = GUILayout.Height(value); + _GUILayoutOption_HeightDict.Add(value, r); + } + + return r; + } + + + static GUIStyle _AnimationEventTooltip; + + static GUIStyle AnimationEventTooltip + { + get + { + if (_AnimationEventTooltip == null) + { + _AnimationEventTooltip = nameof(AnimationEventTooltip); + _AnimationEventTooltip.contentOffset = new Vector2(0, 0); + _AnimationEventTooltip.overflow = new RectOffset(0, 0, 0, 0); + _AnimationEventTooltip.clipping = TextClipping.Clip; + _AnimationEventTooltip.alignment = TextAnchor.MiddleLeft; + } + + return _AnimationEventTooltip; + } + } + + static GUIStyle _AnimationEventTooltipArrow; + + static GUIStyle AnimationEventTooltipArrow => + _AnimationEventTooltipArrow ??= (GUIStyle)(nameof(AnimationEventTooltipArrow)); + + + static Texture2D _LuaIcon = null; + static bool _LuaIconInit = false; + + public static Texture2D LuaIcon + { + get + { + if (!_LuaIconInit) + { + _LuaIconInit = true; + _LuaIcon = AssetDatabase.LoadAssetAtPath("Assets/Editor/LuaScriptEditor/lua@2x.png"); + } + + return _LuaIcon; + } + } + + static Texture2D _LuaModuleIcon = null; + static bool _LuaModuleIconInit = false; + + public static Texture2D LuaModuleIcon + { + get + { + if (!_LuaModuleIconInit) + { + _LuaModuleIconInit = true; + _LuaModuleIcon = + AssetDatabase.LoadAssetAtPath("Assets/Editor/LuaScriptEditor/module@2x.png"); + } + + return _LuaModuleIcon; + } + } + + private static GUIStyle _s_GS_TextFieldImageLeft; + + public static GUIStyle s_GS_TextFieldImageLeft => _s_GS_TextFieldImageLeft ??= new GUIStyle("TextField") + { + imagePosition = ImagePosition.ImageLeft + }; + + private static GUIStyle _s_GS_TextFieldTextOnly; + + public static GUIStyle s_GS_TextFieldTextOnly => _s_GS_TextFieldTextOnly ??= new GUIStyle("TextField") + { + imagePosition = ImagePosition.TextOnly + }; + + + } +} \ No newline at end of file diff --git a/Assets/URS/Utils/Editor/EditorUtils.Style.cs.meta b/Assets/URS/Utils/Editor/EditorUtils.Style.cs.meta new file mode 100644 index 0000000..dc844c6 --- /dev/null +++ b/Assets/URS/Utils/Editor/EditorUtils.Style.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ad46c2440541a6d4abdd535448465825 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/EditorUtils.cs b/Assets/URS/Utils/Editor/EditorUtils.cs new file mode 100644 index 0000000..c67cd3e --- /dev/null +++ b/Assets/URS/Utils/Editor/EditorUtils.cs @@ -0,0 +1,968 @@ +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using UnityEngine; +using System.Text; +using System.Text.RegularExpressions; +using UnityEditor; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using UnityEditor.Animations; +using UnityEngine.Pool; + +namespace NinjaBeats +{ + public static partial class EditorUtils + { + private static Regex labelRegex = new Regex("[A-Z_]+[a-z_0-9]*"); + + static Dictionary formatLabelDict = new Dictionary(); + + public static string FormatLabel(string label) + { + if (!formatLabelDict.TryGetValue(label, out var result)) + { + StringBuilder sb = new StringBuilder(); + var matches = labelRegex.Matches(label); + var newLabel = labelRegex.Replace(label, ""); + if (newLabel.Length > 0) + { + sb.Append(newLabel[0].ToUpper()); + for (int i = 1; i < newLabel.Length; ++i) + { + sb.Append(newLabel[i]); + } + } + + for (int i = 0; i < matches.Count; ++i) + { + sb.Append(" "); + sb.Append(matches[i].Value); + } + + result = sb.ToString(); + formatLabelDict.Add(label, result); + } + + return result; + } + + + + /// + /// 将指定的自然数转换为26进制表示。映射关系:[1-26] ->[A-Z]。 + /// + /// 自然数(如果无效,则返回空字符串)。 + /// 26进制表示。 + public static string ToNumberSystem26(int n) + { + string s = string.Empty; + while (n > 0) + { + int m = n % 26; + if (m == 0) m = 26; + s = (char)(m + 64) + s; + n = (n - m) / 26; + } + + return s; + } + + /// + /// 将指定的26进制表示转换为自然数。映射关系:[A-Z] ->[1-26]。 + /// + /// 26进制表示(如果无效,则返回0)。 + /// 自然数。 + public static int FromNumberSystem26(string s) + { + if (string.IsNullOrEmpty(s)) return 0; + int n = 0; + for (int i = s.Length - 1, j = 1; i >= 0; i--, j *= 26) + { + char c = Char.ToUpper(s[i]); + if (c < 'A' || c > 'Z') return 0; + n += ((int)c - 64) * j; + } + + return n; + } + + public static string[] GetAnimStateNames(Animator animator) + { + UnityEditor.Animations.AnimatorController animatorController = + animator != null ? animator.runtimeAnimatorController as AnimatorController : null; + if (animatorController != null) + { + UnityEditor.Animations.AnimatorStateMachine stateMachine = animatorController.layers?[0]?.stateMachine; + if (stateMachine != null) + { + string[] animatorState = new string[stateMachine.states.Length]; + for (int i = 0; i < stateMachine.states.Length; i++) + { + animatorState[i] = stateMachine.states[i].state.name; + } + + return animatorState; + } + } + + return new string[] { }; + } + + public static GUILayoutOption[] Add(this GUILayoutOption[] self, GUILayoutOption option) + { + int selfCount = self?.Length ?? 0; + GUILayoutOption[] r = new GUILayoutOption[selfCount + 1]; + for (int i = 0; i < selfCount; ++i) + r[i] = self[i]; + r[selfCount] = option; + return r; + } + + public static List GetAllSelectionPrefab() + { + List result = new List(); + foreach (var guid in Selection.assetGUIDs) + { + var path = AssetDatabase.GUIDToAssetPath(guid); + if (Directory.Exists(path)) + GetAllFilesInDir(result, path, ".prefab"); + else if (File.Exists(path)) + CheckFileExtension(result, path, ".prefab"); + + } + + return result; + } + + public static List GetAllSectionFiles(string ext) + { + List result = new List(); + foreach (var guid in Selection.assetGUIDs) + { + var path = AssetDatabase.GUIDToAssetPath(guid); + if (Directory.Exists(path)) + GetAllFilesInDir(result, path, ext); + else if (File.Exists(path)) + CheckFileExtension(result, path, ext); + + } + + return result; + } + + public static List GetAllSelectionScene() + { + List result = new List(); + foreach (var guid in Selection.assetGUIDs) + { + var path = AssetDatabase.GUIDToAssetPath(guid); + if (Directory.Exists(path)) + GetAllFilesInDir(result, path, ".unity"); + else if (File.Exists(path)) + CheckFileExtension(result, path, ".unity"); + + } + + return result; + } + + public static void GetAllFilesInDir(List result, string path, string ext) + { + foreach (var dir in Directory.GetDirectories(path)) + GetAllFilesInDir(result, dir, ext); + + foreach (var dir in Directory.GetFiles(path)) + CheckFileExtension(result, dir, ext); + } + + public static string GetFileFullPathInDir(string dir, string fileName) + { + var fixFileName = fileName.Replace('\\', '/'); + var realName = Path.GetFileName(fixFileName); + foreach (var fullFileName in Directory.GetFiles(dir, realName, SearchOption.AllDirectories)) + { + var fixFullFileName = fullFileName.Replace('\\', '/'); + if (fixFullFileName.EndsWith(fixFileName, StringComparison.OrdinalIgnoreCase)) + return fixFullFileName; + } + + return string.Empty; + } + + private static void CheckFileExtension(List result, string path, string ext) + { + if (string.Equals(Path.GetExtension(path), ext, StringComparison.OrdinalIgnoreCase)) + result.Add(path); + } + + public static List LoadAllAssetsAtPath(string path) where T : UnityEngine.Object + { + List r = new List(); + var list = AssetDatabase.LoadAllAssetsAtPath(path); + foreach (var res in list) + { + if (res is T) + r.Add((T)res); + } + + return r; + } + + public static T LoadAssetAtPath(string path, string name) where T : UnityEngine.Object + { + var list = AssetDatabase.LoadAllAssetsAtPath(path); + foreach (var res in list) + { + if (res is T && res.name == name) + return (T)res; + } + + return null; + } + + public static void TryCopyFile(string src, string dst) + { + try + { + string dir = Path.GetDirectoryName(dst); + if (!Directory.Exists(dir)) + Directory.CreateDirectory(dir); + File.Copy(src, dst, true); + } + catch (Exception e) + { + + } + } + + public static string CalculateMD5(string fileName, params object[] options) + { + try + { + using (var md5 = System.Security.Cryptography.MD5.Create()) + { + byte[] hash = null; + if (options != null && options.Length > 0) + { + var content = ReadAllText(fileName); + foreach (var op in options) + content += "\n" + op.ToString(); + + var bytes = Encoding.UTF8.GetBytes(content); + hash = md5.ComputeHash(bytes); + } + else + { + using (var fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + hash = md5.ComputeHash(fs); + } + + return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); + } + } + catch + { + return ""; + } + } + + public static string CalculateMD5(List fileNameList, params object[] options) + { + if (fileNameList.Count <= 0) + return ""; + + try + { + using (var md5 = System.Security.Cryptography.MD5.Create()) + { + byte[] hash = null; + if (fileNameList.Count > 1 || (options != null && options.Length > 0)) + { + StringBuilder sb = new StringBuilder(); + foreach (var fileName in fileNameList) + { + var content = ReadAllText(fileName); + sb.Append(content); + } + + foreach (var op in options) + { + sb.Append("\n"); + sb.Append(op.ToString()); + } + + var bytes = Encoding.UTF8.GetBytes(sb.ToString()); + hash = md5.ComputeHash(bytes); + } + else + { + using (var fs = File.Open(fileNameList[0], FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + hash = md5.ComputeHash(fs); + } + + return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); + } + } + catch + { + return ""; + } + } + + public static string ReadFileFirstLine(string fileName) + { + try + { + using (var fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + { + using (var sr = new StreamReader(fs)) + { + return sr.ReadLine(); + } + } + } + catch + { + return ""; + } + } + + + public static bool ClearPath(string path, Action exceptionCallback) + { + if (!Directory.Exists(path)) + return true; + + return ForEachFiles(path, "*.*", SearchOption.AllDirectories, (value, i, iCount) => { File.Delete(value); }, + exceptionCallback); + } + + public static void DeleteFiles(string path, Func callback) + { + if (string.IsNullOrWhiteSpace(path)) + return; + if (!Directory.Exists(path)) + return; + + var files = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly); + foreach (var file in files) + { + if (callback(file)) + { + try + { + if (File.Exists(file)) + File.Delete(file); + } + catch (Exception e) + { + UnityEngine.Debug.LogError(e.Message + "\n" + e.StackTrace); + } + } + } + } + + /// + /// + /// + /// + /// + /// 返回true删除 + public static void DeleteFilesExcept(string path, HashSet exceptNameHashset, + Func extraCallback = null) + { + DeleteFiles(path, v => + { + var filename = Path.GetFileName(v); + var dotIdx = filename.IndexOf('.'); + if (dotIdx == -1) + return true; + + var purename = filename.Substring(0, dotIdx); + if (exceptNameHashset.Contains(purename)) + return false; + + if (extraCallback != null) + return extraCallback(filename); + + return true; + }); + } + + class AssetWatcherPostprocessor : AssetPostprocessor + { + public static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, + string[] movedFromAssetPaths) + { + if (s_AssetFileWatcherList.Count == 0) + return; + + if (EditorApplication.isCompiling) + { + s_AssetFileWatcherList.Clear(); + return; + } + + using (HashSetPool.Get(out var pathSet)) + { + foreach (var path in importedAssets) + pathSet.Add(path); + foreach (var path in deletedAssets) + pathSet.Add(path); + foreach (var path in movedAssets) + pathSet.Add(path); + foreach (var path in movedFromAssetPaths) + pathSet.Add(path); + + foreach (var path in pathSet) + { + var extension = Path.GetExtension(path); + foreach (var info in s_AssetFileWatcherList) + { + if (path.Contains(info.path, StringComparison.OrdinalIgnoreCase) && + info.extension.Contains(extension, StringComparison.OrdinalIgnoreCase)) + { + info.callback(path); + } + } + } + } + + } + } + + private class AssetFileWatcherInfo + { + public string path; + public string extension; + public Action callback; + } + + private static List s_AssetFileWatcherList = new(); + + public static void AddAssetFileWatcher(string path, string extension, Action callback) + { + if (string.IsNullOrWhiteSpace(path) || string.IsNullOrWhiteSpace(extension) || callback == null) + return; + + AssetFileWatcherInfo watcher = new(); + watcher.path = path.Replace('\\', '/'); + if (!watcher.path.EndsWith('/')) + watcher.path += "/"; + watcher.extension = extension; + watcher.callback = callback; + s_AssetFileWatcherList.Add(watcher); + } + + + public static bool ForEachFiles(string path, string searchPattern, SearchOption searchOption, + Action callback, Action exceptionCallback) + { + var files = Directory.GetFiles(path, "*.*", searchOption); + try + { + int len = files.Length; + for (int i = 0; i < len; ++i) + { + if (!searchPattern.Contains(Path.GetExtension(files[i]).ToLower())) + continue; + if (callback != null) + callback(files[i], i, len); + } + } + catch (Exception e) + { + if (exceptionCallback != null) + exceptionCallback(e); + return false; + } + + return true; + } + + + + public static void WriteToFile(string filePath, string content, bool checkSame = true, Encoding encoding = null) + { + string directory = Path.GetDirectoryName(filePath); + if (!Directory.Exists(directory)) + Directory.CreateDirectory(directory); + + if (File.Exists(filePath)) + { + if (checkSame) + { + string oldText = null; + try + { + oldText = File.ReadAllText(filePath); + } + catch + { + oldText = null; + } + + oldText = oldText?.Replace("\r", ""); + var newText = content.Replace("\r", ""); + if (oldText == newText) + return; + } + + File.Delete(filePath); + } + + using (var fs = File.Create(filePath)) + { + using (var sw = encoding != null ? new StreamWriter(fs, encoding) : new StreamWriter(fs)) + { + sw.Write(content); + } + } + } + + + + public static string ReadAllText(string filePath) + { + if (!File.Exists(filePath)) + return ""; + + try + { + using (var fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + using (var sr = new StreamReader(fs)) + { + return sr.ReadToEnd(); + } + } + catch + { + return ""; + } + } + + public static void WriteAllText(string filePath, string content) + { + try + { + if (File.Exists(filePath)) + File.Delete(filePath); + + var dir = Path.GetDirectoryName(filePath); + if (!Directory.Exists(dir)) + Directory.CreateDirectory(dir); + + using (var fs = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite)) + using (var sw = new StreamWriter(fs)) + { + sw.Write(content); + } + } + catch + { + + } + } + + + public static string FormatSelf(this string self, string format) + { + return string.Format(format, self); + } + + static int Indent = 0; + + public static void AppendIndentLine(this StringBuilder self, string text, int? indent = null) + { + var r = indent ?? Indent; + for (int i = 0; i < r; ++i) + self.Append('\t'); + self.AppendLine(text); + } + + public static void AppendIndent(this StringBuilder self, string text, int? indent = null) + { + var r = indent ?? Indent; + for (int i = 0; i < r; ++i) + self.Append('\t'); + self.Append(text); + } + + private static void AppendIndentCommentInternal(this StringBuilder self, string comment, int? indent = null) + { + if (string.IsNullOrEmpty(comment)) + return; + + using (StringReader sr = new StringReader(comment)) + { + string line; + while ((line = sr.ReadLine()) != null) + { + if (!string.IsNullOrEmpty(line)) + self.AppendIndentLine($"/// {line}", indent); + } + } + } + + public static void AppendIndentComment(this StringBuilder self, string comment1, int? indent = null) + { + if (string.IsNullOrEmpty(comment1)) + return; + + self.AppendIndentLine("/// ", indent); + self.AppendIndentCommentInternal(comment1, indent); + self.AppendIndentLine("/// ", indent); + } + + public static void AppendIndentComment(this StringBuilder self, string comment1, string comment2, int? indent = null) + { + if (string.IsNullOrEmpty(comment1) && string.IsNullOrEmpty(comment2)) + return; + + self.AppendIndentLine("/// ", indent); + self.AppendIndentCommentInternal(comment1, indent); + self.AppendIndentCommentInternal(comment2, indent); + self.AppendIndentLine("/// ", indent); + } + + public static void AppendIndentCommentAttribute(this StringBuilder self, string comment1, int? indent = null) + { + if (string.IsNullOrEmpty(comment1)) + return; + + self.AppendIndentLine( + $"[EditorCommentAttribute(\"{comment1.Replace("\n", "\\n").Replace("\r", "")}\")]", indent); + } + + public static void AppendIndentCommentAttribute(this StringBuilder self, string comment1, string comment2, int? indent = null) + { + if (string.IsNullOrWhiteSpace(comment1)) + { + AppendIndentCommentAttribute(self, comment2, indent); + } + else if (string.IsNullOrWhiteSpace(comment2)) + { + AppendIndentCommentAttribute(self, comment1, indent); + } + else + { + AppendIndentCommentAttribute(self, comment1 + "\n" + comment2, indent); + } + } + + public static void AppendIndentSDOwnerFieldAttribute(this StringBuilder sb, string className, string fieldName, int? indent = null) + { + sb.AppendIndentLine( + $"[SDOwnerFieldAttribute(typeof({className}), nameof({className}.{fieldName}))]", indent); + } + + public class StringBuilderIndentScope : IDisposable + { + public StringBuilderIndentScope() + { + Indent++; + } + + public void Dispose() + { + Indent--; + } + } + + public static bool CommandLineHasArg(string arg) => Environment.GetCommandLineArgs() + .IndexOf(x => string.Equals(x, arg, StringComparison.OrdinalIgnoreCase)) != -1; + + public static string CommandLineGetArgValue(string arg) + { + var argEquals = arg + "="; + var args = Environment.GetCommandLineArgs(); + var idx = args.IndexOf(x => x.StartsWith(argEquals, StringComparison.OrdinalIgnoreCase)); + if (idx == -1) + return null; + return args[idx].Substring(argEquals.Length); + } + + public static int CommandLineGetArgValueInt(string arg, int defaultValue = 0) + { + try + { + return int.TryParse(CommandLineGetArgValue(arg), out var result) ? result : defaultValue; + } + catch + { + return defaultValue; + } + } + + public static bool CommandLineGetArgValueBool(string arg, bool defaultValue = false) + { + try + { + var str = CommandLineGetArgValue(arg); + if (str == null) + return defaultValue; + if (str.Equals("1") || str.Equals("true", StringComparison.OrdinalIgnoreCase)) + return true; + return false; + } + catch + { + return defaultValue; + } + } + + + private static string s_LogErrorForCommandLinePath = + Path.Combine(Application.dataPath, "../Logs/LogErrorForCommandLine.log"); + + private static string s_LogErrorForCommandLineAsJsonContentPath = + Path.Combine(Application.dataPath, "../Logs/LogErrorForCommandLineAsJsonContent.log"); + + class LogInfo + { + public string msg; + public string trace; + public LogType type; + + public void Append(StringBuilder sb, int index) + { + sb.Append($"[{type}-{index}] {(msg.Length > 500 ? msg.Substring(0, 500) : msg)}\n\n"); + } + } + + public static string Convert2JsonContent(string text) + { + return text + .Replace("\\", "\\\\") + .Replace("\"", "\\\"") + .Replace("/", "\\/") + .Replace("\b", "\\b") + .Replace("\f", "\\f") + .Replace("\t", "\\t") + .Replace("\n", "\\n") + .Replace("\r", "\\r"); + } + + private static List s_LogErrorForCommandLine = new(); + + private static void CommandLineListenError() + { + try + { + if (File.Exists(s_LogErrorForCommandLinePath)) + File.Delete(s_LogErrorForCommandLinePath); + if (File.Exists(s_LogErrorForCommandLineAsJsonContentPath)) + File.Delete(s_LogErrorForCommandLineAsJsonContentPath); + } + catch + { + + } + + Application.logMessageReceived += (condition, trace, type) => + { + switch (type) + { + case LogType.Assert: + case LogType.Exception: + case LogType.Error: + { + s_LogErrorForCommandLine.Add(new LogInfo() + { + msg = condition, + trace = trace, + type = type, + }); + break; + } + } + }; + } + + private static void CommandLineSaveError() + { + try + { + StringBuilder sb = new(); + if (s_LogErrorForCommandLine.Count > 4) + { + s_LogErrorForCommandLine[0].Append(sb, 0); + s_LogErrorForCommandLine[1].Append(sb, 1); + + sb.Append("\n......\n\n"); + + s_LogErrorForCommandLine[s_LogErrorForCommandLine.Count - 2] + .Append(sb, s_LogErrorForCommandLine.Count - 2); + s_LogErrorForCommandLine[s_LogErrorForCommandLine.Count - 1] + .Append(sb, s_LogErrorForCommandLine.Count - 1); + } + else + { + for (int i = 0; i < s_LogErrorForCommandLine.Count; ++i) + s_LogErrorForCommandLine[i].Append(sb, i); + } + + var text = sb.ToString(); + File.WriteAllText(s_LogErrorForCommandLinePath, text); + + File.WriteAllText(s_LogErrorForCommandLineAsJsonContentPath, Convert2JsonContent(text)); + } + catch + { + + } + } + + public static void RunCommandLine(Func task) + { + int code = 0; + try + { + CommandLineListenError(); + code = task() ? 0 : 1; + } + catch (Exception e) + { + code = 1; + Debug.LogError($"{e.Message}\n{e.StackTrace}"); + } + finally + { + CommandLineSaveError(); + EditorApplication.Exit(code); + + } + } + + public static async void RunCommandLineAsync(Func> task) + { + int code = 0; + try + { + CommandLineListenError(); + var success = await task(); + code = success ? 0 : 1; + } + catch (Exception e) + { + code = 1; + Debug.LogError($"{e.Message}\n{e.StackTrace}"); + } + finally + { + CommandLineSaveError(); + EditorApplication.Exit(code); + + } + } + + + + + public delegate TValue DrawDelegate(TLabel label, TValue value); + public delegate TValue DrawWithOptionDelegate(TLabel label, TValue value, params GUILayoutOption[] options); + + public static bool DrawMixedField(this IList valueList, DrawDelegate drawFunc, TLabel label) + { + var isSame = valueList.GroupBy(x => x).Count() == 1; + + using (EditorUtils.ShowMixedValueScope(!isSame)) + { + EditorGUI.BeginChangeCheck(); + var newValue = drawFunc(label, valueList.FirstOrDefault()); + if (EditorGUI.EndChangeCheck()) + { + for (int i = 0; i < valueList.Count; ++i) + valueList[i] = newValue; + return true; + } + } + + return false; + } + + public static bool DrawMixedField(this IList valueList, + DrawWithOptionDelegate drawFunc, TLabel label) => + DrawMixedField(valueList, (a, b) => drawFunc(a, b), label); + + public static bool GetMixedValue(this IList valueList, out TValue value) + { + value = valueList.FirstOrDefault(); + return valueList.GroupBy(x => x).Count() == 1; + } + + + + public static string HttpRequest(string method, string url, (string, string)[] headers, string req_body) + { + try + { + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); + if (headers != null) + { + foreach (var pair in headers) + { + request.Headers.Add(pair.Item1, pair.Item2); + } + } + + if (method != null) + request.Method = method; + request.Timeout = 3000; + request.ContentType = "application/json"; + + if (req_body != null) + { + Debug.Log($"{method} url:{url} request:{req_body}"); + var bytes = Encoding.UTF8.GetBytes(req_body); + request.ContentLength = bytes.Length; + + using (var st = request.GetRequestStream()) + { + st.Write(bytes, 0, bytes.Length); + st.Close(); + } + } + else + { + Debug.Log($"{method} url:{url}"); + } + + string result = null; + HttpWebResponse response = (HttpWebResponse)request.GetResponse(); + Debug.Log($"response status:{response.StatusCode}"); + if (response.StatusCode == HttpStatusCode.OK) + { + using (var st = response.GetResponseStream()) + { + using (var reader = new StreamReader(st)) + { + result = reader.ReadToEnd(); + Debug.Log($"response:{result}"); + } + } + } + + response.Close(); + + return result; + } + catch (Exception e) + { + Debug.LogError($"{e.Message}\n{e.StackTrace}"); + return null; + } + } + + public static IEnumerable GetMeshes(this ModelImporter modelImporter) + { + var assetPath = AssetDatabase.GetAssetPath(modelImporter); + return AssetDatabase.LoadAllAssetsAtPath(assetPath).Where(x => x is Mesh mesh && mesh != null).Cast(); + } + } +} \ No newline at end of file diff --git a/Assets/URS/YooAsset/Editor/Utils/EditorUtils.cs.meta b/Assets/URS/Utils/Editor/EditorUtils.cs.meta similarity index 100% rename from Assets/URS/YooAsset/Editor/Utils/EditorUtils.cs.meta rename to Assets/URS/Utils/Editor/EditorUtils.cs.meta diff --git a/Assets/URS/Utils/Editor/FixedArrayPool.cs b/Assets/URS/Utils/Editor/FixedArrayPool.cs new file mode 100644 index 0000000..b5f6e0c --- /dev/null +++ b/Assets/URS/Utils/Editor/FixedArrayPool.cs @@ -0,0 +1,69 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Pool; + +namespace NinjaBeats +{ + public class FixedArrayPool + { + static Dictionary> _PoolDict = new Dictionary>(); + + public static FixedArrayPool Shared(int size) + { + if (!_PoolDict.TryGetValue(size, out var r)) + { + r = new FixedArrayPool(size); + _PoolDict.Add(size, r); + } + + return r; + } + + public Queue Objects { get; protected set; } + public int ArraySize { get; protected set; } + + public int Count + { + get { return Objects == null ? 0 : Objects.Count; } + } + + public FixedArrayPool(int arraySize) + { + Objects = new Queue(); + ArraySize = arraySize; + } + + virtual public T[] Rent() + { + if (Objects.Count > 0) + { + T[] item = Objects.Dequeue(); + if (item != null) + { + return item; + } + } + + T[] ret = new T[ArraySize]; + return ret; + } + + virtual public bool Return(T[] item) + { + if (item == null) + return false; + if (item.Length != ArraySize) + return false; + + System.Array.Clear(item, 0, ArraySize); + Objects.Enqueue(item); + return true; + } + + public T[][] ToArray() + { + return Objects.ToArray(); + } + } +} \ No newline at end of file diff --git a/Assets/URS/Utils/Editor/FixedArrayPool.cs.meta b/Assets/URS/Utils/Editor/FixedArrayPool.cs.meta new file mode 100644 index 0000000..46f0a66 --- /dev/null +++ b/Assets/URS/Utils/Editor/FixedArrayPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 04ae5dd910b81e0449355d8357104bfb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/FpsHelper.cs b/Assets/URS/Utils/Editor/FpsHelper.cs new file mode 100644 index 0000000..81e9e96 --- /dev/null +++ b/Assets/URS/Utils/Editor/FpsHelper.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using UnityEngine; + +public class FpsHelper : MonoBehaviour +{ + private static FpsHelper s_Instance; + + public static FpsHelper instance + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if (s_Instance == null) + { + var go = new GameObject("FpsHelper"); + DontDestroyOnLoad(go); + s_Instance = go.AddComponent(); + } + + return s_Instance; + } + } + private float m_FrameStartTime = 0; + private bool m_FrameStartTimeFlag = true; + private float m_MinFps = 30; + private float m_MaxFrameCostTime = 1; + private bool m_MinFpsChanged = true; + private float m_ThresholdRate = 0.8f; + public float thresholdRate + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => m_ThresholdRate; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => m_ThresholdRate = Mathf.Clamp01(value); + } + + public float frameCostTime + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => Time.realtimeSinceStartup - m_FrameStartTime; + } + + public float minFps + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + if (m_MinFpsChanged) + minFps = Application.targetFrameRate; + return m_MinFps; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set + { + m_MinFps = Mathf.Clamp(value, 1.0f, 60.0f); + m_MaxFrameCostTime = 1.0f / m_MinFps; + } + } + + public bool needWait + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => frameCostTime >= m_MaxFrameCostTime * m_ThresholdRate; + } + + void Awake() + { + m_FrameStartTime = Time.realtimeSinceStartup; + m_FrameStartTimeFlag = true; + m_MinFpsChanged = true; + GameSettings.onFrameRateChanged += OnFrameRateChanged; + } + + private void OnDestroy() + { + GameSettings.onFrameRateChanged -= OnFrameRateChanged; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + void OnFrameRateChanged(string value) + { + m_MinFpsChanged = true; + } + + void FixedUpdate() + { + if (m_FrameStartTimeFlag) + { + m_FrameStartTimeFlag = false; + m_FrameStartTime = Time.realtimeSinceStartup; + } + } + + void Update() + { + m_FrameStartTimeFlag = true; + } +} diff --git a/Assets/URS/Utils/Editor/FpsHelper.cs.meta b/Assets/URS/Utils/Editor/FpsHelper.cs.meta new file mode 100644 index 0000000..a501bc4 --- /dev/null +++ b/Assets/URS/Utils/Editor/FpsHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e4a26274d61b1814cbae72c1b214cca4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: -20000 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/GameSettings.cs b/Assets/URS/Utils/Editor/GameSettings.cs new file mode 100644 index 0000000..3164ae2 --- /dev/null +++ b/Assets/URS/Utils/Editor/GameSettings.cs @@ -0,0 +1,34 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using NinjaBeats; +using System; +using System.Runtime.CompilerServices; + +public static class GameSettings +{ + + // FrameRate Setting to int + public static int? FrameRateInt + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => PlayerPrefs.HasKey("GAME_FRAMERATE") ? FrameRate?.ToInt32() : null; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => FrameRate = value?.ToString(); + } + + public static Action onFrameRateChanged; + + // FrameRate Setting + public static string FrameRate + { + get => PlayerPrefs.GetString("GAME_FRAMERATE"); + set + { + PlayerPrefs.SetString("GAME_FRAMERATE", value); + onFrameRateChanged?.Invoke(value); + } + } + + +} \ No newline at end of file diff --git a/Assets/URS/Utils/Editor/GameSettings.cs.meta b/Assets/URS/Utils/Editor/GameSettings.cs.meta new file mode 100644 index 0000000..1f9b549 --- /dev/null +++ b/Assets/URS/Utils/Editor/GameSettings.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1b691d25f15f80f4c90d0c789b9480e0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/PoolExtension.cs b/Assets/URS/Utils/Editor/PoolExtension.cs new file mode 100644 index 0000000..e5e91e5 --- /dev/null +++ b/Assets/URS/Utils/Editor/PoolExtension.cs @@ -0,0 +1,16 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace NinjaBeats +{ + + public static class _PoolExtension + { + public static void ReleaseToPool(this List self) => UnityEngine.Pool.ListPool.Release(self); + public static void ReleaseToPool(this HashSet self) => UnityEngine.Pool.HashSetPool.Release(self); + + public static void ReturnToFixedArrayPool(this T[] self) => + FixedArrayPool.Shared(self.Length).Return(self); + } +} \ No newline at end of file diff --git a/Assets/URS/Utils/Editor/PoolExtension.cs.meta b/Assets/URS/Utils/Editor/PoolExtension.cs.meta new file mode 100644 index 0000000..06e6146 --- /dev/null +++ b/Assets/URS/Utils/Editor/PoolExtension.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f8ef76c1f7615544b965ad76d02ee1e9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper.meta b/Assets/URS/Utils/Editor/ReflectionHelper.meta new file mode 100644 index 0000000..de43b8c --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 566c499c39527cd43a96fbe44f9b8f15 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/GenHookTool.cs b/Assets/URS/Utils/Editor/ReflectionHelper/GenHookTool.cs new file mode 100644 index 0000000..71edaac --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/GenHookTool.cs @@ -0,0 +1,186 @@ +using UnityEngine; +using UnityEditor; +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using NinjaBeats.ReflectionHelper; +using Unity.Jobs; + +namespace NinjaBeats +{ + + public partial class ReflectionTool + { + public class GenHookTool : GenToolBase + { + public override GenInfoBase[] genInfoList => s_HookInfoList; + + public class GenHookJob : GenJobBase + { + public GenHookJob(GenToolBase genTool, MemberCollection collection) : base(genTool, collection) + { + this.fileName = $"Hook_{this.typeFlatName}.cs"; + } + + void DoMethodImpl(Member m, MonoHookType hookType, bool isStatic, TypeName returnTypeName, ParameterTypeName[] parameterTypeNames) + { + var strAccess = isStatic ? "static " : ""; + line(); + line($"[MonoHook{(hookType != MonoHookType.Method ? $"(MonoHookType.{hookType})" : "")}]"); + line($"public class {m.uniqueName}"); + line("{"); + indent++; + { + var parameterDecl = string.Join(", ", parameterTypeNames.Select(x => $"{x.ParameterModifier}{x.typeName.name} {x.parameter.Name}")); + + comment($""); + line($"public static string {k_TYPE} = \"{typeFullName}\";"); + line($"public delegate {returnTypeName.name} {k_DELEGATE}({parameterDecl});"); + + line(); + line($"public struct Param"); + line("{"); + indent++; + { + foreach (var p in parameterTypeNames) + { + line($"public {p.typeName.name} {p.parameter.Name};"); + } + + line(); + if (!isStatic) + line($"public object {k_THIS};"); + if (returnTypeName.mode != TypeNameMode.Void) + line($"public {returnTypeName.name} {k_RESULT};"); + line($"public {k_DELEGATE} {k_ORIGINAL};"); + } + indent--; + line("}"); + + line(); + line($"public delegate bool BeginDelegate(ref Param param);"); + line($"public delegate void EndDelegate(ref Param param);"); + line($"public static BeginDelegate OnBegin = null;"); + line($"public static EndDelegate OnEnd = null;"); + + line(); + line($"[MethodImpl(MethodImplOptions.NoOptimization)]"); + line($"public {strAccess}{returnTypeName.name} {k_REPLACE}({parameterDecl})"); + line("{"); + indent++; + { + line($"Param param = new();"); + foreach (var p in parameterTypeNames) + line($"param.{p.parameter.Name} = {p.parameter.Name};"); + if (!isStatic) + line($"param.{k_THIS} = this;"); + if (returnTypeName.mode != TypeNameMode.Void) + line($"param.{k_RESULT} = default;"); + line($"param.{k_ORIGINAL} = {k_ORIGINAL};"); + + line(); + line($"if (OnBegin?.Invoke(ref param) == true)"); + indent++; + { + if (returnTypeName.mode != TypeNameMode.Void) + line($"return param.{k_RESULT};"); + else + line($"return;"); + } + indent--; + + line(); + line($"{(returnTypeName.mode != TypeNameMode.Void ? $"param.{k_RESULT} = " : "")}{k_ORIGINAL}({string.Join(", ", parameterTypeNames.Select(x => $"{x.ParameterModifier}param.{x.parameter.Name}"))});"); + line(); + line($"OnEnd?.Invoke(ref param);"); + + if (returnTypeName.mode != TypeNameMode.Void) + line($"return param.{k_RESULT};"); + } + indent--; + line("}"); + + line(); + line($"[MethodImpl(MethodImplOptions.NoOptimization)]"); + line($"public {strAccess}{returnTypeName.name} {k_ORIGINAL}({parameterDecl})"); + line("{"); + indent++; + { + if (returnTypeName.mode != TypeNameMode.Void) + line($"return default;"); + } + indent--; + line("}"); + } + indent--; + line("}"); + } + + void DoMethod() + { + foreach (var m in collection.methods) + { + var methodInfo = m.methodInfo; + var returnTypeName = GetTypeName(methodInfo.ReturnType); + var parameterTypeNames = methodInfo.GetParameters().Select(GetTypeName).ToArray(); + DoMethodImpl(m, MonoHookType.Method, methodInfo.IsStatic, returnTypeName, parameterTypeNames); + } + } + + void DoConstructor() + { + foreach (var m in collection.constructors) + { + var constructorInfo = m.constructorInfo; + var returnTypeName = GetTypeName(typeof(void)); + var parameterTypeNames = constructorInfo.GetParameters().Select(GetTypeName).ToArray(); + DoMethodImpl(m, MonoHookType.Constructor, false, returnTypeName, parameterTypeNames); + } + } + + public override void Execute() + { + line("//This file was automatically generated by kuroneko."); + line("using System;"); + line("using System.Reflection;"); + line("using System.Runtime.CompilerServices;"); + line(); + line($"namespace NinjaBeats.ReflectionHelper"); + line("{"); + indent++; + { + line($"public partial struct {typeFlatName}"); + line("{"); + indent++; + { + line($"public static class {k_HOOK}"); + line("{"); + indent++; + { + DoMethod(); + DoConstructor(); + } + indent--; + line("}"); + } + indent--; + line("}"); + } + indent--; + line("}"); + + Save(); + } + } + + public override GenJobBase CreateJob(MemberCollection collection) => new GenHookJob(this, collection); + } + + } +} \ No newline at end of file diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/GenHookTool.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/GenHookTool.cs.meta new file mode 100644 index 0000000..0d4def5 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/GenHookTool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5574edb6dc937874591676035a685cd5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/GenWrapTool.cs b/Assets/URS/Utils/Editor/ReflectionHelper/GenWrapTool.cs new file mode 100644 index 0000000..2bdf4e8 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/GenWrapTool.cs @@ -0,0 +1,380 @@ +using UnityEngine; +using UnityEditor; +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using Unity.Jobs; + +namespace NinjaBeats +{ + + public partial class ReflectionTool + { + + public class GenWrapTool : GenToolBase + { + public override GenInfoBase[] genInfoList => s_WrapInfoList; + + public class GenWrapJob : GenJobBase + { + public GenWrapJob(GenToolBase genTool, MemberCollection collection) : base(genTool, collection) + { + this.fileName = $"Wrap_{this.typeFlatName}.cs"; + } + + void DoType() + { + line(); + comment($""); + line($"public static Type {k_TYPE} {{ get; }} = EditorUtils.GetTypeByFullName(\"{typeFullName}\");"); + } + + void DoFieldElementTypeReflection(Member m) + { + var memberType = m.memberInfo.GetRealMemberType(); + var memberTypeName = GetTypeName(memberType); + + switch (memberTypeName.mode) + { + case TypeNameMode.Array: + case TypeNameMode.List: + { + if (memberType.GetArrayOrListElementType(out var elementType)) + { + line(); + line($"private static Type _{k_ELEMENT_PREFIX}{k_PREFIX}{m.uniqueName};"); + line($"public static Type {k_ELEMENT_PREFIX}{k_PREFIX}{m.uniqueName}"); + line("{"); + indent++; + { + line("[MethodImpl(MethodImplOptions.AggressiveInlining)]"); + line($"get => _{k_ELEMENT_PREFIX}{k_PREFIX}{m.uniqueName} ??= EditorUtils.GetTypeByFullName(\"{elementType.FullName}\");"); + } + indent--; + line("}"); + } + break; + } + } + } + + void DoFieldReflection() + { + foreach (var m in collection.fields) + { + line(); + line($"private static FieldInfo _{k_PREFIX}{m.uniqueName};"); + line($"private static FieldInfo {k_PREFIX}{m.uniqueName}"); + line("{"); + indent++; + line("[MethodImpl(MethodImplOptions.AggressiveInlining)]"); + line($"get => _{k_PREFIX}{m.uniqueName} ??= {k_TYPE}?.GetField(\"{m.rawName}\", (BindingFlags)(-1));"); + indent--; + line("}"); + + DoFieldElementTypeReflection(m); + } + + foreach (var m in collection.properties) + { + line(); + line($"private static PropertyInfo _{k_PREFIX}{m.uniqueName};"); + line($"private static PropertyInfo {k_PREFIX}{m.uniqueName}"); + line("{"); + indent++; + line("[MethodImpl(MethodImplOptions.AggressiveInlining)]"); + line($"get => _{k_PREFIX}{m.uniqueName} ??= {k_TYPE}?.GetProperty(\"{m.rawName}\", (BindingFlags)(-1));"); + indent--; + line("}"); + + DoFieldElementTypeReflection(m); + } + } + + void DoMethodReflection() + { + foreach (var m in collection.methods) + { + var parameters = m.methodInfo.GetParameters(); + line(); + line($"private static MethodInfo _{k_PREFIX}{m.uniqueName};"); + line($"private static MethodInfo {k_PREFIX}{m.uniqueName}"); + line("{"); + indent++; + line("[MethodImpl(MethodImplOptions.AggressiveInlining)]"); + if (parameters.Length == 0) + line($"get => _{k_PREFIX}{m.uniqueName} ??= {k_TYPE}?.GetMethodInfoByParameterTypeNames(\"{m.rawName}\");"); + else + line($"get => _{k_PREFIX}{m.uniqueName} ??= {k_TYPE}?.GetMethodInfoByParameterTypeNames(\"{m.rawName}\", {string.Join(", ", parameters.Select(p => $"\"{p.ParameterType.FullName}\""))});"); + indent--; + line("}"); + } + } + + void DoCtor() + { + if (typeIsStatic) + return; + + line(); + line($"public {typeFlatName}(object {k_SELF}) => this.{k_SELF} = {k_SELF} as {objectTypeName};"); + line($"public {objectTypeName} {k_SELF};"); + line($"public bool {k_VALID}"); + line("{"); + indent++; + { + line("[MethodImpl(MethodImplOptions.AggressiveInlining)]"); + line($"get => {k_SELF} != null && {k_TYPE} != null;"); + } + indent--; + line("}"); + + var superType = GetSuperType(type); + if (superType == null) + return; + + var superTypeName = GetTypeName(superType); + line($"public {superTypeName.name} {k_SUPER}"); + line("{"); + indent++; + { + line("[MethodImpl(MethodImplOptions.AggressiveInlining)]"); + line($"get => {superTypeName.Cast(k_SELF)};"); + } + indent--; + line("}"); + } + + void DoField() + { + foreach (var m in collection.fieldOrProperties) + { + var memberInfo = m.memberInfo; + var isStatic = memberInfo.IsRealStatic(); + var canRead = memberInfo.IsRealCanRead(); + var canWrite = memberInfo.IsRealCanWrite(); + var memberType = memberInfo.GetRealMemberType(); + var memberTypeName = GetTypeName(memberType); + + var strAccess = isStatic ? " static " : " "; + var strType = $"{k_PREFIX}{m.uniqueName}.{(m.fieldInfo != null ? "FieldType" : "PropertyType")}"; + var strObj = isStatic ? "null" : k_SELF; + var strMember = m.rawName; + line(); + line($"public{strAccess}{memberTypeName.name} {strMember}"); + line("{"); + indent++; + { + if (canRead) + { + line("[MethodImpl(MethodImplOptions.AggressiveInlining)]"); + line($"get => {memberTypeName.Cast($"{k_PREFIX}{m.uniqueName}?.GetValue({strObj})")};"); + } + + if (canWrite) + { + line("[MethodImpl(MethodImplOptions.AggressiveInlining)]"); + line($"set => {k_PREFIX}{m.uniqueName}?.SetValue({strObj}, {memberTypeName.CastTo("value", strType)});"); + } + } + indent--; + line("}"); + + if (canRead) + { + switch (memberTypeName.mode) + { + case TypeNameMode.Array: + { + var elementType = memberType.GetElementType(); + var elementTypeName = GetTypeName(elementType); + line(); + line("[MethodImpl(MethodImplOptions.AggressiveInlining)]"); + line($"public{strAccess}{elementTypeName.name} {strMember}{k_PREFIX}GetItem(int i) => {elementTypeName.Cast($"{strMember}?.GetValue(i)")};"); + line("[MethodImpl(MethodImplOptions.AggressiveInlining)]"); + line($"public{strAccess}void {strMember}{k_PREFIX}SetItem(int i, {elementTypeName.name} value) => {strMember}?.SetValue({elementTypeName.CastTo("value", $"{k_ELEMENT_PREFIX}{k_PREFIX}{m.uniqueName}")}, i);"); + break; + } + case TypeNameMode.List: + { + if (memberType.GetArrayOrListElementType(out var elementType)) + { + var elementTypeName = GetTypeName(elementType); + line(); + line("[MethodImpl(MethodImplOptions.AggressiveInlining)]"); + line($"public{strAccess}{elementTypeName.name} {strMember}{k_PREFIX}GetItem(int i) => {elementTypeName.Cast($"{strMember}?[i]")};"); + line("[MethodImpl(MethodImplOptions.AggressiveInlining)]"); + line($"public{strAccess}void {strMember}{k_PREFIX}SetItem(int i, {elementTypeName.name} value)"); + line("{"); + indent++; + { + line($"var __list__ = {strMember};"); + line($"if (__list__ == null) return;"); + line($"__list__[i] = {elementTypeName.CastTo("value", $"{k_ELEMENT_PREFIX}{k_PREFIX}{m.uniqueName}")};"); + } + indent--; + line("}"); + } + + break; + } + } + } + } + } + + void DoMethod() + { + foreach (var m in collection.methods) + { + var methodInfo = m.methodInfo; + var isStatic = methodInfo.IsRealStatic(); + var strAccess = isStatic ? " static " : " "; + var strObj = isStatic ? "null" : k_SELF; + var strMethod = m.rawName; + var strGenericDecl = methodInfo.IsGenericMethod ? $"<{string.Join(", ", methodInfo.GetGenericArguments().Select(x => x.Name))}>" : ""; + var parameters = methodInfo.GetParameters(); + var parameterTypeNames = parameters.Select(GetTypeName).ToArray(); + var strParamDecl = string.Join(", ", parameterTypeNames.Select(x => $"{x.ParameterModifier}{x.typeName.name} {x.parameter.Name}")); + var returnTypeName = GetTypeName(methodInfo.ReturnType); + line(); + line($"public{strAccess}{returnTypeName.name} {strMethod}{strGenericDecl}({strParamDecl})"); + line("{"); + indent++; + { + string strParam; + if (parameterTypeNames.Length > 0) + { + strParam = "__params__"; + + line($"var __pool__ = FixedArrayPool.Shared({parameters.Length});"); + line($"var __params__ = __pool__.Rent();"); + for (var i = 0; i < parameterTypeNames.Length; i++) + { + var p = parameterTypeNames[i]; + if (p.refMode == RefMode.Out) + { + var flags = methodInfo.MethodImplementationFlags; + if ((flags & MethodImplAttributes.InternalCall) != 0 || + (flags & MethodImplAttributes.Native) != 0 || + (flags & MethodImplAttributes.PreserveSig) != 0) + { + if (p.typeName.mode == TypeNameMode.Wrap) + line($"__params__[{i}] = Activator.CreateInstance({p.typeName.name}.{k_TYPE});"); + else + line($"__params__[{i}] = Activator.CreateInstance(typeof({p.typeName.name}));"); + } + else + { + line($"__params__[{i}] = null;"); + } + } + else + { + line($"__params__[{i}] = {p.GetValue(p.parameter.Name)};"); + } + } + } + else + { + strParam = "System.Array.Empty()"; + } + + if (returnTypeName.mode == TypeNameMode.Void) + line($"{k_PREFIX}{m.uniqueName}?.Invoke({strObj}, {strParam});"); + else + line($"var __result__ = {k_PREFIX}{m.uniqueName}?.Invoke({strObj}, {strParam});"); + + if (parameterTypeNames.Length > 0) + { + for (var i = 0; i < parameterTypeNames.Length; i++) + { + var p = parameterTypeNames[i]; + if (p.refMode == RefMode.Out || p.refMode == RefMode.Ref) + line($"{p.parameter.Name} = {p.Cast($"__params__[{i}]")};"); + } + + line($"__pool__.Return(__params__);"); + } + + if (returnTypeName.mode != TypeNameMode.Void) + line($"return __result__ != null ? {returnTypeName.Cast("__result__")} : default;"); + } + indent--; + line("}"); + } + } + + void DoDelegate() + { + line(); + foreach (var m in collection.delegates) + { + var delegateInfo = m.delegateInfo; + var methodInfo = delegateInfo.GetMethod("Invoke"); + var returnTypeName = GetTypeName(methodInfo.ReturnType); + var parameters = methodInfo.GetParameters(); + var parameterTypeNames = parameters.Select(GetTypeName).ToArray(); + + line($"public delegate {returnTypeName.name} {m.rawName}({string.Join(", ", parameterTypeNames.Select(x => $"{x.ParameterModifier}{x.typeName.name} {x.parameter.Name}"))});"); + } + } + + public override void Execute() + { + line("//This file was automatically generated by kuroneko."); + line("using System;"); + line("using System.Reflection;"); + line("using System.Runtime.CompilerServices;"); + line(); + line($"namespace NinjaBeats.ReflectionHelper"); + line("{"); + indent++; + { + line($"public partial struct {typeFlatName}"); + line("{"); + indent++; + { + DoType(); + DoDelegate(); + DoField(); + DoMethod(); + DoCtor(); + DoFieldReflection(); + DoMethodReflection(); + } + indent--; + line("}"); + + if (type.IsRealPublic() && !typeIsStatic) + { + line($"public static class {typeFlatName}_Extension"); + line("{"); + indent++; + { + line($"public static {typeFlatName} ReflectionHelper(this {typeFullName} self) => new(self);"); + } + indent--; + line("}"); + } + } + indent--; + line("}"); + + Save(); + } + } + + public override GenJobBase CreateJob(MemberCollection collection) => new GenWrapJob(this, collection); + } + + + } +} \ No newline at end of file diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/GenWrapTool.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/GenWrapTool.cs.meta new file mode 100644 index 0000000..dd6ea41 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/GenWrapTool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1bbaedad98a3d5641bca2788ae75295e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated.meta new file mode 100644 index 0000000..35b1ade --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6a7e5f8ebb531de4a8e622d44defa70b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_AnimationClipInfoProperties.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_AnimationClipInfoProperties.cs new file mode 100644 index 0000000..ea7c4d6 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_AnimationClipInfoProperties.cs @@ -0,0 +1,152 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_AnimationClipInfoProperties + { + public static class __hook__ + { + + [MonoHook] + public class AddEvent + { + /// + /// + /// + public static string __type__ = "UnityEditor.AnimationClipInfoProperties"; + public delegate void __delegate__(float time); + + public struct Param + { + public float time; + + public object __this__; + public __delegate__ __original__; + } + + public delegate bool BeginDelegate(ref Param param); + public delegate void EndDelegate(ref Param param); + public static BeginDelegate OnBegin = null; + public static EndDelegate OnEnd = null; + + [MethodImpl(MethodImplOptions.NoOptimization)] + public void __replace__(float time) + { + Param param = new(); + param.time = time; + param.__this__ = this; + param.__original__ = __original__; + + if (OnBegin?.Invoke(ref param) == true) + return; + + __original__(param.time); + + OnEnd?.Invoke(ref param); + } + + [MethodImpl(MethodImplOptions.NoOptimization)] + public void __original__(float time) + { + } + } + + [MonoHook] + public class SetEvent + { + /// + /// + /// + public static string __type__ = "UnityEditor.AnimationClipInfoProperties"; + public delegate void __delegate__(int index, UnityEngine.AnimationEvent animationEvent); + + public struct Param + { + public int index; + public UnityEngine.AnimationEvent animationEvent; + + public object __this__; + public __delegate__ __original__; + } + + public delegate bool BeginDelegate(ref Param param); + public delegate void EndDelegate(ref Param param); + public static BeginDelegate OnBegin = null; + public static EndDelegate OnEnd = null; + + [MethodImpl(MethodImplOptions.NoOptimization)] + public void __replace__(int index, UnityEngine.AnimationEvent animationEvent) + { + Param param = new(); + param.index = index; + param.animationEvent = animationEvent; + param.__this__ = this; + param.__original__ = __original__; + + if (OnBegin?.Invoke(ref param) == true) + return; + + __original__(param.index, param.animationEvent); + + OnEnd?.Invoke(ref param); + } + + [MethodImpl(MethodImplOptions.NoOptimization)] + public void __original__(int index, UnityEngine.AnimationEvent animationEvent) + { + } + } + + [MonoHook] + public class GetEvent + { + /// + /// + /// + public static string __type__ = "UnityEditor.AnimationClipInfoProperties"; + public delegate UnityEngine.AnimationEvent __delegate__(int index); + + public struct Param + { + public int index; + + public object __this__; + public UnityEngine.AnimationEvent __result__; + public __delegate__ __original__; + } + + public delegate bool BeginDelegate(ref Param param); + public delegate void EndDelegate(ref Param param); + public static BeginDelegate OnBegin = null; + public static EndDelegate OnEnd = null; + + [MethodImpl(MethodImplOptions.NoOptimization)] + public UnityEngine.AnimationEvent __replace__(int index) + { + Param param = new(); + param.index = index; + param.__this__ = this; + param.__result__ = default; + param.__original__ = __original__; + + if (OnBegin?.Invoke(ref param) == true) + return param.__result__; + + param.__result__ = __original__(param.index); + + OnEnd?.Invoke(ref param); + return param.__result__; + } + + [MethodImpl(MethodImplOptions.NoOptimization)] + public UnityEngine.AnimationEvent __original__(int index) + { + return default; + } + } + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_AnimationClipInfoProperties.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_AnimationClipInfoProperties.cs.meta new file mode 100644 index 0000000..566c215 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_AnimationClipInfoProperties.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 651eda2b29c914c4f8bc8f189b1a962e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_AnimationWindowEventInspector.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_AnimationWindowEventInspector.cs new file mode 100644 index 0000000..e79ca14 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_AnimationWindowEventInspector.cs @@ -0,0 +1,58 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_AnimationWindowEventInspector + { + public static class __hook__ + { + + [MonoHook] + public class DoEditRegularParameters + { + /// + /// + /// + public static string __type__ = "UnityEditor.AnimationWindowEventInspector"; + public delegate void __delegate__(UnityEngine.AnimationEvent[] events, System.Type selectedParameter); + + public struct Param + { + public UnityEngine.AnimationEvent[] events; + public System.Type selectedParameter; + + public __delegate__ __original__; + } + + public delegate bool BeginDelegate(ref Param param); + public delegate void EndDelegate(ref Param param); + public static BeginDelegate OnBegin = null; + public static EndDelegate OnEnd = null; + + [MethodImpl(MethodImplOptions.NoOptimization)] + public static void __replace__(UnityEngine.AnimationEvent[] events, System.Type selectedParameter) + { + Param param = new(); + param.events = events; + param.selectedParameter = selectedParameter; + param.__original__ = __original__; + + if (OnBegin?.Invoke(ref param) == true) + return; + + __original__(param.events, param.selectedParameter); + + OnEnd?.Invoke(ref param); + } + + [MethodImpl(MethodImplOptions.NoOptimization)] + public static void __original__(UnityEngine.AnimationEvent[] events, System.Type selectedParameter) + { + } + } + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_AnimationWindowEventInspector.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_AnimationWindowEventInspector.cs.meta new file mode 100644 index 0000000..b0089be --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_AnimationWindowEventInspector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 225a412c37db96543944075f34878d1c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_ConsoleWindow.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_ConsoleWindow.cs new file mode 100644 index 0000000..acddf99 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_ConsoleWindow.cs @@ -0,0 +1,62 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_ConsoleWindow + { + public static class __hook__ + { + + [MonoHook] + public class StacktraceWithHyperlinks + { + /// + /// + /// + public static string __type__ = "UnityEditor.ConsoleWindow"; + public delegate string __delegate__(string stacktraceText, int callstackTextStart); + + public struct Param + { + public string stacktraceText; + public int callstackTextStart; + + public string __result__; + public __delegate__ __original__; + } + + public delegate bool BeginDelegate(ref Param param); + public delegate void EndDelegate(ref Param param); + public static BeginDelegate OnBegin = null; + public static EndDelegate OnEnd = null; + + [MethodImpl(MethodImplOptions.NoOptimization)] + public static string __replace__(string stacktraceText, int callstackTextStart) + { + Param param = new(); + param.stacktraceText = stacktraceText; + param.callstackTextStart = callstackTextStart; + param.__result__ = default; + param.__original__ = __original__; + + if (OnBegin?.Invoke(ref param) == true) + return param.__result__; + + param.__result__ = __original__(param.stacktraceText, param.callstackTextStart); + + OnEnd?.Invoke(ref param); + return param.__result__; + } + + [MethodImpl(MethodImplOptions.NoOptimization)] + public static string __original__(string stacktraceText, int callstackTextStart) + { + return default; + } + } + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_ConsoleWindow.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_ConsoleWindow.cs.meta new file mode 100644 index 0000000..b8833e6 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_ConsoleWindow.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3b19e7c7a3321454fa20392ebb95fbbd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EditorGUIExt.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EditorGUIExt.cs new file mode 100644 index 0000000..09cfa76 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EditorGUIExt.cs @@ -0,0 +1,62 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_EditorGUIExt + { + public static class __hook__ + { + + [MonoHook] + public class GetIndexUnderMouse + { + /// + /// + /// + public static string __type__ = "UnityEditor.EditorGUIExt"; + public delegate int __delegate__(UnityEngine.Rect[] hitPositions, bool[] readOnly); + + public struct Param + { + public UnityEngine.Rect[] hitPositions; + public bool[] readOnly; + + public int __result__; + public __delegate__ __original__; + } + + public delegate bool BeginDelegate(ref Param param); + public delegate void EndDelegate(ref Param param); + public static BeginDelegate OnBegin = null; + public static EndDelegate OnEnd = null; + + [MethodImpl(MethodImplOptions.NoOptimization)] + public static int __replace__(UnityEngine.Rect[] hitPositions, bool[] readOnly) + { + Param param = new(); + param.hitPositions = hitPositions; + param.readOnly = readOnly; + param.__result__ = default; + param.__original__ = __original__; + + if (OnBegin?.Invoke(ref param) == true) + return param.__result__; + + param.__result__ = __original__(param.hitPositions, param.readOnly); + + OnEnd?.Invoke(ref param); + return param.__result__; + } + + [MethodImpl(MethodImplOptions.NoOptimization)] + public static int __original__(UnityEngine.Rect[] hitPositions, bool[] readOnly) + { + return default; + } + } + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EditorGUIExt.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EditorGUIExt.cs.meta new file mode 100644 index 0000000..167047e --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EditorGUIExt.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c64e6b65164f3954da92c1e4ed54c8ef +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EditorGUIUtility.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EditorGUIUtility.cs new file mode 100644 index 0000000..976700a --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EditorGUIUtility.cs @@ -0,0 +1,64 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_EditorGUIUtility + { + public static class __hook__ + { + + [MonoHook] + public class ObjectContent + { + /// + /// + /// + public static string __type__ = "UnityEditor.EditorGUIUtility"; + public delegate UnityEngine.GUIContent __delegate__(UnityEngine.Object obj, System.Type type, int instanceID); + + public struct Param + { + public UnityEngine.Object obj; + public System.Type type; + public int instanceID; + + public UnityEngine.GUIContent __result__; + public __delegate__ __original__; + } + + public delegate bool BeginDelegate(ref Param param); + public delegate void EndDelegate(ref Param param); + public static BeginDelegate OnBegin = null; + public static EndDelegate OnEnd = null; + + [MethodImpl(MethodImplOptions.NoOptimization)] + public static UnityEngine.GUIContent __replace__(UnityEngine.Object obj, System.Type type, int instanceID) + { + Param param = new(); + param.obj = obj; + param.type = type; + param.instanceID = instanceID; + param.__result__ = default; + param.__original__ = __original__; + + if (OnBegin?.Invoke(ref param) == true) + return param.__result__; + + param.__result__ = __original__(param.obj, param.type, param.instanceID); + + OnEnd?.Invoke(ref param); + return param.__result__; + } + + [MethodImpl(MethodImplOptions.NoOptimization)] + public static UnityEngine.GUIContent __original__(UnityEngine.Object obj, System.Type type, int instanceID) + { + return default; + } + } + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EditorGUIUtility.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EditorGUIUtility.cs.meta new file mode 100644 index 0000000..cd41541 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EditorGUIUtility.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: df475d44564797d4facb9463b25febb6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EditorUtility.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EditorUtility.cs new file mode 100644 index 0000000..5d7ea65 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EditorUtility.cs @@ -0,0 +1,68 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_EditorUtility + { + public static class __hook__ + { + + [MonoHook] + public class DisplayCustomMenu + { + /// + /// + /// + public static string __type__ = "UnityEditor.EditorUtility"; + public delegate void __delegate__(UnityEngine.Rect position, UnityEngine.GUIContent[] options, System.Func checkEnabled, int selected, UnityEditor.EditorUtility.SelectMenuItemFunction callback, object userData, bool showHotkey); + + public struct Param + { + public UnityEngine.Rect position; + public UnityEngine.GUIContent[] options; + public System.Func checkEnabled; + public int selected; + public UnityEditor.EditorUtility.SelectMenuItemFunction callback; + public object userData; + public bool showHotkey; + + public __delegate__ __original__; + } + + public delegate bool BeginDelegate(ref Param param); + public delegate void EndDelegate(ref Param param); + public static BeginDelegate OnBegin = null; + public static EndDelegate OnEnd = null; + + [MethodImpl(MethodImplOptions.NoOptimization)] + public static void __replace__(UnityEngine.Rect position, UnityEngine.GUIContent[] options, System.Func checkEnabled, int selected, UnityEditor.EditorUtility.SelectMenuItemFunction callback, object userData, bool showHotkey) + { + Param param = new(); + param.position = position; + param.options = options; + param.checkEnabled = checkEnabled; + param.selected = selected; + param.callback = callback; + param.userData = userData; + param.showHotkey = showHotkey; + param.__original__ = __original__; + + if (OnBegin?.Invoke(ref param) == true) + return; + + __original__(param.position, param.options, param.checkEnabled, param.selected, param.callback, param.userData, param.showHotkey); + + OnEnd?.Invoke(ref param); + } + + [MethodImpl(MethodImplOptions.NoOptimization)] + public static void __original__(UnityEngine.Rect position, UnityEngine.GUIContent[] options, System.Func checkEnabled, int selected, UnityEditor.EditorUtility.SelectMenuItemFunction callback, object userData, bool showHotkey) + { + } + } + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EditorUtility.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EditorUtility.cs.meta new file mode 100644 index 0000000..3ccc518 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EditorUtility.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bfc0596d2ce572f47b74012c0d3ade49 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EventManipulationHandler.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EventManipulationHandler.cs new file mode 100644 index 0000000..9430b19 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EventManipulationHandler.cs @@ -0,0 +1,106 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_EventManipulationHandler + { + public static class __hook__ + { + + [MonoHook] + public class CheckRectsOnMouseMove + { + /// + /// + /// + public static string __type__ = "UnityEditor.EventManipulationHandler"; + public delegate void __delegate__(UnityEngine.Rect eventLineRect, UnityEngine.AnimationEvent[] events, UnityEngine.Rect[] hitRects); + + public struct Param + { + public UnityEngine.Rect eventLineRect; + public UnityEngine.AnimationEvent[] events; + public UnityEngine.Rect[] hitRects; + + public object __this__; + public __delegate__ __original__; + } + + public delegate bool BeginDelegate(ref Param param); + public delegate void EndDelegate(ref Param param); + public static BeginDelegate OnBegin = null; + public static EndDelegate OnEnd = null; + + [MethodImpl(MethodImplOptions.NoOptimization)] + public void __replace__(UnityEngine.Rect eventLineRect, UnityEngine.AnimationEvent[] events, UnityEngine.Rect[] hitRects) + { + Param param = new(); + param.eventLineRect = eventLineRect; + param.events = events; + param.hitRects = hitRects; + param.__this__ = this; + param.__original__ = __original__; + + if (OnBegin?.Invoke(ref param) == true) + return; + + __original__(param.eventLineRect, param.events, param.hitRects); + + OnEnd?.Invoke(ref param); + } + + [MethodImpl(MethodImplOptions.NoOptimization)] + public void __original__(UnityEngine.Rect eventLineRect, UnityEngine.AnimationEvent[] events, UnityEngine.Rect[] hitRects) + { + } + } + + [MonoHook] + public class Draw + { + /// + /// + /// + public static string __type__ = "UnityEditor.EventManipulationHandler"; + public delegate void __delegate__(UnityEngine.Rect window); + + public struct Param + { + public UnityEngine.Rect window; + + public object __this__; + public __delegate__ __original__; + } + + public delegate bool BeginDelegate(ref Param param); + public delegate void EndDelegate(ref Param param); + public static BeginDelegate OnBegin = null; + public static EndDelegate OnEnd = null; + + [MethodImpl(MethodImplOptions.NoOptimization)] + public void __replace__(UnityEngine.Rect window) + { + Param param = new(); + param.window = window; + param.__this__ = this; + param.__original__ = __original__; + + if (OnBegin?.Invoke(ref param) == true) + return; + + __original__(param.window); + + OnEnd?.Invoke(ref param); + } + + [MethodImpl(MethodImplOptions.NoOptimization)] + public void __original__(UnityEngine.Rect window) + { + } + } + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EventManipulationHandler.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EventManipulationHandler.cs.meta new file mode 100644 index 0000000..b019c19 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_EventManipulationHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e7c3280219bfc304ab680cc4820598a1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_LogEntries.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_LogEntries.cs new file mode 100644 index 0000000..eda0081 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_LogEntries.cs @@ -0,0 +1,56 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_LogEntries + { + public static class __hook__ + { + + [MonoHook] + public class RowGotDoubleClicked + { + /// + /// + /// + public static string __type__ = "UnityEditor.LogEntries"; + public delegate void __delegate__(int index); + + public struct Param + { + public int index; + + public __delegate__ __original__; + } + + public delegate bool BeginDelegate(ref Param param); + public delegate void EndDelegate(ref Param param); + public static BeginDelegate OnBegin = null; + public static EndDelegate OnEnd = null; + + [MethodImpl(MethodImplOptions.NoOptimization)] + public static void __replace__(int index) + { + Param param = new(); + param.index = index; + param.__original__ = __original__; + + if (OnBegin?.Invoke(ref param) == true) + return; + + __original__(param.index); + + OnEnd?.Invoke(ref param); + } + + [MethodImpl(MethodImplOptions.NoOptimization)] + public static void __original__(int index) + { + } + } + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_LogEntries.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_LogEntries.cs.meta new file mode 100644 index 0000000..aa7c27f --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_LogEntries.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 22430577bb3314947966e148e9e2b76f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_ModelImporterClipEditor.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_ModelImporterClipEditor.cs new file mode 100644 index 0000000..98bb7be --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_ModelImporterClipEditor.cs @@ -0,0 +1,100 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_ModelImporterClipEditor + { + public static class __hook__ + { + + [MonoHook] + public class AnimationClipGUI + { + /// + /// + /// + public static string __type__ = "UnityEditor.ModelImporterClipEditor"; + public delegate void __delegate__(); + + public struct Param + { + + public object __this__; + public __delegate__ __original__; + } + + public delegate bool BeginDelegate(ref Param param); + public delegate void EndDelegate(ref Param param); + public static BeginDelegate OnBegin = null; + public static EndDelegate OnEnd = null; + + [MethodImpl(MethodImplOptions.NoOptimization)] + public void __replace__() + { + Param param = new(); + param.__this__ = this; + param.__original__ = __original__; + + if (OnBegin?.Invoke(ref param) == true) + return; + + __original__(); + + OnEnd?.Invoke(ref param); + } + + [MethodImpl(MethodImplOptions.NoOptimization)] + public void __original__() + { + } + } + + [MonoHook(MonoHookType.Constructor)] + public class _ctor + { + /// + /// + /// + public static string __type__ = "UnityEditor.ModelImporterClipEditor"; + public delegate void __delegate__(UnityEditor.AssetImporters.AssetImporterEditor panelContainer); + + public struct Param + { + public UnityEditor.AssetImporters.AssetImporterEditor panelContainer; + + public object __this__; + public __delegate__ __original__; + } + + public delegate bool BeginDelegate(ref Param param); + public delegate void EndDelegate(ref Param param); + public static BeginDelegate OnBegin = null; + public static EndDelegate OnEnd = null; + + [MethodImpl(MethodImplOptions.NoOptimization)] + public void __replace__(UnityEditor.AssetImporters.AssetImporterEditor panelContainer) + { + Param param = new(); + param.panelContainer = panelContainer; + param.__this__ = this; + param.__original__ = __original__; + + if (OnBegin?.Invoke(ref param) == true) + return; + + __original__(param.panelContainer); + + OnEnd?.Invoke(ref param); + } + + [MethodImpl(MethodImplOptions.NoOptimization)] + public void __original__(UnityEditor.AssetImporters.AssetImporterEditor panelContainer) + { + } + } + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_ModelImporterClipEditor.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_ModelImporterClipEditor.cs.meta new file mode 100644 index 0000000..cf339dd --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Hook_UnityEditor_ModelImporterClipEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2a64097dcee8fcb4885348acd985bf57 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_AnimationClipEditor.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_AnimationClipEditor.cs new file mode 100644 index 0000000..faf97cf --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_AnimationClipEditor.cs @@ -0,0 +1,1175 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_AnimationClipEditor + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.AnimationClipEditor"); + + + public UnityEngine.AvatarMask mask + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.AvatarMask)(__mask?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __mask?.SetValue(__self__, value); + } + + public string[] takeNames + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string[])(__takeNames?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __takeNames?.SetValue(__self__, value); + } + + public int takeIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__takeIndex?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __takeIndex?.SetValue(__self__, value); + } + + public bool needsToGenerateClipInfo + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__needsToGenerateClipInfo?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __needsToGenerateClipInfo?.SetValue(__self__, value); + } + + public static string s_LoopMeterStr + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__s_LoopMeterStr?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LoopMeterStr?.SetValue(null, value); + } + + public static int s_LoopMeterHint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_LoopMeterHint?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LoopMeterHint?.SetValue(null, value); + } + + public static string s_LoopOrientationMeterStr + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__s_LoopOrientationMeterStr?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LoopOrientationMeterStr?.SetValue(null, value); + } + + public static int s_LoopOrientationMeterHint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_LoopOrientationMeterHint?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LoopOrientationMeterHint?.SetValue(null, value); + } + + public static string s_LoopPositionYMeterStr + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__s_LoopPositionYMeterStr?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LoopPositionYMeterStr?.SetValue(null, value); + } + + public static int s_LoopPositionYMeterHint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_LoopPositionYMeterHint?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LoopPositionYMeterHint?.SetValue(null, value); + } + + public static string s_LoopPositionXZMeterStr + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__s_LoopPositionXZMeterStr?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LoopPositionXZMeterStr?.SetValue(null, value); + } + + public static int s_LoopPositionXZMeterHint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_LoopPositionXZMeterHint?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LoopPositionXZMeterHint?.SetValue(null, value); + } + + public static float s_EventTimelineMax + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__s_EventTimelineMax?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_EventTimelineMax?.SetValue(null, value); + } + + public UnityEngine.AvatarMask m_Mask + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.AvatarMask)(__m_Mask?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Mask?.SetValue(__self__, value); + } + + public UnityEditor_AnimationClipInfoProperties m_ClipInfo + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_AnimationClipInfoProperties(__m_ClipInfo?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ClipInfo?.SetValue(__self__, value.__self__); + } + + public UnityEngine.AnimationClip m_Clip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.AnimationClip)(__m_Clip?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Clip?.SetValue(__self__, value); + } + + public UnityEditor.Animations.AnimatorController m_Controller + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.Animations.AnimatorController)(__m_Controller?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Controller?.SetValue(__self__, value); + } + + public UnityEditor.Animations.AnimatorStateMachine m_StateMachine + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.Animations.AnimatorStateMachine)(__m_StateMachine?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_StateMachine?.SetValue(__self__, value); + } + + public UnityEditor.Animations.AnimatorState m_State + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.Animations.AnimatorState)(__m_State?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_State?.SetValue(__self__, value); + } + + public object m_AvatarPreview + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_AvatarPreview?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AvatarPreview?.SetValue(__self__, value); + } + + public object m_TimeArea + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_TimeArea?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TimeArea?.SetValue(__self__, value); + } + + public object m_EventTimeArea + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_EventTimeArea?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_EventTimeArea?.SetValue(__self__, value); + } + + public bool m_DraggingRange + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_DraggingRange?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_DraggingRange?.SetValue(__self__, value); + } + + public bool m_DraggingRangeBegin + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_DraggingRangeBegin?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_DraggingRangeBegin?.SetValue(__self__, value); + } + + public bool m_DraggingRangeEnd + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_DraggingRangeEnd?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_DraggingRangeEnd?.SetValue(__self__, value); + } + + public float m_DraggingStartFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__m_DraggingStartFrame?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_DraggingStartFrame?.SetValue(__self__, value); + } + + public float m_DraggingStopFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__m_DraggingStopFrame?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_DraggingStopFrame?.SetValue(__self__, value); + } + + public float m_DraggingAdditivePoseFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__m_DraggingAdditivePoseFrame?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_DraggingAdditivePoseFrame?.SetValue(__self__, value); + } + + public bool m_LoopTime + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_LoopTime?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LoopTime?.SetValue(__self__, value); + } + + public bool m_LoopBlend + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_LoopBlend?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LoopBlend?.SetValue(__self__, value); + } + + public bool m_LoopBlendOrientation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_LoopBlendOrientation?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LoopBlendOrientation?.SetValue(__self__, value); + } + + public bool m_LoopBlendPositionY + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_LoopBlendPositionY?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LoopBlendPositionY?.SetValue(__self__, value); + } + + public bool m_LoopBlendPositionXZ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_LoopBlendPositionXZ?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LoopBlendPositionXZ?.SetValue(__self__, value); + } + + public float m_StartFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__m_StartFrame?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_StartFrame?.SetValue(__self__, value); + } + + public float m_StopFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__m_StopFrame?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_StopFrame?.SetValue(__self__, value); + } + + public float m_AdditivePoseFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__m_AdditivePoseFrame?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AdditivePoseFrame?.SetValue(__self__, value); + } + + public float m_InitialClipLength + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__m_InitialClipLength?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_InitialClipLength?.SetValue(__self__, value); + } + + public static bool m_ShowCurves + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_ShowCurves?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ShowCurves?.SetValue(null, value); + } + + public UnityEditor_EventManipulationHandler m_EventManipulationHandler + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_EventManipulationHandler(__m_EventManipulationHandler?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_EventManipulationHandler?.SetValue(__self__, value.__self__); + } + + public static bool m_ShowEvents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_ShowEvents?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ShowEvents?.SetValue(null, value); + } + + public bool m_NeedsToGenerateClipInfo + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_NeedsToGenerateClipInfo?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_NeedsToGenerateClipInfo?.SetValue(__self__, value); + } + + public static int kSamplesPerSecond + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__kSamplesPerSecond?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kSamplesPerSecond?.SetValue(null, value); + } + + public static int kPose + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__kPose?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kPose?.SetValue(null, value); + } + + public static int kRotation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__kRotation?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kRotation?.SetValue(null, value); + } + + public static int kHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__kHeight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kHeight?.SetValue(null, value); + } + + public static int kPosition + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__kPosition?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kPosition?.SetValue(null, value); + } + + public UnityEngine.Vector2[][][] m_QualityCurves + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Vector2[][][])(__m_QualityCurves?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_QualityCurves?.SetValue(__self__, value); + } + + public bool m_DirtyQualityCurves + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_DirtyQualityCurves?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_DirtyQualityCurves?.SetValue(__self__, value); + } + + public bool m_FirstInitialization + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_FirstInitialization?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_FirstInitialization?.SetValue(__self__, value); + } + + public static void EditWithImporter(UnityEngine.AnimationClip clip) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = clip; + __EditWithImporter?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public void UpdateEventsPopupClipInfo(UnityEditor_AnimationClipInfoProperties info) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = info.__self__; + __UpdateEventsPopupClipInfo?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void ShowRange(UnityEditor_AnimationClipInfoProperties info) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = info.__self__; + __ShowRange?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void InitController() + { + __InitController?.Invoke(__self__, System.Array.Empty()); + } + + public bool IsEnabled() + { + var __result__ = __IsEnabled?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void OnHeaderIconGUI(UnityEngine.Rect iconRect) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = iconRect; + __OnHeaderIconGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void OnHeaderTitleGUI(UnityEngine.Rect titleRect, string header) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = titleRect; + __params__[1] = header; + __OnHeaderTitleGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void OnHeaderControlsGUI() + { + __OnHeaderControlsGUI?.Invoke(__self__, System.Array.Empty()); + } + + public void DestroyController() + { + __DestroyController?.Invoke(__self__, System.Array.Empty()); + } + + public void SetPreviewAvatar() + { + __SetPreviewAvatar?.Invoke(__self__, System.Array.Empty()); + } + + public void Init() + { + __Init?.Invoke(__self__, System.Array.Empty()); + } + + public void InitClipTime() + { + __InitClipTime?.Invoke(__self__, System.Array.Empty()); + } + + public void OnEnable() + { + __OnEnable?.Invoke(__self__, System.Array.Empty()); + } + + public void OnDisable() + { + __OnDisable?.Invoke(__self__, System.Array.Empty()); + } + + public bool HasPreviewGUI() + { + var __result__ = __HasPreviewGUI?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void OnPreviewSettings() + { + __OnPreviewSettings?.Invoke(__self__, System.Array.Empty()); + } + + public void CalculateQualityCurves() + { + __CalculateQualityCurves?.Invoke(__self__, System.Array.Empty()); + } + + public void OnInteractivePreviewGUI(UnityEngine.Rect r, UnityEngine.GUIStyle background) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = r; + __params__[1] = background; + __OnInteractivePreviewGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void ClipRangeGUI(ref float startFrame, ref float stopFrame, out bool changedStart, out bool changedStop, bool showAdditivePoseFrame, ref float additivePoseframe, out bool changedAdditivePoseframe) + { + var __pool__ = FixedArrayPool.Shared(7); + var __params__ = __pool__.Rent(); + __params__[0] = startFrame; + __params__[1] = stopFrame; + __params__[2] = null; + __params__[3] = null; + __params__[4] = showAdditivePoseFrame; + __params__[5] = additivePoseframe; + __params__[6] = null; + __ClipRangeGUI?.Invoke(__self__, __params__); + startFrame = (float)(__params__[0]); + stopFrame = (float)(__params__[1]); + changedStart = (bool)(__params__[2]); + changedStop = (bool)(__params__[3]); + additivePoseframe = (float)(__params__[5]); + changedAdditivePoseframe = (bool)(__params__[6]); + __pool__.Return(__params__); + } + + public string GetStatsText() + { + var __result__ = __GetStatsText?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (string)(__result__) : default; + } + + public float GetClipLength() + { + var __result__ = __GetClipLength?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (float)(__result__) : default; + } + + public void OnAssetStoreInspectorGUI() + { + __OnAssetStoreInspectorGUI?.Invoke(__self__, System.Array.Empty()); + } + + public void OnInspectorGUI() + { + __OnInspectorGUI?.Invoke(__self__, System.Array.Empty()); + } + + public void AnimationClipGUI() + { + __AnimationClipGUI?.Invoke(__self__, System.Array.Empty()); + } + + public void CurveGUI() + { + __CurveGUI?.Invoke(__self__, System.Array.Empty()); + } + + public void EventsGUI() + { + __EventsGUI?.Invoke(__self__, System.Array.Empty()); + } + + public void MuscleClipGUI() + { + __MuscleClipGUI?.Invoke(__self__, System.Array.Empty()); + } + + public void LoopToggle(UnityEngine.Rect r, UnityEngine.GUIContent content, ref bool val) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = r; + __params__[1] = content; + __params__[2] = val; + __LoopToggle?.Invoke(__self__, __params__); + val = (bool)(__params__[2]); + __pool__.Return(__params__); + } + + public void LoopQualityLampAndCurve(UnityEngine.Rect position, float value, int lightMeterHint, bool changedStart, bool changedStop, UnityEngine.Vector2[][] curves) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = value; + __params__[2] = lightMeterHint; + __params__[3] = changedStart; + __params__[4] = changedStop; + __params__[5] = curves; + __LoopQualityLampAndCurve?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public UnityEditor_AnimationClipEditor(object __self__) => this.__self__ = __self__ as UnityEngine.Object; + public UnityEngine.Object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + public UnityEditor.Editor __super__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.Editor)(__self__); + } + + private static FieldInfo ___s_LoopMeterStr; + private static FieldInfo __s_LoopMeterStr + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LoopMeterStr ??= __type__?.GetField("s_LoopMeterStr", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_LoopMeterHint; + private static FieldInfo __s_LoopMeterHint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LoopMeterHint ??= __type__?.GetField("s_LoopMeterHint", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_LoopOrientationMeterStr; + private static FieldInfo __s_LoopOrientationMeterStr + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LoopOrientationMeterStr ??= __type__?.GetField("s_LoopOrientationMeterStr", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_LoopOrientationMeterHint; + private static FieldInfo __s_LoopOrientationMeterHint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LoopOrientationMeterHint ??= __type__?.GetField("s_LoopOrientationMeterHint", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_LoopPositionYMeterStr; + private static FieldInfo __s_LoopPositionYMeterStr + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LoopPositionYMeterStr ??= __type__?.GetField("s_LoopPositionYMeterStr", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_LoopPositionYMeterHint; + private static FieldInfo __s_LoopPositionYMeterHint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LoopPositionYMeterHint ??= __type__?.GetField("s_LoopPositionYMeterHint", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_LoopPositionXZMeterStr; + private static FieldInfo __s_LoopPositionXZMeterStr + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LoopPositionXZMeterStr ??= __type__?.GetField("s_LoopPositionXZMeterStr", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_LoopPositionXZMeterHint; + private static FieldInfo __s_LoopPositionXZMeterHint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LoopPositionXZMeterHint ??= __type__?.GetField("s_LoopPositionXZMeterHint", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_EventTimelineMax; + private static FieldInfo __s_EventTimelineMax + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_EventTimelineMax ??= __type__?.GetField("s_EventTimelineMax", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Mask; + private static FieldInfo __m_Mask + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Mask ??= __type__?.GetField("m_Mask", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ClipInfo; + private static FieldInfo __m_ClipInfo + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ClipInfo ??= __type__?.GetField("m_ClipInfo", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Clip; + private static FieldInfo __m_Clip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Clip ??= __type__?.GetField("m_Clip", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Controller; + private static FieldInfo __m_Controller + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Controller ??= __type__?.GetField("m_Controller", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_StateMachine; + private static FieldInfo __m_StateMachine + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_StateMachine ??= __type__?.GetField("m_StateMachine", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_State; + private static FieldInfo __m_State + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_State ??= __type__?.GetField("m_State", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AvatarPreview; + private static FieldInfo __m_AvatarPreview + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AvatarPreview ??= __type__?.GetField("m_AvatarPreview", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TimeArea; + private static FieldInfo __m_TimeArea + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TimeArea ??= __type__?.GetField("m_TimeArea", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_EventTimeArea; + private static FieldInfo __m_EventTimeArea + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_EventTimeArea ??= __type__?.GetField("m_EventTimeArea", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_DraggingRange; + private static FieldInfo __m_DraggingRange + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_DraggingRange ??= __type__?.GetField("m_DraggingRange", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_DraggingRangeBegin; + private static FieldInfo __m_DraggingRangeBegin + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_DraggingRangeBegin ??= __type__?.GetField("m_DraggingRangeBegin", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_DraggingRangeEnd; + private static FieldInfo __m_DraggingRangeEnd + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_DraggingRangeEnd ??= __type__?.GetField("m_DraggingRangeEnd", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_DraggingStartFrame; + private static FieldInfo __m_DraggingStartFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_DraggingStartFrame ??= __type__?.GetField("m_DraggingStartFrame", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_DraggingStopFrame; + private static FieldInfo __m_DraggingStopFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_DraggingStopFrame ??= __type__?.GetField("m_DraggingStopFrame", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_DraggingAdditivePoseFrame; + private static FieldInfo __m_DraggingAdditivePoseFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_DraggingAdditivePoseFrame ??= __type__?.GetField("m_DraggingAdditivePoseFrame", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LoopTime; + private static FieldInfo __m_LoopTime + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LoopTime ??= __type__?.GetField("m_LoopTime", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LoopBlend; + private static FieldInfo __m_LoopBlend + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LoopBlend ??= __type__?.GetField("m_LoopBlend", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LoopBlendOrientation; + private static FieldInfo __m_LoopBlendOrientation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LoopBlendOrientation ??= __type__?.GetField("m_LoopBlendOrientation", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LoopBlendPositionY; + private static FieldInfo __m_LoopBlendPositionY + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LoopBlendPositionY ??= __type__?.GetField("m_LoopBlendPositionY", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LoopBlendPositionXZ; + private static FieldInfo __m_LoopBlendPositionXZ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LoopBlendPositionXZ ??= __type__?.GetField("m_LoopBlendPositionXZ", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_StartFrame; + private static FieldInfo __m_StartFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_StartFrame ??= __type__?.GetField("m_StartFrame", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_StopFrame; + private static FieldInfo __m_StopFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_StopFrame ??= __type__?.GetField("m_StopFrame", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AdditivePoseFrame; + private static FieldInfo __m_AdditivePoseFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AdditivePoseFrame ??= __type__?.GetField("m_AdditivePoseFrame", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_InitialClipLength; + private static FieldInfo __m_InitialClipLength + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_InitialClipLength ??= __type__?.GetField("m_InitialClipLength", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ShowCurves; + private static FieldInfo __m_ShowCurves + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ShowCurves ??= __type__?.GetField("m_ShowCurves", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_EventManipulationHandler; + private static FieldInfo __m_EventManipulationHandler + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_EventManipulationHandler ??= __type__?.GetField("m_EventManipulationHandler", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ShowEvents; + private static FieldInfo __m_ShowEvents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ShowEvents ??= __type__?.GetField("m_ShowEvents", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_NeedsToGenerateClipInfo; + private static FieldInfo __m_NeedsToGenerateClipInfo + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_NeedsToGenerateClipInfo ??= __type__?.GetField("m_NeedsToGenerateClipInfo", (BindingFlags)(-1)); + } + + private static FieldInfo ___kSamplesPerSecond; + private static FieldInfo __kSamplesPerSecond + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kSamplesPerSecond ??= __type__?.GetField("kSamplesPerSecond", (BindingFlags)(-1)); + } + + private static FieldInfo ___kPose; + private static FieldInfo __kPose + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kPose ??= __type__?.GetField("kPose", (BindingFlags)(-1)); + } + + private static FieldInfo ___kRotation; + private static FieldInfo __kRotation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kRotation ??= __type__?.GetField("kRotation", (BindingFlags)(-1)); + } + + private static FieldInfo ___kHeight; + private static FieldInfo __kHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kHeight ??= __type__?.GetField("kHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___kPosition; + private static FieldInfo __kPosition + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kPosition ??= __type__?.GetField("kPosition", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_QualityCurves; + private static FieldInfo __m_QualityCurves + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_QualityCurves ??= __type__?.GetField("m_QualityCurves", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_DirtyQualityCurves; + private static FieldInfo __m_DirtyQualityCurves + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_DirtyQualityCurves ??= __type__?.GetField("m_DirtyQualityCurves", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_FirstInitialization; + private static FieldInfo __m_FirstInitialization + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_FirstInitialization ??= __type__?.GetField("m_FirstInitialization", (BindingFlags)(-1)); + } + + private static PropertyInfo ___mask; + private static PropertyInfo __mask + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___mask ??= __type__?.GetProperty("mask", (BindingFlags)(-1)); + } + + private static PropertyInfo ___takeNames; + private static PropertyInfo __takeNames + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___takeNames ??= __type__?.GetProperty("takeNames", (BindingFlags)(-1)); + } + + private static PropertyInfo ___takeIndex; + private static PropertyInfo __takeIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___takeIndex ??= __type__?.GetProperty("takeIndex", (BindingFlags)(-1)); + } + + private static PropertyInfo ___needsToGenerateClipInfo; + private static PropertyInfo __needsToGenerateClipInfo + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___needsToGenerateClipInfo ??= __type__?.GetProperty("needsToGenerateClipInfo", (BindingFlags)(-1)); + } + + private static MethodInfo ___EditWithImporter; + private static MethodInfo __EditWithImporter + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EditWithImporter ??= __type__?.GetMethodInfoByParameterTypeNames("EditWithImporter", "UnityEngine.AnimationClip"); + } + + private static MethodInfo ___UpdateEventsPopupClipInfo; + private static MethodInfo __UpdateEventsPopupClipInfo + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UpdateEventsPopupClipInfo ??= __type__?.GetMethodInfoByParameterTypeNames("UpdateEventsPopupClipInfo", "UnityEditor.AnimationClipInfoProperties"); + } + + private static MethodInfo ___ShowRange; + private static MethodInfo __ShowRange + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShowRange ??= __type__?.GetMethodInfoByParameterTypeNames("ShowRange", "UnityEditor.AnimationClipInfoProperties"); + } + + private static MethodInfo ___InitController; + private static MethodInfo __InitController + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___InitController ??= __type__?.GetMethodInfoByParameterTypeNames("InitController"); + } + + private static MethodInfo ___IsEnabled; + private static MethodInfo __IsEnabled + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsEnabled ??= __type__?.GetMethodInfoByParameterTypeNames("IsEnabled"); + } + + private static MethodInfo ___OnHeaderIconGUI; + private static MethodInfo __OnHeaderIconGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnHeaderIconGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnHeaderIconGUI", "UnityEngine.Rect"); + } + + private static MethodInfo ___OnHeaderTitleGUI; + private static MethodInfo __OnHeaderTitleGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnHeaderTitleGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnHeaderTitleGUI", "UnityEngine.Rect", "System.String"); + } + + private static MethodInfo ___OnHeaderControlsGUI; + private static MethodInfo __OnHeaderControlsGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnHeaderControlsGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnHeaderControlsGUI"); + } + + private static MethodInfo ___DestroyController; + private static MethodInfo __DestroyController + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DestroyController ??= __type__?.GetMethodInfoByParameterTypeNames("DestroyController"); + } + + private static MethodInfo ___SetPreviewAvatar; + private static MethodInfo __SetPreviewAvatar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetPreviewAvatar ??= __type__?.GetMethodInfoByParameterTypeNames("SetPreviewAvatar"); + } + + private static MethodInfo ___Init; + private static MethodInfo __Init + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Init ??= __type__?.GetMethodInfoByParameterTypeNames("Init"); + } + + private static MethodInfo ___InitClipTime; + private static MethodInfo __InitClipTime + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___InitClipTime ??= __type__?.GetMethodInfoByParameterTypeNames("InitClipTime"); + } + + private static MethodInfo ___OnEnable; + private static MethodInfo __OnEnable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnEnable ??= __type__?.GetMethodInfoByParameterTypeNames("OnEnable"); + } + + private static MethodInfo ___OnDisable; + private static MethodInfo __OnDisable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnDisable ??= __type__?.GetMethodInfoByParameterTypeNames("OnDisable"); + } + + private static MethodInfo ___HasPreviewGUI; + private static MethodInfo __HasPreviewGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasPreviewGUI ??= __type__?.GetMethodInfoByParameterTypeNames("HasPreviewGUI"); + } + + private static MethodInfo ___OnPreviewSettings; + private static MethodInfo __OnPreviewSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnPreviewSettings ??= __type__?.GetMethodInfoByParameterTypeNames("OnPreviewSettings"); + } + + private static MethodInfo ___CalculateQualityCurves; + private static MethodInfo __CalculateQualityCurves + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CalculateQualityCurves ??= __type__?.GetMethodInfoByParameterTypeNames("CalculateQualityCurves"); + } + + private static MethodInfo ___OnInteractivePreviewGUI; + private static MethodInfo __OnInteractivePreviewGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnInteractivePreviewGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnInteractivePreviewGUI", "UnityEngine.Rect", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___ClipRangeGUI; + private static MethodInfo __ClipRangeGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ClipRangeGUI ??= __type__?.GetMethodInfoByParameterTypeNames("ClipRangeGUI", "System.Single&", "System.Single&", "System.Boolean&", "System.Boolean&", "System.Boolean", "System.Single&", "System.Boolean&"); + } + + private static MethodInfo ___GetStatsText; + private static MethodInfo __GetStatsText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetStatsText ??= __type__?.GetMethodInfoByParameterTypeNames("GetStatsText"); + } + + private static MethodInfo ___GetClipLength; + private static MethodInfo __GetClipLength + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetClipLength ??= __type__?.GetMethodInfoByParameterTypeNames("GetClipLength"); + } + + private static MethodInfo ___OnAssetStoreInspectorGUI; + private static MethodInfo __OnAssetStoreInspectorGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnAssetStoreInspectorGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnAssetStoreInspectorGUI"); + } + + private static MethodInfo ___OnInspectorGUI; + private static MethodInfo __OnInspectorGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnInspectorGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnInspectorGUI"); + } + + private static MethodInfo ___AnimationClipGUI; + private static MethodInfo __AnimationClipGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AnimationClipGUI ??= __type__?.GetMethodInfoByParameterTypeNames("AnimationClipGUI"); + } + + private static MethodInfo ___CurveGUI; + private static MethodInfo __CurveGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CurveGUI ??= __type__?.GetMethodInfoByParameterTypeNames("CurveGUI"); + } + + private static MethodInfo ___EventsGUI; + private static MethodInfo __EventsGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EventsGUI ??= __type__?.GetMethodInfoByParameterTypeNames("EventsGUI"); + } + + private static MethodInfo ___MuscleClipGUI; + private static MethodInfo __MuscleClipGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MuscleClipGUI ??= __type__?.GetMethodInfoByParameterTypeNames("MuscleClipGUI"); + } + + private static MethodInfo ___LoopToggle; + private static MethodInfo __LoopToggle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoopToggle ??= __type__?.GetMethodInfoByParameterTypeNames("LoopToggle", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Boolean&"); + } + + private static MethodInfo ___LoopQualityLampAndCurve; + private static MethodInfo __LoopQualityLampAndCurve + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoopQualityLampAndCurve ??= __type__?.GetMethodInfoByParameterTypeNames("LoopQualityLampAndCurve", "UnityEngine.Rect", "System.Single", "System.Int32", "System.Boolean", "System.Boolean", "UnityEngine.Vector2[][]"); + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_AnimationClipEditor.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_AnimationClipEditor.cs.meta new file mode 100644 index 0000000..09ad671 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_AnimationClipEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ad624bceaffaa9f46a5b286a2710eac9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_AnimationClipInfoProperties.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_AnimationClipInfoProperties.cs new file mode 100644 index 0000000..fc44ff0 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_AnimationClipInfoProperties.cs @@ -0,0 +1,1236 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_AnimationClipInfoProperties + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.AnimationClipInfoProperties"); + + + public string name + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__name?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __name?.SetValue(__self__, value); + } + + public string takeName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__takeName?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __takeName?.SetValue(__self__, value); + } + + public long internalID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (long)(__internalID?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __internalID?.SetValue(__self__, value); + } + + public float firstFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__firstFrame?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __firstFrame?.SetValue(__self__, value); + } + + public float lastFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__lastFrame?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __lastFrame?.SetValue(__self__, value); + } + + public int wrapMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__wrapMode?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __wrapMode?.SetValue(__self__, value); + } + + public bool loop + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__loop?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __loop?.SetValue(__self__, value); + } + + public float orientationOffsetY + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__orientationOffsetY?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __orientationOffsetY?.SetValue(__self__, value); + } + + public float level + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__level?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __level?.SetValue(__self__, value); + } + + public float cycleOffset + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__cycleOffset?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __cycleOffset?.SetValue(__self__, value); + } + + public float additiveReferencePoseFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__additiveReferencePoseFrame?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __additiveReferencePoseFrame?.SetValue(__self__, value); + } + + public bool hasAdditiveReferencePose + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__hasAdditiveReferencePose?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __hasAdditiveReferencePose?.SetValue(__self__, value); + } + + public bool loopTime + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__loopTime?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __loopTime?.SetValue(__self__, value); + } + + public bool loopBlend + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__loopBlend?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __loopBlend?.SetValue(__self__, value); + } + + public bool loopBlendOrientation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__loopBlendOrientation?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __loopBlendOrientation?.SetValue(__self__, value); + } + + public bool loopBlendPositionY + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__loopBlendPositionY?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __loopBlendPositionY?.SetValue(__self__, value); + } + + public bool loopBlendPositionXZ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__loopBlendPositionXZ?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __loopBlendPositionXZ?.SetValue(__self__, value); + } + + public bool keepOriginalOrientation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__keepOriginalOrientation?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __keepOriginalOrientation?.SetValue(__self__, value); + } + + public bool keepOriginalPositionY + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__keepOriginalPositionY?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __keepOriginalPositionY?.SetValue(__self__, value); + } + + public bool keepOriginalPositionXZ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__keepOriginalPositionXZ?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __keepOriginalPositionXZ?.SetValue(__self__, value); + } + + public bool heightFromFeet + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__heightFromFeet?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __heightFromFeet?.SetValue(__self__, value); + } + + public bool mirror + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__mirror?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __mirror?.SetValue(__self__, value); + } + + public UnityEditor.ClipAnimationMaskType maskType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.ClipAnimationMaskType)(__maskType?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __maskType?.SetValue(__self__, value); + } + + public UnityEngine.AvatarMask maskSource + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.AvatarMask)(__maskSource?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __maskSource?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty maskTypeProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__maskTypeProperty?.GetValue(__self__)); + } + + public UnityEditor.SerializedProperty maskSourceProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__maskSourceProperty?.GetValue(__self__)); + } + + public UnityEditor.SerializedProperty bodyMaskProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__bodyMaskProperty?.GetValue(__self__)); + } + + public UnityEditor.SerializedProperty transformMaskProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__transformMaskProperty?.GetValue(__self__)); + } + + public UnityEditor.SerializedProperty m_Property + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_Property?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Property?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_Name + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_Name?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Name?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_TakeName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_TakeName?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TakeName?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_InternalId + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_InternalId?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_InternalId?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_FirstFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_FirstFrame?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_FirstFrame?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_LastFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_LastFrame?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LastFrame?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_WrapMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_WrapMode?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_WrapMode?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_Loop + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_Loop?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Loop?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_OrientationOffsetY + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_OrientationOffsetY?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_OrientationOffsetY?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_Level + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_Level?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Level?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_CycleOffset + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_CycleOffset?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_CycleOffset?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_AdditiveReferencePoseFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_AdditiveReferencePoseFrame?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AdditiveReferencePoseFrame?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_HasAdditiveReferencePose + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_HasAdditiveReferencePose?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_HasAdditiveReferencePose?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_LoopTime + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_LoopTime?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LoopTime?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_LoopBlend + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_LoopBlend?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LoopBlend?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_LoopBlendOrientation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_LoopBlendOrientation?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LoopBlendOrientation?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_LoopBlendPositionY + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_LoopBlendPositionY?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LoopBlendPositionY?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_LoopBlendPositionXZ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_LoopBlendPositionXZ?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LoopBlendPositionXZ?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_KeepOriginalOrientation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_KeepOriginalOrientation?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_KeepOriginalOrientation?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_KeepOriginalPositionY + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_KeepOriginalPositionY?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_KeepOriginalPositionY?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_KeepOriginalPositionXZ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_KeepOriginalPositionXZ?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_KeepOriginalPositionXZ?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_HeightFromFeet + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_HeightFromFeet?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_HeightFromFeet?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_Mirror + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_Mirror?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Mirror?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_MaskType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_MaskType?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MaskType?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_MaskSource + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_MaskSource?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MaskSource?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_BodyMask + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_BodyMask?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_BodyMask?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_TransformMask + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_TransformMask?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TransformMask?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_Curves + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_Curves?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Curves?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_Events + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_Events?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Events?.SetValue(__self__, value); + } + + public void ApplyModifiedProperties() + { + __ApplyModifiedProperties?.Invoke(__self__, System.Array.Empty()); + } + + public bool MaskNeedsUpdating() + { + var __result__ = __MaskNeedsUpdating?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void MaskFromClip(UnityEngine.AvatarMask mask) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = mask; + __MaskFromClip?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void MaskToClip(UnityEngine.AvatarMask mask) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = mask; + __MaskToClip?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void ClearCurves() + { + __ClearCurves?.Invoke(__self__, System.Array.Empty()); + } + + public int GetCurveCount() + { + var __result__ = __GetCurveCount?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public UnityEditor.SerializedProperty GetCurveProperty(int index) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = index; + var __result__ = __GetCurveProperty?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEditor.SerializedProperty)(__result__) : default; + } + + public string GetCurveName(int index) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = index; + var __result__ = __GetCurveName?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public void SetCurveName(int index, string name) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = index; + __params__[1] = name; + __SetCurveName?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public UnityEngine.AnimationCurve GetCurve(int index) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = index; + var __result__ = __GetCurve?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.AnimationCurve)(__result__) : default; + } + + public void SetCurve(int index, UnityEngine.AnimationCurve curveValue) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = index; + __params__[1] = curveValue; + __SetCurve?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void AddCurve() + { + __AddCurve?.Invoke(__self__, System.Array.Empty()); + } + + public void RemoveCurve(int index) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = index; + __RemoveCurve?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public UnityEngine.AnimationEvent GetEvent(int index) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = index; + var __result__ = __GetEvent?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.AnimationEvent)(__result__) : default; + } + + public void SetEvent(int index, UnityEngine.AnimationEvent animationEvent) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = index; + __params__[1] = animationEvent; + __SetEvent?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void ClearEvents() + { + __ClearEvents?.Invoke(__self__, System.Array.Empty()); + } + + public int GetEventCount() + { + var __result__ = __GetEventCount?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public void AddEvent(float time) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = time; + __AddEvent?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void RemoveEvent(int index) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = index; + __RemoveEvent?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void SetEvents(UnityEngine.AnimationEvent[] newEvents) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = newEvents; + __SetEvents?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public UnityEngine.AnimationEvent[] GetEvents() + { + var __result__ = __GetEvents?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (UnityEngine.AnimationEvent[])(__result__) : default; + } + + public void AssignToPreviewClip(UnityEngine.AnimationClip clip) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = clip; + __AssignToPreviewClip?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public float FixPrecisionErrors(float f) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = f; + var __result__ = __FixPrecisionErrors?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public void ExtractFromPreviewClip(UnityEngine.AnimationClip clip) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = clip; + __ExtractFromPreviewClip?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public UnityEditor_AnimationClipInfoProperties(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + + private static FieldInfo ___m_Property; + private static FieldInfo __m_Property + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Property ??= __type__?.GetField("m_Property", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Name; + private static FieldInfo __m_Name + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Name ??= __type__?.GetField("m_Name", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TakeName; + private static FieldInfo __m_TakeName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TakeName ??= __type__?.GetField("m_TakeName", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_InternalId; + private static FieldInfo __m_InternalId + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_InternalId ??= __type__?.GetField("m_InternalId", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_FirstFrame; + private static FieldInfo __m_FirstFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_FirstFrame ??= __type__?.GetField("m_FirstFrame", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LastFrame; + private static FieldInfo __m_LastFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LastFrame ??= __type__?.GetField("m_LastFrame", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_WrapMode; + private static FieldInfo __m_WrapMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_WrapMode ??= __type__?.GetField("m_WrapMode", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Loop; + private static FieldInfo __m_Loop + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Loop ??= __type__?.GetField("m_Loop", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_OrientationOffsetY; + private static FieldInfo __m_OrientationOffsetY + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_OrientationOffsetY ??= __type__?.GetField("m_OrientationOffsetY", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Level; + private static FieldInfo __m_Level + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Level ??= __type__?.GetField("m_Level", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_CycleOffset; + private static FieldInfo __m_CycleOffset + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_CycleOffset ??= __type__?.GetField("m_CycleOffset", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AdditiveReferencePoseFrame; + private static FieldInfo __m_AdditiveReferencePoseFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AdditiveReferencePoseFrame ??= __type__?.GetField("m_AdditiveReferencePoseFrame", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_HasAdditiveReferencePose; + private static FieldInfo __m_HasAdditiveReferencePose + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_HasAdditiveReferencePose ??= __type__?.GetField("m_HasAdditiveReferencePose", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LoopTime; + private static FieldInfo __m_LoopTime + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LoopTime ??= __type__?.GetField("m_LoopTime", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LoopBlend; + private static FieldInfo __m_LoopBlend + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LoopBlend ??= __type__?.GetField("m_LoopBlend", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LoopBlendOrientation; + private static FieldInfo __m_LoopBlendOrientation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LoopBlendOrientation ??= __type__?.GetField("m_LoopBlendOrientation", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LoopBlendPositionY; + private static FieldInfo __m_LoopBlendPositionY + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LoopBlendPositionY ??= __type__?.GetField("m_LoopBlendPositionY", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LoopBlendPositionXZ; + private static FieldInfo __m_LoopBlendPositionXZ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LoopBlendPositionXZ ??= __type__?.GetField("m_LoopBlendPositionXZ", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_KeepOriginalOrientation; + private static FieldInfo __m_KeepOriginalOrientation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_KeepOriginalOrientation ??= __type__?.GetField("m_KeepOriginalOrientation", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_KeepOriginalPositionY; + private static FieldInfo __m_KeepOriginalPositionY + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_KeepOriginalPositionY ??= __type__?.GetField("m_KeepOriginalPositionY", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_KeepOriginalPositionXZ; + private static FieldInfo __m_KeepOriginalPositionXZ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_KeepOriginalPositionXZ ??= __type__?.GetField("m_KeepOriginalPositionXZ", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_HeightFromFeet; + private static FieldInfo __m_HeightFromFeet + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_HeightFromFeet ??= __type__?.GetField("m_HeightFromFeet", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Mirror; + private static FieldInfo __m_Mirror + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Mirror ??= __type__?.GetField("m_Mirror", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MaskType; + private static FieldInfo __m_MaskType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MaskType ??= __type__?.GetField("m_MaskType", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MaskSource; + private static FieldInfo __m_MaskSource + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MaskSource ??= __type__?.GetField("m_MaskSource", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_BodyMask; + private static FieldInfo __m_BodyMask + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_BodyMask ??= __type__?.GetField("m_BodyMask", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TransformMask; + private static FieldInfo __m_TransformMask + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TransformMask ??= __type__?.GetField("m_TransformMask", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Curves; + private static FieldInfo __m_Curves + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Curves ??= __type__?.GetField("m_Curves", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Events; + private static FieldInfo __m_Events + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Events ??= __type__?.GetField("m_Events", (BindingFlags)(-1)); + } + + private static PropertyInfo ___name; + private static PropertyInfo __name + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___name ??= __type__?.GetProperty("name", (BindingFlags)(-1)); + } + + private static PropertyInfo ___takeName; + private static PropertyInfo __takeName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___takeName ??= __type__?.GetProperty("takeName", (BindingFlags)(-1)); + } + + private static PropertyInfo ___internalID; + private static PropertyInfo __internalID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___internalID ??= __type__?.GetProperty("internalID", (BindingFlags)(-1)); + } + + private static PropertyInfo ___firstFrame; + private static PropertyInfo __firstFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___firstFrame ??= __type__?.GetProperty("firstFrame", (BindingFlags)(-1)); + } + + private static PropertyInfo ___lastFrame; + private static PropertyInfo __lastFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___lastFrame ??= __type__?.GetProperty("lastFrame", (BindingFlags)(-1)); + } + + private static PropertyInfo ___wrapMode; + private static PropertyInfo __wrapMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___wrapMode ??= __type__?.GetProperty("wrapMode", (BindingFlags)(-1)); + } + + private static PropertyInfo ___loop; + private static PropertyInfo __loop + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___loop ??= __type__?.GetProperty("loop", (BindingFlags)(-1)); + } + + private static PropertyInfo ___orientationOffsetY; + private static PropertyInfo __orientationOffsetY + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___orientationOffsetY ??= __type__?.GetProperty("orientationOffsetY", (BindingFlags)(-1)); + } + + private static PropertyInfo ___level; + private static PropertyInfo __level + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___level ??= __type__?.GetProperty("level", (BindingFlags)(-1)); + } + + private static PropertyInfo ___cycleOffset; + private static PropertyInfo __cycleOffset + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___cycleOffset ??= __type__?.GetProperty("cycleOffset", (BindingFlags)(-1)); + } + + private static PropertyInfo ___additiveReferencePoseFrame; + private static PropertyInfo __additiveReferencePoseFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___additiveReferencePoseFrame ??= __type__?.GetProperty("additiveReferencePoseFrame", (BindingFlags)(-1)); + } + + private static PropertyInfo ___hasAdditiveReferencePose; + private static PropertyInfo __hasAdditiveReferencePose + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___hasAdditiveReferencePose ??= __type__?.GetProperty("hasAdditiveReferencePose", (BindingFlags)(-1)); + } + + private static PropertyInfo ___loopTime; + private static PropertyInfo __loopTime + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___loopTime ??= __type__?.GetProperty("loopTime", (BindingFlags)(-1)); + } + + private static PropertyInfo ___loopBlend; + private static PropertyInfo __loopBlend + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___loopBlend ??= __type__?.GetProperty("loopBlend", (BindingFlags)(-1)); + } + + private static PropertyInfo ___loopBlendOrientation; + private static PropertyInfo __loopBlendOrientation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___loopBlendOrientation ??= __type__?.GetProperty("loopBlendOrientation", (BindingFlags)(-1)); + } + + private static PropertyInfo ___loopBlendPositionY; + private static PropertyInfo __loopBlendPositionY + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___loopBlendPositionY ??= __type__?.GetProperty("loopBlendPositionY", (BindingFlags)(-1)); + } + + private static PropertyInfo ___loopBlendPositionXZ; + private static PropertyInfo __loopBlendPositionXZ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___loopBlendPositionXZ ??= __type__?.GetProperty("loopBlendPositionXZ", (BindingFlags)(-1)); + } + + private static PropertyInfo ___keepOriginalOrientation; + private static PropertyInfo __keepOriginalOrientation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___keepOriginalOrientation ??= __type__?.GetProperty("keepOriginalOrientation", (BindingFlags)(-1)); + } + + private static PropertyInfo ___keepOriginalPositionY; + private static PropertyInfo __keepOriginalPositionY + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___keepOriginalPositionY ??= __type__?.GetProperty("keepOriginalPositionY", (BindingFlags)(-1)); + } + + private static PropertyInfo ___keepOriginalPositionXZ; + private static PropertyInfo __keepOriginalPositionXZ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___keepOriginalPositionXZ ??= __type__?.GetProperty("keepOriginalPositionXZ", (BindingFlags)(-1)); + } + + private static PropertyInfo ___heightFromFeet; + private static PropertyInfo __heightFromFeet + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___heightFromFeet ??= __type__?.GetProperty("heightFromFeet", (BindingFlags)(-1)); + } + + private static PropertyInfo ___mirror; + private static PropertyInfo __mirror + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___mirror ??= __type__?.GetProperty("mirror", (BindingFlags)(-1)); + } + + private static PropertyInfo ___maskType; + private static PropertyInfo __maskType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___maskType ??= __type__?.GetProperty("maskType", (BindingFlags)(-1)); + } + + private static PropertyInfo ___maskSource; + private static PropertyInfo __maskSource + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___maskSource ??= __type__?.GetProperty("maskSource", (BindingFlags)(-1)); + } + + private static PropertyInfo ___maskTypeProperty; + private static PropertyInfo __maskTypeProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___maskTypeProperty ??= __type__?.GetProperty("maskTypeProperty", (BindingFlags)(-1)); + } + + private static PropertyInfo ___maskSourceProperty; + private static PropertyInfo __maskSourceProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___maskSourceProperty ??= __type__?.GetProperty("maskSourceProperty", (BindingFlags)(-1)); + } + + private static PropertyInfo ___bodyMaskProperty; + private static PropertyInfo __bodyMaskProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___bodyMaskProperty ??= __type__?.GetProperty("bodyMaskProperty", (BindingFlags)(-1)); + } + + private static PropertyInfo ___transformMaskProperty; + private static PropertyInfo __transformMaskProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___transformMaskProperty ??= __type__?.GetProperty("transformMaskProperty", (BindingFlags)(-1)); + } + + private static MethodInfo ___ApplyModifiedProperties; + private static MethodInfo __ApplyModifiedProperties + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ApplyModifiedProperties ??= __type__?.GetMethodInfoByParameterTypeNames("ApplyModifiedProperties"); + } + + private static MethodInfo ___MaskNeedsUpdating; + private static MethodInfo __MaskNeedsUpdating + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MaskNeedsUpdating ??= __type__?.GetMethodInfoByParameterTypeNames("MaskNeedsUpdating"); + } + + private static MethodInfo ___MaskFromClip; + private static MethodInfo __MaskFromClip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MaskFromClip ??= __type__?.GetMethodInfoByParameterTypeNames("MaskFromClip", "UnityEngine.AvatarMask"); + } + + private static MethodInfo ___MaskToClip; + private static MethodInfo __MaskToClip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MaskToClip ??= __type__?.GetMethodInfoByParameterTypeNames("MaskToClip", "UnityEngine.AvatarMask"); + } + + private static MethodInfo ___ClearCurves; + private static MethodInfo __ClearCurves + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ClearCurves ??= __type__?.GetMethodInfoByParameterTypeNames("ClearCurves"); + } + + private static MethodInfo ___GetCurveCount; + private static MethodInfo __GetCurveCount + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetCurveCount ??= __type__?.GetMethodInfoByParameterTypeNames("GetCurveCount"); + } + + private static MethodInfo ___GetCurveProperty; + private static MethodInfo __GetCurveProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetCurveProperty ??= __type__?.GetMethodInfoByParameterTypeNames("GetCurveProperty", "System.Int32"); + } + + private static MethodInfo ___GetCurveName; + private static MethodInfo __GetCurveName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetCurveName ??= __type__?.GetMethodInfoByParameterTypeNames("GetCurveName", "System.Int32"); + } + + private static MethodInfo ___SetCurveName; + private static MethodInfo __SetCurveName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetCurveName ??= __type__?.GetMethodInfoByParameterTypeNames("SetCurveName", "System.Int32", "System.String"); + } + + private static MethodInfo ___GetCurve; + private static MethodInfo __GetCurve + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetCurve ??= __type__?.GetMethodInfoByParameterTypeNames("GetCurve", "System.Int32"); + } + + private static MethodInfo ___SetCurve; + private static MethodInfo __SetCurve + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetCurve ??= __type__?.GetMethodInfoByParameterTypeNames("SetCurve", "System.Int32", "UnityEngine.AnimationCurve"); + } + + private static MethodInfo ___AddCurve; + private static MethodInfo __AddCurve + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AddCurve ??= __type__?.GetMethodInfoByParameterTypeNames("AddCurve"); + } + + private static MethodInfo ___RemoveCurve; + private static MethodInfo __RemoveCurve + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RemoveCurve ??= __type__?.GetMethodInfoByParameterTypeNames("RemoveCurve", "System.Int32"); + } + + private static MethodInfo ___GetEvent; + private static MethodInfo __GetEvent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetEvent ??= __type__?.GetMethodInfoByParameterTypeNames("GetEvent", "System.Int32"); + } + + private static MethodInfo ___SetEvent; + private static MethodInfo __SetEvent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetEvent ??= __type__?.GetMethodInfoByParameterTypeNames("SetEvent", "System.Int32", "UnityEngine.AnimationEvent"); + } + + private static MethodInfo ___ClearEvents; + private static MethodInfo __ClearEvents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ClearEvents ??= __type__?.GetMethodInfoByParameterTypeNames("ClearEvents"); + } + + private static MethodInfo ___GetEventCount; + private static MethodInfo __GetEventCount + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetEventCount ??= __type__?.GetMethodInfoByParameterTypeNames("GetEventCount"); + } + + private static MethodInfo ___AddEvent; + private static MethodInfo __AddEvent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AddEvent ??= __type__?.GetMethodInfoByParameterTypeNames("AddEvent", "System.Single"); + } + + private static MethodInfo ___RemoveEvent; + private static MethodInfo __RemoveEvent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RemoveEvent ??= __type__?.GetMethodInfoByParameterTypeNames("RemoveEvent", "System.Int32"); + } + + private static MethodInfo ___SetEvents; + private static MethodInfo __SetEvents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetEvents ??= __type__?.GetMethodInfoByParameterTypeNames("SetEvents", "UnityEngine.AnimationEvent[]"); + } + + private static MethodInfo ___GetEvents; + private static MethodInfo __GetEvents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetEvents ??= __type__?.GetMethodInfoByParameterTypeNames("GetEvents"); + } + + private static MethodInfo ___AssignToPreviewClip; + private static MethodInfo __AssignToPreviewClip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AssignToPreviewClip ??= __type__?.GetMethodInfoByParameterTypeNames("AssignToPreviewClip", "UnityEngine.AnimationClip"); + } + + private static MethodInfo ___FixPrecisionErrors; + private static MethodInfo __FixPrecisionErrors + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FixPrecisionErrors ??= __type__?.GetMethodInfoByParameterTypeNames("FixPrecisionErrors", "System.Single"); + } + + private static MethodInfo ___ExtractFromPreviewClip; + private static MethodInfo __ExtractFromPreviewClip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ExtractFromPreviewClip ??= __type__?.GetMethodInfoByParameterTypeNames("ExtractFromPreviewClip", "UnityEngine.AnimationClip"); + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_AnimationClipInfoProperties.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_AnimationClipInfoProperties.cs.meta new file mode 100644 index 0000000..1f8dd57 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_AnimationClipInfoProperties.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b4652e94e9fcf344ab0a64a43454f241 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_AnimationWindowEvent.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_AnimationWindowEvent.cs new file mode 100644 index 0000000..076c107 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_AnimationWindowEvent.cs @@ -0,0 +1,166 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_AnimationWindowEvent + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.AnimationWindowEvent"); + + + public UnityEngine.GameObject root + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GameObject)(__root?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __root?.SetValue(__self__, value); + } + + public UnityEngine.AnimationClip clip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.AnimationClip)(__clip?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __clip?.SetValue(__self__, value); + } + + public UnityEditor_AnimationClipInfoProperties clipInfo + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_AnimationClipInfoProperties(__clipInfo?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __clipInfo?.SetValue(__self__, value.__self__); + } + + public int eventIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__eventIndex?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __eventIndex?.SetValue(__self__, value); + } + + public static UnityEditor_AnimationWindowEvent CreateAndEdit(UnityEngine.GameObject root, UnityEngine.AnimationClip clip, float time) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = root; + __params__[1] = clip; + __params__[2] = time; + var __result__ = __CreateAndEdit?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? new UnityEditor_AnimationWindowEvent(__result__) : default; + } + + public static UnityEditor_AnimationWindowEvent Edit(UnityEngine.GameObject root, UnityEngine.AnimationClip clip, int eventIndex) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = root; + __params__[1] = clip; + __params__[2] = eventIndex; + var __result__ = __Edit?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? new UnityEditor_AnimationWindowEvent(__result__) : default; + } + + public static UnityEditor_AnimationWindowEvent Edit(UnityEditor_AnimationClipInfoProperties clipInfo, int eventIndex) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = clipInfo.__self__; + __params__[1] = eventIndex; + var __result__ = __Edit__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? new UnityEditor_AnimationWindowEvent(__result__) : default; + } + + public static int InsertAnimationEvent(ref UnityEngine.AnimationEvent[] events, UnityEngine.AnimationClip clip, UnityEngine.AnimationEvent evt) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = events; + __params__[1] = clip; + __params__[2] = evt; + var __result__ = __InsertAnimationEvent?.Invoke(null, __params__); + events = (UnityEngine.AnimationEvent[])(__params__[0]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public UnityEditor_AnimationWindowEvent(object __self__) => this.__self__ = __self__ as UnityEngine.Object; + public UnityEngine.Object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + public UnityEngine.ScriptableObject __super__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.ScriptableObject)(__self__); + } + + private static FieldInfo ___root; + private static FieldInfo __root + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___root ??= __type__?.GetField("root", (BindingFlags)(-1)); + } + + private static FieldInfo ___clip; + private static FieldInfo __clip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___clip ??= __type__?.GetField("clip", (BindingFlags)(-1)); + } + + private static FieldInfo ___clipInfo; + private static FieldInfo __clipInfo + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___clipInfo ??= __type__?.GetField("clipInfo", (BindingFlags)(-1)); + } + + private static FieldInfo ___eventIndex; + private static FieldInfo __eventIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___eventIndex ??= __type__?.GetField("eventIndex", (BindingFlags)(-1)); + } + + private static MethodInfo ___CreateAndEdit; + private static MethodInfo __CreateAndEdit + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CreateAndEdit ??= __type__?.GetMethodInfoByParameterTypeNames("CreateAndEdit", "UnityEngine.GameObject", "UnityEngine.AnimationClip", "System.Single"); + } + + private static MethodInfo ___Edit; + private static MethodInfo __Edit + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Edit ??= __type__?.GetMethodInfoByParameterTypeNames("Edit", "UnityEngine.GameObject", "UnityEngine.AnimationClip", "System.Int32"); + } + + private static MethodInfo ___Edit__2; + private static MethodInfo __Edit__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Edit__2 ??= __type__?.GetMethodInfoByParameterTypeNames("Edit", "UnityEditor.AnimationClipInfoProperties", "System.Int32"); + } + + private static MethodInfo ___InsertAnimationEvent; + private static MethodInfo __InsertAnimationEvent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___InsertAnimationEvent ??= __type__?.GetMethodInfoByParameterTypeNames("InsertAnimationEvent", "UnityEngine.AnimationEvent[]&", "UnityEngine.AnimationClip", "UnityEngine.AnimationEvent"); + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_AnimationWindowEvent.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_AnimationWindowEvent.cs.meta new file mode 100644 index 0000000..5e9c94a --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_AnimationWindowEvent.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ba780727f12cbeb4dac8361fefa37f56 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_BaseAssetImporterTabUI.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_BaseAssetImporterTabUI.cs new file mode 100644 index 0000000..1f6aacf --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_BaseAssetImporterTabUI.cs @@ -0,0 +1,314 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_BaseAssetImporterTabUI + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.BaseAssetImporterTabUI"); + + + public UnityEditor.AssetImporters.AssetImporterEditor panelContainer + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.AssetImporters.AssetImporterEditor)(__panelContainer?.GetValue(__self__)); + } + + public UnityEditor.SerializedObject serializedObject + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedObject)(__serializedObject?.GetValue(__self__)); + } + + public UnityEngine.Object[] targets + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Object[])(__targets?.GetValue(__self__)); + } + + public UnityEngine.Object target + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Object)(__target?.GetValue(__self__)); + } + + public UnityEngine.Object assetTarget + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Object)(__assetTarget?.GetValue(__self__)); + } + + public UnityEngine.Object[] assetTargets + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Object[])(__assetTargets?.GetValue(__self__)); + } + + public int referenceTargetIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__referenceTargetIndex?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __referenceTargetIndex?.SetValue(__self__, value); + } + + public UnityEditor.AssetImporters.AssetImporterEditor m_PanelContainer + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.AssetImporters.AssetImporterEditor)(__m_PanelContainer?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_PanelContainer?.SetValue(__self__, value); + } + + public System.Func Instantiate + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Func)(__Instantiate?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __Instantiate?.SetValue(__self__, value); + } + + public System.Action DestroyImmediate + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Action)(__DestroyImmediate?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __DestroyImmediate?.SetValue(__self__, value); + } + + public void OnEnable() + { + __OnEnable?.Invoke(__self__, System.Array.Empty()); + } + + public void OnDisable() + { + __OnDisable?.Invoke(__self__, System.Array.Empty()); + } + + public void PreApply() + { + __PreApply?.Invoke(__self__, System.Array.Empty()); + } + + public void PostApply() + { + __PostApply?.Invoke(__self__, System.Array.Empty()); + } + + public void ResetValues() + { + __ResetValues?.Invoke(__self__, System.Array.Empty()); + } + + public void OnInspectorGUI() + { + __OnInspectorGUI?.Invoke(__self__, System.Array.Empty()); + } + + public bool HasModified() + { + var __result__ = __HasModified?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void OnPreviewSettings() + { + __OnPreviewSettings?.Invoke(__self__, System.Array.Empty()); + } + + public void OnInteractivePreviewGUI(UnityEngine.Rect r, UnityEngine.GUIStyle background) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = r; + __params__[1] = background; + __OnInteractivePreviewGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public bool HasPreviewGUI() + { + var __result__ = __HasPreviewGUI?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void OnDestroy() + { + __OnDestroy?.Invoke(__self__, System.Array.Empty()); + } + + public void Repaint() + { + __Repaint?.Invoke(__self__, System.Array.Empty()); + } + + public UnityEditor_BaseAssetImporterTabUI(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + + private static FieldInfo ___m_PanelContainer; + private static FieldInfo __m_PanelContainer + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_PanelContainer ??= __type__?.GetField("m_PanelContainer", (BindingFlags)(-1)); + } + + private static FieldInfo ___Instantiate; + private static FieldInfo __Instantiate + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Instantiate ??= __type__?.GetField("Instantiate", (BindingFlags)(-1)); + } + + private static FieldInfo ___DestroyImmediate; + private static FieldInfo __DestroyImmediate + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DestroyImmediate ??= __type__?.GetField("DestroyImmediate", (BindingFlags)(-1)); + } + + private static PropertyInfo ___panelContainer; + private static PropertyInfo __panelContainer + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___panelContainer ??= __type__?.GetProperty("panelContainer", (BindingFlags)(-1)); + } + + private static PropertyInfo ___serializedObject; + private static PropertyInfo __serializedObject + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___serializedObject ??= __type__?.GetProperty("serializedObject", (BindingFlags)(-1)); + } + + private static PropertyInfo ___targets; + private static PropertyInfo __targets + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___targets ??= __type__?.GetProperty("targets", (BindingFlags)(-1)); + } + + private static PropertyInfo ___target; + private static PropertyInfo __target + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___target ??= __type__?.GetProperty("target", (BindingFlags)(-1)); + } + + private static PropertyInfo ___assetTarget; + private static PropertyInfo __assetTarget + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___assetTarget ??= __type__?.GetProperty("assetTarget", (BindingFlags)(-1)); + } + + private static PropertyInfo ___assetTargets; + private static PropertyInfo __assetTargets + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___assetTargets ??= __type__?.GetProperty("assetTargets", (BindingFlags)(-1)); + } + + private static PropertyInfo ___referenceTargetIndex; + private static PropertyInfo __referenceTargetIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___referenceTargetIndex ??= __type__?.GetProperty("referenceTargetIndex", (BindingFlags)(-1)); + } + + private static MethodInfo ___OnEnable; + private static MethodInfo __OnEnable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnEnable ??= __type__?.GetMethodInfoByParameterTypeNames("OnEnable"); + } + + private static MethodInfo ___OnDisable; + private static MethodInfo __OnDisable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnDisable ??= __type__?.GetMethodInfoByParameterTypeNames("OnDisable"); + } + + private static MethodInfo ___PreApply; + private static MethodInfo __PreApply + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PreApply ??= __type__?.GetMethodInfoByParameterTypeNames("PreApply"); + } + + private static MethodInfo ___PostApply; + private static MethodInfo __PostApply + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PostApply ??= __type__?.GetMethodInfoByParameterTypeNames("PostApply"); + } + + private static MethodInfo ___ResetValues; + private static MethodInfo __ResetValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ResetValues ??= __type__?.GetMethodInfoByParameterTypeNames("ResetValues"); + } + + private static MethodInfo ___OnInspectorGUI; + private static MethodInfo __OnInspectorGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnInspectorGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnInspectorGUI"); + } + + private static MethodInfo ___HasModified; + private static MethodInfo __HasModified + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasModified ??= __type__?.GetMethodInfoByParameterTypeNames("HasModified"); + } + + private static MethodInfo ___OnPreviewSettings; + private static MethodInfo __OnPreviewSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnPreviewSettings ??= __type__?.GetMethodInfoByParameterTypeNames("OnPreviewSettings"); + } + + private static MethodInfo ___OnInteractivePreviewGUI; + private static MethodInfo __OnInteractivePreviewGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnInteractivePreviewGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnInteractivePreviewGUI", "UnityEngine.Rect", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___HasPreviewGUI; + private static MethodInfo __HasPreviewGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasPreviewGUI ??= __type__?.GetMethodInfoByParameterTypeNames("HasPreviewGUI"); + } + + private static MethodInfo ___OnDestroy; + private static MethodInfo __OnDestroy + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnDestroy ??= __type__?.GetMethodInfoByParameterTypeNames("OnDestroy"); + } + + private static MethodInfo ___Repaint; + private static MethodInfo __Repaint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Repaint ??= __type__?.GetMethodInfoByParameterTypeNames("Repaint"); + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_BaseAssetImporterTabUI.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_BaseAssetImporterTabUI.cs.meta new file mode 100644 index 0000000..f711b72 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_BaseAssetImporterTabUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fb1bc6f87d827bd4aacf1fd78c32a611 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_BaseTextureImportPlatformSettings.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_BaseTextureImportPlatformSettings.cs new file mode 100644 index 0000000..38cc25b --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_BaseTextureImportPlatformSettings.cs @@ -0,0 +1,332 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_BaseTextureImportPlatformSettings + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.BaseTextureImportPlatformSettings"); + + + public bool textureTypeHasMultipleDifferentValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__textureTypeHasMultipleDifferentValues?.GetValue(__self__)); + } + + public UnityEditor.TextureImporterType textureType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.TextureImporterType)(__textureType?.GetValue(__self__)); + } + + public UnityEditor.SpriteImportMode spriteImportMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SpriteImportMode)(__spriteImportMode?.GetValue(__self__)); + } + + public UnityEditor_TextureImportPlatformSettingsData model + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_TextureImportPlatformSettingsData(__model?.GetValue(__self__)); + } + + public int GetTargetCount() + { + var __result__ = __GetTargetCount?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public bool ShowPresetSettings() + { + var __result__ = __ShowPresetSettings?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public UnityEditor.TextureImporterSettings GetImporterSettings(int i) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = i; + var __result__ = __GetImporterSettings?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEditor.TextureImporterSettings)(__result__) : default; + } + + public bool IsSourceTextureHDR(int i) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = i; + var __result__ = __IsSourceTextureHDR?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public bool DoesSourceTextureHaveAlpha(int i) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = i; + var __result__ = __DoesSourceTextureHaveAlpha?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public UnityEditor.TextureImporterPlatformSettings GetPlatformTextureSettings(int i, string name) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = i; + __params__[1] = name; + var __result__ = __GetPlatformTextureSettings?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEditor.TextureImporterPlatformSettings)(__result__) : default; + } + + public UnityEditor_BaseTextureImportPlatformSettings GetDefaultImportSettings() + { + var __result__ = __GetDefaultImportSettings?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? new UnityEditor_BaseTextureImportPlatformSettings(__result__) : default; + } + + public void SetPlatformTextureSettings(int i, UnityEditor.TextureImporterPlatformSettings platformSettings) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = i; + __params__[1] = platformSettings; + __SetPlatformTextureSettings?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void Init() + { + __Init?.Invoke(__self__, System.Array.Empty()); + } + + public void Sync() + { + __Sync?.Invoke(__self__, System.Array.Empty()); + } + + public void Apply() + { + __Apply?.Invoke(__self__, System.Array.Empty()); + } + + public static Array GetBuildPlayerValidPlatforms() + { + var __result__ = __GetBuildPlayerValidPlatforms?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (Array)(__result__) : default; + } + + public static void ShowPlatformSpecificSettings(System.Collections.IList platformSettings) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = platformSettings; + __ShowPlatformSpecificSettings?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void ShowPlatformSpecificSettings(System.Collections.IList platformSettings, int selected) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = platformSettings; + __params__[1] = selected; + __ShowPlatformSpecificSettings__2?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void SyncPlatformSettings(System.Collections.IList platformSettings) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = platformSettings; + __SyncPlatformSettings?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void InitPlatformSettings(System.Collections.IList platformSettings) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = platformSettings; + __InitPlatformSettings?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void ApplyPlatformSettings(System.Collections.IList platformSettings) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = platformSettings; + __ApplyPlatformSettings?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public UnityEditor_BaseTextureImportPlatformSettings(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + + private static PropertyInfo ___textureTypeHasMultipleDifferentValues; + private static PropertyInfo __textureTypeHasMultipleDifferentValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___textureTypeHasMultipleDifferentValues ??= __type__?.GetProperty("textureTypeHasMultipleDifferentValues", (BindingFlags)(-1)); + } + + private static PropertyInfo ___textureType; + private static PropertyInfo __textureType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___textureType ??= __type__?.GetProperty("textureType", (BindingFlags)(-1)); + } + + private static PropertyInfo ___spriteImportMode; + private static PropertyInfo __spriteImportMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___spriteImportMode ??= __type__?.GetProperty("spriteImportMode", (BindingFlags)(-1)); + } + + private static PropertyInfo ___model; + private static PropertyInfo __model + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___model ??= __type__?.GetProperty("model", (BindingFlags)(-1)); + } + + private static MethodInfo ___GetTargetCount; + private static MethodInfo __GetTargetCount + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetTargetCount ??= __type__?.GetMethodInfoByParameterTypeNames("GetTargetCount"); + } + + private static MethodInfo ___ShowPresetSettings; + private static MethodInfo __ShowPresetSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShowPresetSettings ??= __type__?.GetMethodInfoByParameterTypeNames("ShowPresetSettings"); + } + + private static MethodInfo ___GetImporterSettings; + private static MethodInfo __GetImporterSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetImporterSettings ??= __type__?.GetMethodInfoByParameterTypeNames("GetImporterSettings", "System.Int32"); + } + + private static MethodInfo ___IsSourceTextureHDR; + private static MethodInfo __IsSourceTextureHDR + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsSourceTextureHDR ??= __type__?.GetMethodInfoByParameterTypeNames("IsSourceTextureHDR", "System.Int32"); + } + + private static MethodInfo ___DoesSourceTextureHaveAlpha; + private static MethodInfo __DoesSourceTextureHaveAlpha + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoesSourceTextureHaveAlpha ??= __type__?.GetMethodInfoByParameterTypeNames("DoesSourceTextureHaveAlpha", "System.Int32"); + } + + private static MethodInfo ___GetPlatformTextureSettings; + private static MethodInfo __GetPlatformTextureSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPlatformTextureSettings ??= __type__?.GetMethodInfoByParameterTypeNames("GetPlatformTextureSettings", "System.Int32", "System.String"); + } + + private static MethodInfo ___GetDefaultImportSettings; + private static MethodInfo __GetDefaultImportSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetDefaultImportSettings ??= __type__?.GetMethodInfoByParameterTypeNames("GetDefaultImportSettings"); + } + + private static MethodInfo ___SetPlatformTextureSettings; + private static MethodInfo __SetPlatformTextureSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetPlatformTextureSettings ??= __type__?.GetMethodInfoByParameterTypeNames("SetPlatformTextureSettings", "System.Int32", "UnityEditor.TextureImporterPlatformSettings"); + } + + private static MethodInfo ___Init; + private static MethodInfo __Init + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Init ??= __type__?.GetMethodInfoByParameterTypeNames("Init"); + } + + private static MethodInfo ___Sync; + private static MethodInfo __Sync + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Sync ??= __type__?.GetMethodInfoByParameterTypeNames("Sync"); + } + + private static MethodInfo ___Apply; + private static MethodInfo __Apply + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Apply ??= __type__?.GetMethodInfoByParameterTypeNames("Apply"); + } + + private static MethodInfo ___GetBuildPlayerValidPlatforms; + private static MethodInfo __GetBuildPlayerValidPlatforms + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetBuildPlayerValidPlatforms ??= __type__?.GetMethodInfoByParameterTypeNames("GetBuildPlayerValidPlatforms"); + } + + private static MethodInfo ___ShowPlatformSpecificSettings; + private static MethodInfo __ShowPlatformSpecificSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShowPlatformSpecificSettings ??= __type__?.GetMethodInfoByParameterTypeNames("ShowPlatformSpecificSettings", "System.Collections.Generic.List`1[[UnityEditor.BaseTextureImportPlatformSettings, UnityEditor.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]"); + } + + private static MethodInfo ___ShowPlatformSpecificSettings__2; + private static MethodInfo __ShowPlatformSpecificSettings__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShowPlatformSpecificSettings__2 ??= __type__?.GetMethodInfoByParameterTypeNames("ShowPlatformSpecificSettings", "System.Collections.Generic.List`1[[UnityEditor.BaseTextureImportPlatformSettings, UnityEditor.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "System.Int32"); + } + + private static MethodInfo ___SyncPlatformSettings; + private static MethodInfo __SyncPlatformSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SyncPlatformSettings ??= __type__?.GetMethodInfoByParameterTypeNames("SyncPlatformSettings", "System.Collections.Generic.List`1[[UnityEditor.BaseTextureImportPlatformSettings, UnityEditor.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]"); + } + + private static MethodInfo ___InitPlatformSettings; + private static MethodInfo __InitPlatformSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___InitPlatformSettings ??= __type__?.GetMethodInfoByParameterTypeNames("InitPlatformSettings", "System.Collections.Generic.List`1[[UnityEditor.BaseTextureImportPlatformSettings, UnityEditor.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]"); + } + + private static MethodInfo ___ApplyPlatformSettings; + private static MethodInfo __ApplyPlatformSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ApplyPlatformSettings ??= __type__?.GetMethodInfoByParameterTypeNames("ApplyPlatformSettings", "System.Collections.Generic.List`1[[UnityEditor.BaseTextureImportPlatformSettings, UnityEditor.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]"); + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_BaseTextureImportPlatformSettings.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_BaseTextureImportPlatformSettings.cs.meta new file mode 100644 index 0000000..7bec955 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_BaseTextureImportPlatformSettings.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1642816fa46e9874987b3fe9e65886e4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_Build_BuildPlatform.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_Build_BuildPlatform.cs new file mode 100644 index 0000000..a8e580d --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_Build_BuildPlatform.cs @@ -0,0 +1,169 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_Build_BuildPlatform + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.Build.BuildPlatform"); + + + public UnityEditor.BuildTargetGroup targetGroup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.BuildTargetGroup)(__targetGroup?.GetValue(__self__)); + } + + public UnityEngine.GUIContent title + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__title?.GetValue(__self__)); + } + + public UnityEngine.Texture2D smallIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Texture2D)(__smallIcon?.GetValue(__self__)); + } + + public string name + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__name?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __name?.SetValue(__self__, value); + } + + public UnityEditor.Build.NamedBuildTarget namedBuildTarget + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.Build.NamedBuildTarget)(__namedBuildTarget?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __namedBuildTarget?.SetValue(__self__, value); + } + + public bool hideInUi + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__hideInUi?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __hideInUi?.SetValue(__self__, value); + } + + public string tooltip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__tooltip?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __tooltip?.SetValue(__self__, value); + } + + public UnityEditor.BuildTarget defaultTarget + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.BuildTarget)(__defaultTarget?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __defaultTarget?.SetValue(__self__, value); + } + + public object m_Title + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_Title?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Title?.SetValue(__self__, value); + } + + public object m_SmallTitle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_SmallTitle?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SmallTitle?.SetValue(__self__, value); + } + + public UnityEditor_Build_BuildPlatform(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + + private static FieldInfo ___name; + private static FieldInfo __name + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___name ??= __type__?.GetField("name", (BindingFlags)(-1)); + } + + private static FieldInfo ___namedBuildTarget; + private static FieldInfo __namedBuildTarget + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___namedBuildTarget ??= __type__?.GetField("namedBuildTarget", (BindingFlags)(-1)); + } + + private static FieldInfo ___hideInUi; + private static FieldInfo __hideInUi + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___hideInUi ??= __type__?.GetField("hideInUi", (BindingFlags)(-1)); + } + + private static FieldInfo ___tooltip; + private static FieldInfo __tooltip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___tooltip ??= __type__?.GetField("tooltip", (BindingFlags)(-1)); + } + + private static FieldInfo ___defaultTarget; + private static FieldInfo __defaultTarget + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___defaultTarget ??= __type__?.GetField("defaultTarget", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Title; + private static FieldInfo __m_Title + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Title ??= __type__?.GetField("m_Title", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SmallTitle; + private static FieldInfo __m_SmallTitle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SmallTitle ??= __type__?.GetField("m_SmallTitle", (BindingFlags)(-1)); + } + + private static PropertyInfo ___targetGroup; + private static PropertyInfo __targetGroup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___targetGroup ??= __type__?.GetProperty("targetGroup", (BindingFlags)(-1)); + } + + private static PropertyInfo ___title; + private static PropertyInfo __title + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___title ??= __type__?.GetProperty("title", (BindingFlags)(-1)); + } + + private static PropertyInfo ___smallIcon; + private static PropertyInfo __smallIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___smallIcon ??= __type__?.GetProperty("smallIcon", (BindingFlags)(-1)); + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_Build_BuildPlatform.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_Build_BuildPlatform.cs.meta new file mode 100644 index 0000000..cde145a --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_Build_BuildPlatform.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 610665bb2adfce84eb7f15ed286f8b7b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_Build_BuildPlatforms.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_Build_BuildPlatforms.cs new file mode 100644 index 0000000..dff8537 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_Build_BuildPlatforms.cs @@ -0,0 +1,212 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_Build_BuildPlatforms + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.Build.BuildPlatforms"); + + + public static UnityEditor_Build_BuildPlatforms instance + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_Build_BuildPlatforms(__instance?.GetValue(null)); + } + + public static UnityEditor_Build_BuildPlatforms s_Instance + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_Build_BuildPlatforms(__s_Instance?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_Instance?.SetValue(null, value.__self__); + } + + public Array buildPlatforms + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (Array)(__buildPlatforms?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __buildPlatforms?.SetValue(__self__, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public UnityEditor_Build_BuildPlatform buildPlatforms__GetItem(int i) => new UnityEditor_Build_BuildPlatform(buildPlatforms?.GetValue(i)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void buildPlatforms__SetItem(int i, UnityEditor_Build_BuildPlatform value) => buildPlatforms?.SetValue(value.__self__, i); + + public string GetBuildTargetDisplayName(UnityEditor.BuildTargetGroup buildTargetGroup, UnityEditor.BuildTarget target, int subtarget) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = buildTargetGroup; + __params__[1] = target; + __params__[2] = subtarget; + var __result__ = __GetBuildTargetDisplayName?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public string GetBuildTargetDisplayName(UnityEditor.Build.NamedBuildTarget namedBuildTarget, UnityEditor.BuildTarget target) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = namedBuildTarget; + __params__[1] = target; + var __result__ = __GetBuildTargetDisplayName__2?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public string GetModuleDisplayName(UnityEditor.Build.NamedBuildTarget namedBuildTarget, UnityEditor.BuildTarget buildTarget) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = namedBuildTarget; + __params__[1] = buildTarget; + var __result__ = __GetModuleDisplayName?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public int BuildPlatformIndexFromNamedBuildTarget(UnityEditor.Build.NamedBuildTarget target) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = target; + var __result__ = __BuildPlatformIndexFromNamedBuildTarget?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public UnityEditor_Build_BuildPlatform BuildPlatformFromNamedBuildTarget(UnityEditor.Build.NamedBuildTarget target) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = target; + var __result__ = __BuildPlatformFromNamedBuildTarget?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? new UnityEditor_Build_BuildPlatform(__result__) : default; + } + + public System.Collections.IList GetValidPlatforms(bool includeMetaPlatforms) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = includeMetaPlatforms; + var __result__ = __GetValidPlatforms?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (System.Collections.IList)(__result__) : default; + } + + public System.Collections.IList GetValidPlatforms() + { + var __result__ = __GetValidPlatforms__2?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (System.Collections.IList)(__result__) : default; + } + + public static string[] GetValidPlatformNames() + { + var __result__ = __GetValidPlatformNames?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (string[])(__result__) : default; + } + + public UnityEditor_Build_BuildPlatforms(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + + private static FieldInfo ___s_Instance; + private static FieldInfo __s_Instance + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_Instance ??= __type__?.GetField("s_Instance", (BindingFlags)(-1)); + } + + private static FieldInfo ___buildPlatforms; + private static FieldInfo __buildPlatforms + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___buildPlatforms ??= __type__?.GetField("buildPlatforms", (BindingFlags)(-1)); + } + + private static Type ___E__buildPlatforms; + public static Type __E__buildPlatforms + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___E__buildPlatforms ??= EditorUtils.GetTypeByFullName("UnityEditor.Build.BuildPlatform"); + } + + private static PropertyInfo ___instance; + private static PropertyInfo __instance + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___instance ??= __type__?.GetProperty("instance", (BindingFlags)(-1)); + } + + private static MethodInfo ___GetBuildTargetDisplayName; + private static MethodInfo __GetBuildTargetDisplayName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetBuildTargetDisplayName ??= __type__?.GetMethodInfoByParameterTypeNames("GetBuildTargetDisplayName", "UnityEditor.BuildTargetGroup", "UnityEditor.BuildTarget", "System.Int32"); + } + + private static MethodInfo ___GetBuildTargetDisplayName__2; + private static MethodInfo __GetBuildTargetDisplayName__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetBuildTargetDisplayName__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GetBuildTargetDisplayName", "UnityEditor.Build.NamedBuildTarget", "UnityEditor.BuildTarget"); + } + + private static MethodInfo ___GetModuleDisplayName; + private static MethodInfo __GetModuleDisplayName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetModuleDisplayName ??= __type__?.GetMethodInfoByParameterTypeNames("GetModuleDisplayName", "UnityEditor.Build.NamedBuildTarget", "UnityEditor.BuildTarget"); + } + + private static MethodInfo ___BuildPlatformIndexFromNamedBuildTarget; + private static MethodInfo __BuildPlatformIndexFromNamedBuildTarget + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BuildPlatformIndexFromNamedBuildTarget ??= __type__?.GetMethodInfoByParameterTypeNames("BuildPlatformIndexFromNamedBuildTarget", "UnityEditor.Build.NamedBuildTarget"); + } + + private static MethodInfo ___BuildPlatformFromNamedBuildTarget; + private static MethodInfo __BuildPlatformFromNamedBuildTarget + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BuildPlatformFromNamedBuildTarget ??= __type__?.GetMethodInfoByParameterTypeNames("BuildPlatformFromNamedBuildTarget", "UnityEditor.Build.NamedBuildTarget"); + } + + private static MethodInfo ___GetValidPlatforms; + private static MethodInfo __GetValidPlatforms + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetValidPlatforms ??= __type__?.GetMethodInfoByParameterTypeNames("GetValidPlatforms", "System.Boolean"); + } + + private static MethodInfo ___GetValidPlatforms__2; + private static MethodInfo __GetValidPlatforms__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetValidPlatforms__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GetValidPlatforms"); + } + + private static MethodInfo ___GetValidPlatformNames; + private static MethodInfo __GetValidPlatformNames + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetValidPlatformNames ??= __type__?.GetMethodInfoByParameterTypeNames("GetValidPlatformNames"); + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_Build_BuildPlatforms.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_Build_BuildPlatforms.cs.meta new file mode 100644 index 0000000..d54c16c --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_Build_BuildPlatforms.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a3291bd43d2850b46a7be5a93c087942 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_Editor.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_Editor.cs new file mode 100644 index 0000000..86b4c92 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_Editor.cs @@ -0,0 +1,1109 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_Editor + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.Editor"); + + public delegate void OnEditorGUIDelegate(UnityEditor.Editor editor, UnityEngine.Rect drawRect); + + public UnityEditor.InspectorMode inspectorMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.InspectorMode)(__inspectorMode?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __inspectorMode?.SetValue(__self__, value); + } + + public bool firstInspectedEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__firstInspectedEditor?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __firstInspectedEditor?.SetValue(__self__, value); + } + + public object propertyViewer + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__propertyViewer?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __propertyViewer?.SetValue(__self__, value); + } + + public bool canEditMultipleObjects + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__canEditMultipleObjects?.GetValue(__self__)); + } + + public object preview + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__preview?.GetValue(__self__)); + } + + public object propertyHandlerCache + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__propertyHandlerCache?.GetValue(__self__)); + } + + public bool UnityEditor_IToolModeOwner_areToolModesAvailable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__UnityEditor_IToolModeOwner_areToolModesAvailable?.GetValue(__self__)); + } + + public int referenceTargetIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__referenceTargetIndex?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __referenceTargetIndex?.SetValue(__self__, value); + } + + public string targetTitle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__targetTitle?.GetValue(__self__)); + } + + public UnityEditor.SerializedProperty enabledProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__enabledProperty?.GetValue(__self__)); + } + + public bool isInspectorDirty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__isInspectorDirty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __isInspectorDirty?.SetValue(__self__, value); + } + + public bool alwaysAllowExpansion + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__alwaysAllowExpansion?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __alwaysAllowExpansion?.SetValue(__self__, value); + } + + public UnityEngine.Object[] m_Targets + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Object[])(__m_Targets?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Targets?.SetValue(__self__, value); + } + + public UnityEngine.Object m_Context + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Object)(__m_Context?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Context?.SetValue(__self__, value); + } + + public int m_IsDirty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__m_IsDirty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_IsDirty?.SetValue(__self__, value); + } + + public int m_ReferenceTargetIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__m_ReferenceTargetIndex?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ReferenceTargetIndex?.SetValue(__self__, value); + } + + public object m_PropertyHandlerCache + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_PropertyHandlerCache?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_PropertyHandlerCache?.SetValue(__self__, value); + } + + public object m_DummyPreview + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_DummyPreview?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_DummyPreview?.SetValue(__self__, value); + } + + public object m_AudioFilterGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_AudioFilterGUI?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AudioFilterGUI?.SetValue(__self__, value); + } + + public UnityEditor.SerializedObject m_SerializedObject + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedObject)(__m_SerializedObject?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SerializedObject?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_EnabledProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_EnabledProperty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_EnabledProperty?.SetValue(__self__, value); + } + + public UnityEditor.InspectorMode m_InspectorMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.InspectorMode)(__m_InspectorMode?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_InspectorMode?.SetValue(__self__, value); + } + + public static float kLineHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kLineHeight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kLineHeight?.SetValue(null, value); + } + + public bool hideInspector + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__hideInspector?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __hideInspector?.SetValue(__self__, value); + } + + public static float kImageSectionWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kImageSectionWidth?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kImageSectionWidth?.SetValue(null, value); + } + + public static float k_WideModeMinWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__k_WideModeMinWidth?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __k_WideModeMinWidth?.SetValue(null, value); + } + + public static float k_HeaderHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__k_HeaderHeight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __k_HeaderHeight?.SetValue(null, value); + } + + public static OnEditorGUIDelegate OnPostIconGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (__OnPostIconGUI?.GetValue(null) as Delegate)?.Cast(); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __OnPostIconGUI?.SetValue(null, value?.Cast(__OnPostIconGUI.FieldType)); + } + + public static bool m_AllowMultiObjectAccess + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_AllowMultiObjectAccess?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AllowMultiObjectAccess?.SetValue(null, value); + } + + public static System.Action finishedDefaultHeaderGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Action)(__finishedDefaultHeaderGUI?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __finishedDefaultHeaderGUI?.SetValue(null, value); + } + + public bool HasLargeHeader() + { + var __result__ = __HasLargeHeader?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void CleanupPropertyEditor() + { + __CleanupPropertyEditor?.Invoke(__self__, System.Array.Empty()); + } + + public void OnDisableINTERNAL() + { + __OnDisableINTERNAL?.Invoke(__self__, System.Array.Empty()); + } + + public UnityEditor.SerializedObject GetSerializedObjectInternal() + { + var __result__ = __GetSerializedObjectInternal?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (UnityEditor.SerializedObject)(__result__) : default; + } + + public void CreateSerializedObject() + { + __CreateSerializedObject?.Invoke(__self__, System.Array.Empty()); + } + + public static void AssignCachedProperties(T self, UnityEditor.SerializedProperty root) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = self; + __params__[1] = root; + __AssignCachedProperties?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public void InternalSetTargets(UnityEngine.Object[] t) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = t; + __InternalSetTargets?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void InternalSetHidden(bool hidden) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = hidden; + __InternalSetHidden?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void InternalSetContextObject(UnityEngine.Object context) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = context; + __InternalSetContextObject?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public UnityEngine.Bounds UnityEditor_IToolModeOwner_GetWorldBoundsOfTargets() + { + var __result__ = __UnityEditor_IToolModeOwner_GetWorldBoundsOfTargets?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (UnityEngine.Bounds)(__result__) : default; + } + + public UnityEngine.Bounds GetWorldBoundsOfTarget(UnityEngine.Object targetObject) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = targetObject; + var __result__ = __GetWorldBoundsOfTarget?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Bounds)(__result__) : default; + } + + public bool UnityEditor_IToolModeOwner_ModeSurvivesSelectionChange(int toolMode) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = toolMode; + var __result__ = __UnityEditor_IToolModeOwner_ModeSurvivesSelectionChange?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public void OnForceReloadInspector() + { + __OnForceReloadInspector?.Invoke(__self__, System.Array.Empty()); + } + + public bool GetOptimizedGUIBlock(bool isDirty, bool isVisible, out float height) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = isDirty; + __params__[1] = isVisible; + __params__[2] = null; + var __result__ = __GetOptimizedGUIBlock?.Invoke(__self__, __params__); + height = (float)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public bool OnOptimizedInspectorGUI(UnityEngine.Rect contentRect) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = contentRect; + var __result__ = __OnOptimizedInspectorGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void DrawPropertiesExcluding(UnityEditor.SerializedObject obj, string[] propertyToExclude) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = obj; + __params__[1] = propertyToExclude; + __DrawPropertiesExcluding?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static bool DoDrawDefaultInspector(UnityEditor.SerializedObject obj) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = obj; + var __result__ = __DoDrawDefaultInspector?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public bool DoDrawDefaultInspector() + { + var __result__ = __DoDrawDefaultInspector__2?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void OnHeaderGUI() + { + __OnHeaderGUI?.Invoke(__self__, System.Array.Empty()); + } + + public void OnHeaderControlsGUI() + { + __OnHeaderControlsGUI?.Invoke(__self__, System.Array.Empty()); + } + + public void ShowOpenButton(UnityEngine.Object[] assets, bool enableCondition) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = assets; + __params__[1] = enableCondition; + __ShowOpenButton?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public bool ShouldHideOpenButton() + { + var __result__ = __ShouldHideOpenButton?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public bool CanOpenMultipleObjects() + { + var __result__ = __CanOpenMultipleObjects?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public bool ShouldTryToMakeEditableOnOpen() + { + var __result__ = __ShouldTryToMakeEditableOnOpen?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void OnHeaderIconGUI(UnityEngine.Rect iconRect) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = iconRect; + __OnHeaderIconGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void OnHeaderTitleGUI(UnityEngine.Rect titleRect, string header) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = titleRect; + __params__[1] = header; + __OnHeaderTitleGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public UnityEngine.Rect DrawHeaderHelpAndSettingsGUI(UnityEngine.Rect r) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = r; + var __result__ = __DrawHeaderHelpAndSettingsGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public void DrawHeaderFromInsideHierarchy() + { + __DrawHeaderFromInsideHierarchy?.Invoke(__self__, System.Array.Empty()); + } + + public static UnityEngine.Rect DrawHeaderGUI(UnityEditor.Editor editor, string header) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = editor; + __params__[1] = header; + var __result__ = __DrawHeaderGUI?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static UnityEngine.Rect DrawHeaderGUI(UnityEditor.Editor editor, string header, float leftMargin) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = editor; + __params__[1] = header; + __params__[2] = leftMargin; + var __result__ = __DrawHeaderGUI__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static void CheckForMainObjectNameMismatch(UnityEditor.Editor editor) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = editor; + __CheckForMainObjectNameMismatch?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public void DrawPostIconContent(UnityEngine.Rect iconRect) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = iconRect; + __DrawPostIconContent?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void DrawPostIconContent() + { + __DrawPostIconContent__2?.Invoke(__self__, System.Array.Empty()); + } + + public bool CanBeExpandedViaAFoldout() + { + var __result__ = __CanBeExpandedViaAFoldout?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public bool CanBeExpandedViaAFoldoutWithoutUpdate() + { + var __result__ = __CanBeExpandedViaAFoldoutWithoutUpdate?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool IsAppropriateFileOpenForEdit(UnityEngine.Object assetObject) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = assetObject; + var __result__ = __IsAppropriateFileOpenForEdit?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public bool IsEnabled() + { + var __result__ = __IsEnabled?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public bool IsOpenForEdit() + { + var __result__ = __IsOpenForEdit?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void OnAssetStoreInspectorGUI() + { + __OnAssetStoreInspectorGUI?.Invoke(__self__, System.Array.Empty()); + } + + public static UnityEditor.Editor CreateEditorWithContextInternal(UnityEngine.Object[] targetObjects, UnityEngine.Object context, System.Type editorType) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = targetObjects; + __params__[1] = context; + __params__[2] = editorType; + var __result__ = __CreateEditorWithContextInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEditor.Editor)(__result__) : default; + } + + public static UnityEngine.Vector2 GetCurrentMousePosition() + { + var __result__ = __GetCurrentMousePosition?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (UnityEngine.Vector2)(__result__) : default; + } + + public int UnityEditor_IToolModeOwner_GetInstanceID() + { + var __result__ = __UnityEditor_IToolModeOwner_GetInstanceID?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public static void GetCurrentMousePosition_Injected(out UnityEngine.Vector2 ret) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = Activator.CreateInstance(typeof(UnityEngine.Vector2)); + __GetCurrentMousePosition_Injected?.Invoke(null, __params__); + ret = (UnityEngine.Vector2)(__params__[0]); + __pool__.Return(__params__); + } + + public UnityEditor_Editor(object __self__) => this.__self__ = __self__ as UnityEngine.Object; + public UnityEngine.Object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + public UnityEditor.Editor __super__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.Editor)(__self__); + } + + private static FieldInfo ___m_Targets; + private static FieldInfo __m_Targets + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Targets ??= __type__?.GetField("m_Targets", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Context; + private static FieldInfo __m_Context + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Context ??= __type__?.GetField("m_Context", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_IsDirty; + private static FieldInfo __m_IsDirty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_IsDirty ??= __type__?.GetField("m_IsDirty", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ReferenceTargetIndex; + private static FieldInfo __m_ReferenceTargetIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ReferenceTargetIndex ??= __type__?.GetField("m_ReferenceTargetIndex", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_PropertyHandlerCache; + private static FieldInfo __m_PropertyHandlerCache + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_PropertyHandlerCache ??= __type__?.GetField("m_PropertyHandlerCache", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_DummyPreview; + private static FieldInfo __m_DummyPreview + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_DummyPreview ??= __type__?.GetField("m_DummyPreview", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AudioFilterGUI; + private static FieldInfo __m_AudioFilterGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AudioFilterGUI ??= __type__?.GetField("m_AudioFilterGUI", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SerializedObject; + private static FieldInfo __m_SerializedObject + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SerializedObject ??= __type__?.GetField("m_SerializedObject", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_EnabledProperty; + private static FieldInfo __m_EnabledProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_EnabledProperty ??= __type__?.GetField("m_EnabledProperty", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_InspectorMode; + private static FieldInfo __m_InspectorMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_InspectorMode ??= __type__?.GetField("m_InspectorMode", (BindingFlags)(-1)); + } + + private static FieldInfo ___kLineHeight; + private static FieldInfo __kLineHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kLineHeight ??= __type__?.GetField("kLineHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___hideInspector; + private static FieldInfo __hideInspector + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___hideInspector ??= __type__?.GetField("hideInspector", (BindingFlags)(-1)); + } + + private static FieldInfo ___kImageSectionWidth; + private static FieldInfo __kImageSectionWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kImageSectionWidth ??= __type__?.GetField("kImageSectionWidth", (BindingFlags)(-1)); + } + + private static FieldInfo ___k_WideModeMinWidth; + private static FieldInfo __k_WideModeMinWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___k_WideModeMinWidth ??= __type__?.GetField("k_WideModeMinWidth", (BindingFlags)(-1)); + } + + private static FieldInfo ___k_HeaderHeight; + private static FieldInfo __k_HeaderHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___k_HeaderHeight ??= __type__?.GetField("k_HeaderHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___OnPostIconGUI; + private static FieldInfo __OnPostIconGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnPostIconGUI ??= __type__?.GetField("OnPostIconGUI", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AllowMultiObjectAccess; + private static FieldInfo __m_AllowMultiObjectAccess + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AllowMultiObjectAccess ??= __type__?.GetField("m_AllowMultiObjectAccess", (BindingFlags)(-1)); + } + + private static FieldInfo ___finishedDefaultHeaderGUI; + private static FieldInfo __finishedDefaultHeaderGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___finishedDefaultHeaderGUI ??= __type__?.GetField("finishedDefaultHeaderGUI", (BindingFlags)(-1)); + } + + private static PropertyInfo ___inspectorMode; + private static PropertyInfo __inspectorMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___inspectorMode ??= __type__?.GetProperty("inspectorMode", (BindingFlags)(-1)); + } + + private static PropertyInfo ___firstInspectedEditor; + private static PropertyInfo __firstInspectedEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___firstInspectedEditor ??= __type__?.GetProperty("firstInspectedEditor", (BindingFlags)(-1)); + } + + private static PropertyInfo ___propertyViewer; + private static PropertyInfo __propertyViewer + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___propertyViewer ??= __type__?.GetProperty("propertyViewer", (BindingFlags)(-1)); + } + + private static PropertyInfo ___canEditMultipleObjects; + private static PropertyInfo __canEditMultipleObjects + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___canEditMultipleObjects ??= __type__?.GetProperty("canEditMultipleObjects", (BindingFlags)(-1)); + } + + private static PropertyInfo ___preview; + private static PropertyInfo __preview + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___preview ??= __type__?.GetProperty("preview", (BindingFlags)(-1)); + } + + private static PropertyInfo ___propertyHandlerCache; + private static PropertyInfo __propertyHandlerCache + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___propertyHandlerCache ??= __type__?.GetProperty("propertyHandlerCache", (BindingFlags)(-1)); + } + + private static PropertyInfo ___UnityEditor_IToolModeOwner_areToolModesAvailable; + private static PropertyInfo __UnityEditor_IToolModeOwner_areToolModesAvailable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UnityEditor_IToolModeOwner_areToolModesAvailable ??= __type__?.GetProperty("UnityEditor_IToolModeOwner_areToolModesAvailable", (BindingFlags)(-1)); + } + + private static PropertyInfo ___referenceTargetIndex; + private static PropertyInfo __referenceTargetIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___referenceTargetIndex ??= __type__?.GetProperty("referenceTargetIndex", (BindingFlags)(-1)); + } + + private static PropertyInfo ___targetTitle; + private static PropertyInfo __targetTitle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___targetTitle ??= __type__?.GetProperty("targetTitle", (BindingFlags)(-1)); + } + + private static PropertyInfo ___enabledProperty; + private static PropertyInfo __enabledProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___enabledProperty ??= __type__?.GetProperty("enabledProperty", (BindingFlags)(-1)); + } + + private static PropertyInfo ___isInspectorDirty; + private static PropertyInfo __isInspectorDirty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___isInspectorDirty ??= __type__?.GetProperty("isInspectorDirty", (BindingFlags)(-1)); + } + + private static PropertyInfo ___alwaysAllowExpansion; + private static PropertyInfo __alwaysAllowExpansion + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___alwaysAllowExpansion ??= __type__?.GetProperty("alwaysAllowExpansion", (BindingFlags)(-1)); + } + + private static MethodInfo ___HasLargeHeader; + private static MethodInfo __HasLargeHeader + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasLargeHeader ??= __type__?.GetMethodInfoByParameterTypeNames("HasLargeHeader"); + } + + private static MethodInfo ___CleanupPropertyEditor; + private static MethodInfo __CleanupPropertyEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CleanupPropertyEditor ??= __type__?.GetMethodInfoByParameterTypeNames("CleanupPropertyEditor"); + } + + private static MethodInfo ___OnDisableINTERNAL; + private static MethodInfo __OnDisableINTERNAL + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnDisableINTERNAL ??= __type__?.GetMethodInfoByParameterTypeNames("OnDisableINTERNAL"); + } + + private static MethodInfo ___GetSerializedObjectInternal; + private static MethodInfo __GetSerializedObjectInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSerializedObjectInternal ??= __type__?.GetMethodInfoByParameterTypeNames("GetSerializedObjectInternal"); + } + + private static MethodInfo ___CreateSerializedObject; + private static MethodInfo __CreateSerializedObject + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CreateSerializedObject ??= __type__?.GetMethodInfoByParameterTypeNames("CreateSerializedObject"); + } + + private static MethodInfo ___AssignCachedProperties; + private static MethodInfo __AssignCachedProperties + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AssignCachedProperties ??= __type__?.GetMethodInfoByParameterTypeNames("AssignCachedProperties", "", "UnityEditor.SerializedProperty"); + } + + private static MethodInfo ___InternalSetTargets; + private static MethodInfo __InternalSetTargets + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___InternalSetTargets ??= __type__?.GetMethodInfoByParameterTypeNames("InternalSetTargets", "UnityEngine.Object[]"); + } + + private static MethodInfo ___InternalSetHidden; + private static MethodInfo __InternalSetHidden + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___InternalSetHidden ??= __type__?.GetMethodInfoByParameterTypeNames("InternalSetHidden", "System.Boolean"); + } + + private static MethodInfo ___InternalSetContextObject; + private static MethodInfo __InternalSetContextObject + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___InternalSetContextObject ??= __type__?.GetMethodInfoByParameterTypeNames("InternalSetContextObject", "UnityEngine.Object"); + } + + private static MethodInfo ___UnityEditor_IToolModeOwner_GetWorldBoundsOfTargets; + private static MethodInfo __UnityEditor_IToolModeOwner_GetWorldBoundsOfTargets + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UnityEditor_IToolModeOwner_GetWorldBoundsOfTargets ??= __type__?.GetMethodInfoByParameterTypeNames("UnityEditor_IToolModeOwner_GetWorldBoundsOfTargets"); + } + + private static MethodInfo ___GetWorldBoundsOfTarget; + private static MethodInfo __GetWorldBoundsOfTarget + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetWorldBoundsOfTarget ??= __type__?.GetMethodInfoByParameterTypeNames("GetWorldBoundsOfTarget", "UnityEngine.Object"); + } + + private static MethodInfo ___UnityEditor_IToolModeOwner_ModeSurvivesSelectionChange; + private static MethodInfo __UnityEditor_IToolModeOwner_ModeSurvivesSelectionChange + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UnityEditor_IToolModeOwner_ModeSurvivesSelectionChange ??= __type__?.GetMethodInfoByParameterTypeNames("UnityEditor_IToolModeOwner_ModeSurvivesSelectionChange", "System.Int32"); + } + + private static MethodInfo ___OnForceReloadInspector; + private static MethodInfo __OnForceReloadInspector + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnForceReloadInspector ??= __type__?.GetMethodInfoByParameterTypeNames("OnForceReloadInspector"); + } + + private static MethodInfo ___GetOptimizedGUIBlock; + private static MethodInfo __GetOptimizedGUIBlock + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetOptimizedGUIBlock ??= __type__?.GetMethodInfoByParameterTypeNames("GetOptimizedGUIBlock", "System.Boolean", "System.Boolean", "System.Single&"); + } + + private static MethodInfo ___OnOptimizedInspectorGUI; + private static MethodInfo __OnOptimizedInspectorGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnOptimizedInspectorGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnOptimizedInspectorGUI", "UnityEngine.Rect"); + } + + private static MethodInfo ___DrawPropertiesExcluding; + private static MethodInfo __DrawPropertiesExcluding + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawPropertiesExcluding ??= __type__?.GetMethodInfoByParameterTypeNames("DrawPropertiesExcluding", "UnityEditor.SerializedObject", "System.String[]"); + } + + private static MethodInfo ___DoDrawDefaultInspector; + private static MethodInfo __DoDrawDefaultInspector + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoDrawDefaultInspector ??= __type__?.GetMethodInfoByParameterTypeNames("DoDrawDefaultInspector", "UnityEditor.SerializedObject"); + } + + private static MethodInfo ___DoDrawDefaultInspector__2; + private static MethodInfo __DoDrawDefaultInspector__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoDrawDefaultInspector__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DoDrawDefaultInspector"); + } + + private static MethodInfo ___OnHeaderGUI; + private static MethodInfo __OnHeaderGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnHeaderGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnHeaderGUI"); + } + + private static MethodInfo ___OnHeaderControlsGUI; + private static MethodInfo __OnHeaderControlsGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnHeaderControlsGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnHeaderControlsGUI"); + } + + private static MethodInfo ___ShowOpenButton; + private static MethodInfo __ShowOpenButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShowOpenButton ??= __type__?.GetMethodInfoByParameterTypeNames("ShowOpenButton", "UnityEngine.Object[]", "System.Boolean"); + } + + private static MethodInfo ___ShouldHideOpenButton; + private static MethodInfo __ShouldHideOpenButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShouldHideOpenButton ??= __type__?.GetMethodInfoByParameterTypeNames("ShouldHideOpenButton"); + } + + private static MethodInfo ___CanOpenMultipleObjects; + private static MethodInfo __CanOpenMultipleObjects + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CanOpenMultipleObjects ??= __type__?.GetMethodInfoByParameterTypeNames("CanOpenMultipleObjects"); + } + + private static MethodInfo ___ShouldTryToMakeEditableOnOpen; + private static MethodInfo __ShouldTryToMakeEditableOnOpen + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShouldTryToMakeEditableOnOpen ??= __type__?.GetMethodInfoByParameterTypeNames("ShouldTryToMakeEditableOnOpen"); + } + + private static MethodInfo ___OnHeaderIconGUI; + private static MethodInfo __OnHeaderIconGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnHeaderIconGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnHeaderIconGUI", "UnityEngine.Rect"); + } + + private static MethodInfo ___OnHeaderTitleGUI; + private static MethodInfo __OnHeaderTitleGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnHeaderTitleGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnHeaderTitleGUI", "UnityEngine.Rect", "System.String"); + } + + private static MethodInfo ___DrawHeaderHelpAndSettingsGUI; + private static MethodInfo __DrawHeaderHelpAndSettingsGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawHeaderHelpAndSettingsGUI ??= __type__?.GetMethodInfoByParameterTypeNames("DrawHeaderHelpAndSettingsGUI", "UnityEngine.Rect"); + } + + private static MethodInfo ___DrawHeaderFromInsideHierarchy; + private static MethodInfo __DrawHeaderFromInsideHierarchy + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawHeaderFromInsideHierarchy ??= __type__?.GetMethodInfoByParameterTypeNames("DrawHeaderFromInsideHierarchy"); + } + + private static MethodInfo ___DrawHeaderGUI; + private static MethodInfo __DrawHeaderGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawHeaderGUI ??= __type__?.GetMethodInfoByParameterTypeNames("DrawHeaderGUI", "UnityEditor.Editor", "System.String"); + } + + private static MethodInfo ___DrawHeaderGUI__2; + private static MethodInfo __DrawHeaderGUI__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawHeaderGUI__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DrawHeaderGUI", "UnityEditor.Editor", "System.String", "System.Single"); + } + + private static MethodInfo ___CheckForMainObjectNameMismatch; + private static MethodInfo __CheckForMainObjectNameMismatch + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CheckForMainObjectNameMismatch ??= __type__?.GetMethodInfoByParameterTypeNames("CheckForMainObjectNameMismatch", "UnityEditor.Editor"); + } + + private static MethodInfo ___DrawPostIconContent; + private static MethodInfo __DrawPostIconContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawPostIconContent ??= __type__?.GetMethodInfoByParameterTypeNames("DrawPostIconContent", "UnityEngine.Rect"); + } + + private static MethodInfo ___DrawPostIconContent__2; + private static MethodInfo __DrawPostIconContent__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawPostIconContent__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DrawPostIconContent"); + } + + private static MethodInfo ___CanBeExpandedViaAFoldout; + private static MethodInfo __CanBeExpandedViaAFoldout + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CanBeExpandedViaAFoldout ??= __type__?.GetMethodInfoByParameterTypeNames("CanBeExpandedViaAFoldout"); + } + + private static MethodInfo ___CanBeExpandedViaAFoldoutWithoutUpdate; + private static MethodInfo __CanBeExpandedViaAFoldoutWithoutUpdate + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CanBeExpandedViaAFoldoutWithoutUpdate ??= __type__?.GetMethodInfoByParameterTypeNames("CanBeExpandedViaAFoldoutWithoutUpdate"); + } + + private static MethodInfo ___IsAppropriateFileOpenForEdit; + private static MethodInfo __IsAppropriateFileOpenForEdit + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsAppropriateFileOpenForEdit ??= __type__?.GetMethodInfoByParameterTypeNames("IsAppropriateFileOpenForEdit", "UnityEngine.Object"); + } + + private static MethodInfo ___IsEnabled; + private static MethodInfo __IsEnabled + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsEnabled ??= __type__?.GetMethodInfoByParameterTypeNames("IsEnabled"); + } + + private static MethodInfo ___IsOpenForEdit; + private static MethodInfo __IsOpenForEdit + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsOpenForEdit ??= __type__?.GetMethodInfoByParameterTypeNames("IsOpenForEdit"); + } + + private static MethodInfo ___OnAssetStoreInspectorGUI; + private static MethodInfo __OnAssetStoreInspectorGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnAssetStoreInspectorGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnAssetStoreInspectorGUI"); + } + + private static MethodInfo ___CreateEditorWithContextInternal; + private static MethodInfo __CreateEditorWithContextInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CreateEditorWithContextInternal ??= __type__?.GetMethodInfoByParameterTypeNames("CreateEditorWithContextInternal", "UnityEngine.Object[]", "UnityEngine.Object", "System.Type"); + } + + private static MethodInfo ___GetCurrentMousePosition; + private static MethodInfo __GetCurrentMousePosition + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetCurrentMousePosition ??= __type__?.GetMethodInfoByParameterTypeNames("GetCurrentMousePosition"); + } + + private static MethodInfo ___UnityEditor_IToolModeOwner_GetInstanceID; + private static MethodInfo __UnityEditor_IToolModeOwner_GetInstanceID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UnityEditor_IToolModeOwner_GetInstanceID ??= __type__?.GetMethodInfoByParameterTypeNames("UnityEditor_IToolModeOwner_GetInstanceID"); + } + + private static MethodInfo ___GetCurrentMousePosition_Injected; + private static MethodInfo __GetCurrentMousePosition_Injected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetCurrentMousePosition_Injected ??= __type__?.GetMethodInfoByParameterTypeNames("GetCurrentMousePosition_Injected", "UnityEngine.Vector2&"); + } + } + public static class UnityEditor_Editor_Extension + { + public static UnityEditor_Editor ReflectionHelper(this UnityEditor.Editor self) => new(self); + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_Editor.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_Editor.cs.meta new file mode 100644 index 0000000..81431c5 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_Editor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2d757bc6a4cbb944fa0713b8499c0474 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUI.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUI.cs new file mode 100644 index 0000000..42d268c --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUI.cs @@ -0,0 +1,8724 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_EditorGUI + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.EditorGUI"); + + public delegate UnityEngine.Object ObjectFieldValidator(UnityEngine.Object[] references, System.Type objType, UnityEditor.SerializedProperty property, object options); + + public static float kMiniLabelW + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kMiniLabelW?.GetValue(null)); + } + + public static float lineHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__lineHeight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __lineHeight?.SetValue(null, value); + } + + public static UnityEngine.GUIContent mixedValueContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__mixedValueContent?.GetValue(null)); + } + + public static float indent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__indent?.GetValue(null)); + } + + public static UnityEngine.Texture2D transparentCheckerTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Texture2D)(__transparentCheckerTexture?.GetValue(null)); + } + + public static UnityEngine.Material colorMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Material)(__colorMaterial?.GetValue(null)); + } + + public static UnityEngine.Material colorVTMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Material)(__colorVTMaterial?.GetValue(null)); + } + + public static UnityEngine.Material alphaMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Material)(__alphaMaterial?.GetValue(null)); + } + + public static UnityEngine.Material alphaVTMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Material)(__alphaVTMaterial?.GetValue(null)); + } + + public static UnityEngine.Material transparentMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Material)(__transparentMaterial?.GetValue(null)); + } + + public static UnityEngine.Material transparentVTMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Material)(__transparentVTMaterial?.GetValue(null)); + } + + public static UnityEngine.Material normalmapMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Material)(__normalmapMaterial?.GetValue(null)); + } + + public static UnityEngine.Material normalmapVTMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Material)(__normalmapVTMaterial?.GetValue(null)); + } + + public static UnityEngine.Material lightmapRGBMMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Material)(__lightmapRGBMMaterial?.GetValue(null)); + } + + public static UnityEngine.Material lightmapDoubleLDRMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Material)(__lightmapDoubleLDRMaterial?.GetValue(null)); + } + + public static UnityEngine.Material lightmapFullHDRMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Material)(__lightmapFullHDRMaterial?.GetValue(null)); + } + + public static UnityEngine.Material guiTextureClipVerticallyMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Material)(__guiTextureClipVerticallyMaterial?.GetValue(null)); + } + + public static bool isCollectingTooltips + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__isCollectingTooltips?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __isCollectingTooltips?.SetValue(null, value); + } + + public static UnityEditor_EditorGUI_RecycledTextEditor activeEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_EditorGUI_RecycledTextEditor(__activeEditor?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __activeEditor?.SetValue(null, value.__self__); + } + + public static object s_DelayedTextEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__s_DelayedTextEditor?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_DelayedTextEditor?.SetValue(null, value); + } + + public static UnityEditor_EditorGUI_RecycledTextEditor s_RecycledEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_EditorGUI_RecycledTextEditor(__s_RecycledEditor?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_RecycledEditor?.SetValue(null, value.__self__); + } + + public static string s_OriginalText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__s_OriginalText?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_OriginalText?.SetValue(null, value); + } + + public static string s_RecycledCurrentEditingString + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__s_RecycledCurrentEditingString?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_RecycledCurrentEditingString?.SetValue(null, value); + } + + public static bool bKeyEventActive + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__bKeyEventActive?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __bKeyEventActive?.SetValue(null, value); + } + + public static bool s_DragToPosition + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__s_DragToPosition?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_DragToPosition?.SetValue(null, value); + } + + public static bool s_Dragged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__s_Dragged?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_Dragged?.SetValue(null, value); + } + + public static bool s_SelectAllOnMouseUp + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__s_SelectAllOnMouseUp?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_SelectAllOnMouseUp?.SetValue(null, value); + } + + public static double kFoldoutExpandTimeout + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (double)(__kFoldoutExpandTimeout?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kFoldoutExpandTimeout?.SetValue(null, value); + } + + public static double s_FoldoutDestTime + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (double)(__s_FoldoutDestTime?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_FoldoutDestTime?.SetValue(null, value); + } + + public static int s_DragUpdatedOverID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_DragUpdatedOverID?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_DragUpdatedOverID?.SetValue(null, value); + } + + public static int kSearchFieldTextLimit + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__kSearchFieldTextLimit?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kSearchFieldTextLimit?.SetValue(null, value); + } + + public static bool s_SearchFieldTextLimitApproved + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__s_SearchFieldTextLimitApproved?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_SearchFieldTextLimitApproved?.SetValue(null, value); + } + + public static int s_SavekeyboardControl + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_SavekeyboardControl?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_SavekeyboardControl?.SetValue(null, value); + } + + public static int s_FoldoutHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_FoldoutHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_FoldoutHash?.SetValue(null, value); + } + + public static int s_TagFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_TagFieldHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_TagFieldHash?.SetValue(null, value); + } + + public static int s_PPtrHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_PPtrHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_PPtrHash?.SetValue(null, value); + } + + public static int s_ObjectFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_ObjectFieldHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ObjectFieldHash?.SetValue(null, value); + } + + public static int s_ToggleHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_ToggleHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ToggleHash?.SetValue(null, value); + } + + public static int s_ColorHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_ColorHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ColorHash?.SetValue(null, value); + } + + public static int s_CurveHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_CurveHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_CurveHash?.SetValue(null, value); + } + + public static int s_LayerMaskField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_LayerMaskField?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LayerMaskField?.SetValue(null, value); + } + + public static int s_MaskField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_MaskField?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_MaskField?.SetValue(null, value); + } + + public static int s_EnumFlagsField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_EnumFlagsField?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_EnumFlagsField?.SetValue(null, value); + } + + public static int s_GenericField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_GenericField?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_GenericField?.SetValue(null, value); + } + + public static int s_PopupHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_PopupHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_PopupHash?.SetValue(null, value); + } + + public static int s_KeyEventFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_KeyEventFieldHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_KeyEventFieldHash?.SetValue(null, value); + } + + public static int s_TextFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_TextFieldHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_TextFieldHash?.SetValue(null, value); + } + + public static int s_SearchFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_SearchFieldHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_SearchFieldHash?.SetValue(null, value); + } + + public static int s_TextAreaHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_TextAreaHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_TextAreaHash?.SetValue(null, value); + } + + public static int s_PasswordFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_PasswordFieldHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_PasswordFieldHash?.SetValue(null, value); + } + + public static int s_FloatFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_FloatFieldHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_FloatFieldHash?.SetValue(null, value); + } + + public static int s_DelayedTextFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_DelayedTextFieldHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_DelayedTextFieldHash?.SetValue(null, value); + } + + public static int s_ArraySizeFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_ArraySizeFieldHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ArraySizeFieldHash?.SetValue(null, value); + } + + public static int s_SliderHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_SliderHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_SliderHash?.SetValue(null, value); + } + + public static int s_SliderKnobHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_SliderKnobHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_SliderKnobHash?.SetValue(null, value); + } + + public static int s_MinMaxSliderHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_MinMaxSliderHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_MinMaxSliderHash?.SetValue(null, value); + } + + public static int s_TitlebarHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_TitlebarHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_TitlebarHash?.SetValue(null, value); + } + + public static int s_ProgressBarHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_ProgressBarHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ProgressBarHash?.SetValue(null, value); + } + + public static int s_SelectableLabelHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_SelectableLabelHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_SelectableLabelHash?.SetValue(null, value); + } + + public static int s_SortingLayerFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_SortingLayerFieldHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_SortingLayerFieldHash?.SetValue(null, value); + } + + public static int s_TextFieldDropDownHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_TextFieldDropDownHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_TextFieldDropDownHash?.SetValue(null, value); + } + + public static object s_DragCandidateState + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__s_DragCandidateState?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_DragCandidateState?.SetValue(null, value); + } + + public static float kDragDeadzone + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kDragDeadzone?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kDragDeadzone?.SetValue(null, value); + } + + public static UnityEngine.Vector2 s_DragStartPos + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Vector2)(__s_DragStartPos?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_DragStartPos?.SetValue(null, value); + } + + public static double s_DragStartValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (double)(__s_DragStartValue?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_DragStartValue?.SetValue(null, value); + } + + public static long s_DragStartIntValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (long)(__s_DragStartIntValue?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_DragStartIntValue?.SetValue(null, value); + } + + public static double s_DragSensitivity + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (double)(__s_DragSensitivity?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_DragSensitivity?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_LargerChar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_LargerChar?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LargerChar?.SetValue(null, value); + } + + public static float kPrefixPaddingRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kPrefixPaddingRight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kPrefixPaddingRight?.SetValue(null, value); + } + + public static float kLabelW + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kLabelW?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kLabelW?.SetValue(null, value); + } + + public static float kSpacing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kSpacing?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kSpacing?.SetValue(null, value); + } + + public static float kSpacingSubLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kSpacingSubLabel?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kSpacingSubLabel?.SetValue(null, value); + } + + public static float kSliderMinW + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kSliderMinW?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kSliderMinW?.SetValue(null, value); + } + + public static float kSliderMaxW + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kSliderMaxW?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kSliderMaxW?.SetValue(null, value); + } + + public static float kSingleLineHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kSingleLineHeight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kSingleLineHeight?.SetValue(null, value); + } + + public static float kSingleSmallLineHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kSingleSmallLineHeight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kSingleSmallLineHeight?.SetValue(null, value); + } + + public static float kStructHeaderLineHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kStructHeaderLineHeight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kStructHeaderLineHeight?.SetValue(null, value); + } + + public static float kObjectFieldThumbnailHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kObjectFieldThumbnailHeight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kObjectFieldThumbnailHeight?.SetValue(null, value); + } + + public static float kObjectFieldMiniThumbnailHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kObjectFieldMiniThumbnailHeight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kObjectFieldMiniThumbnailHeight?.SetValue(null, value); + } + + public static float kObjectFieldMiniThumbnailWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kObjectFieldMiniThumbnailWidth?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kObjectFieldMiniThumbnailWidth?.SetValue(null, value); + } + + public static string kFloatFieldFormatString + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__kFloatFieldFormatString?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kFloatFieldFormatString?.SetValue(null, value); + } + + public static string kDoubleFieldFormatString + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__kDoubleFieldFormatString?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kDoubleFieldFormatString?.SetValue(null, value); + } + + public static string kIntFieldFormatString + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__kIntFieldFormatString?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kIntFieldFormatString?.SetValue(null, value); + } + + public static int ms_IndentLevel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__ms_IndentLevel?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __ms_IndentLevel?.SetValue(null, value); + } + + public static float kIndentPerLevel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kIndentPerLevel?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kIndentPerLevel?.SetValue(null, value); + } + + public static int kControlVerticalSpacingLegacy + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__kControlVerticalSpacingLegacy?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kControlVerticalSpacingLegacy?.SetValue(null, value); + } + + public static int kDefaultSpacing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__kDefaultSpacing?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kDefaultSpacing?.SetValue(null, value); + } + + public static object kControlVerticalSpacing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__kControlVerticalSpacing?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kControlVerticalSpacing?.SetValue(null, value); + } + + public static object kVerticalSpacingMultiField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__kVerticalSpacingMultiField?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kVerticalSpacingMultiField?.SetValue(null, value); + } + + public static string s_UnitString + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__s_UnitString?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_UnitString?.SetValue(null, value); + } + + public static int kInspTitlebarIconWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__kInspTitlebarIconWidth?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kInspTitlebarIconWidth?.SetValue(null, value); + } + + public static int kInspTitlebarFoldoutIconWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__kInspTitlebarFoldoutIconWidth?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kInspTitlebarFoldoutIconWidth?.SetValue(null, value); + } + + public static object kWindowToolbarHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__kWindowToolbarHeight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kWindowToolbarHeight?.SetValue(null, value); + } + + public static int kTabButtonHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__kTabButtonHeight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kTabButtonHeight?.SetValue(null, value); + } + + public static string kEnabledPropertyName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__kEnabledPropertyName?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kEnabledPropertyName?.SetValue(null, value); + } + + public static string k_MultiEditValueString + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__k_MultiEditValueString?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __k_MultiEditValueString?.SetValue(null, value); + } + + public static float kDropDownArrowMargin + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kDropDownArrowMargin?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kDropDownArrowMargin?.SetValue(null, value); + } + + public static float kDropDownArrowWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kDropDownArrowWidth?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kDropDownArrowWidth?.SetValue(null, value); + } + + public static float kDropDownArrowHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kDropDownArrowHeight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kDropDownArrowHeight?.SetValue(null, value); + } + + public static float[] s_Vector2Floats + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float[])(__s_Vector2Floats?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_Vector2Floats?.SetValue(null, value); + } + + public static int[] s_Vector2Ints + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int[])(__s_Vector2Ints?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_Vector2Ints?.SetValue(null, value); + } + + public static UnityEngine.GUIContent[] s_XYLabels + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent[])(__s_XYLabels?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_XYLabels?.SetValue(null, value); + } + + public static float[] s_Vector3Floats + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float[])(__s_Vector3Floats?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_Vector3Floats?.SetValue(null, value); + } + + public static int[] s_Vector3Ints + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int[])(__s_Vector3Ints?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_Vector3Ints?.SetValue(null, value); + } + + public static UnityEngine.GUIContent[] s_XYZLabels + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent[])(__s_XYZLabels?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_XYZLabels?.SetValue(null, value); + } + + public static float[] s_Vector4Floats + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float[])(__s_Vector4Floats?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_Vector4Floats?.SetValue(null, value); + } + + public static UnityEngine.GUIContent[] s_XYZWLabels + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent[])(__s_XYZWLabels?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_XYZWLabels?.SetValue(null, value); + } + + public static float kQuaternionFloatPrecision + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kQuaternionFloatPrecision?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kQuaternionFloatPrecision?.SetValue(null, value); + } + + public static UnityEngine.GUIContent[] s_WHLabels + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent[])(__s_WHLabels?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_WHLabels?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_CenterLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_CenterLabel?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_CenterLabel?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_ExtentLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_ExtentLabel?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ExtentLabel?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_PositionLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_PositionLabel?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_PositionLabel?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_SizeLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_SizeLabel?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_SizeLabel?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_PleasePressAKey + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_PleasePressAKey?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_PleasePressAKey?.SetValue(null, value); + } + + public static string s_PrefabInContextPreviewValuesTooltip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__s_PrefabInContextPreviewValuesTooltip?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_PrefabInContextPreviewValuesTooltip?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_ClipingPlanesLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_ClipingPlanesLabel?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ClipingPlanesLabel?.SetValue(null, value); + } + + public static UnityEngine.GUIContent[] s_NearAndFarLabels + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent[])(__s_NearAndFarLabels?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_NearAndFarLabels?.SetValue(null, value); + } + + public static float kNearFarLabelsWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kNearFarLabelsWidth?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kNearFarLabelsWidth?.SetValue(null, value); + } + + public static int s_ColorPickID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_ColorPickID?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ColorPickID?.SetValue(null, value); + } + + public static int s_CurveID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_CurveID?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_CurveID?.SetValue(null, value); + } + + public static UnityEngine.Color kCurveColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Color)(__kCurveColor?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kCurveColor?.SetValue(null, value); + } + + public static UnityEngine.Color kCurveBGColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Color)(__kCurveBGColor?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kCurveBGColor?.SetValue(null, value); + } + + public static object kSplitLineSkinnedColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__kSplitLineSkinnedColor?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kSplitLineSkinnedColor?.SetValue(null, value); + } + + public static UnityEngine.Color k_OverrideMarginColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Color)(__k_OverrideMarginColor?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __k_OverrideMarginColor?.SetValue(null, value); + } + + public static UnityEngine.Color k_OverrideMarginColorSelected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Color)(__k_OverrideMarginColorSelected?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __k_OverrideMarginColorSelected?.SetValue(null, value); + } + + public static int kInspTitlebarSpacing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__kInspTitlebarSpacing?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kInspTitlebarSpacing?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_PropertyFieldTempContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_PropertyFieldTempContent?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_PropertyFieldTempContent?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_IconDropDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_IconDropDown?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_IconDropDown?.SetValue(null, value); + } + + public static UnityEngine.Material s_IconTextureInactive + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Material)(__s_IconTextureInactive?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_IconTextureInactive?.SetValue(null, value); + } + + public static bool s_HasPrefixLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__s_HasPrefixLabel?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_HasPrefixLabel?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_PrefixLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_PrefixLabel?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_PrefixLabel?.SetValue(null, value); + } + + public static UnityEngine.Rect s_PrefixTotalRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Rect)(__s_PrefixTotalRect?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_PrefixTotalRect?.SetValue(null, value); + } + + public static UnityEngine.Rect s_PrefixRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Rect)(__s_PrefixRect?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_PrefixRect?.SetValue(null, value); + } + + public static UnityEngine.GUIStyle s_PrefixStyle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__s_PrefixStyle?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_PrefixStyle?.SetValue(null, value); + } + + public static UnityEngine.GUIStyle s_IconButtonStyle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__s_IconButtonStyle?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_IconButtonStyle?.SetValue(null, value); + } + + public static UnityEngine.Color s_PrefixGUIColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Color)(__s_PrefixGUIColor?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_PrefixGUIColor?.SetValue(null, value); + } + + public static string s_LabelHighlightContext + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__s_LabelHighlightContext?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LabelHighlightContext?.SetValue(null, value); + } + + public static UnityEngine.Color s_LabelHighlightColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Color)(__s_LabelHighlightColor?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LabelHighlightColor?.SetValue(null, value); + } + + public static UnityEngine.Color s_LabelHighlightSelectionColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Color)(__s_LabelHighlightSelectionColor?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LabelHighlightSelectionColor?.SetValue(null, value); + } + + public static string[] m_FlagNames + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string[])(__m_FlagNames?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_FlagNames?.SetValue(null, value); + } + + public static int[] m_FlagValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int[])(__m_FlagValues?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_FlagValues?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_MixedValueContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_MixedValueContent?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_MixedValueContent?.SetValue(null, value); + } + + public static UnityEngine.Color s_MixedValueContentColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Color)(__s_MixedValueContentColor?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_MixedValueContentColor?.SetValue(null, value); + } + + public static UnityEngine.Color s_MixedValueContentColorTemp + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Color)(__s_MixedValueContentColorTemp?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_MixedValueContentColorTemp?.SetValue(null, value); + } + + public static object s_ShowRepaintDots + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__s_ShowRepaintDots?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ShowRepaintDots?.SetValue(null, value); + } + + public static object s_PropertyStack + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__s_PropertyStack?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_PropertyStack?.SetValue(null, value); + } + + public static System.Collections.Generic.Stack s_EnabledStack + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Generic.Stack)(__s_EnabledStack?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_EnabledStack?.SetValue(null, value); + } + + public static System.Collections.Generic.Stack> s_IsInsideListStack + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Generic.Stack>)(__s_IsInsideListStack?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_IsInsideListStack?.SetValue(null, value); + } + + public static System.Collections.Generic.Stack s_ChangedStack + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Generic.Stack)(__s_ChangedStack?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ChangedStack?.SetValue(null, value); + } + + public static System.Action hyperLinkClicked + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Action)(__hyperLinkClicked?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __hyperLinkClicked?.SetValue(null, value); + } + + public static string s_AllowedCharactersForFloat + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__s_AllowedCharactersForFloat?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_AllowedCharactersForFloat?.SetValue(null, value); + } + + public static string s_AllowedCharactersForInt + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__s_AllowedCharactersForInt?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_AllowedCharactersForInt?.SetValue(null, value); + } + + public static System.Func s_CurrentCheckEnumEnabled + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Func)(__s_CurrentCheckEnumEnabled?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_CurrentCheckEnumEnabled?.SetValue(null, value); + } + + public static object s_CurrentEnumData + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__s_CurrentEnumData?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_CurrentEnumData?.SetValue(null, value); + } + + public static float kEyedropperSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kEyedropperSize?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kEyedropperSize?.SetValue(null, value); + } + + public static UnityEditor.SerializedProperty s_PendingPropertyKeyboardHandling + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__s_PendingPropertyKeyboardHandling?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_PendingPropertyKeyboardHandling?.SetValue(null, value); + } + + public static UnityEditor.SerializedProperty s_PendingPropertyDelete + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__s_PendingPropertyDelete?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_PendingPropertyDelete?.SetValue(null, value); + } + + public static string[] s_LayerNames + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string[])(__s_LayerNames?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LayerNames?.SetValue(null, value); + } + + public static int[] s_LayerValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int[])(__s_LayerValues?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LayerValues?.SetValue(null, value); + } + + public static string s_ArrayMultiInfoFormatString + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__s_ArrayMultiInfoFormatString?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ArrayMultiInfoFormatString?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_ArrayMultiInfoContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_ArrayMultiInfoContent?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ArrayMultiInfoContent?.SetValue(null, value); + } + + public static Unity.Profiling.ProfilerMarker s_EvalExpressionMarker + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (Unity.Profiling.ProfilerMarker)(__s_EvalExpressionMarker?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_EvalExpressionMarker?.SetValue(null, value); + } + + public static bool s_CollectingToolTips + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__s_CollectingToolTips?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_CollectingToolTips?.SetValue(null, value); + } + + public static bool s_FoldoutHeaderGroupActive + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__s_FoldoutHeaderGroupActive?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_FoldoutHeaderGroupActive?.SetValue(null, value); + } + + public static int s_FoldoutHeaderHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_FoldoutHeaderHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_FoldoutHeaderHash?.SetValue(null, value); + } + + public static int s_GradientHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_GradientHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_GradientHash?.SetValue(null, value); + } + + public static int s_GradientID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_GradientID?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_GradientID?.SetValue(null, value); + } + + public static int s_DropdownButtonHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_DropdownButtonHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_DropdownButtonHash?.SetValue(null, value); + } + + public static int s_MouseDeltaReaderHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_MouseDeltaReaderHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_MouseDeltaReaderHash?.SetValue(null, value); + } + + public static UnityEngine.Vector2 s_MouseDeltaReaderLastPos + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Vector2)(__s_MouseDeltaReaderLastPos?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_MouseDeltaReaderLastPos?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_SceneMismatch + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_SceneMismatch?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_SceneMismatch?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_TypeMismatch + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_TypeMismatch?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_TypeMismatch?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_Select + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_Select?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_Select?.SetValue(null, value); + } + + public static string kEmptyDropDownElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__kEmptyDropDownElement?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kEmptyDropDownElement?.SetValue(null, value); + } + + public static void BeginHandleMixedValueContentColor() + { + __BeginHandleMixedValueContentColor?.Invoke(null, System.Array.Empty()); + } + + public static void EndHandleMixedValueContentColor() + { + __EndHandleMixedValueContentColor?.Invoke(null, System.Array.Empty()); + } + + public static bool IsEditingTextField() + { + var __result__ = __IsEditingTextField?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void EndEditingActiveTextField() + { + __EndEditingActiveTextField?.Invoke(null, System.Array.Empty()); + } + + public static void ClearStacks() + { + __ClearStacks?.Invoke(null, System.Array.Empty()); + } + + public static void BeginDisabled(bool disabled) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = disabled; + __BeginDisabled?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void EndDisabled() + { + __EndDisabled?.Invoke(null, System.Array.Empty()); + } + + public static void BeginIsInsideList(int depth) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = depth; + __BeginIsInsideList?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static int GetInsideListDepth() + { + var __result__ = __GetInsideListDepth?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public static void EndIsInsideList() + { + __EndIsInsideList?.Invoke(null, System.Array.Empty()); + } + + public static void ShowTextEditorPopupMenu() + { + __ShowTextEditorPopupMenu?.Invoke(null, System.Array.Empty()); + } + + public static void BeginCollectTooltips() + { + __BeginCollectTooltips?.Invoke(null, System.Array.Empty()); + } + + public static void EndCollectTooltips() + { + __EndCollectTooltips?.Invoke(null, System.Array.Empty()); + } + + public static void DoDropShadowLabel(UnityEngine.Rect position, UnityEngine.GUIContent content, UnityEngine.GUIStyle style, float shadowOpa) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = content; + __params__[2] = style; + __params__[3] = shadowOpa; + __DoDropShadowLabel?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void DrawLabelShadow(UnityEngine.Rect position, UnityEngine.GUIContent content, UnityEngine.GUIStyle style, float shadowOpa) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = content; + __params__[2] = style; + __params__[3] = shadowOpa; + __DrawLabelShadow?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void Draw4(UnityEngine.Rect position, UnityEngine.GUIContent content, float offset, float alpha, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = content; + __params__[2] = offset; + __params__[3] = alpha; + __params__[4] = style; + __Draw4?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static string ValidateTextLimit(string editorText) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = editorText; + var __result__ = __ValidateTextLimit?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static bool IsPrintableChar(char c) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = c; + var __result__ = __IsPrintableChar?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool MightBePrintableKey(UnityEngine.Event evt) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = evt; + var __result__ = __MightBePrintableKey?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static UnityEngine.EventType GetEventTypeForControlAllowDisabledContextMenuPaste(UnityEngine.Event evt, int id) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = evt; + __params__[1] = id; + var __result__ = __GetEventTypeForControlAllowDisabledContextMenuPaste?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.EventType)(__result__) : default; + } + + public static string DoTextField(UnityEditor_EditorGUI_RecycledTextEditor editor, int id, UnityEngine.Rect position, string text, UnityEngine.GUIStyle style, string allowedletters, out bool changed, bool reset, bool multiline, bool passwordField) + { + var __pool__ = FixedArrayPool.Shared(10); + var __params__ = __pool__.Rent(); + __params__[0] = editor.__self__; + __params__[1] = id; + __params__[2] = position; + __params__[3] = text; + __params__[4] = style; + __params__[5] = allowedletters; + __params__[6] = null; + __params__[7] = reset; + __params__[8] = multiline; + __params__[9] = passwordField; + var __result__ = __DoTextField?.Invoke(null, __params__); + changed = (bool)(__params__[6]); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string DoTextField(UnityEditor_EditorGUI_RecycledTextEditor editor, int id, UnityEngine.Rect position, string text, UnityEngine.GUIStyle style, string allowedletters, out bool changed, bool reset, bool multiline, bool passwordField, UnityEngine.GUIStyle cancelButtonStyle, bool checkTextLimit) + { + var __pool__ = FixedArrayPool.Shared(12); + var __params__ = __pool__.Rent(); + __params__[0] = editor.__self__; + __params__[1] = id; + __params__[2] = position; + __params__[3] = text; + __params__[4] = style; + __params__[5] = allowedletters; + __params__[6] = null; + __params__[7] = reset; + __params__[8] = multiline; + __params__[9] = passwordField; + __params__[10] = cancelButtonStyle; + __params__[11] = checkTextLimit; + var __result__ = __DoTextField__2?.Invoke(null, __params__); + changed = (bool)(__params__[6]); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static bool HasClickedOnHyperlink(string text, int cursorIndex, UnityEditor_EditorGUI_RecycledTextEditor editor, out System.Collections.Generic.Dictionary hyperLinkData) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = text; + __params__[1] = cursorIndex; + __params__[2] = editor.__self__; + __params__[3] = null; + var __result__ = __HasClickedOnHyperlink?.Invoke(null, __params__); + hyperLinkData = (System.Collections.Generic.Dictionary)(__params__[3]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void EditorGUI_OpenFileOnHyperLinkClicked(UnityEditor.EditorWindow window, UnityEditor.HyperLinkClickedEventArgs args) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = window; + __params__[1] = args; + __EditorGUI_OpenFileOnHyperLinkClicked?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Event KeyEventField(UnityEngine.Rect position, UnityEngine.Event evt) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = evt; + var __result__ = __KeyEventField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Event)(__result__) : default; + } + + public static UnityEngine.Event DoKeyEventField(UnityEngine.Rect position, UnityEngine.Event _event, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = _event; + __params__[2] = style; + var __result__ = __DoKeyEventField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Event)(__result__) : default; + } + + public static UnityEngine.Rect GetInspectorTitleBarObjectFoldoutRenderRect(UnityEngine.Rect rect) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + var __result__ = __GetInspectorTitleBarObjectFoldoutRenderRect?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static UnityEngine.Rect GetInspectorTitleBarObjectFoldoutRenderRect(UnityEngine.Rect rect, UnityEngine.GUIStyle baseStyle) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = baseStyle; + var __result__ = __GetInspectorTitleBarObjectFoldoutRenderRect__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static bool IsValidForContextMenu(UnityEngine.Object target) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = target; + var __result__ = __IsValidForContextMenu?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool DoObjectMouseInteraction(bool foldout, UnityEngine.Rect interactionRect, UnityEngine.Object[] targetObjs, int id) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = foldout; + __params__[1] = interactionRect; + __params__[2] = targetObjs; + __params__[3] = id; + var __result__ = __DoObjectMouseInteraction?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void DoObjectFoldoutInternal(bool foldout, UnityEngine.Rect renderRect, int id) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = foldout; + __params__[1] = renderRect; + __params__[2] = id; + __DoObjectFoldoutInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static bool DoObjectFoldout(bool foldout, UnityEngine.Rect interactionRect, UnityEngine.Rect renderRect, UnityEngine.Object[] targetObjs, int id) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = foldout; + __params__[1] = interactionRect; + __params__[2] = renderRect; + __params__[3] = targetObjs; + __params__[4] = id; + var __result__ = __DoObjectFoldout?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void LabelFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, UnityEngine.GUIContent label2, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = label2; + __params__[3] = style; + __LabelFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static bool ToggleLeftInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, bool value, UnityEngine.GUIStyle labelStyle) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __params__[3] = labelStyle; + var __result__ = __ToggleLeftInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool DoToggle(UnityEngine.Rect position, int id, bool value, UnityEngine.GUIContent content, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = id; + __params__[2] = value; + __params__[3] = content; + __params__[4] = style; + var __result__ = __DoToggle?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static string TextFieldInternal(int id, UnityEngine.Rect position, string text, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = id; + __params__[1] = position; + __params__[2] = text; + __params__[3] = style; + var __result__ = __TextFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string TextFieldInternal(int id, UnityEngine.Rect position, string text, UnityEngine.GUIStyle style, UnityEngine.GUIStyle cancelButtonStyle) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = id; + __params__[1] = position; + __params__[2] = text; + __params__[3] = style; + __params__[4] = cancelButtonStyle; + var __result__ = __TextFieldInternal__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string TextFieldInternal(UnityEngine.Rect position, string text, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = text; + __params__[2] = style; + var __result__ = __TextFieldInternal__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string TextFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, string text, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = text; + __params__[3] = style; + var __result__ = __TextFieldInternal__4?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string TextFieldInternal(int id, UnityEngine.Rect position, UnityEngine.GUIContent label, string text, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = id; + __params__[1] = position; + __params__[2] = label; + __params__[3] = text; + __params__[4] = style; + var __result__ = __TextFieldInternal__5?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string ToolbarSearchField(UnityEngine.Rect position, string text, bool showWithPopupArrow) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = text; + __params__[2] = showWithPopupArrow; + var __result__ = __ToolbarSearchField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string ToolbarSearchField(int id, UnityEngine.Rect position, string text, bool showWithPopupArrow) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = id; + __params__[1] = position; + __params__[2] = text; + __params__[3] = showWithPopupArrow; + var __result__ = __ToolbarSearchField__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string ToolbarSearchField(int id, UnityEngine.Rect position, string text, UnityEngine.GUIStyle searchFieldStyle, UnityEngine.GUIStyle cancelButtonStyle) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = id; + __params__[1] = position; + __params__[2] = text; + __params__[3] = searchFieldStyle; + __params__[4] = cancelButtonStyle; + var __result__ = __ToolbarSearchField__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string ToolbarSearchField(UnityEngine.Rect position, string[] searchModes, ref int searchMode, string text) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = searchModes; + __params__[2] = searchMode; + __params__[3] = text; + var __result__ = __ToolbarSearchField__4?.Invoke(null, __params__); + searchMode = (int)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string ToolbarSearchField(int id, UnityEngine.Rect position, string[] searchModes, ref int searchMode, string text) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = id; + __params__[1] = position; + __params__[2] = searchModes; + __params__[3] = searchMode; + __params__[4] = text; + var __result__ = __ToolbarSearchField__5?.Invoke(null, __params__); + searchMode = (int)(__params__[3]); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string ToolbarSearchField(int id, UnityEngine.Rect position, string[] searchModes, ref int searchMode, string text, UnityEngine.GUIStyle searchFieldWithPopupStyle, UnityEngine.GUIStyle searchFieldNoPopupStyle, UnityEngine.GUIStyle cancelButtonStyle) + { + var __pool__ = FixedArrayPool.Shared(8); + var __params__ = __pool__.Rent(); + __params__[0] = id; + __params__[1] = position; + __params__[2] = searchModes; + __params__[3] = searchMode; + __params__[4] = text; + __params__[5] = searchFieldWithPopupStyle; + __params__[6] = searchFieldNoPopupStyle; + __params__[7] = cancelButtonStyle; + var __result__ = __ToolbarSearchField__6?.Invoke(null, __params__); + searchMode = (int)(__params__[3]); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string SearchField(UnityEngine.Rect position, string text) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = text; + var __result__ = __SearchField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string ScrollableTextAreaInternal(UnityEngine.Rect position, string text, ref UnityEngine.Vector2 scrollPosition, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = text; + __params__[2] = scrollPosition; + __params__[3] = style; + var __result__ = __ScrollableTextAreaInternal?.Invoke(null, __params__); + scrollPosition = (UnityEngine.Vector2)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string TextAreaInternal(UnityEngine.Rect position, string text, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = text; + __params__[2] = style; + var __result__ = __TextAreaInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static void SelectableLabelInternal(UnityEngine.Rect position, string text, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = text; + __params__[2] = style; + __SelectableLabelInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static string PasswordFieldInternal(UnityEngine.Rect position, string password, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = password; + __params__[2] = style; + var __result__ = __PasswordFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string PasswordFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, string password, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = password; + __params__[3] = style; + var __result__ = __PasswordFieldInternal__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static float FloatFieldInternal(UnityEngine.Rect position, float value, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = value; + __params__[2] = style; + var __result__ = __FloatFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float FloatFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, float value, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __params__[3] = style; + var __result__ = __FloatFieldInternal__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static void FloatFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, ref object value, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __params__[3] = style; + __FloatFieldInternal__3?.Invoke(null, __params__); + value = (object)(__params__[2]); + __pool__.Return(__params__); + } + + public static double DoubleFieldInternal(UnityEngine.Rect position, double value, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = value; + __params__[2] = style; + var __result__ = __DoubleFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (double)(__result__) : default; + } + + public static double DoubleFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, double value, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __params__[3] = style; + var __result__ = __DoubleFieldInternal__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (double)(__result__) : default; + } + + public static void DoubleFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, ref object value, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __params__[3] = style; + __DoubleFieldInternal__3?.Invoke(null, __params__); + value = (object)(__params__[2]); + __pool__.Return(__params__); + } + + public static void DragNumberValue(UnityEngine.Rect dragHotZone, int id, bool isDouble, ref double doubleVal, ref long longVal, double dragSensitivity) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = dragHotZone; + __params__[1] = id; + __params__[2] = isDouble; + __params__[3] = doubleVal; + __params__[4] = longVal; + __params__[5] = dragSensitivity; + __DragNumberValue?.Invoke(null, __params__); + doubleVal = (double)(__params__[3]); + longVal = (long)(__params__[4]); + __pool__.Return(__params__); + } + + public static void DragNumberValue(UnityEngine.Rect dragHotZone, int id, ref object value, double dragSensitivity) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = dragHotZone; + __params__[1] = id; + __params__[2] = value; + __params__[3] = dragSensitivity; + __DragNumberValue__2?.Invoke(null, __params__); + value = (object)(__params__[2]); + __pool__.Return(__params__); + } + + public static float DoFloatField(UnityEditor_EditorGUI_RecycledTextEditor editor, UnityEngine.Rect position, UnityEngine.Rect dragHotZone, int id, float value, string formatString, UnityEngine.GUIStyle style, bool draggable) + { + var __pool__ = FixedArrayPool.Shared(8); + var __params__ = __pool__.Rent(); + __params__[0] = editor.__self__; + __params__[1] = position; + __params__[2] = dragHotZone; + __params__[3] = id; + __params__[4] = value; + __params__[5] = formatString; + __params__[6] = style; + __params__[7] = draggable; + var __result__ = __DoFloatField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float DoFloatField(UnityEditor_EditorGUI_RecycledTextEditor editor, UnityEngine.Rect position, UnityEngine.Rect dragHotZone, int id, float value, string formatString, UnityEngine.GUIStyle style, bool draggable, float dragSensitivity) + { + var __pool__ = FixedArrayPool.Shared(9); + var __params__ = __pool__.Rent(); + __params__[0] = editor.__self__; + __params__[1] = position; + __params__[2] = dragHotZone; + __params__[3] = id; + __params__[4] = value; + __params__[5] = formatString; + __params__[6] = style; + __params__[7] = draggable; + __params__[8] = dragSensitivity; + var __result__ = __DoFloatField__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static int DoIntField(UnityEditor_EditorGUI_RecycledTextEditor editor, UnityEngine.Rect position, UnityEngine.Rect dragHotZone, int id, int value, string formatString, UnityEngine.GUIStyle style, bool draggable, float dragSensitivity) + { + var __pool__ = FixedArrayPool.Shared(9); + var __params__ = __pool__.Rent(); + __params__[0] = editor.__self__; + __params__[1] = position; + __params__[2] = dragHotZone; + __params__[3] = id; + __params__[4] = value; + __params__[5] = formatString; + __params__[6] = style; + __params__[7] = draggable; + __params__[8] = dragSensitivity; + var __result__ = __DoIntField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static double DoDoubleField(UnityEditor_EditorGUI_RecycledTextEditor editor, UnityEngine.Rect position, UnityEngine.Rect dragHotZone, int id, double value, string formatString, UnityEngine.GUIStyle style, bool draggable) + { + var __pool__ = FixedArrayPool.Shared(8); + var __params__ = __pool__.Rent(); + __params__[0] = editor.__self__; + __params__[1] = position; + __params__[2] = dragHotZone; + __params__[3] = id; + __params__[4] = value; + __params__[5] = formatString; + __params__[6] = style; + __params__[7] = draggable; + var __result__ = __DoDoubleField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (double)(__result__) : default; + } + + public static double DoDoubleField(UnityEditor_EditorGUI_RecycledTextEditor editor, UnityEngine.Rect position, UnityEngine.Rect dragHotZone, int id, double value, string formatString, UnityEngine.GUIStyle style, bool draggable, double dragSensitivity) + { + var __pool__ = FixedArrayPool.Shared(9); + var __params__ = __pool__.Rent(); + __params__[0] = editor.__self__; + __params__[1] = position; + __params__[2] = dragHotZone; + __params__[3] = id; + __params__[4] = value; + __params__[5] = formatString; + __params__[6] = style; + __params__[7] = draggable; + __params__[8] = dragSensitivity; + var __result__ = __DoDoubleField__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (double)(__result__) : default; + } + + public static long DoLongField(UnityEditor_EditorGUI_RecycledTextEditor editor, UnityEngine.Rect position, UnityEngine.Rect dragHotZone, int id, long value, string formatString, UnityEngine.GUIStyle style, bool draggable, double dragSensitivity) + { + var __pool__ = FixedArrayPool.Shared(9); + var __params__ = __pool__.Rent(); + __params__[0] = editor.__self__; + __params__[1] = position; + __params__[2] = dragHotZone; + __params__[3] = id; + __params__[4] = value; + __params__[5] = formatString; + __params__[6] = style; + __params__[7] = draggable; + __params__[8] = dragSensitivity; + var __result__ = __DoLongField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (long)(__result__) : default; + } + + public static bool HasKeyboardFocus(int controlID) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = controlID; + var __result__ = __HasKeyboardFocus?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void DoNumberField(UnityEditor_EditorGUI_RecycledTextEditor editor, UnityEngine.Rect position, UnityEngine.Rect dragHotZone, int id, bool isDouble, ref double doubleVal, ref long longVal, string formatString, UnityEngine.GUIStyle style, bool draggable, double dragSensitivity) + { + var __pool__ = FixedArrayPool.Shared(11); + var __params__ = __pool__.Rent(); + __params__[0] = editor.__self__; + __params__[1] = position; + __params__[2] = dragHotZone; + __params__[3] = id; + __params__[4] = isDouble; + __params__[5] = doubleVal; + __params__[6] = longVal; + __params__[7] = formatString; + __params__[8] = style; + __params__[9] = draggable; + __params__[10] = dragSensitivity; + __DoNumberField?.Invoke(null, __params__); + doubleVal = (double)(__params__[5]); + longVal = (long)(__params__[6]); + __pool__.Return(__params__); + } + + public static void DoNumberField(UnityEditor_EditorGUI_RecycledTextEditor editor, UnityEngine.Rect position, UnityEngine.Rect dragHotZone, int id, ref object value, string formatString, UnityEngine.GUIStyle style, bool draggable, double dragSensitivity) + { + var __pool__ = FixedArrayPool.Shared(9); + var __params__ = __pool__.Rent(); + __params__[0] = editor.__self__; + __params__[1] = position; + __params__[2] = dragHotZone; + __params__[3] = id; + __params__[4] = value; + __params__[5] = formatString; + __params__[6] = style; + __params__[7] = draggable; + __params__[8] = dragSensitivity; + __DoNumberField__2?.Invoke(null, __params__); + value = (object)(__params__[4]); + __pool__.Return(__params__); + } + + public static bool StringToDouble(string str, out double value) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = str; + __params__[1] = null; + var __result__ = __StringToDouble?.Invoke(null, __params__); + value = (double)(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool StringToDouble(string str, out double value, out object expression) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = str; + __params__[1] = null; + __params__[2] = null; + var __result__ = __StringToDouble__2?.Invoke(null, __params__); + value = (double)(__params__[1]); + expression = (object)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void StringToDouble(string str, ref object value) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = str; + __params__[1] = value; + __StringToDouble__3?.Invoke(null, __params__); + value = (object)(__params__[1]); + __pool__.Return(__params__); + } + + public static bool StringToDouble(string str, string initialValueAsString, out double value) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = str; + __params__[1] = initialValueAsString; + __params__[2] = null; + var __result__ = __StringToDouble__4?.Invoke(null, __params__); + value = (double)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool StringToFloat(string str, string initialValueAsString, out float value) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = str; + __params__[1] = initialValueAsString; + __params__[2] = null; + var __result__ = __StringToFloat?.Invoke(null, __params__); + value = (float)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool StringToLong(string str, out long value) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = str; + __params__[1] = null; + var __result__ = __StringToLong?.Invoke(null, __params__); + value = (long)(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool StringToLong(string str, out long value, out object expression) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = str; + __params__[1] = null; + __params__[2] = null; + var __result__ = __StringToLong__2?.Invoke(null, __params__); + value = (long)(__params__[1]); + expression = (object)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void StringToLong(string str, ref object value) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = str; + __params__[1] = value; + __StringToLong__3?.Invoke(null, __params__); + value = (object)(__params__[1]); + __pool__.Return(__params__); + } + + public static bool StringToLong(string str, string initialValueAsString, out long value) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = str; + __params__[1] = initialValueAsString; + __params__[2] = null; + var __result__ = __StringToLong__4?.Invoke(null, __params__); + value = (long)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool StringToInt(string str, string initialValueAsString, out int value) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = str; + __params__[1] = initialValueAsString; + __params__[2] = null; + var __result__ = __StringToInt?.Invoke(null, __params__); + value = (int)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static int ArraySizeField(UnityEngine.Rect position, UnityEngine.GUIContent label, int value, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __params__[3] = style; + var __result__ = __ArraySizeField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static string DelayedTextFieldInternal(UnityEngine.Rect position, string value, string allowedLetters, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = value; + __params__[2] = allowedLetters; + __params__[3] = style; + var __result__ = __DelayedTextFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string DelayedTextFieldInternal(UnityEngine.Rect position, int id, UnityEngine.GUIContent label, string value, string allowedLetters, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = id; + __params__[2] = label; + __params__[3] = value; + __params__[4] = allowedLetters; + __params__[5] = style; + var __result__ = __DelayedTextFieldInternal__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static void DelayedTextFieldInternal(UnityEngine.Rect position, int id, UnityEditor.SerializedProperty property, string allowedLetters, UnityEngine.GUIContent label, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = id; + __params__[2] = property; + __params__[3] = allowedLetters; + __params__[4] = label; + __params__[5] = style; + __DelayedTextFieldInternal__3?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void DelayedNumberFieldInternal(UnityEngine.Rect position, UnityEngine.Rect dragHotZone, int id, bool isDouble, ref double doubleVal, ref long longVal, string formatString, UnityEngine.GUIStyle style, bool draggable, double dragSensitivity) + { + var __pool__ = FixedArrayPool.Shared(10); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = dragHotZone; + __params__[2] = id; + __params__[3] = isDouble; + __params__[4] = doubleVal; + __params__[5] = longVal; + __params__[6] = formatString; + __params__[7] = style; + __params__[8] = draggable; + __params__[9] = dragSensitivity; + __DelayedNumberFieldInternal?.Invoke(null, __params__); + doubleVal = (double)(__params__[4]); + longVal = (long)(__params__[5]); + __pool__.Return(__params__); + } + + public static void DelayedNumberFieldInternal(UnityEngine.Rect position, UnityEngine.Rect dragHotZone, int id, ref object value, string formatString, UnityEngine.GUIStyle style, bool draggable, double dragSensitivity) + { + var __pool__ = FixedArrayPool.Shared(8); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = dragHotZone; + __params__[2] = id; + __params__[3] = value; + __params__[4] = formatString; + __params__[5] = style; + __params__[6] = draggable; + __params__[7] = dragSensitivity; + __DelayedNumberFieldInternal__2?.Invoke(null, __params__); + value = (object)(__params__[3]); + __pool__.Return(__params__); + } + + public static float DelayedFloatFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, float value, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __params__[3] = style; + var __result__ = __DelayedFloatFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static void DelayedFloatFieldInternal(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __DelayedFloatFieldInternal__2?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static double DelayedDoubleFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, double value, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __params__[3] = style; + var __result__ = __DelayedDoubleFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (double)(__result__) : default; + } + + public static int DelayedIntFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, int value, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __params__[3] = style; + var __result__ = __DelayedIntFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static void DelayedIntFieldInternal(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __DelayedIntFieldInternal__2?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static bool SetDelayedDraggable(ref UnityEngine.Rect position, ref UnityEngine.Rect dragHotzone, UnityEngine.GUIContent label, int id) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = dragHotzone; + __params__[2] = label; + __params__[3] = id; + var __result__ = __SetDelayedDraggable?.Invoke(null, __params__); + position = (UnityEngine.Rect)(__params__[0]); + dragHotzone = (UnityEngine.Rect)(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static int IntFieldInternal(UnityEngine.Rect position, int value, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = value; + __params__[2] = style; + var __result__ = __IntFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int IntFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, int value, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __params__[3] = style; + var __result__ = __IntFieldInternal__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static long LongFieldInternal(UnityEngine.Rect position, long value, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = value; + __params__[2] = style; + var __result__ = __LongFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (long)(__result__) : default; + } + + public static long LongFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, long value, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __params__[3] = style; + var __result__ = __LongFieldInternal__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (long)(__result__) : default; + } + + public static void LongFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, ref object value, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __params__[3] = style; + __LongFieldInternal__3?.Invoke(null, __params__); + value = (object)(__params__[2]); + __pool__.Return(__params__); + } + + public static float Slider(UnityEngine.Rect position, UnityEngine.GUIContent label, float value, float leftValue, float rightValue, UnityEngine.GUIStyle textfieldStyle) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __params__[3] = leftValue; + __params__[4] = rightValue; + __params__[5] = textfieldStyle; + var __result__ = __Slider?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float Slider(UnityEngine.Rect position, UnityEngine.GUIContent label, float value, float sliderMin, float sliderMax, float textFieldMin, float textFieldMax) + { + var __pool__ = FixedArrayPool.Shared(7); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __params__[3] = sliderMin; + __params__[4] = sliderMax; + __params__[5] = textFieldMin; + __params__[6] = textFieldMax; + var __result__ = __Slider__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float Slider(UnityEngine.Rect position, UnityEngine.GUIContent label, float value, float sliderMin, float sliderMax, float textFieldMin, float textFieldMax, UnityEngine.GUIStyle textfieldStyle, UnityEngine.GUIStyle sliderStyle, UnityEngine.GUIStyle thumbStyle, UnityEngine.Texture2D sliderBackground, UnityEngine.GUIStyle thumbStyleExtent) + { + var __pool__ = FixedArrayPool.Shared(12); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __params__[3] = sliderMin; + __params__[4] = sliderMax; + __params__[5] = textFieldMin; + __params__[6] = textFieldMax; + __params__[7] = textfieldStyle; + __params__[8] = sliderStyle; + __params__[9] = thumbStyle; + __params__[10] = sliderBackground; + __params__[11] = thumbStyleExtent; + var __result__ = __Slider__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float PowerSlider(UnityEngine.Rect position, string label, float sliderValue, float leftValue, float rightValue, float power) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = sliderValue; + __params__[3] = leftValue; + __params__[4] = rightValue; + __params__[5] = power; + var __result__ = __PowerSlider?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float PowerSlider(UnityEngine.Rect position, UnityEngine.GUIContent label, float sliderValue, float leftValue, float rightValue, float power) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = sliderValue; + __params__[3] = leftValue; + __params__[4] = rightValue; + __params__[5] = power; + var __result__ = __PowerSlider__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float PowerSlider(UnityEngine.Rect position, UnityEngine.GUIContent label, float sliderValue, float leftValue, float rightValue, UnityEngine.GUIStyle textfieldStyle, float power) + { + var __pool__ = FixedArrayPool.Shared(7); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = sliderValue; + __params__[3] = leftValue; + __params__[4] = rightValue; + __params__[5] = textfieldStyle; + __params__[6] = power; + var __result__ = __PowerSlider__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float PowPreserveSign(float f, float p) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = f; + __params__[1] = p; + var __result__ = __PowPreserveSign?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static UnityEditor.GenericMenu FillPropertyContextMenu(UnityEditor.SerializedProperty property, UnityEditor.SerializedProperty linkedProperty, UnityEditor.GenericMenu menu) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = property; + __params__[1] = linkedProperty; + __params__[2] = menu; + var __result__ = __FillPropertyContextMenu?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEditor.GenericMenu)(__result__) : default; + } + + public static void DoPropertyContextMenu(UnityEditor.SerializedProperty property, UnityEditor.SerializedProperty linkedProperty, UnityEditor.GenericMenu menu) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = property; + __params__[1] = linkedProperty; + __params__[2] = menu; + __DoPropertyContextMenu?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void Slider(UnityEngine.Rect position, UnityEditor.SerializedProperty property, float sliderLeftValue, float sliderRightValue, float textLeftValue, float textRightValue, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(7); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = sliderLeftValue; + __params__[3] = sliderRightValue; + __params__[4] = textLeftValue; + __params__[5] = textRightValue; + __params__[6] = label; + __Slider__4?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static int IntSlider(UnityEngine.Rect position, int value, int leftValue, int rightValue, float power, UnityEngine.GUIStyle textfieldStyle, UnityEngine.GUIStyle sliderStyle, UnityEngine.GUIStyle thumbStyle, UnityEngine.Texture2D sliderBackground, UnityEngine.GUIStyle thumbStyleExtent) + { + var __pool__ = FixedArrayPool.Shared(10); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = value; + __params__[2] = leftValue; + __params__[3] = rightValue; + __params__[4] = power; + __params__[5] = textfieldStyle; + __params__[6] = sliderStyle; + __params__[7] = thumbStyle; + __params__[8] = sliderBackground; + __params__[9] = thumbStyleExtent; + var __result__ = __IntSlider?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static void DoTwoLabels(UnityEngine.Rect rect, UnityEngine.GUIContent leftLabel, UnityEngine.GUIContent rightLabel, UnityEngine.GUIStyle labelStyle) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = leftLabel; + __params__[2] = rightLabel; + __params__[3] = labelStyle; + __DoTwoLabels?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static float DoSlider(UnityEngine.Rect position, UnityEngine.Rect dragZonePosition, int id, float value, float left, float right, string formatString, float power) + { + var __pool__ = FixedArrayPool.Shared(8); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = dragZonePosition; + __params__[2] = id; + __params__[3] = value; + __params__[4] = left; + __params__[5] = right; + __params__[6] = formatString; + __params__[7] = power; + var __result__ = __DoSlider?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float DoSlider(UnityEngine.Rect position, UnityEngine.Rect dragZonePosition, int id, float value, float left, float right, string formatString, UnityEngine.GUIStyle textfieldStyle, float power) + { + var __pool__ = FixedArrayPool.Shared(9); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = dragZonePosition; + __params__[2] = id; + __params__[3] = value; + __params__[4] = left; + __params__[5] = right; + __params__[6] = formatString; + __params__[7] = textfieldStyle; + __params__[8] = power; + var __result__ = __DoSlider__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float DoSlider(UnityEngine.Rect position, UnityEngine.Rect dragZonePosition, int id, float value, float left, float right, string formatString, float power, UnityEngine.GUIStyle textfieldStyle, UnityEngine.GUIStyle sliderStyle, UnityEngine.GUIStyle thumbStyle, UnityEngine.Texture2D sliderBackground, UnityEngine.GUIStyle thumbStyleExtent) + { + var __pool__ = FixedArrayPool.Shared(13); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = dragZonePosition; + __params__[2] = id; + __params__[3] = value; + __params__[4] = left; + __params__[5] = right; + __params__[6] = formatString; + __params__[7] = power; + __params__[8] = textfieldStyle; + __params__[9] = sliderStyle; + __params__[10] = thumbStyle; + __params__[11] = sliderBackground; + __params__[12] = thumbStyleExtent; + var __result__ = __DoSlider__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float DoSlider(UnityEngine.Rect position, UnityEngine.Rect dragZonePosition, int id, float value, float sliderMin, float sliderMax, string formatString, float textFieldMin, float textFieldMax, float power, UnityEngine.GUIStyle textfieldStyle, UnityEngine.GUIStyle sliderStyle, UnityEngine.GUIStyle thumbStyle, UnityEngine.Texture2D sliderBackground, UnityEngine.GUIStyle thumbStyleExtent) + { + var __pool__ = FixedArrayPool.Shared(15); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = dragZonePosition; + __params__[2] = id; + __params__[3] = value; + __params__[4] = sliderMin; + __params__[5] = sliderMax; + __params__[6] = formatString; + __params__[7] = textFieldMin; + __params__[8] = textFieldMax; + __params__[9] = power; + __params__[10] = textfieldStyle; + __params__[11] = sliderStyle; + __params__[12] = thumbStyle; + __params__[13] = sliderBackground; + __params__[14] = thumbStyleExtent; + var __result__ = __DoSlider__4?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static void DoMinMaxSlider(UnityEngine.Rect position, int id, ref float minValue, ref float maxValue, float minLimit, float maxLimit) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = id; + __params__[2] = minValue; + __params__[3] = maxValue; + __params__[4] = minLimit; + __params__[5] = maxLimit; + __DoMinMaxSlider?.Invoke(null, __params__); + minValue = (float)(__params__[2]); + maxValue = (float)(__params__[3]); + __pool__.Return(__params__); + } + + public static int PopupInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, int selectedIndex, UnityEngine.GUIContent[] displayedOptions, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = selectedIndex; + __params__[3] = displayedOptions; + __params__[4] = style; + var __result__ = __PopupInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int PopupInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, int selectedIndex, UnityEngine.GUIContent[] displayedOptions, System.Func checkEnabled, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = selectedIndex; + __params__[3] = displayedOptions; + __params__[4] = checkEnabled; + __params__[5] = style; + var __result__ = __PopupInternal__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int Popup(UnityEngine.Rect position, UnityEngine.GUIContent label, int selectedIndex, string[] displayedOptions, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = selectedIndex; + __params__[3] = displayedOptions; + __params__[4] = style; + var __result__ = __Popup?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int Popup(UnityEngine.Rect position, UnityEngine.GUIContent label, int selectedIndex, string[] displayedOptions) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = selectedIndex; + __params__[3] = displayedOptions; + var __result__ = __Popup__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static void Popup(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __Popup__3?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void Popup(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent[] displayedOptions, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = displayedOptions; + __params__[3] = label; + __Popup__4?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static bool CheckCurrentEnumTypeEnabled(int value) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = value; + var __result__ = __CheckCurrentEnumTypeEnabled?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static System.Enum EnumPopupInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, System.Enum selected, System.Func checkEnabled, bool includeObsolete, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = selected; + __params__[3] = checkEnabled; + __params__[4] = includeObsolete; + __params__[5] = style; + var __result__ = __EnumPopupInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (System.Enum)(__result__) : default; + } + + public static System.Enum EnumPopupInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, System.Enum selected, System.Type enumType, System.Func checkEnabled, bool includeObsolete, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(7); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = selected; + __params__[3] = enumType; + __params__[4] = checkEnabled; + __params__[5] = includeObsolete; + __params__[6] = style; + var __result__ = __EnumPopupInternal__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (System.Enum)(__result__) : default; + } + + public static int EnumPopupInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, int flagValue, System.Type enumType, System.Func checkEnabled, bool includeObsolete, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(7); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = flagValue; + __params__[3] = enumType; + __params__[4] = checkEnabled; + __params__[5] = includeObsolete; + __params__[6] = style; + var __result__ = __EnumPopupInternal__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int IntPopupInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, int selectedValue, UnityEngine.GUIContent[] displayedOptions, int[] optionValues, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = selectedValue; + __params__[3] = displayedOptions; + __params__[4] = optionValues; + __params__[5] = style; + var __result__ = __IntPopupInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static void IntPopupInternal(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent[] displayedOptions, int[] optionValues, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = displayedOptions; + __params__[3] = optionValues; + __params__[4] = label; + __IntPopupInternal__2?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void SortingLayerField(UnityEngine.Rect position, UnityEngine.GUIContent label, UnityEditor.SerializedProperty layerID, UnityEngine.GUIStyle style, UnityEngine.GUIStyle labelStyle) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = layerID; + __params__[3] = style; + __params__[4] = labelStyle; + __SortingLayerField?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static int DoPopup(UnityEngine.Rect position, int controlID, int selected, UnityEngine.GUIContent[] popupValues, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = controlID; + __params__[2] = selected; + __params__[3] = popupValues; + __params__[4] = style; + var __result__ = __DoPopup?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int DoPopup(UnityEngine.Rect position, int controlID, int selected, UnityEngine.GUIContent[] popupValues, System.Func checkEnabled, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = controlID; + __params__[2] = selected; + __params__[3] = popupValues; + __params__[4] = checkEnabled; + __params__[5] = style; + var __result__ = __DoPopup__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static string TagFieldInternal(UnityEngine.Rect position, string tag, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = tag; + __params__[2] = style; + var __result__ = __TagFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string TagFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, string tag, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = tag; + __params__[3] = style; + var __result__ = __TagFieldInternal__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static int LayerFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, int layer, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = layer; + __params__[3] = style; + var __result__ = __LayerFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int MaskFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, int mask, string[] displayedOptions, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = mask; + __params__[3] = displayedOptions; + __params__[4] = style; + var __result__ = __MaskFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int MaskFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, int mask, string[] displayedOptions, int[] optionValues, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = mask; + __params__[3] = displayedOptions; + __params__[4] = optionValues; + __params__[5] = style; + var __result__ = __MaskFieldInternal__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int MaskFieldInternal(UnityEngine.Rect position, int mask, string[] displayedOptions, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = mask; + __params__[2] = displayedOptions; + __params__[3] = style; + var __result__ = __MaskFieldInternal__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static System.Enum EnumFlagsField(UnityEngine.Rect position, UnityEngine.GUIContent label, System.Enum enumValue, bool includeObsolete, out int changedFlags, out bool changedToValue, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(7); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = enumValue; + __params__[3] = includeObsolete; + __params__[4] = null; + __params__[5] = null; + __params__[6] = style; + var __result__ = __EnumFlagsField?.Invoke(null, __params__); + changedFlags = (int)(__params__[4]); + changedToValue = (bool)(__params__[5]); + __pool__.Return(__params__); + return __result__ != null ? (System.Enum)(__result__) : default; + } + + public static System.Enum EnumFlagsField(UnityEngine.Rect position, UnityEngine.GUIContent label, System.Enum enumValue, System.Type enumType, bool includeObsolete, out int changedFlags, out bool changedToValue, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(8); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = enumValue; + __params__[3] = enumType; + __params__[4] = includeObsolete; + __params__[5] = null; + __params__[6] = null; + __params__[7] = style; + var __result__ = __EnumFlagsField__2?.Invoke(null, __params__); + changedFlags = (int)(__params__[5]); + changedToValue = (bool)(__params__[6]); + __pool__.Return(__params__); + return __result__ != null ? (System.Enum)(__result__) : default; + } + + public static int EnumFlagsField(UnityEngine.Rect position, UnityEngine.GUIContent label, int enumValue, System.Type enumType, bool includeObsolete, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = enumValue; + __params__[3] = enumType; + __params__[4] = includeObsolete; + __params__[5] = style; + var __result__ = __EnumFlagsField__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static void ObjectField(UnityEngine.Rect position, UnityEditor.SerializedProperty property, System.Type objType, UnityEngine.GUIContent label, UnityEngine.GUIStyle style, ObjectFieldValidator validator) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = objType; + __params__[3] = label; + __params__[4] = style; + __params__[5] = validator?.Cast(null); + __ObjectField?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void ObjectFieldInternal(UnityEngine.Rect position, UnityEditor.SerializedProperty property, System.Type objType, UnityEngine.GUIContent label, UnityEngine.GUIStyle style, ObjectFieldValidator validator) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = objType; + __params__[3] = label; + __params__[4] = style; + __params__[5] = validator?.Cast(null); + __ObjectFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Rect GetObjectFieldThumbnailRect(UnityEngine.Rect position, System.Type objType) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = objType; + var __result__ = __GetObjectFieldThumbnailRect?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static void GetRectsForMiniThumbnailField(UnityEngine.Rect position, out UnityEngine.Rect thumbRect, out UnityEngine.Rect labelRect) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = null; + __params__[2] = null; + __GetRectsForMiniThumbnailField?.Invoke(null, __params__); + thumbRect = (UnityEngine.Rect)(__params__[1]); + labelRect = (UnityEngine.Rect)(__params__[2]); + __pool__.Return(__params__); + } + + public static UnityEngine.Object MiniThumbnailObjectField(UnityEngine.Rect position, UnityEngine.GUIContent label, UnityEngine.Object obj, System.Type objType) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = obj; + __params__[3] = objType; + var __result__ = __MiniThumbnailObjectField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Object)(__result__) : default; + } + + public static UnityEngine.GameObject GetGameObjectFromObject(UnityEngine.Object obj) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = obj; + var __result__ = __GetGameObjectFromObject?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GameObject)(__result__) : default; + } + + public static bool CheckForCrossSceneReferencing(UnityEngine.Object obj1, UnityEngine.Object obj2) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = obj1; + __params__[1] = obj2; + var __result__ = __CheckForCrossSceneReferencing?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool ValidateObjectReferenceValue(UnityEditor.SerializedProperty property, UnityEngine.Object obj, object options) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = property; + __params__[1] = obj; + __params__[2] = options; + var __result__ = __ValidateObjectReferenceValue?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static UnityEngine.Object ValidateObjectFieldAssignment(UnityEngine.Object[] references, System.Type objType, UnityEditor.SerializedProperty property, object options) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = references; + __params__[1] = objType; + __params__[2] = property; + __params__[3] = options; + var __result__ = __ValidateObjectFieldAssignment?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Object)(__result__) : default; + } + + public static UnityEngine.Vector2 Vector2Field(UnityEngine.Rect position, UnityEngine.GUIContent label, UnityEngine.Vector2 value, bool setWideMode) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __params__[3] = setWideMode; + var __result__ = __Vector2Field?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector2)(__result__) : default; + } + + public static UnityEngine.Vector2 Vector2Field(UnityEngine.Rect position, UnityEngine.Vector2 value) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = value; + var __result__ = __Vector2Field__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector2)(__result__) : default; + } + + public static UnityEngine.Vector3 Vector3Field(UnityEngine.Rect position, UnityEngine.Vector3 value) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = value; + var __result__ = __Vector3Field?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector3)(__result__) : default; + } + + public static UnityEngine.Vector3 LinkedVector3Field(UnityEngine.Rect position, UnityEngine.GUIContent label, UnityEngine.Vector3 value, ref bool proportionalScale) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __params__[3] = proportionalScale; + var __result__ = __LinkedVector3Field?.Invoke(null, __params__); + proportionalScale = (bool)(__params__[3]); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector3)(__result__) : default; + } + + public static UnityEngine.Vector3 LinkedVector3Field(UnityEngine.Rect position, UnityEngine.GUIContent label, UnityEngine.GUIContent toggleContent, UnityEngine.Vector3 value, ref bool proportionalScale, UnityEngine.Vector3 initialScale, uint mixedValues, ref int axisModified, UnityEditor.SerializedProperty property, UnityEditor.SerializedProperty proportionalScaleProperty) + { + var __pool__ = FixedArrayPool.Shared(10); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = toggleContent; + __params__[3] = value; + __params__[4] = proportionalScale; + __params__[5] = initialScale; + __params__[6] = mixedValues; + __params__[7] = axisModified; + __params__[8] = property; + __params__[9] = proportionalScaleProperty; + var __result__ = __LinkedVector3Field__2?.Invoke(null, __params__); + proportionalScale = (bool)(__params__[4]); + axisModified = (int)(__params__[7]); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector3)(__result__) : default; + } + + public static UnityEngine.Vector3 LinkedVector3Field(UnityEngine.Rect position, UnityEngine.Vector3 value, bool proportionalScale) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = value; + __params__[2] = proportionalScale; + var __result__ = __LinkedVector3Field__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector3)(__result__) : default; + } + + public static UnityEngine.Vector3 LinkedVector3Field(UnityEngine.Rect position, UnityEngine.Vector3 value, bool proportionalScale, uint mixedValues, UnityEngine.Vector3 initialScale, ref int axisModified, UnityEditor.SerializedProperty property) + { + var __pool__ = FixedArrayPool.Shared(7); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = value; + __params__[2] = proportionalScale; + __params__[3] = mixedValues; + __params__[4] = initialScale; + __params__[5] = axisModified; + __params__[6] = property; + var __result__ = __LinkedVector3Field__4?.Invoke(null, __params__); + axisModified = (int)(__params__[5]); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector3)(__result__) : default; + } + + public static void Vector2Field(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __Vector2Field__3?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void Vector3Field(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __Vector3Field__2?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void QuaternionEulerField(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __QuaternionEulerField?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void Vector4Field(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __Vector4Field?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Vector4 Vector4FieldNoIndent(UnityEngine.Rect position, UnityEngine.Vector4 value) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = value; + var __result__ = __Vector4FieldNoIndent?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector4)(__result__) : default; + } + + public static UnityEngine.Vector2Int Vector2IntField(UnityEngine.Rect position, UnityEngine.Vector2Int value) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = value; + var __result__ = __Vector2IntField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector2Int)(__result__) : default; + } + + public static void Vector2IntField(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __Vector2IntField__2?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Vector3Int Vector3IntField(UnityEngine.Rect position, UnityEngine.Vector3Int value) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = value; + var __result__ = __Vector3IntField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector3Int)(__result__) : default; + } + + public static void Vector3IntField(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __Vector3IntField__2?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Rect RectFieldNoIndent(UnityEngine.Rect position, UnityEngine.Rect value) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = value; + var __result__ = __RectFieldNoIndent?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static void RectField(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __RectField?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void RectIntField(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __RectIntField?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Rect DrawBoundsFieldLabelsAndAdjustPositionForValues(UnityEngine.Rect position, bool drawOutside, UnityEngine.GUIContent firstContent, UnityEngine.GUIContent secondContent) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = drawOutside; + __params__[2] = firstContent; + __params__[3] = secondContent; + var __result__ = __DrawBoundsFieldLabelsAndAdjustPositionForValues?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static UnityEngine.Bounds BoundsFieldNoIndent(UnityEngine.Rect position, UnityEngine.Bounds value, bool isBelowLabel) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = value; + __params__[2] = isBelowLabel; + var __result__ = __BoundsFieldNoIndent?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Bounds)(__result__) : default; + } + + public static void BoundsField(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __BoundsField?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.BoundsInt BoundsIntFieldNoIndent(UnityEngine.Rect position, UnityEngine.BoundsInt value, bool isBelowLabel) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = value; + __params__[2] = isBelowLabel; + var __result__ = __BoundsIntFieldNoIndent?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.BoundsInt)(__result__) : default; + } + + public static void BoundsIntField(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __BoundsIntField?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static float GetLabelWidth(UnityEngine.GUIContent Label, float prefixLabelWidth) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = Label; + __params__[1] = prefixLabelWidth; + var __result__ = __GetLabelWidth?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static void MultiFloatFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent[] subLabels, float[] values, float prefixLabelWidth) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = subLabels; + __params__[2] = values; + __params__[3] = prefixLabelWidth; + __MultiFloatFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void LockingMultiFloatFieldInternal(UnityEngine.Rect position, bool locked, UnityEngine.GUIContent[] subLabels, float[] values, float prefixLabelWidth) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = locked; + __params__[2] = subLabels; + __params__[3] = values; + __params__[4] = prefixLabelWidth; + __LockingMultiFloatFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void LockingMultiFloatFieldInternal(UnityEngine.Rect position, bool locked, uint mixedValues, UnityEngine.GUIContent[] subLabels, float[] values, float[] initialValues, UnityEditor.SerializedProperty property, float prefixLabelWidth) + { + var __pool__ = FixedArrayPool.Shared(8); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = locked; + __params__[2] = mixedValues; + __params__[3] = subLabels; + __params__[4] = values; + __params__[5] = initialValues; + __params__[6] = property; + __params__[7] = prefixLabelWidth; + __LockingMultiFloatFieldInternal__2?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void MultiIntFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent[] subLabels, int[] values) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = subLabels; + __params__[2] = values; + __MultiIntFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void MultiPropertyFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent[] subLabels, UnityEditor.SerializedProperty valuesIterator, object visibility, bool[] disabledMask, float prefixLabelWidth) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = subLabels; + __params__[2] = valuesIterator; + __params__[3] = visibility; + __params__[4] = disabledMask; + __params__[5] = prefixLabelWidth; + __MultiPropertyFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void PropertiesField(UnityEngine.Rect position, UnityEngine.GUIContent label, UnityEditor.SerializedProperty[] properties, UnityEngine.GUIContent[] propertyLabels, float propertyLabelsWidth) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = properties; + __params__[3] = propertyLabels; + __params__[4] = propertyLabelsWidth; + __PropertiesField?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static int CycleButton(UnityEngine.Rect position, int selected, UnityEngine.GUIContent[] options, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = selected; + __params__[2] = options; + __params__[3] = style; + var __result__ = __CycleButton?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static UnityEngine.Color ColorField(UnityEngine.Rect position, UnityEngine.Color value, bool showEyedropper, bool showAlpha) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = value; + __params__[2] = showEyedropper; + __params__[3] = showAlpha; + var __result__ = __ColorField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Color)(__result__) : default; + } + + public static UnityEngine.Color ColorField(UnityEngine.Rect position, UnityEngine.GUIContent label, UnityEngine.Color value, bool showEyedropper, bool showAlpha) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __params__[3] = showEyedropper; + __params__[4] = showAlpha; + var __result__ = __ColorField__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Color)(__result__) : default; + } + + public static UnityEngine.Color DoColorField(UnityEngine.Rect position, int id, UnityEngine.Color value, bool showEyedropper, bool showAlpha, bool hdr) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = id; + __params__[2] = value; + __params__[3] = showEyedropper; + __params__[4] = showAlpha; + __params__[5] = hdr; + var __result__ = __DoColorField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Color)(__result__) : default; + } + + public static void SetCurveEditorWindowCurve(UnityEngine.AnimationCurve value, UnityEditor.SerializedProperty property, UnityEngine.Color color) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = value; + __params__[1] = property; + __params__[2] = color; + __SetCurveEditorWindowCurve?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.AnimationCurve DoCurveField(UnityEngine.Rect position, int id, UnityEngine.AnimationCurve value, UnityEngine.Color color, UnityEngine.Rect ranges, UnityEditor.SerializedProperty property) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = id; + __params__[2] = value; + __params__[3] = color; + __params__[4] = ranges; + __params__[5] = property; + var __result__ = __DoCurveField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.AnimationCurve)(__result__) : default; + } + + public static void ShowCurvePopup(UnityEngine.Rect ranges) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = ranges; + __ShowCurvePopup?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Vector2 GetObjectIconDropDownSize(float width, float height) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = width; + __params__[1] = height; + var __result__ = __GetObjectIconDropDownSize?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector2)(__result__) : default; + } + + public static void ObjectIconDropDown(UnityEngine.Rect position, UnityEngine.Object[] targets, bool showLabelIcons, UnityEngine.Texture2D nullIcon, UnityEditor.SerializedProperty iconProperty) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = targets; + __params__[2] = showLabelIcons; + __params__[3] = nullIcon; + __params__[4] = iconProperty; + __ObjectIconDropDown?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Rect GetIconRect(UnityEngine.Rect position, UnityEngine.GUIStyle baseStyle) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = baseStyle; + var __result__ = __GetIconRect?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static UnityEngine.Rect GetTextRect(UnityEngine.Rect position, UnityEngine.Rect iconRect, UnityEngine.Rect settingsRect, UnityEngine.GUIStyle baseStyle, UnityEngine.GUIStyle textStyle) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = iconRect; + __params__[2] = settingsRect; + __params__[3] = baseStyle; + __params__[4] = textStyle; + var __result__ = __GetTextRect?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static UnityEngine.Rect GetSettingsRect(UnityEngine.Rect position, UnityEngine.GUIStyle baseStyle, UnityEngine.GUIStyle iconButtonStyle) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = baseStyle; + __params__[2] = iconButtonStyle; + var __result__ = __GetSettingsRect?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static bool EnableCheckBoxInTitlebar(UnityEngine.Object targetObj) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = targetObj; + var __result__ = __EnableCheckBoxInTitlebar?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void DoInspectorTitlebar(UnityEngine.Rect position, int id, bool foldout, UnityEngine.Object[] targetObjs, UnityEditor.SerializedProperty enabledProperty, UnityEngine.GUIStyle baseStyle) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = id; + __params__[2] = foldout; + __params__[3] = targetObjs; + __params__[4] = enabledProperty; + __params__[5] = baseStyle; + __DoInspectorTitlebar?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static bool ShouldDrawOverrideBackground(UnityEngine.Object[] targetObjs, UnityEngine.Event evt, UnityEngine.Component comp) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = targetObjs; + __params__[1] = evt; + __params__[2] = comp; + var __result__ = __ShouldDrawOverrideBackground?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void RemovedComponentTitlebar(UnityEngine.Rect position, UnityEngine.GameObject instanceGo, UnityEngine.Component sourceComponent) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = instanceGo; + __params__[2] = sourceComponent; + __RemovedComponentTitlebar?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static bool ToggleTitlebar(UnityEngine.Rect position, UnityEngine.GUIContent label, bool foldout, ref bool toggleValue) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = foldout; + __params__[3] = toggleValue; + var __result__ = __ToggleTitlebar?.Invoke(null, __params__); + toggleValue = (bool)(__params__[3]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool FoldoutTitlebar(UnityEngine.Rect position, UnityEngine.GUIContent label, bool foldout, bool skipIconSpacing) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = foldout; + __params__[3] = skipIconSpacing; + var __result__ = __FoldoutTitlebar?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool FoldoutTitlebar(UnityEngine.Rect position, UnityEngine.GUIContent label, bool foldout, bool skipIconSpacing, UnityEngine.GUIStyle baseStyle, UnityEngine.GUIStyle textStyle) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = foldout; + __params__[3] = skipIconSpacing; + __params__[4] = baseStyle; + __params__[5] = textStyle; + var __result__ = __FoldoutTitlebar__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool HelpIconButton(UnityEngine.Rect position, UnityEngine.Object[] objs) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = objs; + var __result__ = __HelpIconButton?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool FoldoutInternal(UnityEngine.Rect position, bool foldout, UnityEngine.GUIContent content, bool toggleOnLabelClick, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = foldout; + __params__[2] = content; + __params__[3] = toggleOnLabelClick; + __params__[4] = style; + var __result__ = __FoldoutInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool ProgressBar(UnityEngine.Rect position, float value, UnityEngine.GUIContent content, bool textOnBar, UnityEngine.GUIStyle progressBarBackgroundStyle, UnityEngine.GUIStyle progressBarStyle, UnityEngine.GUIStyle progressBarTextStyle) + { + var __pool__ = FixedArrayPool.Shared(7); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = value; + __params__[2] = content; + __params__[3] = textOnBar; + __params__[4] = progressBarBackgroundStyle; + __params__[5] = progressBarStyle; + __params__[6] = progressBarTextStyle; + var __result__ = __ProgressBar?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool LabelHasContent(UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = label; + var __result__ = __LabelHasContent?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void PrepareCurrentPrefixLabel(int controlId) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = controlId; + __PrepareCurrentPrefixLabel?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static bool IsLabelHighlightEnabled() + { + var __result__ = __IsLabelHighlightEnabled?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void BeginLabelHighlight(string searchContext, UnityEngine.Color searchHighlightSelectionColor, UnityEngine.Color searchHighlightColor) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = searchContext; + __params__[1] = searchHighlightSelectionColor; + __params__[2] = searchHighlightColor; + __BeginLabelHighlight?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void EndLabelHighlight() + { + __EndLabelHighlight?.Invoke(null, System.Array.Empty()); + } + + public static bool DrawLabelHighlight(UnityEngine.Rect position, UnityEngine.GUIContent label, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = style; + var __result__ = __DrawLabelHighlight?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void HandlePrefixLabelInternal(UnityEngine.Rect totalPosition, UnityEngine.Rect labelPosition, UnityEngine.GUIContent label, int id, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = totalPosition; + __params__[1] = labelPosition; + __params__[2] = label; + __params__[3] = id; + __params__[4] = style; + __HandlePrefixLabelInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static bool UseVTMaterial(UnityEngine.Texture texture) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = texture; + var __result__ = __UseVTMaterial?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static UnityEngine.Rect MultiFieldPrefixLabel(UnityEngine.Rect totalPosition, int id, UnityEngine.GUIContent label, int columns) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = totalPosition; + __params__[1] = id; + __params__[2] = label; + __params__[3] = columns; + var __result__ = __MultiFieldPrefixLabel?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static UnityEngine.Rect MultiFieldPrefixLabel(UnityEngine.Rect totalPosition, int id, UnityEngine.GUIContent label, int columns, float labelWidthIndent, bool setWideMode) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = totalPosition; + __params__[1] = id; + __params__[2] = label; + __params__[3] = columns; + __params__[4] = labelWidthIndent; + __params__[5] = setWideMode; + var __result__ = __MultiFieldPrefixLabel__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static UnityEngine.GUIContent BeginPropertyInternal(UnityEngine.Rect totalPosition, UnityEngine.GUIContent label, UnityEditor.SerializedProperty property) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = totalPosition; + __params__[1] = label; + __params__[2] = property; + var __result__ = __BeginPropertyInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GUIContent)(__result__) : default; + } + + public static void DrawOverrideBackground(UnityEngine.Rect position, bool fixupRectForHeadersAndBackgrounds) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = fixupRectForHeadersAndBackgrounds; + __DrawOverrideBackground?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void DrawMarginLineForRect(UnityEngine.Rect position, UnityEngine.Color color) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = color; + __DrawMarginLineForRect?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void DoPropertyFieldKeyboardHandling(UnityEditor.SerializedProperty property) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = property; + __DoPropertyFieldKeyboardHandling?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void LayerMaskField(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __params__[3] = style; + __LayerMaskField?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void LayerMaskField(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __LayerMaskField__2?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.LayerMask LayerMaskField(UnityEngine.Rect position, UnityEngine.LayerMask layers, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = layers; + __params__[2] = label; + var __result__ = __LayerMaskField__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.LayerMask)(__result__) : default; + } + + public static uint LayerMaskField(UnityEngine.Rect position, uint layers, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = layers; + __params__[2] = label; + var __result__ = __LayerMaskField__4?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (uint)(__result__) : default; + } + + public static uint LayerMaskField(UnityEngine.Rect position, uint layers, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = layers; + __params__[2] = property; + __params__[3] = label; + __params__[4] = style; + var __result__ = __LayerMaskField__5?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (uint)(__result__) : default; + } + + public static void ShowRepaints() + { + __ShowRepaints?.Invoke(null, System.Array.Empty()); + } + + public static void DrawTextureAlphaInternal(UnityEngine.Rect position, UnityEngine.Texture image, UnityEngine.ScaleMode scaleMode, float imageAspect, float mipLevel) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = image; + __params__[2] = scaleMode; + __params__[3] = imageAspect; + __params__[4] = mipLevel; + __DrawTextureAlphaInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void DrawTextureTransparentInternal(UnityEngine.Rect position, UnityEngine.Texture image, UnityEngine.ScaleMode scaleMode, float imageAspect, float mipLevel, UnityEngine.Rendering.ColorWriteMask colorWriteMask, float exposure) + { + var __pool__ = FixedArrayPool.Shared(7); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = image; + __params__[2] = scaleMode; + __params__[3] = imageAspect; + __params__[4] = mipLevel; + __params__[5] = colorWriteMask; + __params__[6] = exposure; + __DrawTextureTransparentInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void DrawTransparencyCheckerTexture(UnityEngine.Rect position, UnityEngine.ScaleMode scaleMode, float imageAspect) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = scaleMode; + __params__[2] = imageAspect; + __DrawTransparencyCheckerTexture?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void DrawPreviewTextureInternal(UnityEngine.Rect position, UnityEngine.Texture image, UnityEngine.Material mat, UnityEngine.ScaleMode scaleMode, float imageAspect, float mipLevel, UnityEngine.Rendering.ColorWriteMask colorWriteMask, float exposure) + { + var __pool__ = FixedArrayPool.Shared(8); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = image; + __params__[2] = mat; + __params__[3] = scaleMode; + __params__[4] = imageAspect; + __params__[5] = mipLevel; + __params__[6] = colorWriteMask; + __params__[7] = exposure; + __DrawPreviewTextureInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void StreamTexture(UnityEngine.Texture texture, UnityEngine.Material mat, float mipLevel) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = texture; + __params__[1] = mat; + __params__[2] = mipLevel; + __StreamTexture?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Material GetMaterialForSpecialTexture(UnityEngine.Texture t, UnityEngine.Material defaultMat, bool manualTex2Linear, bool useVTMaterialWhenPossible) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = t; + __params__[1] = defaultMat; + __params__[2] = manualTex2Linear; + __params__[3] = useVTMaterialWhenPossible; + var __result__ = __GetMaterialForSpecialTexture?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Material)(__result__) : default; + } + + public static void SetExpandedRecurse(UnityEditor.SerializedProperty property, bool expanded) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = property; + __params__[1] = expanded; + __SetExpandedRecurse?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static float GetSinglePropertyHeight(UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = property; + __params__[1] = label; + var __result__ = __GetSinglePropertyHeight?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float GetPropertyHeightInternal(UnityEditor.SerializedProperty property, UnityEngine.GUIContent label, bool includeChildren) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = property; + __params__[1] = label; + __params__[2] = includeChildren; + var __result__ = __GetPropertyHeightInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static bool HasVisibleChildFields(UnityEditor.SerializedProperty property, bool isUIElements) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = property; + __params__[1] = isUIElements; + var __result__ = __HasVisibleChildFields?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool PropertyFieldInternal(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label, bool includeChildren) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __params__[3] = includeChildren; + var __result__ = __PropertyFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool DefaultPropertyField(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + var __result__ = __DefaultPropertyField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void DrawLegend(UnityEngine.Rect position, UnityEngine.Color color, string label, bool enabled) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = color; + __params__[2] = label; + __params__[3] = enabled; + __DrawLegend?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static string TextFieldDropDown(UnityEngine.Rect position, string text, string[] dropDownElement) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = text; + __params__[2] = dropDownElement; + var __result__ = __TextFieldDropDown?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string TextFieldDropDown(UnityEngine.Rect position, UnityEngine.GUIContent label, string text, string[] dropDownElement) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = text; + __params__[3] = dropDownElement; + var __result__ = __TextFieldDropDown__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string DelayedTextFieldDropDown(UnityEngine.Rect position, string text, string[] dropDownElement) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = text; + __params__[2] = dropDownElement; + var __result__ = __DelayedTextFieldDropDown?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string DelayedTextFieldDropDown(UnityEngine.Rect position, UnityEngine.GUIContent label, string text, string[] dropDownElement) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = text; + __params__[3] = dropDownElement; + var __result__ = __DelayedTextFieldDropDown__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static bool DropdownButton(int id, UnityEngine.Rect position, UnityEngine.GUIContent content, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = id; + __params__[1] = position; + __params__[2] = content; + __params__[3] = style; + var __result__ = __DropdownButton?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static int AdvancedPopup(UnityEngine.Rect rect, int selectedIndex, string[] displayedOptions) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = selectedIndex; + __params__[2] = displayedOptions; + var __result__ = __AdvancedPopup?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int AdvancedPopup(UnityEngine.Rect rect, int selectedIndex, string[] displayedOptions, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = selectedIndex; + __params__[2] = displayedOptions; + __params__[3] = style; + var __result__ = __AdvancedPopup__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int AdvancedLazyPopup(UnityEngine.Rect rect, string displayedOption, int selectedIndex, Delegate displayedOptionsFunc, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = displayedOption; + __params__[2] = selectedIndex; + __params__[3] = displayedOptionsFunc; + __params__[4] = style; + var __result__ = __AdvancedLazyPopup?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static void DelayedTextFieldHelper(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __params__[3] = style; + __DelayedTextFieldHelper?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void FloatField(UnityEngine.Rect position, UnityEngine.GUIContent label, ref object value) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __FloatField?.Invoke(null, __params__); + value = (object)(__params__[2]); + __pool__.Return(__params__); + } + + public static void DoubleField(UnityEngine.Rect position, UnityEngine.GUIContent label, ref object value) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __DoubleField?.Invoke(null, __params__); + value = (object)(__params__[2]); + __pool__.Return(__params__); + } + + public static void LongField(UnityEngine.Rect position, UnityEngine.GUIContent label, ref object value) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = value; + __LongField?.Invoke(null, __params__); + value = (object)(__params__[2]); + __pool__.Return(__params__); + } + + public static void EnumPopup(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __EnumPopup?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static float CalcPrefixLabelWidth(UnityEngine.GUIContent label, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = style; + var __result__ = __CalcPrefixLabelWidth?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static System.Enum EnumMaskField(UnityEngine.Rect position, UnityEngine.GUIContent label, System.Enum enumValue, UnityEngine.GUIStyle style, out int changedFlags, out bool changedToValue) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = enumValue; + __params__[3] = style; + __params__[4] = null; + __params__[5] = null; + var __result__ = __EnumMaskField?.Invoke(null, __params__); + changedFlags = (int)(__params__[4]); + changedToValue = (bool)(__params__[5]); + __pool__.Return(__params__); + return __result__ != null ? (System.Enum)(__result__) : default; + } + + public static System.Enum EnumMaskFieldInternal(UnityEngine.Rect position, System.Enum enumValue, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = enumValue; + __params__[2] = style; + var __result__ = __EnumMaskFieldInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (System.Enum)(__result__) : default; + } + + public static System.Enum EnumMaskFieldInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, System.Enum enumValue, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = enumValue; + __params__[3] = style; + var __result__ = __EnumMaskFieldInternal__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (System.Enum)(__result__) : default; + } + + public static System.Enum DoEnumMaskField(UnityEngine.Rect position, UnityEngine.GUIContent label, System.Enum enumValue, UnityEngine.GUIStyle style, out int changedFlags, out bool changedToValue) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = enumValue; + __params__[3] = style; + __params__[4] = null; + __params__[5] = null; + var __result__ = __DoEnumMaskField?.Invoke(null, __params__); + changedFlags = (int)(__params__[4]); + changedToValue = (bool)(__params__[5]); + __pool__.Return(__params__); + return __result__ != null ? (System.Enum)(__result__) : default; + } + + public static System.Enum EnumMaskPopup(UnityEngine.Rect position, string label, System.Enum selected, out int changedFlags, out bool changedToValue, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = selected; + __params__[3] = null; + __params__[4] = null; + __params__[5] = style; + var __result__ = __EnumMaskPopup?.Invoke(null, __params__); + changedFlags = (int)(__params__[3]); + changedToValue = (bool)(__params__[4]); + __pool__.Return(__params__); + return __result__ != null ? (System.Enum)(__result__) : default; + } + + public static System.Enum EnumMaskPopup(UnityEngine.Rect position, UnityEngine.GUIContent label, System.Enum selected, out int changedFlags, out bool changedToValue, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = selected; + __params__[3] = null; + __params__[4] = null; + __params__[5] = style; + var __result__ = __EnumMaskPopup__2?.Invoke(null, __params__); + changedFlags = (int)(__params__[3]); + changedToValue = (bool)(__params__[4]); + __pool__.Return(__params__); + return __result__ != null ? (System.Enum)(__result__) : default; + } + + public static System.Enum EnumMaskPopupInternal(UnityEngine.Rect position, UnityEngine.GUIContent label, System.Enum selected, out int changedFlags, out bool changedToValue, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = selected; + __params__[3] = null; + __params__[4] = null; + __params__[5] = style; + var __result__ = __EnumMaskPopupInternal?.Invoke(null, __params__); + changedFlags = (int)(__params__[3]); + changedToValue = (bool)(__params__[4]); + __pool__.Return(__params__); + return __result__ != null ? (System.Enum)(__result__) : default; + } + + public static float AngularDial(UnityEngine.Rect rect, UnityEngine.GUIContent label, float angle, UnityEngine.Texture thumbTexture, UnityEngine.GUIStyle background, UnityEngine.GUIStyle thumb) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = label; + __params__[2] = angle; + __params__[3] = thumbTexture; + __params__[4] = background; + __params__[5] = thumb; + var __result__ = __AngularDial?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float UseAngularDialEventAndGetAngle(int id, UnityEngine.Event evt, UnityEngine.Vector2 center, float angle) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = id; + __params__[1] = evt; + __params__[2] = center; + __params__[3] = angle; + var __result__ = __UseAngularDialEventAndGetAngle?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static bool ButtonWithRotatedIcon(UnityEngine.Rect rect, UnityEngine.GUIContent guiContent, float iconAngle, bool mouseDownButton, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = guiContent; + __params__[2] = iconAngle; + __params__[3] = mouseDownButton; + __params__[4] = style; + var __result__ = __ButtonWithRotatedIcon?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static UnityEngine.Gradient GradientField(UnityEngine.Rect position, UnityEditor.SerializedProperty property) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + var __result__ = __GradientField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Gradient)(__result__) : default; + } + + public static UnityEngine.Gradient GradientField(UnityEngine.Rect position, UnityEditor.SerializedProperty property, bool hdr) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = hdr; + var __result__ = __GradientField__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Gradient)(__result__) : default; + } + + public static UnityEngine.Gradient GradientField(UnityEngine.Rect position, UnityEditor.SerializedProperty property, bool hdr, UnityEngine.ColorSpace colorSpace) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = hdr; + __params__[3] = colorSpace; + var __result__ = __GradientField__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Gradient)(__result__) : default; + } + + public static UnityEngine.Gradient GradientField(UnityEngine.Rect position, string label, UnityEditor.SerializedProperty property) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = property; + var __result__ = __GradientField__4?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Gradient)(__result__) : default; + } + + public static UnityEngine.Gradient GradientField(UnityEngine.Rect position, UnityEngine.GUIContent label, UnityEditor.SerializedProperty property) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = property; + var __result__ = __GradientField__5?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Gradient)(__result__) : default; + } + + public static UnityEngine.Gradient DoGradientField(UnityEngine.Rect position, int id, UnityEngine.Gradient value, UnityEditor.SerializedProperty property, bool hdr, UnityEngine.ColorSpace space) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = id; + __params__[2] = value; + __params__[3] = property; + __params__[4] = hdr; + __params__[5] = space; + var __result__ = __DoGradientField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Gradient)(__result__) : default; + } + + public static UnityEngine.Color32 HexColorTextField(UnityEngine.Rect rect, UnityEngine.GUIContent label, UnityEngine.Color32 color, bool showAlpha) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = label; + __params__[2] = color; + __params__[3] = showAlpha; + var __result__ = __HexColorTextField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Color32)(__result__) : default; + } + + public static UnityEngine.Color32 HexColorTextField(UnityEngine.Rect rect, UnityEngine.GUIContent label, UnityEngine.Color32 color, bool showAlpha, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = label; + __params__[2] = color; + __params__[3] = showAlpha; + __params__[4] = style; + var __result__ = __HexColorTextField__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Color32)(__result__) : default; + } + + public static UnityEngine.Color32 DoHexColorTextField(int id, UnityEngine.Rect rect, UnityEngine.Color32 color, bool showAlpha, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = id; + __params__[1] = rect; + __params__[2] = color; + __params__[3] = showAlpha; + __params__[4] = style; + var __result__ = __DoHexColorTextField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Color32)(__result__) : default; + } + + public static bool Button(UnityEngine.Rect position, UnityEngine.GUIContent content) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = content; + var __result__ = __Button?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool Button(UnityEngine.Rect position, UnityEngine.GUIContent content, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = content; + __params__[2] = style; + var __result__ = __Button__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool IconButton(int id, UnityEngine.Rect position, UnityEngine.GUIContent content, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = id; + __params__[1] = position; + __params__[2] = content; + __params__[3] = style; + var __result__ = __IconButton?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static float WidthResizer(UnityEngine.Rect position, float width, float minWidth, float maxWidth) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = width; + __params__[2] = minWidth; + __params__[3] = maxWidth; + var __result__ = __WidthResizer?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float WidthResizer(UnityEngine.Rect position, float width, float minWidth, float maxWidth, out bool hasControl) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = width; + __params__[2] = minWidth; + __params__[3] = maxWidth; + __params__[4] = null; + var __result__ = __WidthResizer__2?.Invoke(null, __params__); + hasControl = (bool)(__params__[4]); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float HeightResizer(UnityEngine.Rect position, float height, float minHeight, float maxHeight) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = height; + __params__[2] = minHeight; + __params__[3] = maxHeight; + var __result__ = __HeightResizer?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float HeightResizer(UnityEngine.Rect position, float height, float minHeight, float maxHeight, out bool hasControl) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = height; + __params__[2] = minHeight; + __params__[3] = maxHeight; + __params__[4] = null; + var __result__ = __HeightResizer__2?.Invoke(null, __params__); + hasControl = (bool)(__params__[4]); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static UnityEngine.Vector2 MouseDeltaReader(UnityEngine.Rect position, bool activated) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = activated; + var __result__ = __MouseDeltaReader?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector2)(__result__) : default; + } + + public static bool ButtonWithDropdownList(string buttonName, string[] buttonNames, UnityEditor.GenericMenu.MenuFunction2 callback, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = buttonName; + __params__[1] = buttonNames; + __params__[2] = callback; + __params__[3] = options; + var __result__ = __ButtonWithDropdownList?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool ButtonWithDropdownList(UnityEngine.GUIContent content, string[] buttonNames, UnityEditor.GenericMenu.MenuFunction2 callback, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = content; + __params__[1] = buttonNames; + __params__[2] = callback; + __params__[3] = options; + var __result__ = __ButtonWithDropdownList__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void GameViewSizePopup(UnityEngine.Rect buttonRect, UnityEditor.GameViewSizeGroupType groupType, int selectedIndex, object gameView, UnityEngine.GUIStyle guiStyle) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = buttonRect; + __params__[1] = groupType; + __params__[2] = selectedIndex; + __params__[3] = gameView; + __params__[4] = guiStyle; + __GameViewSizePopup?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void DrawDelimiterLine(UnityEngine.Rect rect) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __DrawDelimiterLine?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void DrawOutline(UnityEngine.Rect rect, float size, UnityEngine.Color color) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = size; + __params__[2] = color; + __DrawOutline?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static float Knob(UnityEngine.Rect position, UnityEngine.Vector2 knobSize, float currentValue, float start, float end, string unit, UnityEngine.Color backgroundColor, UnityEngine.Color activeColor, bool showValue, int id) + { + var __pool__ = FixedArrayPool.Shared(10); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = knobSize; + __params__[2] = currentValue; + __params__[3] = start; + __params__[4] = end; + __params__[5] = unit; + __params__[6] = backgroundColor; + __params__[7] = activeColor; + __params__[8] = showValue; + __params__[9] = id; + var __result__ = __Knob?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float OffsetKnob(UnityEngine.Rect position, float currentValue, float start, float end, float median, string unit, UnityEngine.Color backgroundColor, UnityEngine.Color activeColor, UnityEngine.GUIStyle knob, int id) + { + var __pool__ = FixedArrayPool.Shared(10); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = currentValue; + __params__[2] = start; + __params__[3] = end; + __params__[4] = median; + __params__[5] = unit; + __params__[6] = backgroundColor; + __params__[7] = activeColor; + __params__[8] = knob; + __params__[9] = id; + var __result__ = __OffsetKnob?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static UnityEngine.Object DoObjectField(UnityEngine.Rect position, UnityEngine.Rect dropRect, int id, UnityEngine.Object obj, UnityEngine.Object objBeingEdited, System.Type objType, ObjectFieldValidator validator, bool allowSceneObjects, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(9); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = dropRect; + __params__[2] = id; + __params__[3] = obj; + __params__[4] = objBeingEdited; + __params__[5] = objType; + __params__[6] = validator?.Cast(null); + __params__[7] = allowSceneObjects; + __params__[8] = style; + var __result__ = __DoObjectField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Object)(__result__) : default; + } + + public static UnityEngine.Object DoObjectField(UnityEngine.Rect position, UnityEngine.Rect dropRect, int id, UnityEngine.Object obj, UnityEngine.Object objBeingEdited, System.Type objType, ObjectFieldValidator validator, bool allowSceneObjects, System.Type additionalType, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(10); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = dropRect; + __params__[2] = id; + __params__[3] = obj; + __params__[4] = objBeingEdited; + __params__[5] = objType; + __params__[6] = validator?.Cast(null); + __params__[7] = allowSceneObjects; + __params__[8] = additionalType; + __params__[9] = style; + var __result__ = __DoObjectField__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Object)(__result__) : default; + } + + public static UnityEngine.Object DoObjectField(UnityEngine.Rect position, UnityEngine.Rect dropRect, int id, System.Type objType, UnityEditor.SerializedProperty property, ObjectFieldValidator validator, bool allowSceneObjects, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(8); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = dropRect; + __params__[2] = id; + __params__[3] = objType; + __params__[4] = property; + __params__[5] = validator?.Cast(null); + __params__[6] = allowSceneObjects; + __params__[7] = style; + var __result__ = __DoObjectField__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Object)(__result__) : default; + } + + public static void PingObjectOrShowPreviewOnClick(UnityEngine.Object targetObject, UnityEngine.Rect position) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = targetObject; + __params__[1] = position; + __PingObjectOrShowPreviewOnClick?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void PingObjectInSceneViewOnClick(UnityEngine.Material targetMaterial) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = targetMaterial; + __PingObjectInSceneViewOnClick?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Object AssignSelectedObject(UnityEditor.SerializedProperty property, ObjectFieldValidator validator, System.Type objectType, UnityEngine.Event evt) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = property; + __params__[1] = validator?.Cast(null); + __params__[2] = objectType; + __params__[3] = evt; + var __result__ = __AssignSelectedObject?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Object)(__result__) : default; + } + + public static UnityEngine.Rect GetButtonRect(object visualType, UnityEngine.Rect position) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = visualType; + __params__[1] = position; + var __result__ = __GetButtonRect?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static bool HasValidScript(UnityEngine.Object obj) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = obj; + var __result__ = __HasValidScript?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool ValidDroppedObject(UnityEngine.Object[] references, System.Type objType, out string errorString) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = references; + __params__[1] = objType; + __params__[2] = null; + var __result__ = __ValidDroppedObject?.Invoke(null, __params__); + errorString = (string)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static UnityEngine.Object DoObjectField(UnityEngine.Rect position, UnityEngine.Rect dropRect, int id, UnityEngine.Object obj, System.Type objType, UnityEditor.SerializedProperty property, ObjectFieldValidator validator, bool allowSceneObjects, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(9); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = dropRect; + __params__[2] = id; + __params__[3] = obj; + __params__[4] = objType; + __params__[5] = property; + __params__[6] = validator?.Cast(null); + __params__[7] = allowSceneObjects; + __params__[8] = style; + var __result__ = __DoObjectField__4?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Object)(__result__) : default; + } + + public static UnityEngine.Object DoObjectField(UnityEngine.Rect position, UnityEngine.Rect dropRect, int id, UnityEngine.Object obj, UnityEngine.Object objBeingEdited, System.Type objType, UnityEditor.SerializedProperty property, ObjectFieldValidator validator, bool allowSceneObjects, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(10); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = dropRect; + __params__[2] = id; + __params__[3] = obj; + __params__[4] = objBeingEdited; + __params__[5] = objType; + __params__[6] = property; + __params__[7] = validator?.Cast(null); + __params__[8] = allowSceneObjects; + __params__[9] = style; + var __result__ = __DoObjectField__5?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Object)(__result__) : default; + } + + public static UnityEngine.Object DoObjectField(UnityEngine.Rect position, UnityEngine.Rect dropRect, int id, UnityEngine.Object obj, UnityEngine.Object objBeingEdited, System.Type objType, System.Type additionalType, UnityEditor.SerializedProperty property, ObjectFieldValidator validator, bool allowSceneObjects, UnityEngine.GUIStyle style, System.Action onObjectSelectorClosed, System.Action onObjectSelectedUpdated) + { + var __pool__ = FixedArrayPool.Shared(13); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = dropRect; + __params__[2] = id; + __params__[3] = obj; + __params__[4] = objBeingEdited; + __params__[5] = objType; + __params__[6] = additionalType; + __params__[7] = property; + __params__[8] = validator?.Cast(null); + __params__[9] = allowSceneObjects; + __params__[10] = style; + __params__[11] = onObjectSelectorClosed; + __params__[12] = onObjectSelectedUpdated; + var __result__ = __DoObjectField__6?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Object)(__result__) : default; + } + + public static UnityEngine.Object DoObjectField(UnityEngine.Rect position, UnityEngine.Rect dropRect, int id, UnityEngine.Object obj, UnityEngine.Object objBeingEdited, System.Type objType, System.Type additionalType, UnityEditor.SerializedProperty property, ObjectFieldValidator validator, bool allowSceneObjects, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(11); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = dropRect; + __params__[2] = id; + __params__[3] = obj; + __params__[4] = objBeingEdited; + __params__[5] = objType; + __params__[6] = additionalType; + __params__[7] = property; + __params__[8] = validator?.Cast(null); + __params__[9] = allowSceneObjects; + __params__[10] = style; + var __result__ = __DoObjectField__7?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Object)(__result__) : default; + } + + public static UnityEngine.Object DoObjectField(UnityEngine.Rect position, UnityEngine.Rect dropRect, int id, UnityEngine.Object obj, UnityEngine.Object objBeingEdited, System.Type objType, System.Type additionalType, UnityEditor.SerializedProperty property, ObjectFieldValidator validator, bool allowSceneObjects, UnityEngine.GUIStyle style, UnityEngine.GUIStyle buttonStyle, System.Action onObjectSelectorClosed, System.Action onObjectSelectedUpdated) + { + var __pool__ = FixedArrayPool.Shared(14); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = dropRect; + __params__[2] = id; + __params__[3] = obj; + __params__[4] = objBeingEdited; + __params__[5] = objType; + __params__[6] = additionalType; + __params__[7] = property; + __params__[8] = validator?.Cast(null); + __params__[9] = allowSceneObjects; + __params__[10] = style; + __params__[11] = buttonStyle; + __params__[12] = onObjectSelectorClosed; + __params__[13] = onObjectSelectedUpdated; + var __result__ = __DoObjectField__8?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Object)(__result__) : default; + } + + public static void DrawObjectFieldLargeThumb(UnityEngine.Rect position, int id, UnityEngine.Object obj, UnityEngine.GUIContent content) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = id; + __params__[2] = obj; + __params__[3] = content; + __DrawObjectFieldLargeThumb?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void DrawObjectFieldMiniThumb(UnityEngine.Rect position, int id, UnityEngine.Object obj, UnityEngine.GUIContent content) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = id; + __params__[2] = obj; + __params__[3] = content; + __DrawObjectFieldMiniThumb?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Object DoDropField(UnityEngine.Rect position, int id, System.Type objType, ObjectFieldValidator validator, bool allowSceneObjects, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = id; + __params__[2] = objType; + __params__[3] = validator?.Cast(null); + __params__[4] = allowSceneObjects; + __params__[5] = style; + var __result__ = __DoDropField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Object)(__result__) : default; + } + + public static void SliderWithTexture(UnityEngine.Rect position, UnityEngine.GUIContent label, UnityEditor.SerializedProperty property, float sliderMin, float sliderMax, float power, UnityEngine.Texture2D sliderBackground) + { + var __pool__ = FixedArrayPool.Shared(7); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = property; + __params__[3] = sliderMin; + __params__[4] = sliderMax; + __params__[5] = power; + __params__[6] = sliderBackground; + __SliderWithTexture?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static float SliderWithTexture(UnityEngine.Rect rect, UnityEngine.GUIContent label, float sliderValue, float sliderMin, float sliderMax, string formatString, UnityEngine.Texture2D sliderBackground, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(8); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = label; + __params__[2] = sliderValue; + __params__[3] = sliderMin; + __params__[4] = sliderMax; + __params__[5] = formatString; + __params__[6] = sliderBackground; + __params__[7] = options; + var __result__ = __SliderWithTexture__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float SliderWithTexture(UnityEngine.Rect position, UnityEngine.GUIContent label, float sliderValue, float sliderMin, float sliderMax, string formatString, float textFieldMin, float textFieldMax, float power, UnityEngine.Texture2D sliderBackground) + { + var __pool__ = FixedArrayPool.Shared(10); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = label; + __params__[2] = sliderValue; + __params__[3] = sliderMin; + __params__[4] = sliderMax; + __params__[5] = formatString; + __params__[6] = textFieldMin; + __params__[7] = textFieldMax; + __params__[8] = power; + __params__[9] = sliderBackground; + var __result__ = __SliderWithTexture__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static void TargetChoiceField(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __TargetChoiceField?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void TargetChoiceField(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEngine.GUIContent label, Delegate func) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = label; + __params__[3] = func; + __TargetChoiceField__2?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static string DoTextFieldDropDown(UnityEngine.Rect rect, int id, string text, string[] dropDownElements, bool delayed) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = id; + __params__[2] = text; + __params__[3] = dropDownElements; + __params__[4] = delayed; + var __result__ = __DoTextFieldDropDown?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static void PromptConfirmation(UnityEditor.SerializedObject serializedObject, UnityEditor.SerializedProperty serializedProperty, UnityEngine.Object selectedRenderPipelineAsset) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = serializedObject; + __params__[1] = serializedProperty; + __params__[2] = selectedRenderPipelineAsset; + __PromptConfirmation?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void RenderPipelineAssetField(UnityEngine.GUIContent content, UnityEditor.SerializedObject serializedObject, UnityEditor.SerializedProperty serializedProperty) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = content; + __params__[1] = serializedObject; + __params__[2] = serializedProperty; + __RenderPipelineAssetField?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void RenderPipelineAssetField(UnityEditor.SerializedObject serializedObject, UnityEditor.SerializedProperty serializedProperty) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = serializedObject; + __params__[1] = serializedProperty; + __RenderPipelineAssetField__2?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public UnityEditor_EditorGUI(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + public UnityEditor.EditorGUI __super__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.EditorGUI)(__self__); + } + + private static FieldInfo ___activeEditor; + private static FieldInfo __activeEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___activeEditor ??= __type__?.GetField("activeEditor", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_DelayedTextEditor; + private static FieldInfo __s_DelayedTextEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_DelayedTextEditor ??= __type__?.GetField("s_DelayedTextEditor", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_RecycledEditor; + private static FieldInfo __s_RecycledEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_RecycledEditor ??= __type__?.GetField("s_RecycledEditor", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_OriginalText; + private static FieldInfo __s_OriginalText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_OriginalText ??= __type__?.GetField("s_OriginalText", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_RecycledCurrentEditingString; + private static FieldInfo __s_RecycledCurrentEditingString + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_RecycledCurrentEditingString ??= __type__?.GetField("s_RecycledCurrentEditingString", (BindingFlags)(-1)); + } + + private static FieldInfo ___bKeyEventActive; + private static FieldInfo __bKeyEventActive + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___bKeyEventActive ??= __type__?.GetField("bKeyEventActive", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_DragToPosition; + private static FieldInfo __s_DragToPosition + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_DragToPosition ??= __type__?.GetField("s_DragToPosition", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_Dragged; + private static FieldInfo __s_Dragged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_Dragged ??= __type__?.GetField("s_Dragged", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_SelectAllOnMouseUp; + private static FieldInfo __s_SelectAllOnMouseUp + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_SelectAllOnMouseUp ??= __type__?.GetField("s_SelectAllOnMouseUp", (BindingFlags)(-1)); + } + + private static FieldInfo ___kFoldoutExpandTimeout; + private static FieldInfo __kFoldoutExpandTimeout + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kFoldoutExpandTimeout ??= __type__?.GetField("kFoldoutExpandTimeout", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_FoldoutDestTime; + private static FieldInfo __s_FoldoutDestTime + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_FoldoutDestTime ??= __type__?.GetField("s_FoldoutDestTime", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_DragUpdatedOverID; + private static FieldInfo __s_DragUpdatedOverID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_DragUpdatedOverID ??= __type__?.GetField("s_DragUpdatedOverID", (BindingFlags)(-1)); + } + + private static FieldInfo ___kSearchFieldTextLimit; + private static FieldInfo __kSearchFieldTextLimit + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kSearchFieldTextLimit ??= __type__?.GetField("kSearchFieldTextLimit", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_SearchFieldTextLimitApproved; + private static FieldInfo __s_SearchFieldTextLimitApproved + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_SearchFieldTextLimitApproved ??= __type__?.GetField("s_SearchFieldTextLimitApproved", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_SavekeyboardControl; + private static FieldInfo __s_SavekeyboardControl + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_SavekeyboardControl ??= __type__?.GetField("s_SavekeyboardControl", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_FoldoutHash; + private static FieldInfo __s_FoldoutHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_FoldoutHash ??= __type__?.GetField("s_FoldoutHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_TagFieldHash; + private static FieldInfo __s_TagFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_TagFieldHash ??= __type__?.GetField("s_TagFieldHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_PPtrHash; + private static FieldInfo __s_PPtrHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_PPtrHash ??= __type__?.GetField("s_PPtrHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ObjectFieldHash; + private static FieldInfo __s_ObjectFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ObjectFieldHash ??= __type__?.GetField("s_ObjectFieldHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ToggleHash; + private static FieldInfo __s_ToggleHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ToggleHash ??= __type__?.GetField("s_ToggleHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ColorHash; + private static FieldInfo __s_ColorHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ColorHash ??= __type__?.GetField("s_ColorHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_CurveHash; + private static FieldInfo __s_CurveHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_CurveHash ??= __type__?.GetField("s_CurveHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_LayerMaskField; + private static FieldInfo __s_LayerMaskField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LayerMaskField ??= __type__?.GetField("s_LayerMaskField", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_MaskField; + private static FieldInfo __s_MaskField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_MaskField ??= __type__?.GetField("s_MaskField", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_EnumFlagsField; + private static FieldInfo __s_EnumFlagsField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_EnumFlagsField ??= __type__?.GetField("s_EnumFlagsField", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_GenericField; + private static FieldInfo __s_GenericField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_GenericField ??= __type__?.GetField("s_GenericField", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_PopupHash; + private static FieldInfo __s_PopupHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_PopupHash ??= __type__?.GetField("s_PopupHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_KeyEventFieldHash; + private static FieldInfo __s_KeyEventFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_KeyEventFieldHash ??= __type__?.GetField("s_KeyEventFieldHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_TextFieldHash; + private static FieldInfo __s_TextFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_TextFieldHash ??= __type__?.GetField("s_TextFieldHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_SearchFieldHash; + private static FieldInfo __s_SearchFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_SearchFieldHash ??= __type__?.GetField("s_SearchFieldHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_TextAreaHash; + private static FieldInfo __s_TextAreaHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_TextAreaHash ??= __type__?.GetField("s_TextAreaHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_PasswordFieldHash; + private static FieldInfo __s_PasswordFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_PasswordFieldHash ??= __type__?.GetField("s_PasswordFieldHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_FloatFieldHash; + private static FieldInfo __s_FloatFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_FloatFieldHash ??= __type__?.GetField("s_FloatFieldHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_DelayedTextFieldHash; + private static FieldInfo __s_DelayedTextFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_DelayedTextFieldHash ??= __type__?.GetField("s_DelayedTextFieldHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ArraySizeFieldHash; + private static FieldInfo __s_ArraySizeFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ArraySizeFieldHash ??= __type__?.GetField("s_ArraySizeFieldHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_SliderHash; + private static FieldInfo __s_SliderHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_SliderHash ??= __type__?.GetField("s_SliderHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_SliderKnobHash; + private static FieldInfo __s_SliderKnobHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_SliderKnobHash ??= __type__?.GetField("s_SliderKnobHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_MinMaxSliderHash; + private static FieldInfo __s_MinMaxSliderHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_MinMaxSliderHash ??= __type__?.GetField("s_MinMaxSliderHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_TitlebarHash; + private static FieldInfo __s_TitlebarHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_TitlebarHash ??= __type__?.GetField("s_TitlebarHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ProgressBarHash; + private static FieldInfo __s_ProgressBarHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ProgressBarHash ??= __type__?.GetField("s_ProgressBarHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_SelectableLabelHash; + private static FieldInfo __s_SelectableLabelHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_SelectableLabelHash ??= __type__?.GetField("s_SelectableLabelHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_SortingLayerFieldHash; + private static FieldInfo __s_SortingLayerFieldHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_SortingLayerFieldHash ??= __type__?.GetField("s_SortingLayerFieldHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_TextFieldDropDownHash; + private static FieldInfo __s_TextFieldDropDownHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_TextFieldDropDownHash ??= __type__?.GetField("s_TextFieldDropDownHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_DragCandidateState; + private static FieldInfo __s_DragCandidateState + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_DragCandidateState ??= __type__?.GetField("s_DragCandidateState", (BindingFlags)(-1)); + } + + private static FieldInfo ___kDragDeadzone; + private static FieldInfo __kDragDeadzone + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kDragDeadzone ??= __type__?.GetField("kDragDeadzone", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_DragStartPos; + private static FieldInfo __s_DragStartPos + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_DragStartPos ??= __type__?.GetField("s_DragStartPos", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_DragStartValue; + private static FieldInfo __s_DragStartValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_DragStartValue ??= __type__?.GetField("s_DragStartValue", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_DragStartIntValue; + private static FieldInfo __s_DragStartIntValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_DragStartIntValue ??= __type__?.GetField("s_DragStartIntValue", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_DragSensitivity; + private static FieldInfo __s_DragSensitivity + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_DragSensitivity ??= __type__?.GetField("s_DragSensitivity", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_LargerChar; + private static FieldInfo __s_LargerChar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LargerChar ??= __type__?.GetField("s_LargerChar", (BindingFlags)(-1)); + } + + private static FieldInfo ___kPrefixPaddingRight; + private static FieldInfo __kPrefixPaddingRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kPrefixPaddingRight ??= __type__?.GetField("kPrefixPaddingRight", (BindingFlags)(-1)); + } + + private static FieldInfo ___kLabelW; + private static FieldInfo __kLabelW + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kLabelW ??= __type__?.GetField("kLabelW", (BindingFlags)(-1)); + } + + private static FieldInfo ___kSpacing; + private static FieldInfo __kSpacing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kSpacing ??= __type__?.GetField("kSpacing", (BindingFlags)(-1)); + } + + private static FieldInfo ___kSpacingSubLabel; + private static FieldInfo __kSpacingSubLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kSpacingSubLabel ??= __type__?.GetField("kSpacingSubLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___kSliderMinW; + private static FieldInfo __kSliderMinW + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kSliderMinW ??= __type__?.GetField("kSliderMinW", (BindingFlags)(-1)); + } + + private static FieldInfo ___kSliderMaxW; + private static FieldInfo __kSliderMaxW + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kSliderMaxW ??= __type__?.GetField("kSliderMaxW", (BindingFlags)(-1)); + } + + private static FieldInfo ___kSingleLineHeight; + private static FieldInfo __kSingleLineHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kSingleLineHeight ??= __type__?.GetField("kSingleLineHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___kSingleSmallLineHeight; + private static FieldInfo __kSingleSmallLineHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kSingleSmallLineHeight ??= __type__?.GetField("kSingleSmallLineHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___kStructHeaderLineHeight; + private static FieldInfo __kStructHeaderLineHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kStructHeaderLineHeight ??= __type__?.GetField("kStructHeaderLineHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___kObjectFieldThumbnailHeight; + private static FieldInfo __kObjectFieldThumbnailHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kObjectFieldThumbnailHeight ??= __type__?.GetField("kObjectFieldThumbnailHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___kObjectFieldMiniThumbnailHeight; + private static FieldInfo __kObjectFieldMiniThumbnailHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kObjectFieldMiniThumbnailHeight ??= __type__?.GetField("kObjectFieldMiniThumbnailHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___kObjectFieldMiniThumbnailWidth; + private static FieldInfo __kObjectFieldMiniThumbnailWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kObjectFieldMiniThumbnailWidth ??= __type__?.GetField("kObjectFieldMiniThumbnailWidth", (BindingFlags)(-1)); + } + + private static FieldInfo ___kFloatFieldFormatString; + private static FieldInfo __kFloatFieldFormatString + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kFloatFieldFormatString ??= __type__?.GetField("kFloatFieldFormatString", (BindingFlags)(-1)); + } + + private static FieldInfo ___kDoubleFieldFormatString; + private static FieldInfo __kDoubleFieldFormatString + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kDoubleFieldFormatString ??= __type__?.GetField("kDoubleFieldFormatString", (BindingFlags)(-1)); + } + + private static FieldInfo ___kIntFieldFormatString; + private static FieldInfo __kIntFieldFormatString + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kIntFieldFormatString ??= __type__?.GetField("kIntFieldFormatString", (BindingFlags)(-1)); + } + + private static FieldInfo ___ms_IndentLevel; + private static FieldInfo __ms_IndentLevel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ms_IndentLevel ??= __type__?.GetField("ms_IndentLevel", (BindingFlags)(-1)); + } + + private static FieldInfo ___kIndentPerLevel; + private static FieldInfo __kIndentPerLevel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kIndentPerLevel ??= __type__?.GetField("kIndentPerLevel", (BindingFlags)(-1)); + } + + private static FieldInfo ___kControlVerticalSpacingLegacy; + private static FieldInfo __kControlVerticalSpacingLegacy + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kControlVerticalSpacingLegacy ??= __type__?.GetField("kControlVerticalSpacingLegacy", (BindingFlags)(-1)); + } + + private static FieldInfo ___kDefaultSpacing; + private static FieldInfo __kDefaultSpacing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kDefaultSpacing ??= __type__?.GetField("kDefaultSpacing", (BindingFlags)(-1)); + } + + private static FieldInfo ___kControlVerticalSpacing; + private static FieldInfo __kControlVerticalSpacing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kControlVerticalSpacing ??= __type__?.GetField("kControlVerticalSpacing", (BindingFlags)(-1)); + } + + private static FieldInfo ___kVerticalSpacingMultiField; + private static FieldInfo __kVerticalSpacingMultiField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kVerticalSpacingMultiField ??= __type__?.GetField("kVerticalSpacingMultiField", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_UnitString; + private static FieldInfo __s_UnitString + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_UnitString ??= __type__?.GetField("s_UnitString", (BindingFlags)(-1)); + } + + private static FieldInfo ___kInspTitlebarIconWidth; + private static FieldInfo __kInspTitlebarIconWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kInspTitlebarIconWidth ??= __type__?.GetField("kInspTitlebarIconWidth", (BindingFlags)(-1)); + } + + private static FieldInfo ___kInspTitlebarFoldoutIconWidth; + private static FieldInfo __kInspTitlebarFoldoutIconWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kInspTitlebarFoldoutIconWidth ??= __type__?.GetField("kInspTitlebarFoldoutIconWidth", (BindingFlags)(-1)); + } + + private static FieldInfo ___kWindowToolbarHeight; + private static FieldInfo __kWindowToolbarHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kWindowToolbarHeight ??= __type__?.GetField("kWindowToolbarHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___kTabButtonHeight; + private static FieldInfo __kTabButtonHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kTabButtonHeight ??= __type__?.GetField("kTabButtonHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___kEnabledPropertyName; + private static FieldInfo __kEnabledPropertyName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kEnabledPropertyName ??= __type__?.GetField("kEnabledPropertyName", (BindingFlags)(-1)); + } + + private static FieldInfo ___k_MultiEditValueString; + private static FieldInfo __k_MultiEditValueString + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___k_MultiEditValueString ??= __type__?.GetField("k_MultiEditValueString", (BindingFlags)(-1)); + } + + private static FieldInfo ___kDropDownArrowMargin; + private static FieldInfo __kDropDownArrowMargin + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kDropDownArrowMargin ??= __type__?.GetField("kDropDownArrowMargin", (BindingFlags)(-1)); + } + + private static FieldInfo ___kDropDownArrowWidth; + private static FieldInfo __kDropDownArrowWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kDropDownArrowWidth ??= __type__?.GetField("kDropDownArrowWidth", (BindingFlags)(-1)); + } + + private static FieldInfo ___kDropDownArrowHeight; + private static FieldInfo __kDropDownArrowHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kDropDownArrowHeight ??= __type__?.GetField("kDropDownArrowHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_Vector2Floats; + private static FieldInfo __s_Vector2Floats + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_Vector2Floats ??= __type__?.GetField("s_Vector2Floats", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_Vector2Ints; + private static FieldInfo __s_Vector2Ints + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_Vector2Ints ??= __type__?.GetField("s_Vector2Ints", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_XYLabels; + private static FieldInfo __s_XYLabels + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_XYLabels ??= __type__?.GetField("s_XYLabels", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_Vector3Floats; + private static FieldInfo __s_Vector3Floats + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_Vector3Floats ??= __type__?.GetField("s_Vector3Floats", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_Vector3Ints; + private static FieldInfo __s_Vector3Ints + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_Vector3Ints ??= __type__?.GetField("s_Vector3Ints", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_XYZLabels; + private static FieldInfo __s_XYZLabels + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_XYZLabels ??= __type__?.GetField("s_XYZLabels", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_Vector4Floats; + private static FieldInfo __s_Vector4Floats + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_Vector4Floats ??= __type__?.GetField("s_Vector4Floats", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_XYZWLabels; + private static FieldInfo __s_XYZWLabels + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_XYZWLabels ??= __type__?.GetField("s_XYZWLabels", (BindingFlags)(-1)); + } + + private static FieldInfo ___kQuaternionFloatPrecision; + private static FieldInfo __kQuaternionFloatPrecision + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kQuaternionFloatPrecision ??= __type__?.GetField("kQuaternionFloatPrecision", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_WHLabels; + private static FieldInfo __s_WHLabels + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_WHLabels ??= __type__?.GetField("s_WHLabels", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_CenterLabel; + private static FieldInfo __s_CenterLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_CenterLabel ??= __type__?.GetField("s_CenterLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ExtentLabel; + private static FieldInfo __s_ExtentLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ExtentLabel ??= __type__?.GetField("s_ExtentLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_PositionLabel; + private static FieldInfo __s_PositionLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_PositionLabel ??= __type__?.GetField("s_PositionLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_SizeLabel; + private static FieldInfo __s_SizeLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_SizeLabel ??= __type__?.GetField("s_SizeLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_PleasePressAKey; + private static FieldInfo __s_PleasePressAKey + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_PleasePressAKey ??= __type__?.GetField("s_PleasePressAKey", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_PrefabInContextPreviewValuesTooltip; + private static FieldInfo __s_PrefabInContextPreviewValuesTooltip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_PrefabInContextPreviewValuesTooltip ??= __type__?.GetField("s_PrefabInContextPreviewValuesTooltip", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ClipingPlanesLabel; + private static FieldInfo __s_ClipingPlanesLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ClipingPlanesLabel ??= __type__?.GetField("s_ClipingPlanesLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_NearAndFarLabels; + private static FieldInfo __s_NearAndFarLabels + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_NearAndFarLabels ??= __type__?.GetField("s_NearAndFarLabels", (BindingFlags)(-1)); + } + + private static FieldInfo ___kNearFarLabelsWidth; + private static FieldInfo __kNearFarLabelsWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kNearFarLabelsWidth ??= __type__?.GetField("kNearFarLabelsWidth", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ColorPickID; + private static FieldInfo __s_ColorPickID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ColorPickID ??= __type__?.GetField("s_ColorPickID", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_CurveID; + private static FieldInfo __s_CurveID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_CurveID ??= __type__?.GetField("s_CurveID", (BindingFlags)(-1)); + } + + private static FieldInfo ___kCurveColor; + private static FieldInfo __kCurveColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kCurveColor ??= __type__?.GetField("kCurveColor", (BindingFlags)(-1)); + } + + private static FieldInfo ___kCurveBGColor; + private static FieldInfo __kCurveBGColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kCurveBGColor ??= __type__?.GetField("kCurveBGColor", (BindingFlags)(-1)); + } + + private static FieldInfo ___kSplitLineSkinnedColor; + private static FieldInfo __kSplitLineSkinnedColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kSplitLineSkinnedColor ??= __type__?.GetField("kSplitLineSkinnedColor", (BindingFlags)(-1)); + } + + private static FieldInfo ___k_OverrideMarginColor; + private static FieldInfo __k_OverrideMarginColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___k_OverrideMarginColor ??= __type__?.GetField("k_OverrideMarginColor", (BindingFlags)(-1)); + } + + private static FieldInfo ___k_OverrideMarginColorSelected; + private static FieldInfo __k_OverrideMarginColorSelected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___k_OverrideMarginColorSelected ??= __type__?.GetField("k_OverrideMarginColorSelected", (BindingFlags)(-1)); + } + + private static FieldInfo ___kInspTitlebarSpacing; + private static FieldInfo __kInspTitlebarSpacing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kInspTitlebarSpacing ??= __type__?.GetField("kInspTitlebarSpacing", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_PropertyFieldTempContent; + private static FieldInfo __s_PropertyFieldTempContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_PropertyFieldTempContent ??= __type__?.GetField("s_PropertyFieldTempContent", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_IconDropDown; + private static FieldInfo __s_IconDropDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_IconDropDown ??= __type__?.GetField("s_IconDropDown", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_IconTextureInactive; + private static FieldInfo __s_IconTextureInactive + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_IconTextureInactive ??= __type__?.GetField("s_IconTextureInactive", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_HasPrefixLabel; + private static FieldInfo __s_HasPrefixLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_HasPrefixLabel ??= __type__?.GetField("s_HasPrefixLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_PrefixLabel; + private static FieldInfo __s_PrefixLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_PrefixLabel ??= __type__?.GetField("s_PrefixLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_PrefixTotalRect; + private static FieldInfo __s_PrefixTotalRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_PrefixTotalRect ??= __type__?.GetField("s_PrefixTotalRect", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_PrefixRect; + private static FieldInfo __s_PrefixRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_PrefixRect ??= __type__?.GetField("s_PrefixRect", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_PrefixStyle; + private static FieldInfo __s_PrefixStyle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_PrefixStyle ??= __type__?.GetField("s_PrefixStyle", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_IconButtonStyle; + private static FieldInfo __s_IconButtonStyle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_IconButtonStyle ??= __type__?.GetField("s_IconButtonStyle", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_PrefixGUIColor; + private static FieldInfo __s_PrefixGUIColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_PrefixGUIColor ??= __type__?.GetField("s_PrefixGUIColor", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_LabelHighlightContext; + private static FieldInfo __s_LabelHighlightContext + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LabelHighlightContext ??= __type__?.GetField("s_LabelHighlightContext", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_LabelHighlightColor; + private static FieldInfo __s_LabelHighlightColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LabelHighlightColor ??= __type__?.GetField("s_LabelHighlightColor", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_LabelHighlightSelectionColor; + private static FieldInfo __s_LabelHighlightSelectionColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LabelHighlightSelectionColor ??= __type__?.GetField("s_LabelHighlightSelectionColor", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_FlagNames; + private static FieldInfo __m_FlagNames + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_FlagNames ??= __type__?.GetField("m_FlagNames", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_FlagValues; + private static FieldInfo __m_FlagValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_FlagValues ??= __type__?.GetField("m_FlagValues", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_MixedValueContent; + private static FieldInfo __s_MixedValueContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_MixedValueContent ??= __type__?.GetField("s_MixedValueContent", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_MixedValueContentColor; + private static FieldInfo __s_MixedValueContentColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_MixedValueContentColor ??= __type__?.GetField("s_MixedValueContentColor", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_MixedValueContentColorTemp; + private static FieldInfo __s_MixedValueContentColorTemp + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_MixedValueContentColorTemp ??= __type__?.GetField("s_MixedValueContentColorTemp", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ShowRepaintDots; + private static FieldInfo __s_ShowRepaintDots + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ShowRepaintDots ??= __type__?.GetField("s_ShowRepaintDots", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_PropertyStack; + private static FieldInfo __s_PropertyStack + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_PropertyStack ??= __type__?.GetField("s_PropertyStack", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_EnabledStack; + private static FieldInfo __s_EnabledStack + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_EnabledStack ??= __type__?.GetField("s_EnabledStack", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_IsInsideListStack; + private static FieldInfo __s_IsInsideListStack + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_IsInsideListStack ??= __type__?.GetField("s_IsInsideListStack", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ChangedStack; + private static FieldInfo __s_ChangedStack + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ChangedStack ??= __type__?.GetField("s_ChangedStack", (BindingFlags)(-1)); + } + + private static FieldInfo ___hyperLinkClicked; + private static FieldInfo __hyperLinkClicked + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___hyperLinkClicked ??= __type__?.GetField("hyperLinkClicked", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_AllowedCharactersForFloat; + private static FieldInfo __s_AllowedCharactersForFloat + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_AllowedCharactersForFloat ??= __type__?.GetField("s_AllowedCharactersForFloat", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_AllowedCharactersForInt; + private static FieldInfo __s_AllowedCharactersForInt + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_AllowedCharactersForInt ??= __type__?.GetField("s_AllowedCharactersForInt", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_CurrentCheckEnumEnabled; + private static FieldInfo __s_CurrentCheckEnumEnabled + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_CurrentCheckEnumEnabled ??= __type__?.GetField("s_CurrentCheckEnumEnabled", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_CurrentEnumData; + private static FieldInfo __s_CurrentEnumData + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_CurrentEnumData ??= __type__?.GetField("s_CurrentEnumData", (BindingFlags)(-1)); + } + + private static FieldInfo ___kEyedropperSize; + private static FieldInfo __kEyedropperSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kEyedropperSize ??= __type__?.GetField("kEyedropperSize", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_PendingPropertyKeyboardHandling; + private static FieldInfo __s_PendingPropertyKeyboardHandling + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_PendingPropertyKeyboardHandling ??= __type__?.GetField("s_PendingPropertyKeyboardHandling", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_PendingPropertyDelete; + private static FieldInfo __s_PendingPropertyDelete + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_PendingPropertyDelete ??= __type__?.GetField("s_PendingPropertyDelete", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_LayerNames; + private static FieldInfo __s_LayerNames + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LayerNames ??= __type__?.GetField("s_LayerNames", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_LayerValues; + private static FieldInfo __s_LayerValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LayerValues ??= __type__?.GetField("s_LayerValues", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ArrayMultiInfoFormatString; + private static FieldInfo __s_ArrayMultiInfoFormatString + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ArrayMultiInfoFormatString ??= __type__?.GetField("s_ArrayMultiInfoFormatString", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ArrayMultiInfoContent; + private static FieldInfo __s_ArrayMultiInfoContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ArrayMultiInfoContent ??= __type__?.GetField("s_ArrayMultiInfoContent", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_EvalExpressionMarker; + private static FieldInfo __s_EvalExpressionMarker + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_EvalExpressionMarker ??= __type__?.GetField("s_EvalExpressionMarker", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_CollectingToolTips; + private static FieldInfo __s_CollectingToolTips + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_CollectingToolTips ??= __type__?.GetField("s_CollectingToolTips", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_FoldoutHeaderGroupActive; + private static FieldInfo __s_FoldoutHeaderGroupActive + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_FoldoutHeaderGroupActive ??= __type__?.GetField("s_FoldoutHeaderGroupActive", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_FoldoutHeaderHash; + private static FieldInfo __s_FoldoutHeaderHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_FoldoutHeaderHash ??= __type__?.GetField("s_FoldoutHeaderHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_GradientHash; + private static FieldInfo __s_GradientHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_GradientHash ??= __type__?.GetField("s_GradientHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_GradientID; + private static FieldInfo __s_GradientID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_GradientID ??= __type__?.GetField("s_GradientID", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_DropdownButtonHash; + private static FieldInfo __s_DropdownButtonHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_DropdownButtonHash ??= __type__?.GetField("s_DropdownButtonHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_MouseDeltaReaderHash; + private static FieldInfo __s_MouseDeltaReaderHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_MouseDeltaReaderHash ??= __type__?.GetField("s_MouseDeltaReaderHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_MouseDeltaReaderLastPos; + private static FieldInfo __s_MouseDeltaReaderLastPos + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_MouseDeltaReaderLastPos ??= __type__?.GetField("s_MouseDeltaReaderLastPos", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_SceneMismatch; + private static FieldInfo __s_SceneMismatch + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_SceneMismatch ??= __type__?.GetField("s_SceneMismatch", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_TypeMismatch; + private static FieldInfo __s_TypeMismatch + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_TypeMismatch ??= __type__?.GetField("s_TypeMismatch", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_Select; + private static FieldInfo __s_Select + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_Select ??= __type__?.GetField("s_Select", (BindingFlags)(-1)); + } + + private static FieldInfo ___kEmptyDropDownElement; + private static FieldInfo __kEmptyDropDownElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kEmptyDropDownElement ??= __type__?.GetField("kEmptyDropDownElement", (BindingFlags)(-1)); + } + + private static PropertyInfo ___kMiniLabelW; + private static PropertyInfo __kMiniLabelW + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kMiniLabelW ??= __type__?.GetProperty("kMiniLabelW", (BindingFlags)(-1)); + } + + private static PropertyInfo ___lineHeight; + private static PropertyInfo __lineHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___lineHeight ??= __type__?.GetProperty("lineHeight", (BindingFlags)(-1)); + } + + private static PropertyInfo ___mixedValueContent; + private static PropertyInfo __mixedValueContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___mixedValueContent ??= __type__?.GetProperty("mixedValueContent", (BindingFlags)(-1)); + } + + private static PropertyInfo ___indent; + private static PropertyInfo __indent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___indent ??= __type__?.GetProperty("indent", (BindingFlags)(-1)); + } + + private static PropertyInfo ___transparentCheckerTexture; + private static PropertyInfo __transparentCheckerTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___transparentCheckerTexture ??= __type__?.GetProperty("transparentCheckerTexture", (BindingFlags)(-1)); + } + + private static PropertyInfo ___colorMaterial; + private static PropertyInfo __colorMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___colorMaterial ??= __type__?.GetProperty("colorMaterial", (BindingFlags)(-1)); + } + + private static PropertyInfo ___colorVTMaterial; + private static PropertyInfo __colorVTMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___colorVTMaterial ??= __type__?.GetProperty("colorVTMaterial", (BindingFlags)(-1)); + } + + private static PropertyInfo ___alphaMaterial; + private static PropertyInfo __alphaMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___alphaMaterial ??= __type__?.GetProperty("alphaMaterial", (BindingFlags)(-1)); + } + + private static PropertyInfo ___alphaVTMaterial; + private static PropertyInfo __alphaVTMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___alphaVTMaterial ??= __type__?.GetProperty("alphaVTMaterial", (BindingFlags)(-1)); + } + + private static PropertyInfo ___transparentMaterial; + private static PropertyInfo __transparentMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___transparentMaterial ??= __type__?.GetProperty("transparentMaterial", (BindingFlags)(-1)); + } + + private static PropertyInfo ___transparentVTMaterial; + private static PropertyInfo __transparentVTMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___transparentVTMaterial ??= __type__?.GetProperty("transparentVTMaterial", (BindingFlags)(-1)); + } + + private static PropertyInfo ___normalmapMaterial; + private static PropertyInfo __normalmapMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___normalmapMaterial ??= __type__?.GetProperty("normalmapMaterial", (BindingFlags)(-1)); + } + + private static PropertyInfo ___normalmapVTMaterial; + private static PropertyInfo __normalmapVTMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___normalmapVTMaterial ??= __type__?.GetProperty("normalmapVTMaterial", (BindingFlags)(-1)); + } + + private static PropertyInfo ___lightmapRGBMMaterial; + private static PropertyInfo __lightmapRGBMMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___lightmapRGBMMaterial ??= __type__?.GetProperty("lightmapRGBMMaterial", (BindingFlags)(-1)); + } + + private static PropertyInfo ___lightmapDoubleLDRMaterial; + private static PropertyInfo __lightmapDoubleLDRMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___lightmapDoubleLDRMaterial ??= __type__?.GetProperty("lightmapDoubleLDRMaterial", (BindingFlags)(-1)); + } + + private static PropertyInfo ___lightmapFullHDRMaterial; + private static PropertyInfo __lightmapFullHDRMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___lightmapFullHDRMaterial ??= __type__?.GetProperty("lightmapFullHDRMaterial", (BindingFlags)(-1)); + } + + private static PropertyInfo ___guiTextureClipVerticallyMaterial; + private static PropertyInfo __guiTextureClipVerticallyMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___guiTextureClipVerticallyMaterial ??= __type__?.GetProperty("guiTextureClipVerticallyMaterial", (BindingFlags)(-1)); + } + + private static PropertyInfo ___isCollectingTooltips; + private static PropertyInfo __isCollectingTooltips + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___isCollectingTooltips ??= __type__?.GetProperty("isCollectingTooltips", (BindingFlags)(-1)); + } + + private static MethodInfo ___BeginHandleMixedValueContentColor; + private static MethodInfo __BeginHandleMixedValueContentColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginHandleMixedValueContentColor ??= __type__?.GetMethodInfoByParameterTypeNames("BeginHandleMixedValueContentColor"); + } + + private static MethodInfo ___EndHandleMixedValueContentColor; + private static MethodInfo __EndHandleMixedValueContentColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EndHandleMixedValueContentColor ??= __type__?.GetMethodInfoByParameterTypeNames("EndHandleMixedValueContentColor"); + } + + private static MethodInfo ___IsEditingTextField; + private static MethodInfo __IsEditingTextField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsEditingTextField ??= __type__?.GetMethodInfoByParameterTypeNames("IsEditingTextField"); + } + + private static MethodInfo ___EndEditingActiveTextField; + private static MethodInfo __EndEditingActiveTextField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EndEditingActiveTextField ??= __type__?.GetMethodInfoByParameterTypeNames("EndEditingActiveTextField"); + } + + private static MethodInfo ___ClearStacks; + private static MethodInfo __ClearStacks + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ClearStacks ??= __type__?.GetMethodInfoByParameterTypeNames("ClearStacks"); + } + + private static MethodInfo ___BeginDisabled; + private static MethodInfo __BeginDisabled + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginDisabled ??= __type__?.GetMethodInfoByParameterTypeNames("BeginDisabled", "System.Boolean"); + } + + private static MethodInfo ___EndDisabled; + private static MethodInfo __EndDisabled + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EndDisabled ??= __type__?.GetMethodInfoByParameterTypeNames("EndDisabled"); + } + + private static MethodInfo ___BeginIsInsideList; + private static MethodInfo __BeginIsInsideList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginIsInsideList ??= __type__?.GetMethodInfoByParameterTypeNames("BeginIsInsideList", "System.Int32"); + } + + private static MethodInfo ___GetInsideListDepth; + private static MethodInfo __GetInsideListDepth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetInsideListDepth ??= __type__?.GetMethodInfoByParameterTypeNames("GetInsideListDepth"); + } + + private static MethodInfo ___EndIsInsideList; + private static MethodInfo __EndIsInsideList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EndIsInsideList ??= __type__?.GetMethodInfoByParameterTypeNames("EndIsInsideList"); + } + + private static MethodInfo ___ShowTextEditorPopupMenu; + private static MethodInfo __ShowTextEditorPopupMenu + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShowTextEditorPopupMenu ??= __type__?.GetMethodInfoByParameterTypeNames("ShowTextEditorPopupMenu"); + } + + private static MethodInfo ___BeginCollectTooltips; + private static MethodInfo __BeginCollectTooltips + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginCollectTooltips ??= __type__?.GetMethodInfoByParameterTypeNames("BeginCollectTooltips"); + } + + private static MethodInfo ___EndCollectTooltips; + private static MethodInfo __EndCollectTooltips + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EndCollectTooltips ??= __type__?.GetMethodInfoByParameterTypeNames("EndCollectTooltips"); + } + + private static MethodInfo ___DoDropShadowLabel; + private static MethodInfo __DoDropShadowLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoDropShadowLabel ??= __type__?.GetMethodInfoByParameterTypeNames("DoDropShadowLabel", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEngine.GUIStyle", "System.Single"); + } + + private static MethodInfo ___DrawLabelShadow; + private static MethodInfo __DrawLabelShadow + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawLabelShadow ??= __type__?.GetMethodInfoByParameterTypeNames("DrawLabelShadow", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEngine.GUIStyle", "System.Single"); + } + + private static MethodInfo ___Draw4; + private static MethodInfo __Draw4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Draw4 ??= __type__?.GetMethodInfoByParameterTypeNames("Draw4", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Single", "System.Single", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___ValidateTextLimit; + private static MethodInfo __ValidateTextLimit + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ValidateTextLimit ??= __type__?.GetMethodInfoByParameterTypeNames("ValidateTextLimit", "System.String"); + } + + private static MethodInfo ___IsPrintableChar; + private static MethodInfo __IsPrintableChar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsPrintableChar ??= __type__?.GetMethodInfoByParameterTypeNames("IsPrintableChar", "System.Char"); + } + + private static MethodInfo ___MightBePrintableKey; + private static MethodInfo __MightBePrintableKey + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MightBePrintableKey ??= __type__?.GetMethodInfoByParameterTypeNames("MightBePrintableKey", "UnityEngine.Event"); + } + + private static MethodInfo ___GetEventTypeForControlAllowDisabledContextMenuPaste; + private static MethodInfo __GetEventTypeForControlAllowDisabledContextMenuPaste + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetEventTypeForControlAllowDisabledContextMenuPaste ??= __type__?.GetMethodInfoByParameterTypeNames("GetEventTypeForControlAllowDisabledContextMenuPaste", "UnityEngine.Event", "System.Int32"); + } + + private static MethodInfo ___DoTextField; + private static MethodInfo __DoTextField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoTextField ??= __type__?.GetMethodInfoByParameterTypeNames("DoTextField", "UnityEditor.EditorGUI+RecycledTextEditor", "System.Int32", "UnityEngine.Rect", "System.String", "UnityEngine.GUIStyle", "System.String", "System.Boolean&", "System.Boolean", "System.Boolean", "System.Boolean"); + } + + private static MethodInfo ___DoTextField__2; + private static MethodInfo __DoTextField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoTextField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DoTextField", "UnityEditor.EditorGUI+RecycledTextEditor", "System.Int32", "UnityEngine.Rect", "System.String", "UnityEngine.GUIStyle", "System.String", "System.Boolean&", "System.Boolean", "System.Boolean", "System.Boolean", "UnityEngine.GUIStyle", "System.Boolean"); + } + + private static MethodInfo ___HasClickedOnHyperlink; + private static MethodInfo __HasClickedOnHyperlink + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasClickedOnHyperlink ??= __type__?.GetMethodInfoByParameterTypeNames("HasClickedOnHyperlink", "System.String", "System.Int32", "UnityEditor.EditorGUI+RecycledTextEditor", "System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]&"); + } + + private static MethodInfo ___EditorGUI_OpenFileOnHyperLinkClicked; + private static MethodInfo __EditorGUI_OpenFileOnHyperLinkClicked + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EditorGUI_OpenFileOnHyperLinkClicked ??= __type__?.GetMethodInfoByParameterTypeNames("EditorGUI_OpenFileOnHyperLinkClicked", "UnityEditor.EditorWindow", "UnityEditor.HyperLinkClickedEventArgs"); + } + + private static MethodInfo ___KeyEventField; + private static MethodInfo __KeyEventField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___KeyEventField ??= __type__?.GetMethodInfoByParameterTypeNames("KeyEventField", "UnityEngine.Rect", "UnityEngine.Event"); + } + + private static MethodInfo ___DoKeyEventField; + private static MethodInfo __DoKeyEventField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoKeyEventField ??= __type__?.GetMethodInfoByParameterTypeNames("DoKeyEventField", "UnityEngine.Rect", "UnityEngine.Event", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___GetInspectorTitleBarObjectFoldoutRenderRect; + private static MethodInfo __GetInspectorTitleBarObjectFoldoutRenderRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetInspectorTitleBarObjectFoldoutRenderRect ??= __type__?.GetMethodInfoByParameterTypeNames("GetInspectorTitleBarObjectFoldoutRenderRect", "UnityEngine.Rect"); + } + + private static MethodInfo ___GetInspectorTitleBarObjectFoldoutRenderRect__2; + private static MethodInfo __GetInspectorTitleBarObjectFoldoutRenderRect__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetInspectorTitleBarObjectFoldoutRenderRect__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GetInspectorTitleBarObjectFoldoutRenderRect", "UnityEngine.Rect", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___IsValidForContextMenu; + private static MethodInfo __IsValidForContextMenu + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsValidForContextMenu ??= __type__?.GetMethodInfoByParameterTypeNames("IsValidForContextMenu", "UnityEngine.Object"); + } + + private static MethodInfo ___DoObjectMouseInteraction; + private static MethodInfo __DoObjectMouseInteraction + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoObjectMouseInteraction ??= __type__?.GetMethodInfoByParameterTypeNames("DoObjectMouseInteraction", "System.Boolean", "UnityEngine.Rect", "UnityEngine.Object[]", "System.Int32"); + } + + private static MethodInfo ___DoObjectFoldoutInternal; + private static MethodInfo __DoObjectFoldoutInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoObjectFoldoutInternal ??= __type__?.GetMethodInfoByParameterTypeNames("DoObjectFoldoutInternal", "System.Boolean", "UnityEngine.Rect", "System.Int32"); + } + + private static MethodInfo ___DoObjectFoldout; + private static MethodInfo __DoObjectFoldout + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoObjectFoldout ??= __type__?.GetMethodInfoByParameterTypeNames("DoObjectFoldout", "System.Boolean", "UnityEngine.Rect", "UnityEngine.Rect", "UnityEngine.Object[]", "System.Int32"); + } + + private static MethodInfo ___LabelFieldInternal; + private static MethodInfo __LabelFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LabelFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("LabelFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEngine.GUIContent", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___ToggleLeftInternal; + private static MethodInfo __ToggleLeftInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ToggleLeftInternal ??= __type__?.GetMethodInfoByParameterTypeNames("ToggleLeftInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Boolean", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DoToggle; + private static MethodInfo __DoToggle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoToggle ??= __type__?.GetMethodInfoByParameterTypeNames("DoToggle", "UnityEngine.Rect", "System.Int32", "System.Boolean", "UnityEngine.GUIContent", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___TextFieldInternal; + private static MethodInfo __TextFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TextFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("TextFieldInternal", "System.Int32", "UnityEngine.Rect", "System.String", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___TextFieldInternal__2; + private static MethodInfo __TextFieldInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TextFieldInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("TextFieldInternal", "System.Int32", "UnityEngine.Rect", "System.String", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___TextFieldInternal__3; + private static MethodInfo __TextFieldInternal__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TextFieldInternal__3 ??= __type__?.GetMethodInfoByParameterTypeNames("TextFieldInternal", "UnityEngine.Rect", "System.String", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___TextFieldInternal__4; + private static MethodInfo __TextFieldInternal__4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TextFieldInternal__4 ??= __type__?.GetMethodInfoByParameterTypeNames("TextFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.String", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___TextFieldInternal__5; + private static MethodInfo __TextFieldInternal__5 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TextFieldInternal__5 ??= __type__?.GetMethodInfoByParameterTypeNames("TextFieldInternal", "System.Int32", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.String", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___ToolbarSearchField; + private static MethodInfo __ToolbarSearchField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ToolbarSearchField ??= __type__?.GetMethodInfoByParameterTypeNames("ToolbarSearchField", "UnityEngine.Rect", "System.String", "System.Boolean"); + } + + private static MethodInfo ___ToolbarSearchField__2; + private static MethodInfo __ToolbarSearchField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ToolbarSearchField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("ToolbarSearchField", "System.Int32", "UnityEngine.Rect", "System.String", "System.Boolean"); + } + + private static MethodInfo ___ToolbarSearchField__3; + private static MethodInfo __ToolbarSearchField__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ToolbarSearchField__3 ??= __type__?.GetMethodInfoByParameterTypeNames("ToolbarSearchField", "System.Int32", "UnityEngine.Rect", "System.String", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___ToolbarSearchField__4; + private static MethodInfo __ToolbarSearchField__4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ToolbarSearchField__4 ??= __type__?.GetMethodInfoByParameterTypeNames("ToolbarSearchField", "UnityEngine.Rect", "System.String[]", "System.Int32&", "System.String"); + } + + private static MethodInfo ___ToolbarSearchField__5; + private static MethodInfo __ToolbarSearchField__5 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ToolbarSearchField__5 ??= __type__?.GetMethodInfoByParameterTypeNames("ToolbarSearchField", "System.Int32", "UnityEngine.Rect", "System.String[]", "System.Int32&", "System.String"); + } + + private static MethodInfo ___ToolbarSearchField__6; + private static MethodInfo __ToolbarSearchField__6 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ToolbarSearchField__6 ??= __type__?.GetMethodInfoByParameterTypeNames("ToolbarSearchField", "System.Int32", "UnityEngine.Rect", "System.String[]", "System.Int32&", "System.String", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___SearchField; + private static MethodInfo __SearchField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SearchField ??= __type__?.GetMethodInfoByParameterTypeNames("SearchField", "UnityEngine.Rect", "System.String"); + } + + private static MethodInfo ___ScrollableTextAreaInternal; + private static MethodInfo __ScrollableTextAreaInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ScrollableTextAreaInternal ??= __type__?.GetMethodInfoByParameterTypeNames("ScrollableTextAreaInternal", "UnityEngine.Rect", "System.String", "UnityEngine.Vector2&", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___TextAreaInternal; + private static MethodInfo __TextAreaInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TextAreaInternal ??= __type__?.GetMethodInfoByParameterTypeNames("TextAreaInternal", "UnityEngine.Rect", "System.String", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___SelectableLabelInternal; + private static MethodInfo __SelectableLabelInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SelectableLabelInternal ??= __type__?.GetMethodInfoByParameterTypeNames("SelectableLabelInternal", "UnityEngine.Rect", "System.String", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___PasswordFieldInternal; + private static MethodInfo __PasswordFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PasswordFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("PasswordFieldInternal", "UnityEngine.Rect", "System.String", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___PasswordFieldInternal__2; + private static MethodInfo __PasswordFieldInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PasswordFieldInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("PasswordFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.String", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___FloatFieldInternal; + private static MethodInfo __FloatFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FloatFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("FloatFieldInternal", "UnityEngine.Rect", "System.Single", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___FloatFieldInternal__2; + private static MethodInfo __FloatFieldInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FloatFieldInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("FloatFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Single", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___FloatFieldInternal__3; + private static MethodInfo __FloatFieldInternal__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FloatFieldInternal__3 ??= __type__?.GetMethodInfoByParameterTypeNames("FloatFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEditor.EditorGUI+NumberFieldValue&", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DoubleFieldInternal; + private static MethodInfo __DoubleFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoubleFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("DoubleFieldInternal", "UnityEngine.Rect", "System.Double", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DoubleFieldInternal__2; + private static MethodInfo __DoubleFieldInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoubleFieldInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DoubleFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Double", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DoubleFieldInternal__3; + private static MethodInfo __DoubleFieldInternal__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoubleFieldInternal__3 ??= __type__?.GetMethodInfoByParameterTypeNames("DoubleFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEditor.EditorGUI+NumberFieldValue&", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DragNumberValue; + private static MethodInfo __DragNumberValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DragNumberValue ??= __type__?.GetMethodInfoByParameterTypeNames("DragNumberValue", "UnityEngine.Rect", "System.Int32", "System.Boolean", "System.Double&", "System.Int64&", "System.Double"); + } + + private static MethodInfo ___DragNumberValue__2; + private static MethodInfo __DragNumberValue__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DragNumberValue__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DragNumberValue", "UnityEngine.Rect", "System.Int32", "UnityEditor.EditorGUI+NumberFieldValue&", "System.Double"); + } + + private static MethodInfo ___DoFloatField; + private static MethodInfo __DoFloatField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoFloatField ??= __type__?.GetMethodInfoByParameterTypeNames("DoFloatField", "UnityEditor.EditorGUI+RecycledTextEditor", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "System.Single", "System.String", "UnityEngine.GUIStyle", "System.Boolean"); + } + + private static MethodInfo ___DoFloatField__2; + private static MethodInfo __DoFloatField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoFloatField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DoFloatField", "UnityEditor.EditorGUI+RecycledTextEditor", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "System.Single", "System.String", "UnityEngine.GUIStyle", "System.Boolean", "System.Single"); + } + + private static MethodInfo ___DoIntField; + private static MethodInfo __DoIntField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoIntField ??= __type__?.GetMethodInfoByParameterTypeNames("DoIntField", "UnityEditor.EditorGUI+RecycledTextEditor", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "System.Int32", "System.String", "UnityEngine.GUIStyle", "System.Boolean", "System.Single"); + } + + private static MethodInfo ___DoDoubleField; + private static MethodInfo __DoDoubleField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoDoubleField ??= __type__?.GetMethodInfoByParameterTypeNames("DoDoubleField", "UnityEditor.EditorGUI+RecycledTextEditor", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "System.Double", "System.String", "UnityEngine.GUIStyle", "System.Boolean"); + } + + private static MethodInfo ___DoDoubleField__2; + private static MethodInfo __DoDoubleField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoDoubleField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DoDoubleField", "UnityEditor.EditorGUI+RecycledTextEditor", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "System.Double", "System.String", "UnityEngine.GUIStyle", "System.Boolean", "System.Double"); + } + + private static MethodInfo ___DoLongField; + private static MethodInfo __DoLongField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoLongField ??= __type__?.GetMethodInfoByParameterTypeNames("DoLongField", "UnityEditor.EditorGUI+RecycledTextEditor", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "System.Int64", "System.String", "UnityEngine.GUIStyle", "System.Boolean", "System.Double"); + } + + private static MethodInfo ___HasKeyboardFocus; + private static MethodInfo __HasKeyboardFocus + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasKeyboardFocus ??= __type__?.GetMethodInfoByParameterTypeNames("HasKeyboardFocus", "System.Int32"); + } + + private static MethodInfo ___DoNumberField; + private static MethodInfo __DoNumberField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoNumberField ??= __type__?.GetMethodInfoByParameterTypeNames("DoNumberField", "UnityEditor.EditorGUI+RecycledTextEditor", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "System.Boolean", "System.Double&", "System.Int64&", "System.String", "UnityEngine.GUIStyle", "System.Boolean", "System.Double"); + } + + private static MethodInfo ___DoNumberField__2; + private static MethodInfo __DoNumberField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoNumberField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DoNumberField", "UnityEditor.EditorGUI+RecycledTextEditor", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "UnityEditor.EditorGUI+NumberFieldValue&", "System.String", "UnityEngine.GUIStyle", "System.Boolean", "System.Double"); + } + + private static MethodInfo ___StringToDouble; + private static MethodInfo __StringToDouble + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___StringToDouble ??= __type__?.GetMethodInfoByParameterTypeNames("StringToDouble", "System.String", "System.Double&"); + } + + private static MethodInfo ___StringToDouble__2; + private static MethodInfo __StringToDouble__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___StringToDouble__2 ??= __type__?.GetMethodInfoByParameterTypeNames("StringToDouble", "System.String", "System.Double&", "UnityEditor.ExpressionEvaluator+Expression&"); + } + + private static MethodInfo ___StringToDouble__3; + private static MethodInfo __StringToDouble__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___StringToDouble__3 ??= __type__?.GetMethodInfoByParameterTypeNames("StringToDouble", "System.String", "UnityEditor.EditorGUI+NumberFieldValue&"); + } + + private static MethodInfo ___StringToDouble__4; + private static MethodInfo __StringToDouble__4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___StringToDouble__4 ??= __type__?.GetMethodInfoByParameterTypeNames("StringToDouble", "System.String", "System.String", "System.Double&"); + } + + private static MethodInfo ___StringToFloat; + private static MethodInfo __StringToFloat + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___StringToFloat ??= __type__?.GetMethodInfoByParameterTypeNames("StringToFloat", "System.String", "System.String", "System.Single&"); + } + + private static MethodInfo ___StringToLong; + private static MethodInfo __StringToLong + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___StringToLong ??= __type__?.GetMethodInfoByParameterTypeNames("StringToLong", "System.String", "System.Int64&"); + } + + private static MethodInfo ___StringToLong__2; + private static MethodInfo __StringToLong__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___StringToLong__2 ??= __type__?.GetMethodInfoByParameterTypeNames("StringToLong", "System.String", "System.Int64&", "UnityEditor.ExpressionEvaluator+Expression&"); + } + + private static MethodInfo ___StringToLong__3; + private static MethodInfo __StringToLong__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___StringToLong__3 ??= __type__?.GetMethodInfoByParameterTypeNames("StringToLong", "System.String", "UnityEditor.EditorGUI+NumberFieldValue&"); + } + + private static MethodInfo ___StringToLong__4; + private static MethodInfo __StringToLong__4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___StringToLong__4 ??= __type__?.GetMethodInfoByParameterTypeNames("StringToLong", "System.String", "System.String", "System.Int64&"); + } + + private static MethodInfo ___StringToInt; + private static MethodInfo __StringToInt + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___StringToInt ??= __type__?.GetMethodInfoByParameterTypeNames("StringToInt", "System.String", "System.String", "System.Int32&"); + } + + private static MethodInfo ___ArraySizeField; + private static MethodInfo __ArraySizeField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ArraySizeField ??= __type__?.GetMethodInfoByParameterTypeNames("ArraySizeField", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Int32", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DelayedTextFieldInternal; + private static MethodInfo __DelayedTextFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DelayedTextFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("DelayedTextFieldInternal", "UnityEngine.Rect", "System.String", "System.String", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DelayedTextFieldInternal__2; + private static MethodInfo __DelayedTextFieldInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DelayedTextFieldInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DelayedTextFieldInternal", "UnityEngine.Rect", "System.Int32", "UnityEngine.GUIContent", "System.String", "System.String", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DelayedTextFieldInternal__3; + private static MethodInfo __DelayedTextFieldInternal__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DelayedTextFieldInternal__3 ??= __type__?.GetMethodInfoByParameterTypeNames("DelayedTextFieldInternal", "UnityEngine.Rect", "System.Int32", "UnityEditor.SerializedProperty", "System.String", "UnityEngine.GUIContent", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DelayedNumberFieldInternal; + private static MethodInfo __DelayedNumberFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DelayedNumberFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("DelayedNumberFieldInternal", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "System.Boolean", "System.Double&", "System.Int64&", "System.String", "UnityEngine.GUIStyle", "System.Boolean", "System.Double"); + } + + private static MethodInfo ___DelayedNumberFieldInternal__2; + private static MethodInfo __DelayedNumberFieldInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DelayedNumberFieldInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DelayedNumberFieldInternal", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "UnityEditor.EditorGUI+NumberFieldValue&", "System.String", "UnityEngine.GUIStyle", "System.Boolean", "System.Double"); + } + + private static MethodInfo ___DelayedFloatFieldInternal; + private static MethodInfo __DelayedFloatFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DelayedFloatFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("DelayedFloatFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Single", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DelayedFloatFieldInternal__2; + private static MethodInfo __DelayedFloatFieldInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DelayedFloatFieldInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DelayedFloatFieldInternal", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___DelayedDoubleFieldInternal; + private static MethodInfo __DelayedDoubleFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DelayedDoubleFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("DelayedDoubleFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Double", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DelayedIntFieldInternal; + private static MethodInfo __DelayedIntFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DelayedIntFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("DelayedIntFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Int32", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DelayedIntFieldInternal__2; + private static MethodInfo __DelayedIntFieldInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DelayedIntFieldInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DelayedIntFieldInternal", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___SetDelayedDraggable; + private static MethodInfo __SetDelayedDraggable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetDelayedDraggable ??= __type__?.GetMethodInfoByParameterTypeNames("SetDelayedDraggable", "UnityEngine.Rect&", "UnityEngine.Rect&", "UnityEngine.GUIContent", "System.Int32"); + } + + private static MethodInfo ___IntFieldInternal; + private static MethodInfo __IntFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IntFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("IntFieldInternal", "UnityEngine.Rect", "System.Int32", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___IntFieldInternal__2; + private static MethodInfo __IntFieldInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IntFieldInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("IntFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Int32", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___LongFieldInternal; + private static MethodInfo __LongFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LongFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("LongFieldInternal", "UnityEngine.Rect", "System.Int64", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___LongFieldInternal__2; + private static MethodInfo __LongFieldInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LongFieldInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("LongFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Int64", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___LongFieldInternal__3; + private static MethodInfo __LongFieldInternal__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LongFieldInternal__3 ??= __type__?.GetMethodInfoByParameterTypeNames("LongFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEditor.EditorGUI+NumberFieldValue&", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___Slider; + private static MethodInfo __Slider + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Slider ??= __type__?.GetMethodInfoByParameterTypeNames("Slider", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Single", "System.Single", "System.Single", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___Slider__2; + private static MethodInfo __Slider__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Slider__2 ??= __type__?.GetMethodInfoByParameterTypeNames("Slider", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Single", "System.Single", "System.Single", "System.Single", "System.Single"); + } + + private static MethodInfo ___Slider__3; + private static MethodInfo __Slider__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Slider__3 ??= __type__?.GetMethodInfoByParameterTypeNames("Slider", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Single", "System.Single", "System.Single", "System.Single", "System.Single", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle", "UnityEngine.Texture2D", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___PowerSlider; + private static MethodInfo __PowerSlider + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PowerSlider ??= __type__?.GetMethodInfoByParameterTypeNames("PowerSlider", "UnityEngine.Rect", "System.String", "System.Single", "System.Single", "System.Single", "System.Single"); + } + + private static MethodInfo ___PowerSlider__2; + private static MethodInfo __PowerSlider__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PowerSlider__2 ??= __type__?.GetMethodInfoByParameterTypeNames("PowerSlider", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Single", "System.Single", "System.Single", "System.Single"); + } + + private static MethodInfo ___PowerSlider__3; + private static MethodInfo __PowerSlider__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PowerSlider__3 ??= __type__?.GetMethodInfoByParameterTypeNames("PowerSlider", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Single", "System.Single", "System.Single", "UnityEngine.GUIStyle", "System.Single"); + } + + private static MethodInfo ___PowPreserveSign; + private static MethodInfo __PowPreserveSign + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PowPreserveSign ??= __type__?.GetMethodInfoByParameterTypeNames("PowPreserveSign", "System.Single", "System.Single"); + } + + private static MethodInfo ___FillPropertyContextMenu; + private static MethodInfo __FillPropertyContextMenu + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FillPropertyContextMenu ??= __type__?.GetMethodInfoByParameterTypeNames("FillPropertyContextMenu", "UnityEditor.SerializedProperty", "UnityEditor.SerializedProperty", "UnityEditor.GenericMenu"); + } + + private static MethodInfo ___DoPropertyContextMenu; + private static MethodInfo __DoPropertyContextMenu + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoPropertyContextMenu ??= __type__?.GetMethodInfoByParameterTypeNames("DoPropertyContextMenu", "UnityEditor.SerializedProperty", "UnityEditor.SerializedProperty", "UnityEditor.GenericMenu"); + } + + private static MethodInfo ___Slider__4; + private static MethodInfo __Slider__4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Slider__4 ??= __type__?.GetMethodInfoByParameterTypeNames("Slider", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "System.Single", "System.Single", "System.Single", "System.Single", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___IntSlider; + private static MethodInfo __IntSlider + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IntSlider ??= __type__?.GetMethodInfoByParameterTypeNames("IntSlider", "UnityEngine.Rect", "System.Int32", "System.Int32", "System.Int32", "System.Single", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle", "UnityEngine.Texture2D", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DoTwoLabels; + private static MethodInfo __DoTwoLabels + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoTwoLabels ??= __type__?.GetMethodInfoByParameterTypeNames("DoTwoLabels", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEngine.GUIContent", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DoSlider; + private static MethodInfo __DoSlider + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoSlider ??= __type__?.GetMethodInfoByParameterTypeNames("DoSlider", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "System.Single", "System.Single", "System.Single", "System.String", "System.Single"); + } + + private static MethodInfo ___DoSlider__2; + private static MethodInfo __DoSlider__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoSlider__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DoSlider", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "System.Single", "System.Single", "System.Single", "System.String", "UnityEngine.GUIStyle", "System.Single"); + } + + private static MethodInfo ___DoSlider__3; + private static MethodInfo __DoSlider__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoSlider__3 ??= __type__?.GetMethodInfoByParameterTypeNames("DoSlider", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "System.Single", "System.Single", "System.Single", "System.String", "System.Single", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle", "UnityEngine.Texture2D", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DoSlider__4; + private static MethodInfo __DoSlider__4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoSlider__4 ??= __type__?.GetMethodInfoByParameterTypeNames("DoSlider", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "System.Single", "System.Single", "System.Single", "System.String", "System.Single", "System.Single", "System.Single", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle", "UnityEngine.Texture2D", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DoMinMaxSlider; + private static MethodInfo __DoMinMaxSlider + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoMinMaxSlider ??= __type__?.GetMethodInfoByParameterTypeNames("DoMinMaxSlider", "UnityEngine.Rect", "System.Int32", "System.Single&", "System.Single&", "System.Single", "System.Single"); + } + + private static MethodInfo ___PopupInternal; + private static MethodInfo __PopupInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PopupInternal ??= __type__?.GetMethodInfoByParameterTypeNames("PopupInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Int32", "UnityEngine.GUIContent[]", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___PopupInternal__2; + private static MethodInfo __PopupInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PopupInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("PopupInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Int32", "UnityEngine.GUIContent[]", "System.Func`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___Popup; + private static MethodInfo __Popup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Popup ??= __type__?.GetMethodInfoByParameterTypeNames("Popup", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Int32", "System.String[]", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___Popup__2; + private static MethodInfo __Popup__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Popup__2 ??= __type__?.GetMethodInfoByParameterTypeNames("Popup", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Int32", "System.String[]"); + } + + private static MethodInfo ___Popup__3; + private static MethodInfo __Popup__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Popup__3 ??= __type__?.GetMethodInfoByParameterTypeNames("Popup", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___Popup__4; + private static MethodInfo __Popup__4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Popup__4 ??= __type__?.GetMethodInfoByParameterTypeNames("Popup", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent[]", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___CheckCurrentEnumTypeEnabled; + private static MethodInfo __CheckCurrentEnumTypeEnabled + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CheckCurrentEnumTypeEnabled ??= __type__?.GetMethodInfoByParameterTypeNames("CheckCurrentEnumTypeEnabled", "System.Int32"); + } + + private static MethodInfo ___EnumPopupInternal; + private static MethodInfo __EnumPopupInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EnumPopupInternal ??= __type__?.GetMethodInfoByParameterTypeNames("EnumPopupInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Enum", "System.Func`2[[System.Enum, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", "System.Boolean", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___EnumPopupInternal__2; + private static MethodInfo __EnumPopupInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EnumPopupInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("EnumPopupInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Enum", "System.Type", "System.Func`2[[System.Enum, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", "System.Boolean", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___EnumPopupInternal__3; + private static MethodInfo __EnumPopupInternal__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EnumPopupInternal__3 ??= __type__?.GetMethodInfoByParameterTypeNames("EnumPopupInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Int32", "System.Type", "System.Func`2[[System.Enum, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", "System.Boolean", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___IntPopupInternal; + private static MethodInfo __IntPopupInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IntPopupInternal ??= __type__?.GetMethodInfoByParameterTypeNames("IntPopupInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Int32", "UnityEngine.GUIContent[]", "System.Int32[]", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___IntPopupInternal__2; + private static MethodInfo __IntPopupInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IntPopupInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("IntPopupInternal", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent[]", "System.Int32[]", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___SortingLayerField; + private static MethodInfo __SortingLayerField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SortingLayerField ??= __type__?.GetMethodInfoByParameterTypeNames("SortingLayerField", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEditor.SerializedProperty", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DoPopup; + private static MethodInfo __DoPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoPopup ??= __type__?.GetMethodInfoByParameterTypeNames("DoPopup", "UnityEngine.Rect", "System.Int32", "System.Int32", "UnityEngine.GUIContent[]", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DoPopup__2; + private static MethodInfo __DoPopup__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoPopup__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DoPopup", "UnityEngine.Rect", "System.Int32", "System.Int32", "UnityEngine.GUIContent[]", "System.Func`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___TagFieldInternal; + private static MethodInfo __TagFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TagFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("TagFieldInternal", "UnityEngine.Rect", "System.String", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___TagFieldInternal__2; + private static MethodInfo __TagFieldInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TagFieldInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("TagFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.String", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___LayerFieldInternal; + private static MethodInfo __LayerFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LayerFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("LayerFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Int32", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___MaskFieldInternal; + private static MethodInfo __MaskFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MaskFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("MaskFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Int32", "System.String[]", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___MaskFieldInternal__2; + private static MethodInfo __MaskFieldInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MaskFieldInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("MaskFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Int32", "System.String[]", "System.Int32[]", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___MaskFieldInternal__3; + private static MethodInfo __MaskFieldInternal__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MaskFieldInternal__3 ??= __type__?.GetMethodInfoByParameterTypeNames("MaskFieldInternal", "UnityEngine.Rect", "System.Int32", "System.String[]", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___EnumFlagsField; + private static MethodInfo __EnumFlagsField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EnumFlagsField ??= __type__?.GetMethodInfoByParameterTypeNames("EnumFlagsField", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Enum", "System.Boolean", "System.Int32&", "System.Boolean&", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___EnumFlagsField__2; + private static MethodInfo __EnumFlagsField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EnumFlagsField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("EnumFlagsField", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Enum", "System.Type", "System.Boolean", "System.Int32&", "System.Boolean&", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___EnumFlagsField__3; + private static MethodInfo __EnumFlagsField__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EnumFlagsField__3 ??= __type__?.GetMethodInfoByParameterTypeNames("EnumFlagsField", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Int32", "System.Type", "System.Boolean", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___ObjectField; + private static MethodInfo __ObjectField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ObjectField ??= __type__?.GetMethodInfoByParameterTypeNames("ObjectField", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "System.Type", "UnityEngine.GUIContent", "UnityEngine.GUIStyle", "UnityEditor.EditorGUI+ObjectFieldValidator"); + } + + private static MethodInfo ___ObjectFieldInternal; + private static MethodInfo __ObjectFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ObjectFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("ObjectFieldInternal", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "System.Type", "UnityEngine.GUIContent", "UnityEngine.GUIStyle", "UnityEditor.EditorGUI+ObjectFieldValidator"); + } + + private static MethodInfo ___GetObjectFieldThumbnailRect; + private static MethodInfo __GetObjectFieldThumbnailRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetObjectFieldThumbnailRect ??= __type__?.GetMethodInfoByParameterTypeNames("GetObjectFieldThumbnailRect", "UnityEngine.Rect", "System.Type"); + } + + private static MethodInfo ___GetRectsForMiniThumbnailField; + private static MethodInfo __GetRectsForMiniThumbnailField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetRectsForMiniThumbnailField ??= __type__?.GetMethodInfoByParameterTypeNames("GetRectsForMiniThumbnailField", "UnityEngine.Rect", "UnityEngine.Rect&", "UnityEngine.Rect&"); + } + + private static MethodInfo ___MiniThumbnailObjectField; + private static MethodInfo __MiniThumbnailObjectField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MiniThumbnailObjectField ??= __type__?.GetMethodInfoByParameterTypeNames("MiniThumbnailObjectField", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEngine.Object", "System.Type"); + } + + private static MethodInfo ___GetGameObjectFromObject; + private static MethodInfo __GetGameObjectFromObject + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetGameObjectFromObject ??= __type__?.GetMethodInfoByParameterTypeNames("GetGameObjectFromObject", "UnityEngine.Object"); + } + + private static MethodInfo ___CheckForCrossSceneReferencing; + private static MethodInfo __CheckForCrossSceneReferencing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CheckForCrossSceneReferencing ??= __type__?.GetMethodInfoByParameterTypeNames("CheckForCrossSceneReferencing", "UnityEngine.Object", "UnityEngine.Object"); + } + + private static MethodInfo ___ValidateObjectReferenceValue; + private static MethodInfo __ValidateObjectReferenceValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ValidateObjectReferenceValue ??= __type__?.GetMethodInfoByParameterTypeNames("ValidateObjectReferenceValue", "UnityEditor.SerializedProperty", "UnityEngine.Object", "UnityEditor.EditorGUI+ObjectFieldValidatorOptions"); + } + + private static MethodInfo ___ValidateObjectFieldAssignment; + private static MethodInfo __ValidateObjectFieldAssignment + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ValidateObjectFieldAssignment ??= __type__?.GetMethodInfoByParameterTypeNames("ValidateObjectFieldAssignment", "UnityEngine.Object[]", "System.Type", "UnityEditor.SerializedProperty", "UnityEditor.EditorGUI+ObjectFieldValidatorOptions"); + } + + private static MethodInfo ___Vector2Field; + private static MethodInfo __Vector2Field + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Vector2Field ??= __type__?.GetMethodInfoByParameterTypeNames("Vector2Field", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEngine.Vector2", "System.Boolean"); + } + + private static MethodInfo ___Vector2Field__2; + private static MethodInfo __Vector2Field__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Vector2Field__2 ??= __type__?.GetMethodInfoByParameterTypeNames("Vector2Field", "UnityEngine.Rect", "UnityEngine.Vector2"); + } + + private static MethodInfo ___Vector3Field; + private static MethodInfo __Vector3Field + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Vector3Field ??= __type__?.GetMethodInfoByParameterTypeNames("Vector3Field", "UnityEngine.Rect", "UnityEngine.Vector3"); + } + + private static MethodInfo ___LinkedVector3Field; + private static MethodInfo __LinkedVector3Field + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LinkedVector3Field ??= __type__?.GetMethodInfoByParameterTypeNames("LinkedVector3Field", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEngine.Vector3", "System.Boolean&"); + } + + private static MethodInfo ___LinkedVector3Field__2; + private static MethodInfo __LinkedVector3Field__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LinkedVector3Field__2 ??= __type__?.GetMethodInfoByParameterTypeNames("LinkedVector3Field", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEngine.GUIContent", "UnityEngine.Vector3", "System.Boolean&", "UnityEngine.Vector3", "System.UInt32", "System.Int32&", "UnityEditor.SerializedProperty", "UnityEditor.SerializedProperty"); + } + + private static MethodInfo ___LinkedVector3Field__3; + private static MethodInfo __LinkedVector3Field__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LinkedVector3Field__3 ??= __type__?.GetMethodInfoByParameterTypeNames("LinkedVector3Field", "UnityEngine.Rect", "UnityEngine.Vector3", "System.Boolean"); + } + + private static MethodInfo ___LinkedVector3Field__4; + private static MethodInfo __LinkedVector3Field__4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LinkedVector3Field__4 ??= __type__?.GetMethodInfoByParameterTypeNames("LinkedVector3Field", "UnityEngine.Rect", "UnityEngine.Vector3", "System.Boolean", "System.UInt32", "UnityEngine.Vector3", "System.Int32&", "UnityEditor.SerializedProperty"); + } + + private static MethodInfo ___Vector2Field__3; + private static MethodInfo __Vector2Field__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Vector2Field__3 ??= __type__?.GetMethodInfoByParameterTypeNames("Vector2Field", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___Vector3Field__2; + private static MethodInfo __Vector3Field__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Vector3Field__2 ??= __type__?.GetMethodInfoByParameterTypeNames("Vector3Field", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___QuaternionEulerField; + private static MethodInfo __QuaternionEulerField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___QuaternionEulerField ??= __type__?.GetMethodInfoByParameterTypeNames("QuaternionEulerField", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___Vector4Field; + private static MethodInfo __Vector4Field + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Vector4Field ??= __type__?.GetMethodInfoByParameterTypeNames("Vector4Field", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___Vector4FieldNoIndent; + private static MethodInfo __Vector4FieldNoIndent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Vector4FieldNoIndent ??= __type__?.GetMethodInfoByParameterTypeNames("Vector4FieldNoIndent", "UnityEngine.Rect", "UnityEngine.Vector4"); + } + + private static MethodInfo ___Vector2IntField; + private static MethodInfo __Vector2IntField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Vector2IntField ??= __type__?.GetMethodInfoByParameterTypeNames("Vector2IntField", "UnityEngine.Rect", "UnityEngine.Vector2Int"); + } + + private static MethodInfo ___Vector2IntField__2; + private static MethodInfo __Vector2IntField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Vector2IntField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("Vector2IntField", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___Vector3IntField; + private static MethodInfo __Vector3IntField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Vector3IntField ??= __type__?.GetMethodInfoByParameterTypeNames("Vector3IntField", "UnityEngine.Rect", "UnityEngine.Vector3Int"); + } + + private static MethodInfo ___Vector3IntField__2; + private static MethodInfo __Vector3IntField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Vector3IntField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("Vector3IntField", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___RectFieldNoIndent; + private static MethodInfo __RectFieldNoIndent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RectFieldNoIndent ??= __type__?.GetMethodInfoByParameterTypeNames("RectFieldNoIndent", "UnityEngine.Rect", "UnityEngine.Rect"); + } + + private static MethodInfo ___RectField; + private static MethodInfo __RectField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RectField ??= __type__?.GetMethodInfoByParameterTypeNames("RectField", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___RectIntField; + private static MethodInfo __RectIntField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RectIntField ??= __type__?.GetMethodInfoByParameterTypeNames("RectIntField", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___DrawBoundsFieldLabelsAndAdjustPositionForValues; + private static MethodInfo __DrawBoundsFieldLabelsAndAdjustPositionForValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawBoundsFieldLabelsAndAdjustPositionForValues ??= __type__?.GetMethodInfoByParameterTypeNames("DrawBoundsFieldLabelsAndAdjustPositionForValues", "UnityEngine.Rect", "System.Boolean", "UnityEngine.GUIContent", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___BoundsFieldNoIndent; + private static MethodInfo __BoundsFieldNoIndent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BoundsFieldNoIndent ??= __type__?.GetMethodInfoByParameterTypeNames("BoundsFieldNoIndent", "UnityEngine.Rect", "UnityEngine.Bounds", "System.Boolean"); + } + + private static MethodInfo ___BoundsField; + private static MethodInfo __BoundsField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BoundsField ??= __type__?.GetMethodInfoByParameterTypeNames("BoundsField", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___BoundsIntFieldNoIndent; + private static MethodInfo __BoundsIntFieldNoIndent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BoundsIntFieldNoIndent ??= __type__?.GetMethodInfoByParameterTypeNames("BoundsIntFieldNoIndent", "UnityEngine.Rect", "UnityEngine.BoundsInt", "System.Boolean"); + } + + private static MethodInfo ___BoundsIntField; + private static MethodInfo __BoundsIntField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BoundsIntField ??= __type__?.GetMethodInfoByParameterTypeNames("BoundsIntField", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___GetLabelWidth; + private static MethodInfo __GetLabelWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetLabelWidth ??= __type__?.GetMethodInfoByParameterTypeNames("GetLabelWidth", "UnityEngine.GUIContent", "System.Single"); + } + + private static MethodInfo ___MultiFloatFieldInternal; + private static MethodInfo __MultiFloatFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MultiFloatFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("MultiFloatFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent[]", "System.Single[]", "System.Single"); + } + + private static MethodInfo ___LockingMultiFloatFieldInternal; + private static MethodInfo __LockingMultiFloatFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LockingMultiFloatFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("LockingMultiFloatFieldInternal", "UnityEngine.Rect", "System.Boolean", "UnityEngine.GUIContent[]", "System.Single[]", "System.Single"); + } + + private static MethodInfo ___LockingMultiFloatFieldInternal__2; + private static MethodInfo __LockingMultiFloatFieldInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LockingMultiFloatFieldInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("LockingMultiFloatFieldInternal", "UnityEngine.Rect", "System.Boolean", "System.UInt32", "UnityEngine.GUIContent[]", "System.Single[]", "System.Single[]", "UnityEditor.SerializedProperty", "System.Single"); + } + + private static MethodInfo ___MultiIntFieldInternal; + private static MethodInfo __MultiIntFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MultiIntFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("MultiIntFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent[]", "System.Int32[]"); + } + + private static MethodInfo ___MultiPropertyFieldInternal; + private static MethodInfo __MultiPropertyFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MultiPropertyFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("MultiPropertyFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent[]", "UnityEditor.SerializedProperty", "UnityEditor.EditorGUI+PropertyVisibility", "System.Boolean[]", "System.Single"); + } + + private static MethodInfo ___PropertiesField; + private static MethodInfo __PropertiesField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PropertiesField ??= __type__?.GetMethodInfoByParameterTypeNames("PropertiesField", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEditor.SerializedProperty[]", "UnityEngine.GUIContent[]", "System.Single"); + } + + private static MethodInfo ___CycleButton; + private static MethodInfo __CycleButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CycleButton ??= __type__?.GetMethodInfoByParameterTypeNames("CycleButton", "UnityEngine.Rect", "System.Int32", "UnityEngine.GUIContent[]", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___ColorField; + private static MethodInfo __ColorField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ColorField ??= __type__?.GetMethodInfoByParameterTypeNames("ColorField", "UnityEngine.Rect", "UnityEngine.Color", "System.Boolean", "System.Boolean"); + } + + private static MethodInfo ___ColorField__2; + private static MethodInfo __ColorField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ColorField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("ColorField", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEngine.Color", "System.Boolean", "System.Boolean"); + } + + private static MethodInfo ___DoColorField; + private static MethodInfo __DoColorField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoColorField ??= __type__?.GetMethodInfoByParameterTypeNames("DoColorField", "UnityEngine.Rect", "System.Int32", "UnityEngine.Color", "System.Boolean", "System.Boolean", "System.Boolean"); + } + + private static MethodInfo ___SetCurveEditorWindowCurve; + private static MethodInfo __SetCurveEditorWindowCurve + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetCurveEditorWindowCurve ??= __type__?.GetMethodInfoByParameterTypeNames("SetCurveEditorWindowCurve", "UnityEngine.AnimationCurve", "UnityEditor.SerializedProperty", "UnityEngine.Color"); + } + + private static MethodInfo ___DoCurveField; + private static MethodInfo __DoCurveField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoCurveField ??= __type__?.GetMethodInfoByParameterTypeNames("DoCurveField", "UnityEngine.Rect", "System.Int32", "UnityEngine.AnimationCurve", "UnityEngine.Color", "UnityEngine.Rect", "UnityEditor.SerializedProperty"); + } + + private static MethodInfo ___ShowCurvePopup; + private static MethodInfo __ShowCurvePopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShowCurvePopup ??= __type__?.GetMethodInfoByParameterTypeNames("ShowCurvePopup", "UnityEngine.Rect"); + } + + private static MethodInfo ___GetObjectIconDropDownSize; + private static MethodInfo __GetObjectIconDropDownSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetObjectIconDropDownSize ??= __type__?.GetMethodInfoByParameterTypeNames("GetObjectIconDropDownSize", "System.Single", "System.Single"); + } + + private static MethodInfo ___ObjectIconDropDown; + private static MethodInfo __ObjectIconDropDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ObjectIconDropDown ??= __type__?.GetMethodInfoByParameterTypeNames("ObjectIconDropDown", "UnityEngine.Rect", "UnityEngine.Object[]", "System.Boolean", "UnityEngine.Texture2D", "UnityEditor.SerializedProperty"); + } + + private static MethodInfo ___GetIconRect; + private static MethodInfo __GetIconRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetIconRect ??= __type__?.GetMethodInfoByParameterTypeNames("GetIconRect", "UnityEngine.Rect", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___GetTextRect; + private static MethodInfo __GetTextRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetTextRect ??= __type__?.GetMethodInfoByParameterTypeNames("GetTextRect", "UnityEngine.Rect", "UnityEngine.Rect", "UnityEngine.Rect", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___GetSettingsRect; + private static MethodInfo __GetSettingsRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSettingsRect ??= __type__?.GetMethodInfoByParameterTypeNames("GetSettingsRect", "UnityEngine.Rect", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___EnableCheckBoxInTitlebar; + private static MethodInfo __EnableCheckBoxInTitlebar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EnableCheckBoxInTitlebar ??= __type__?.GetMethodInfoByParameterTypeNames("EnableCheckBoxInTitlebar", "UnityEngine.Object"); + } + + private static MethodInfo ___DoInspectorTitlebar; + private static MethodInfo __DoInspectorTitlebar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoInspectorTitlebar ??= __type__?.GetMethodInfoByParameterTypeNames("DoInspectorTitlebar", "UnityEngine.Rect", "System.Int32", "System.Boolean", "UnityEngine.Object[]", "UnityEditor.SerializedProperty", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___ShouldDrawOverrideBackground; + private static MethodInfo __ShouldDrawOverrideBackground + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShouldDrawOverrideBackground ??= __type__?.GetMethodInfoByParameterTypeNames("ShouldDrawOverrideBackground", "UnityEngine.Object[]", "UnityEngine.Event", "UnityEngine.Component"); + } + + private static MethodInfo ___RemovedComponentTitlebar; + private static MethodInfo __RemovedComponentTitlebar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RemovedComponentTitlebar ??= __type__?.GetMethodInfoByParameterTypeNames("RemovedComponentTitlebar", "UnityEngine.Rect", "UnityEngine.GameObject", "UnityEngine.Component"); + } + + private static MethodInfo ___ToggleTitlebar; + private static MethodInfo __ToggleTitlebar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ToggleTitlebar ??= __type__?.GetMethodInfoByParameterTypeNames("ToggleTitlebar", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Boolean", "System.Boolean&"); + } + + private static MethodInfo ___FoldoutTitlebar; + private static MethodInfo __FoldoutTitlebar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FoldoutTitlebar ??= __type__?.GetMethodInfoByParameterTypeNames("FoldoutTitlebar", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Boolean", "System.Boolean"); + } + + private static MethodInfo ___FoldoutTitlebar__2; + private static MethodInfo __FoldoutTitlebar__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FoldoutTitlebar__2 ??= __type__?.GetMethodInfoByParameterTypeNames("FoldoutTitlebar", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Boolean", "System.Boolean", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___HelpIconButton; + private static MethodInfo __HelpIconButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HelpIconButton ??= __type__?.GetMethodInfoByParameterTypeNames("HelpIconButton", "UnityEngine.Rect", "UnityEngine.Object[]"); + } + + private static MethodInfo ___FoldoutInternal; + private static MethodInfo __FoldoutInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FoldoutInternal ??= __type__?.GetMethodInfoByParameterTypeNames("FoldoutInternal", "UnityEngine.Rect", "System.Boolean", "UnityEngine.GUIContent", "System.Boolean", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___ProgressBar; + private static MethodInfo __ProgressBar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ProgressBar ??= __type__?.GetMethodInfoByParameterTypeNames("ProgressBar", "UnityEngine.Rect", "System.Single", "UnityEngine.GUIContent", "System.Boolean", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___LabelHasContent; + private static MethodInfo __LabelHasContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LabelHasContent ??= __type__?.GetMethodInfoByParameterTypeNames("LabelHasContent", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___PrepareCurrentPrefixLabel; + private static MethodInfo __PrepareCurrentPrefixLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PrepareCurrentPrefixLabel ??= __type__?.GetMethodInfoByParameterTypeNames("PrepareCurrentPrefixLabel", "System.Int32"); + } + + private static MethodInfo ___IsLabelHighlightEnabled; + private static MethodInfo __IsLabelHighlightEnabled + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsLabelHighlightEnabled ??= __type__?.GetMethodInfoByParameterTypeNames("IsLabelHighlightEnabled"); + } + + private static MethodInfo ___BeginLabelHighlight; + private static MethodInfo __BeginLabelHighlight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginLabelHighlight ??= __type__?.GetMethodInfoByParameterTypeNames("BeginLabelHighlight", "System.String", "UnityEngine.Color", "UnityEngine.Color"); + } + + private static MethodInfo ___EndLabelHighlight; + private static MethodInfo __EndLabelHighlight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EndLabelHighlight ??= __type__?.GetMethodInfoByParameterTypeNames("EndLabelHighlight"); + } + + private static MethodInfo ___DrawLabelHighlight; + private static MethodInfo __DrawLabelHighlight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawLabelHighlight ??= __type__?.GetMethodInfoByParameterTypeNames("DrawLabelHighlight", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___HandlePrefixLabelInternal; + private static MethodInfo __HandlePrefixLabelInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HandlePrefixLabelInternal ??= __type__?.GetMethodInfoByParameterTypeNames("HandlePrefixLabelInternal", "UnityEngine.Rect", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Int32", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___UseVTMaterial; + private static MethodInfo __UseVTMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UseVTMaterial ??= __type__?.GetMethodInfoByParameterTypeNames("UseVTMaterial", "UnityEngine.Texture"); + } + + private static MethodInfo ___MultiFieldPrefixLabel; + private static MethodInfo __MultiFieldPrefixLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MultiFieldPrefixLabel ??= __type__?.GetMethodInfoByParameterTypeNames("MultiFieldPrefixLabel", "UnityEngine.Rect", "System.Int32", "UnityEngine.GUIContent", "System.Int32"); + } + + private static MethodInfo ___MultiFieldPrefixLabel__2; + private static MethodInfo __MultiFieldPrefixLabel__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MultiFieldPrefixLabel__2 ??= __type__?.GetMethodInfoByParameterTypeNames("MultiFieldPrefixLabel", "UnityEngine.Rect", "System.Int32", "UnityEngine.GUIContent", "System.Int32", "System.Single", "System.Boolean"); + } + + private static MethodInfo ___BeginPropertyInternal; + private static MethodInfo __BeginPropertyInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginPropertyInternal ??= __type__?.GetMethodInfoByParameterTypeNames("BeginPropertyInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEditor.SerializedProperty"); + } + + private static MethodInfo ___DrawOverrideBackground; + private static MethodInfo __DrawOverrideBackground + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawOverrideBackground ??= __type__?.GetMethodInfoByParameterTypeNames("DrawOverrideBackground", "UnityEngine.Rect", "System.Boolean"); + } + + private static MethodInfo ___DrawMarginLineForRect; + private static MethodInfo __DrawMarginLineForRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawMarginLineForRect ??= __type__?.GetMethodInfoByParameterTypeNames("DrawMarginLineForRect", "UnityEngine.Rect", "UnityEngine.Color"); + } + + private static MethodInfo ___DoPropertyFieldKeyboardHandling; + private static MethodInfo __DoPropertyFieldKeyboardHandling + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoPropertyFieldKeyboardHandling ??= __type__?.GetMethodInfoByParameterTypeNames("DoPropertyFieldKeyboardHandling", "UnityEditor.SerializedProperty"); + } + + private static MethodInfo ___LayerMaskField; + private static MethodInfo __LayerMaskField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LayerMaskField ??= __type__?.GetMethodInfoByParameterTypeNames("LayerMaskField", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___LayerMaskField__2; + private static MethodInfo __LayerMaskField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LayerMaskField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("LayerMaskField", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___LayerMaskField__3; + private static MethodInfo __LayerMaskField__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LayerMaskField__3 ??= __type__?.GetMethodInfoByParameterTypeNames("LayerMaskField", "UnityEngine.Rect", "UnityEngine.LayerMask", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___LayerMaskField__4; + private static MethodInfo __LayerMaskField__4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LayerMaskField__4 ??= __type__?.GetMethodInfoByParameterTypeNames("LayerMaskField", "UnityEngine.Rect", "System.UInt32", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___LayerMaskField__5; + private static MethodInfo __LayerMaskField__5 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LayerMaskField__5 ??= __type__?.GetMethodInfoByParameterTypeNames("LayerMaskField", "UnityEngine.Rect", "System.UInt32", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___ShowRepaints; + private static MethodInfo __ShowRepaints + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShowRepaints ??= __type__?.GetMethodInfoByParameterTypeNames("ShowRepaints"); + } + + private static MethodInfo ___DrawTextureAlphaInternal; + private static MethodInfo __DrawTextureAlphaInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawTextureAlphaInternal ??= __type__?.GetMethodInfoByParameterTypeNames("DrawTextureAlphaInternal", "UnityEngine.Rect", "UnityEngine.Texture", "UnityEngine.ScaleMode", "System.Single", "System.Single"); + } + + private static MethodInfo ___DrawTextureTransparentInternal; + private static MethodInfo __DrawTextureTransparentInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawTextureTransparentInternal ??= __type__?.GetMethodInfoByParameterTypeNames("DrawTextureTransparentInternal", "UnityEngine.Rect", "UnityEngine.Texture", "UnityEngine.ScaleMode", "System.Single", "System.Single", "UnityEngine.Rendering.ColorWriteMask", "System.Single"); + } + + private static MethodInfo ___DrawTransparencyCheckerTexture; + private static MethodInfo __DrawTransparencyCheckerTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawTransparencyCheckerTexture ??= __type__?.GetMethodInfoByParameterTypeNames("DrawTransparencyCheckerTexture", "UnityEngine.Rect", "UnityEngine.ScaleMode", "System.Single"); + } + + private static MethodInfo ___DrawPreviewTextureInternal; + private static MethodInfo __DrawPreviewTextureInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawPreviewTextureInternal ??= __type__?.GetMethodInfoByParameterTypeNames("DrawPreviewTextureInternal", "UnityEngine.Rect", "UnityEngine.Texture", "UnityEngine.Material", "UnityEngine.ScaleMode", "System.Single", "System.Single", "UnityEngine.Rendering.ColorWriteMask", "System.Single"); + } + + private static MethodInfo ___StreamTexture; + private static MethodInfo __StreamTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___StreamTexture ??= __type__?.GetMethodInfoByParameterTypeNames("StreamTexture", "UnityEngine.Texture", "UnityEngine.Material", "System.Single"); + } + + private static MethodInfo ___GetMaterialForSpecialTexture; + private static MethodInfo __GetMaterialForSpecialTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMaterialForSpecialTexture ??= __type__?.GetMethodInfoByParameterTypeNames("GetMaterialForSpecialTexture", "UnityEngine.Texture", "UnityEngine.Material", "System.Boolean", "System.Boolean"); + } + + private static MethodInfo ___SetExpandedRecurse; + private static MethodInfo __SetExpandedRecurse + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetExpandedRecurse ??= __type__?.GetMethodInfoByParameterTypeNames("SetExpandedRecurse", "UnityEditor.SerializedProperty", "System.Boolean"); + } + + private static MethodInfo ___GetSinglePropertyHeight; + private static MethodInfo __GetSinglePropertyHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSinglePropertyHeight ??= __type__?.GetMethodInfoByParameterTypeNames("GetSinglePropertyHeight", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___GetPropertyHeightInternal; + private static MethodInfo __GetPropertyHeightInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPropertyHeightInternal ??= __type__?.GetMethodInfoByParameterTypeNames("GetPropertyHeightInternal", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent", "System.Boolean"); + } + + private static MethodInfo ___HasVisibleChildFields; + private static MethodInfo __HasVisibleChildFields + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasVisibleChildFields ??= __type__?.GetMethodInfoByParameterTypeNames("HasVisibleChildFields", "UnityEditor.SerializedProperty", "System.Boolean"); + } + + private static MethodInfo ___PropertyFieldInternal; + private static MethodInfo __PropertyFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PropertyFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("PropertyFieldInternal", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent", "System.Boolean"); + } + + private static MethodInfo ___DefaultPropertyField; + private static MethodInfo __DefaultPropertyField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DefaultPropertyField ??= __type__?.GetMethodInfoByParameterTypeNames("DefaultPropertyField", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___DrawLegend; + private static MethodInfo __DrawLegend + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawLegend ??= __type__?.GetMethodInfoByParameterTypeNames("DrawLegend", "UnityEngine.Rect", "UnityEngine.Color", "System.String", "System.Boolean"); + } + + private static MethodInfo ___TextFieldDropDown; + private static MethodInfo __TextFieldDropDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TextFieldDropDown ??= __type__?.GetMethodInfoByParameterTypeNames("TextFieldDropDown", "UnityEngine.Rect", "System.String", "System.String[]"); + } + + private static MethodInfo ___TextFieldDropDown__2; + private static MethodInfo __TextFieldDropDown__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TextFieldDropDown__2 ??= __type__?.GetMethodInfoByParameterTypeNames("TextFieldDropDown", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.String", "System.String[]"); + } + + private static MethodInfo ___DelayedTextFieldDropDown; + private static MethodInfo __DelayedTextFieldDropDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DelayedTextFieldDropDown ??= __type__?.GetMethodInfoByParameterTypeNames("DelayedTextFieldDropDown", "UnityEngine.Rect", "System.String", "System.String[]"); + } + + private static MethodInfo ___DelayedTextFieldDropDown__2; + private static MethodInfo __DelayedTextFieldDropDown__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DelayedTextFieldDropDown__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DelayedTextFieldDropDown", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.String", "System.String[]"); + } + + private static MethodInfo ___DropdownButton; + private static MethodInfo __DropdownButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DropdownButton ??= __type__?.GetMethodInfoByParameterTypeNames("DropdownButton", "System.Int32", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___AdvancedPopup; + private static MethodInfo __AdvancedPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AdvancedPopup ??= __type__?.GetMethodInfoByParameterTypeNames("AdvancedPopup", "UnityEngine.Rect", "System.Int32", "System.String[]"); + } + + private static MethodInfo ___AdvancedPopup__2; + private static MethodInfo __AdvancedPopup__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AdvancedPopup__2 ??= __type__?.GetMethodInfoByParameterTypeNames("AdvancedPopup", "UnityEngine.Rect", "System.Int32", "System.String[]", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___AdvancedLazyPopup; + private static MethodInfo __AdvancedLazyPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AdvancedLazyPopup ??= __type__?.GetMethodInfoByParameterTypeNames("AdvancedLazyPopup", "UnityEngine.Rect", "System.String", "System.Int32", "System.Func`1[[UnityEditor.Tuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], UnityEditor.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DelayedTextFieldHelper; + private static MethodInfo __DelayedTextFieldHelper + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DelayedTextFieldHelper ??= __type__?.GetMethodInfoByParameterTypeNames("DelayedTextFieldHelper", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___FloatField; + private static MethodInfo __FloatField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FloatField ??= __type__?.GetMethodInfoByParameterTypeNames("FloatField", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEditor.EditorGUI+NumberFieldValue&"); + } + + private static MethodInfo ___DoubleField; + private static MethodInfo __DoubleField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoubleField ??= __type__?.GetMethodInfoByParameterTypeNames("DoubleField", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEditor.EditorGUI+NumberFieldValue&"); + } + + private static MethodInfo ___LongField; + private static MethodInfo __LongField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LongField ??= __type__?.GetMethodInfoByParameterTypeNames("LongField", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEditor.EditorGUI+NumberFieldValue&"); + } + + private static MethodInfo ___EnumPopup; + private static MethodInfo __EnumPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EnumPopup ??= __type__?.GetMethodInfoByParameterTypeNames("EnumPopup", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___CalcPrefixLabelWidth; + private static MethodInfo __CalcPrefixLabelWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CalcPrefixLabelWidth ??= __type__?.GetMethodInfoByParameterTypeNames("CalcPrefixLabelWidth", "UnityEngine.GUIContent", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___EnumMaskField; + private static MethodInfo __EnumMaskField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EnumMaskField ??= __type__?.GetMethodInfoByParameterTypeNames("EnumMaskField", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Enum", "UnityEngine.GUIStyle", "System.Int32&", "System.Boolean&"); + } + + private static MethodInfo ___EnumMaskFieldInternal; + private static MethodInfo __EnumMaskFieldInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EnumMaskFieldInternal ??= __type__?.GetMethodInfoByParameterTypeNames("EnumMaskFieldInternal", "UnityEngine.Rect", "System.Enum", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___EnumMaskFieldInternal__2; + private static MethodInfo __EnumMaskFieldInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EnumMaskFieldInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("EnumMaskFieldInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Enum", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DoEnumMaskField; + private static MethodInfo __DoEnumMaskField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoEnumMaskField ??= __type__?.GetMethodInfoByParameterTypeNames("DoEnumMaskField", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Enum", "UnityEngine.GUIStyle", "System.Int32&", "System.Boolean&"); + } + + private static MethodInfo ___EnumMaskPopup; + private static MethodInfo __EnumMaskPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EnumMaskPopup ??= __type__?.GetMethodInfoByParameterTypeNames("EnumMaskPopup", "UnityEngine.Rect", "System.String", "System.Enum", "System.Int32&", "System.Boolean&", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___EnumMaskPopup__2; + private static MethodInfo __EnumMaskPopup__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EnumMaskPopup__2 ??= __type__?.GetMethodInfoByParameterTypeNames("EnumMaskPopup", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Enum", "System.Int32&", "System.Boolean&", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___EnumMaskPopupInternal; + private static MethodInfo __EnumMaskPopupInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EnumMaskPopupInternal ??= __type__?.GetMethodInfoByParameterTypeNames("EnumMaskPopupInternal", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Enum", "System.Int32&", "System.Boolean&", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___AngularDial; + private static MethodInfo __AngularDial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AngularDial ??= __type__?.GetMethodInfoByParameterTypeNames("AngularDial", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Single", "UnityEngine.Texture", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___UseAngularDialEventAndGetAngle; + private static MethodInfo __UseAngularDialEventAndGetAngle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UseAngularDialEventAndGetAngle ??= __type__?.GetMethodInfoByParameterTypeNames("UseAngularDialEventAndGetAngle", "System.Int32", "UnityEngine.Event", "UnityEngine.Vector2", "System.Single"); + } + + private static MethodInfo ___ButtonWithRotatedIcon; + private static MethodInfo __ButtonWithRotatedIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ButtonWithRotatedIcon ??= __type__?.GetMethodInfoByParameterTypeNames("ButtonWithRotatedIcon", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Single", "System.Boolean", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___GradientField; + private static MethodInfo __GradientField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GradientField ??= __type__?.GetMethodInfoByParameterTypeNames("GradientField", "UnityEngine.Rect", "UnityEditor.SerializedProperty"); + } + + private static MethodInfo ___GradientField__2; + private static MethodInfo __GradientField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GradientField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GradientField", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "System.Boolean"); + } + + private static MethodInfo ___GradientField__3; + private static MethodInfo __GradientField__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GradientField__3 ??= __type__?.GetMethodInfoByParameterTypeNames("GradientField", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "System.Boolean", "UnityEngine.ColorSpace"); + } + + private static MethodInfo ___GradientField__4; + private static MethodInfo __GradientField__4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GradientField__4 ??= __type__?.GetMethodInfoByParameterTypeNames("GradientField", "UnityEngine.Rect", "System.String", "UnityEditor.SerializedProperty"); + } + + private static MethodInfo ___GradientField__5; + private static MethodInfo __GradientField__5 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GradientField__5 ??= __type__?.GetMethodInfoByParameterTypeNames("GradientField", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEditor.SerializedProperty"); + } + + private static MethodInfo ___DoGradientField; + private static MethodInfo __DoGradientField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoGradientField ??= __type__?.GetMethodInfoByParameterTypeNames("DoGradientField", "UnityEngine.Rect", "System.Int32", "UnityEngine.Gradient", "UnityEditor.SerializedProperty", "System.Boolean", "UnityEngine.ColorSpace"); + } + + private static MethodInfo ___HexColorTextField; + private static MethodInfo __HexColorTextField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HexColorTextField ??= __type__?.GetMethodInfoByParameterTypeNames("HexColorTextField", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEngine.Color32", "System.Boolean"); + } + + private static MethodInfo ___HexColorTextField__2; + private static MethodInfo __HexColorTextField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HexColorTextField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("HexColorTextField", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEngine.Color32", "System.Boolean", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DoHexColorTextField; + private static MethodInfo __DoHexColorTextField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoHexColorTextField ??= __type__?.GetMethodInfoByParameterTypeNames("DoHexColorTextField", "System.Int32", "UnityEngine.Rect", "UnityEngine.Color32", "System.Boolean", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___Button; + private static MethodInfo __Button + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Button ??= __type__?.GetMethodInfoByParameterTypeNames("Button", "UnityEngine.Rect", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___Button__2; + private static MethodInfo __Button__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Button__2 ??= __type__?.GetMethodInfoByParameterTypeNames("Button", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___IconButton; + private static MethodInfo __IconButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IconButton ??= __type__?.GetMethodInfoByParameterTypeNames("IconButton", "System.Int32", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___WidthResizer; + private static MethodInfo __WidthResizer + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___WidthResizer ??= __type__?.GetMethodInfoByParameterTypeNames("WidthResizer", "UnityEngine.Rect", "System.Single", "System.Single", "System.Single"); + } + + private static MethodInfo ___WidthResizer__2; + private static MethodInfo __WidthResizer__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___WidthResizer__2 ??= __type__?.GetMethodInfoByParameterTypeNames("WidthResizer", "UnityEngine.Rect", "System.Single", "System.Single", "System.Single", "System.Boolean&"); + } + + private static MethodInfo ___HeightResizer; + private static MethodInfo __HeightResizer + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HeightResizer ??= __type__?.GetMethodInfoByParameterTypeNames("HeightResizer", "UnityEngine.Rect", "System.Single", "System.Single", "System.Single"); + } + + private static MethodInfo ___HeightResizer__2; + private static MethodInfo __HeightResizer__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HeightResizer__2 ??= __type__?.GetMethodInfoByParameterTypeNames("HeightResizer", "UnityEngine.Rect", "System.Single", "System.Single", "System.Single", "System.Boolean&"); + } + + private static MethodInfo ___MouseDeltaReader; + private static MethodInfo __MouseDeltaReader + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MouseDeltaReader ??= __type__?.GetMethodInfoByParameterTypeNames("MouseDeltaReader", "UnityEngine.Rect", "System.Boolean"); + } + + private static MethodInfo ___ButtonWithDropdownList; + private static MethodInfo __ButtonWithDropdownList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ButtonWithDropdownList ??= __type__?.GetMethodInfoByParameterTypeNames("ButtonWithDropdownList", "System.String", "System.String[]", "UnityEditor.GenericMenu+MenuFunction2", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___ButtonWithDropdownList__2; + private static MethodInfo __ButtonWithDropdownList__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ButtonWithDropdownList__2 ??= __type__?.GetMethodInfoByParameterTypeNames("ButtonWithDropdownList", "UnityEngine.GUIContent", "System.String[]", "UnityEditor.GenericMenu+MenuFunction2", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___GameViewSizePopup; + private static MethodInfo __GameViewSizePopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GameViewSizePopup ??= __type__?.GetMethodInfoByParameterTypeNames("GameViewSizePopup", "UnityEngine.Rect", "UnityEditor.GameViewSizeGroupType", "System.Int32", "UnityEditor.IGameViewSizeMenuUser", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DrawDelimiterLine; + private static MethodInfo __DrawDelimiterLine + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawDelimiterLine ??= __type__?.GetMethodInfoByParameterTypeNames("DrawDelimiterLine", "UnityEngine.Rect"); + } + + private static MethodInfo ___DrawOutline; + private static MethodInfo __DrawOutline + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawOutline ??= __type__?.GetMethodInfoByParameterTypeNames("DrawOutline", "UnityEngine.Rect", "System.Single", "UnityEngine.Color"); + } + + private static MethodInfo ___Knob; + private static MethodInfo __Knob + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Knob ??= __type__?.GetMethodInfoByParameterTypeNames("Knob", "UnityEngine.Rect", "UnityEngine.Vector2", "System.Single", "System.Single", "System.Single", "System.String", "UnityEngine.Color", "UnityEngine.Color", "System.Boolean", "System.Int32"); + } + + private static MethodInfo ___OffsetKnob; + private static MethodInfo __OffsetKnob + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OffsetKnob ??= __type__?.GetMethodInfoByParameterTypeNames("OffsetKnob", "UnityEngine.Rect", "System.Single", "System.Single", "System.Single", "System.Single", "System.String", "UnityEngine.Color", "UnityEngine.Color", "UnityEngine.GUIStyle", "System.Int32"); + } + + private static MethodInfo ___DoObjectField; + private static MethodInfo __DoObjectField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoObjectField ??= __type__?.GetMethodInfoByParameterTypeNames("DoObjectField", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "UnityEngine.Object", "UnityEngine.Object", "System.Type", "UnityEditor.EditorGUI+ObjectFieldValidator", "System.Boolean", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DoObjectField__2; + private static MethodInfo __DoObjectField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoObjectField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DoObjectField", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "UnityEngine.Object", "UnityEngine.Object", "System.Type", "UnityEditor.EditorGUI+ObjectFieldValidator", "System.Boolean", "System.Type", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DoObjectField__3; + private static MethodInfo __DoObjectField__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoObjectField__3 ??= __type__?.GetMethodInfoByParameterTypeNames("DoObjectField", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "System.Type", "UnityEditor.SerializedProperty", "UnityEditor.EditorGUI+ObjectFieldValidator", "System.Boolean", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___PingObjectOrShowPreviewOnClick; + private static MethodInfo __PingObjectOrShowPreviewOnClick + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PingObjectOrShowPreviewOnClick ??= __type__?.GetMethodInfoByParameterTypeNames("PingObjectOrShowPreviewOnClick", "UnityEngine.Object", "UnityEngine.Rect"); + } + + private static MethodInfo ___PingObjectInSceneViewOnClick; + private static MethodInfo __PingObjectInSceneViewOnClick + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PingObjectInSceneViewOnClick ??= __type__?.GetMethodInfoByParameterTypeNames("PingObjectInSceneViewOnClick", "UnityEngine.Material"); + } + + private static MethodInfo ___AssignSelectedObject; + private static MethodInfo __AssignSelectedObject + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AssignSelectedObject ??= __type__?.GetMethodInfoByParameterTypeNames("AssignSelectedObject", "UnityEditor.SerializedProperty", "UnityEditor.EditorGUI+ObjectFieldValidator", "System.Type", "UnityEngine.Event"); + } + + private static MethodInfo ___GetButtonRect; + private static MethodInfo __GetButtonRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetButtonRect ??= __type__?.GetMethodInfoByParameterTypeNames("GetButtonRect", "UnityEditor.EditorGUI+ObjectFieldVisualType", "UnityEngine.Rect"); + } + + private static MethodInfo ___HasValidScript; + private static MethodInfo __HasValidScript + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasValidScript ??= __type__?.GetMethodInfoByParameterTypeNames("HasValidScript", "UnityEngine.Object"); + } + + private static MethodInfo ___ValidDroppedObject; + private static MethodInfo __ValidDroppedObject + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ValidDroppedObject ??= __type__?.GetMethodInfoByParameterTypeNames("ValidDroppedObject", "UnityEngine.Object[]", "System.Type", "System.String&"); + } + + private static MethodInfo ___DoObjectField__4; + private static MethodInfo __DoObjectField__4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoObjectField__4 ??= __type__?.GetMethodInfoByParameterTypeNames("DoObjectField", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "UnityEngine.Object", "System.Type", "UnityEditor.SerializedProperty", "UnityEditor.EditorGUI+ObjectFieldValidator", "System.Boolean", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DoObjectField__5; + private static MethodInfo __DoObjectField__5 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoObjectField__5 ??= __type__?.GetMethodInfoByParameterTypeNames("DoObjectField", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "UnityEngine.Object", "UnityEngine.Object", "System.Type", "UnityEditor.SerializedProperty", "UnityEditor.EditorGUI+ObjectFieldValidator", "System.Boolean", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DoObjectField__6; + private static MethodInfo __DoObjectField__6 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoObjectField__6 ??= __type__?.GetMethodInfoByParameterTypeNames("DoObjectField", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "UnityEngine.Object", "UnityEngine.Object", "System.Type", "System.Type", "UnityEditor.SerializedProperty", "UnityEditor.EditorGUI+ObjectFieldValidator", "System.Boolean", "UnityEngine.GUIStyle", "System.Action`1[[UnityEngine.Object, UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "System.Action`1[[UnityEngine.Object, UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]"); + } + + private static MethodInfo ___DoObjectField__7; + private static MethodInfo __DoObjectField__7 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoObjectField__7 ??= __type__?.GetMethodInfoByParameterTypeNames("DoObjectField", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "UnityEngine.Object", "UnityEngine.Object", "System.Type", "System.Type", "UnityEditor.SerializedProperty", "UnityEditor.EditorGUI+ObjectFieldValidator", "System.Boolean", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DoObjectField__8; + private static MethodInfo __DoObjectField__8 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoObjectField__8 ??= __type__?.GetMethodInfoByParameterTypeNames("DoObjectField", "UnityEngine.Rect", "UnityEngine.Rect", "System.Int32", "UnityEngine.Object", "UnityEngine.Object", "System.Type", "System.Type", "UnityEditor.SerializedProperty", "UnityEditor.EditorGUI+ObjectFieldValidator", "System.Boolean", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle", "System.Action`1[[UnityEngine.Object, UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "System.Action`1[[UnityEngine.Object, UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]"); + } + + private static MethodInfo ___DrawObjectFieldLargeThumb; + private static MethodInfo __DrawObjectFieldLargeThumb + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawObjectFieldLargeThumb ??= __type__?.GetMethodInfoByParameterTypeNames("DrawObjectFieldLargeThumb", "UnityEngine.Rect", "System.Int32", "UnityEngine.Object", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___DrawObjectFieldMiniThumb; + private static MethodInfo __DrawObjectFieldMiniThumb + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawObjectFieldMiniThumb ??= __type__?.GetMethodInfoByParameterTypeNames("DrawObjectFieldMiniThumb", "UnityEngine.Rect", "System.Int32", "UnityEngine.Object", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___DoDropField; + private static MethodInfo __DoDropField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoDropField ??= __type__?.GetMethodInfoByParameterTypeNames("DoDropField", "UnityEngine.Rect", "System.Int32", "System.Type", "UnityEditor.EditorGUI+ObjectFieldValidator", "System.Boolean", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___SliderWithTexture; + private static MethodInfo __SliderWithTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SliderWithTexture ??= __type__?.GetMethodInfoByParameterTypeNames("SliderWithTexture", "UnityEngine.Rect", "UnityEngine.GUIContent", "UnityEditor.SerializedProperty", "System.Single", "System.Single", "System.Single", "UnityEngine.Texture2D"); + } + + private static MethodInfo ___SliderWithTexture__2; + private static MethodInfo __SliderWithTexture__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SliderWithTexture__2 ??= __type__?.GetMethodInfoByParameterTypeNames("SliderWithTexture", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Single", "System.Single", "System.Single", "System.String", "UnityEngine.Texture2D", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___SliderWithTexture__3; + private static MethodInfo __SliderWithTexture__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SliderWithTexture__3 ??= __type__?.GetMethodInfoByParameterTypeNames("SliderWithTexture", "UnityEngine.Rect", "UnityEngine.GUIContent", "System.Single", "System.Single", "System.Single", "System.String", "System.Single", "System.Single", "System.Single", "UnityEngine.Texture2D"); + } + + private static MethodInfo ___TargetChoiceField; + private static MethodInfo __TargetChoiceField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TargetChoiceField ??= __type__?.GetMethodInfoByParameterTypeNames("TargetChoiceField", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___TargetChoiceField__2; + private static MethodInfo __TargetChoiceField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TargetChoiceField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("TargetChoiceField", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent", "UnityEditor.TargetChoiceHandler+TargetChoiceMenuFunction"); + } + + private static MethodInfo ___DoTextFieldDropDown; + private static MethodInfo __DoTextFieldDropDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoTextFieldDropDown ??= __type__?.GetMethodInfoByParameterTypeNames("DoTextFieldDropDown", "UnityEngine.Rect", "System.Int32", "System.String", "System.String[]", "System.Boolean"); + } + + private static MethodInfo ___PromptConfirmation; + private static MethodInfo __PromptConfirmation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PromptConfirmation ??= __type__?.GetMethodInfoByParameterTypeNames("PromptConfirmation", "UnityEditor.SerializedObject", "UnityEditor.SerializedProperty", "UnityEngine.Object"); + } + + private static MethodInfo ___RenderPipelineAssetField; + private static MethodInfo __RenderPipelineAssetField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RenderPipelineAssetField ??= __type__?.GetMethodInfoByParameterTypeNames("RenderPipelineAssetField", "UnityEngine.GUIContent", "UnityEditor.SerializedObject", "UnityEditor.SerializedProperty"); + } + + private static MethodInfo ___RenderPipelineAssetField__2; + private static MethodInfo __RenderPipelineAssetField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RenderPipelineAssetField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("RenderPipelineAssetField", "UnityEditor.SerializedObject", "UnityEditor.SerializedProperty"); + } + } + public static class UnityEditor_EditorGUI_Extension + { + public static UnityEditor_EditorGUI ReflectionHelper(this UnityEditor.EditorGUI self) => new(self); + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUI.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUI.cs.meta new file mode 100644 index 0000000..ab539f3 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUI.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c56668eaf1b526f4a84f7e7a7988a63f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUILayout.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUILayout.cs new file mode 100644 index 0000000..df1f70c --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUILayout.cs @@ -0,0 +1,1821 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_EditorGUILayout + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.EditorGUILayout"); + + + public static float kLabelFloatMinW + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kLabelFloatMinW?.GetValue(null)); + } + + public static float kLabelFloatMaxW + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kLabelFloatMaxW?.GetValue(null)); + } + + public static UnityEngine.Rect s_LastRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Rect)(__s_LastRect?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LastRect?.SetValue(null, value); + } + + public static float kPlatformTabWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kPlatformTabWidth?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kPlatformTabWidth?.SetValue(null, value); + } + + public static object s_SelectedDefault + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__s_SelectedDefault?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_SelectedDefault?.SetValue(null, value); + } + + public static UnityEngine.GUIStyle s_TabOnlyOne + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__s_TabOnlyOne?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_TabOnlyOne?.SetValue(null, value); + } + + public static UnityEngine.GUIStyle s_TabFirst + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__s_TabFirst?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_TabFirst?.SetValue(null, value); + } + + public static UnityEngine.GUIStyle s_TabMiddle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__s_TabMiddle?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_TabMiddle?.SetValue(null, value); + } + + public static UnityEngine.GUIStyle s_TabLast + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__s_TabLast?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_TabLast?.SetValue(null, value); + } + + public static object s_ButtonArrays + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__s_ButtonArrays?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ButtonArrays?.SetValue(null, value); + } + + public static object s_BoolArrays + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__s_BoolArrays?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_BoolArrays?.SetValue(null, value); + } + + public static System.Collections.Generic.List s_CustomEditorTools + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Generic.List)(__s_CustomEditorTools?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_CustomEditorTools?.SetValue(null, value); + } + + public static System.Collections.Generic.List s_CustomEditorContexts + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Generic.List)(__s_CustomEditorContexts?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_CustomEditorContexts?.SetValue(null, value); + } + + public static void DelayedTextField(UnityEditor.SerializedProperty property, UnityEngine.GUIContent label, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = property; + __params__[1] = label; + __params__[2] = style; + __params__[3] = options; + __DelayedTextField?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static string ToolbarSearchField(string text, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = text; + __params__[1] = options; + var __result__ = __ToolbarSearchField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string ToolbarSearchField(string text, string[] searchModes, ref int searchMode, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = text; + __params__[1] = searchModes; + __params__[2] = searchMode; + __params__[3] = options; + var __result__ = __ToolbarSearchField__2?.Invoke(null, __params__); + searchMode = (int)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static UnityEngine.Event KeyEventField(UnityEngine.Event e, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = e; + __params__[1] = options; + var __result__ = __KeyEventField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Event)(__result__) : default; + } + + public static void VUMeterHorizontal(float value, float peak, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = value; + __params__[1] = peak; + __params__[2] = options; + __VUMeterHorizontal?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void VUMeterHorizontal(float value, ref object data, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = value; + __params__[1] = data; + __params__[2] = options; + __VUMeterHorizontal__2?.Invoke(null, __params__); + data = (object)(__params__[1]); + __pool__.Return(__params__); + } + + public static float Slider(UnityEngine.GUIContent label, float value, float sliderLeftValue, float sliderRightValue, float textLeftValue, float textRightValue, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(7); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = value; + __params__[2] = sliderLeftValue; + __params__[3] = sliderRightValue; + __params__[4] = textLeftValue; + __params__[5] = textRightValue; + __params__[6] = options; + var __result__ = __Slider?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static void GetSliderParts(UnityEngine.GUIStyle baseStyle, ref UnityEngine.GUIStyle textFieldStyle, ref UnityEngine.GUIStyle thumbStyle, ref UnityEngine.GUIStyle thumbExtentStyle) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = baseStyle; + __params__[1] = textFieldStyle; + __params__[2] = thumbStyle; + __params__[3] = thumbExtentStyle; + __GetSliderParts?.Invoke(null, __params__); + textFieldStyle = (UnityEngine.GUIStyle)(__params__[1]); + thumbStyle = (UnityEngine.GUIStyle)(__params__[2]); + thumbExtentStyle = (UnityEngine.GUIStyle)(__params__[3]); + __pool__.Return(__params__); + } + + public static void GetHorizontalSliderParts(UnityEngine.GUIStyle baseStyle, out UnityEngine.GUIStyle textFieldStyle, out UnityEngine.GUIStyle thumbStyle, out UnityEngine.GUIStyle thumbExtentStyle) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = baseStyle; + __params__[1] = null; + __params__[2] = null; + __params__[3] = null; + __GetHorizontalSliderParts?.Invoke(null, __params__); + textFieldStyle = (UnityEngine.GUIStyle)(__params__[1]); + thumbStyle = (UnityEngine.GUIStyle)(__params__[2]); + thumbExtentStyle = (UnityEngine.GUIStyle)(__params__[3]); + __pool__.Return(__params__); + } + + public static void GetVerticalSliderParts(UnityEngine.GUIStyle baseStyle, out UnityEngine.GUIStyle textFieldStyle, out UnityEngine.GUIStyle thumbStyle, out UnityEngine.GUIStyle thumbExtentStyle) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = baseStyle; + __params__[1] = null; + __params__[2] = null; + __params__[3] = null; + __GetVerticalSliderParts?.Invoke(null, __params__); + textFieldStyle = (UnityEngine.GUIStyle)(__params__[1]); + thumbStyle = (UnityEngine.GUIStyle)(__params__[2]); + thumbExtentStyle = (UnityEngine.GUIStyle)(__params__[3]); + __pool__.Return(__params__); + } + + public static float Slider(UnityEngine.GUIContent label, float value, float sliderLeftValue, float sliderRightValue, float textLeftValue, float textRightValue, UnityEngine.GUIStyle sliderStyle, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(8); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = value; + __params__[2] = sliderLeftValue; + __params__[3] = sliderRightValue; + __params__[4] = textLeftValue; + __params__[5] = textRightValue; + __params__[6] = sliderStyle; + __params__[7] = options; + var __result__ = __Slider__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float Slider(UnityEngine.GUIContent label, float value, float sliderLeftValue, float sliderRightValue, float textLeftValue, float textRightValue, UnityEngine.GUIStyle sliderTextField, UnityEngine.GUIStyle sliderStyle, UnityEngine.GUIStyle sliderThumbStyle, UnityEngine.Texture2D sliderBackground, UnityEngine.GUIStyle sliderThumbStyleExtent, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(12); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = value; + __params__[2] = sliderLeftValue; + __params__[3] = sliderRightValue; + __params__[4] = textLeftValue; + __params__[5] = textRightValue; + __params__[6] = sliderTextField; + __params__[7] = sliderStyle; + __params__[8] = sliderThumbStyle; + __params__[9] = sliderBackground; + __params__[10] = sliderThumbStyleExtent; + __params__[11] = options; + var __result__ = __Slider__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static void Slider(UnityEditor.SerializedProperty property, float sliderLeftValue, float sliderRightValue, float textLeftValue, float textRightValue, UnityEngine.GUIContent label, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(7); + var __params__ = __pool__.Rent(); + __params__[0] = property; + __params__[1] = sliderLeftValue; + __params__[2] = sliderRightValue; + __params__[3] = textLeftValue; + __params__[4] = textRightValue; + __params__[5] = label; + __params__[6] = options; + __Slider__4?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static float PowerSlider(string label, float value, float leftValue, float rightValue, float power, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = value; + __params__[2] = leftValue; + __params__[3] = rightValue; + __params__[4] = power; + __params__[5] = options; + var __result__ = __PowerSlider?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float PowerSlider(UnityEngine.GUIContent label, float value, float leftValue, float rightValue, float power, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = value; + __params__[2] = leftValue; + __params__[3] = rightValue; + __params__[4] = power; + __params__[5] = options; + var __result__ = __PowerSlider__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static int IntSlider(int value, int leftValue, int rightValue, float power, UnityEngine.GUIStyle sliderStyle, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = value; + __params__[1] = leftValue; + __params__[2] = rightValue; + __params__[3] = power; + __params__[4] = sliderStyle; + __params__[5] = options; + var __result__ = __IntSlider?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int IntSlider(int value, int leftValue, int rightValue, float power, UnityEngine.GUIStyle textfieldStyle, UnityEngine.GUIStyle sliderStyle, UnityEngine.GUIStyle thumbStyle, UnityEngine.Texture2D sliderBackground, UnityEngine.GUIStyle thumbStyleExtent, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(10); + var __params__ = __pool__.Rent(); + __params__[0] = value; + __params__[1] = leftValue; + __params__[2] = rightValue; + __params__[3] = power; + __params__[4] = textfieldStyle; + __params__[5] = sliderStyle; + __params__[6] = thumbStyle; + __params__[7] = sliderBackground; + __params__[8] = thumbStyleExtent; + __params__[9] = options; + var __result__ = __IntSlider__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int Popup(UnityEngine.GUIContent label, int selectedIndex, string[] displayedOptions, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = selectedIndex; + __params__[2] = displayedOptions; + __params__[3] = style; + __params__[4] = options; + var __result__ = __Popup?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static void Popup(UnityEditor.SerializedProperty property, UnityEngine.GUIContent[] displayedOptions, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = property; + __params__[1] = displayedOptions; + __params__[2] = options; + __Popup__2?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void Popup(UnityEditor.SerializedProperty property, UnityEngine.GUIContent[] displayedOptions, UnityEngine.GUIContent label, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = property; + __params__[1] = displayedOptions; + __params__[2] = label; + __params__[3] = options; + __Popup__3?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void ObjectField(UnityEditor.SerializedProperty property, System.Type objType, UnityEngine.GUIContent label, UnityEditor_EditorGUI.ObjectFieldValidator validator, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = property; + __params__[1] = objType; + __params__[2] = label; + __params__[3] = validator?.Cast(null); + __params__[4] = options; + __ObjectField?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Object MiniThumbnailObjectField(UnityEngine.GUIContent label, UnityEngine.Object obj, System.Type objType, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = obj; + __params__[2] = objType; + __params__[3] = options; + var __result__ = __MiniThumbnailObjectField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Object)(__result__) : default; + } + + public static UnityEngine.Vector3 LinkedVector3Field(UnityEngine.GUIContent label, UnityEngine.Vector3 value, ref bool proportionalScale, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = value; + __params__[2] = proportionalScale; + __params__[3] = options; + var __result__ = __LinkedVector3Field?.Invoke(null, __params__); + proportionalScale = (bool)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector3)(__result__) : default; + } + + public static UnityEngine.Vector3 LinkedVector3Field(UnityEngine.GUIContent label, UnityEngine.Vector3 value, UnityEngine.Vector3 initialValue, ref bool proportionalScale, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = value; + __params__[2] = initialValue; + __params__[3] = proportionalScale; + __params__[4] = options; + var __result__ = __LinkedVector3Field__2?.Invoke(null, __params__); + proportionalScale = (bool)(__params__[3]); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector3)(__result__) : default; + } + + public static void PropertiesField(UnityEngine.GUIContent label, UnityEditor.SerializedProperty[] properties, UnityEngine.GUIContent[] propertyLabels, float propertyLabelsWidth, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = properties; + __params__[2] = propertyLabels; + __params__[3] = propertyLabelsWidth; + __params__[4] = options; + __PropertiesField?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static int CycleButton(int selected, UnityEngine.GUIContent[] contents, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = selected; + __params__[1] = contents; + __params__[2] = style; + __params__[3] = options; + var __result__ = __CycleButton?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static bool ToggleTitlebar(bool foldout, UnityEngine.GUIContent label, ref bool toggleValue) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = foldout; + __params__[1] = label; + __params__[2] = toggleValue; + var __result__ = __ToggleTitlebar?.Invoke(null, __params__); + toggleValue = (bool)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool ToggleTitlebar(bool foldout, UnityEngine.GUIContent label, UnityEditor.SerializedProperty property) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = foldout; + __params__[1] = label; + __params__[2] = property; + var __result__ = __ToggleTitlebar__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool FoldoutTitlebar(bool foldout, UnityEngine.GUIContent label, bool skipIconSpacing) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = foldout; + __params__[1] = label; + __params__[2] = skipIconSpacing; + var __result__ = __FoldoutTitlebar?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool FoldoutTitlebar(bool foldout, UnityEngine.GUIContent label, bool skipIconSpacing, UnityEngine.GUIStyle baseStyle, UnityEngine.GUIStyle textStyle) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = foldout; + __params__[1] = label; + __params__[2] = skipIconSpacing; + __params__[3] = baseStyle; + __params__[4] = textStyle; + var __result__ = __FoldoutTitlebar__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool FoldoutInternal(bool foldout, UnityEngine.GUIContent content, bool toggleOnLabelClick, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = foldout; + __params__[1] = content; + __params__[2] = toggleOnLabelClick; + __params__[3] = style; + var __result__ = __FoldoutInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static uint LayerMaskField(uint layers, UnityEngine.GUIContent label, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = layers; + __params__[1] = label; + __params__[2] = options; + var __result__ = __LayerMaskField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (uint)(__result__) : default; + } + + public static UnityEngine.LayerMask LayerMaskField(UnityEngine.LayerMask layers, UnityEngine.GUIContent label, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = layers; + __params__[1] = label; + __params__[2] = options; + var __result__ = __LayerMaskField__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.LayerMask)(__result__) : default; + } + + public static void LayerMaskField(UnityEditor.SerializedProperty property, UnityEngine.GUIContent label, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = property; + __params__[1] = label; + __params__[2] = options; + __LayerMaskField__3?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void PrefixLabelInternal(UnityEngine.GUIContent label, UnityEngine.GUIStyle followingStyle, UnityEngine.GUIStyle labelStyle) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = followingStyle; + __params__[2] = labelStyle; + __PrefixLabelInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Rect BeginHorizontal(UnityEngine.GUIContent content, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = content; + __params__[1] = style; + __params__[2] = options; + var __result__ = __BeginHorizontal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static UnityEngine.Rect BeginVertical(UnityEngine.GUIContent content, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = content; + __params__[1] = style; + __params__[2] = options; + var __result__ = __BeginVertical?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static UnityEngine.Vector2 BeginScrollView(UnityEngine.Vector2 scrollPosition, bool alwaysShowHorizontal, bool alwaysShowVertical, UnityEngine.GUIStyle horizontalScrollbar, UnityEngine.GUIStyle verticalScrollbar, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = scrollPosition; + __params__[1] = alwaysShowHorizontal; + __params__[2] = alwaysShowVertical; + __params__[3] = horizontalScrollbar; + __params__[4] = verticalScrollbar; + __params__[5] = options; + var __result__ = __BeginScrollView?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector2)(__result__) : default; + } + + public static UnityEngine.Vector2 BeginVerticalScrollView(UnityEngine.Vector2 scrollPosition, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = scrollPosition; + __params__[1] = options; + var __result__ = __BeginVerticalScrollView?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector2)(__result__) : default; + } + + public static UnityEngine.Vector2 BeginVerticalScrollView(UnityEngine.Vector2 scrollPosition, bool alwaysShowVertical, UnityEngine.GUIStyle verticalScrollbar, UnityEngine.GUIStyle background, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = scrollPosition; + __params__[1] = alwaysShowVertical; + __params__[2] = verticalScrollbar; + __params__[3] = background; + __params__[4] = options; + var __result__ = __BeginVerticalScrollView__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector2)(__result__) : default; + } + + public static UnityEngine.Vector2 BeginHorizontalScrollView(UnityEngine.Vector2 scrollPosition, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = scrollPosition; + __params__[1] = options; + var __result__ = __BeginHorizontalScrollView?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector2)(__result__) : default; + } + + public static UnityEngine.Vector2 BeginHorizontalScrollView(UnityEngine.Vector2 scrollPosition, bool alwaysShowHorizontal, UnityEngine.GUIStyle horizontalScrollbar, UnityEngine.GUIStyle background, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = scrollPosition; + __params__[1] = alwaysShowHorizontal; + __params__[2] = horizontalScrollbar; + __params__[3] = background; + __params__[4] = options; + var __result__ = __BeginHorizontalScrollView__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector2)(__result__) : default; + } + + public static void EndScrollView(bool handleScrollWheel) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = handleScrollWheel; + __EndScrollView?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static bool IsChildrenIncluded(UnityEditor.SerializedProperty prop) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = prop; + var __result__ = __IsChildrenIncluded?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static UnityEngine.Rect GetSliderRect(bool hasLabel, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = hasLabel; + __params__[1] = options; + var __result__ = __GetSliderRect?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static UnityEngine.Rect GetSliderRect(bool hasLabel, UnityEngine.GUIStyle sliderStyle, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = hasLabel; + __params__[1] = sliderStyle; + __params__[2] = options; + var __result__ = __GetSliderRect__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static UnityEngine.Rect GetToggleRect(bool hasLabel, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = hasLabel; + __params__[1] = options; + var __result__ = __GetToggleRect?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static int BeginPlatformGrouping(Array platforms, UnityEngine.GUIContent defaultTab) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = platforms; + __params__[1] = defaultTab; + var __result__ = __BeginPlatformGrouping?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static UnityEngine.Rect GetTabRect(UnityEngine.Rect rect, int tabIndex, int tabCount, out UnityEngine.GUIStyle tabStyle) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = tabIndex; + __params__[2] = tabCount; + __params__[3] = null; + var __result__ = __GetTabRect?.Invoke(null, __params__); + tabStyle = (UnityEngine.GUIStyle)(__params__[3]); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static int BeginPlatformGrouping(Array platforms, UnityEngine.GUIContent defaultTab, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = platforms; + __params__[1] = defaultTab; + __params__[2] = style; + var __result__ = __BeginPlatformGrouping__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int BeginPlatformGrouping(Array platforms, UnityEngine.GUIContent defaultTab, UnityEngine.GUIStyle style, System.Func showOverrideForPlatform) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = platforms; + __params__[1] = defaultTab; + __params__[2] = style; + __params__[3] = showOverrideForPlatform; + var __result__ = __BeginPlatformGrouping__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static void EndPlatformGrouping() + { + __EndPlatformGrouping?.Invoke(null, System.Array.Empty()); + } + + public static void MultiSelectionObjectTitleBar(UnityEngine.Object[] objects) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = objects; + __MultiSelectionObjectTitleBar?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static bool BitToggleField(string label, UnityEditor.SerializedProperty bitFieldProperty, int flag) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = bitFieldProperty; + __params__[2] = flag; + var __result__ = __BitToggleField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void SortingLayerField(UnityEngine.GUIContent label, UnityEditor.SerializedProperty layerID, UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = layerID; + __params__[2] = style; + __SortingLayerField?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static string TextFieldDropDown(string text, string[] dropDownElement) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = text; + __params__[1] = dropDownElement; + var __result__ = __TextFieldDropDown?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string TextFieldDropDown(UnityEngine.GUIContent label, string text, string[] dropDownElement) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = text; + __params__[2] = dropDownElement; + var __result__ = __TextFieldDropDown__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string DelayedTextFieldDropDown(string text, string[] dropDownElement) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = text; + __params__[1] = dropDownElement; + var __result__ = __DelayedTextFieldDropDown?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string DelayedTextFieldDropDown(UnityEngine.GUIContent label, string text, string[] dropDownElement) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = text; + __params__[2] = dropDownElement; + var __result__ = __DelayedTextFieldDropDown__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static bool DropDownToggle(ref bool toggled, UnityEngine.GUIContent content, UnityEngine.GUIStyle toggleStyle) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = toggled; + __params__[1] = content; + __params__[2] = toggleStyle; + var __result__ = __DropDownToggle?.Invoke(null, __params__); + toggled = (bool)(__params__[0]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool DropDownToggle(ref bool toggled, UnityEngine.GUIContent content, UnityEngine.GUIStyle toggleStyle, UnityEngine.GUIStyle toggleDropdownButtonStyle) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = toggled; + __params__[1] = content; + __params__[2] = toggleStyle; + __params__[3] = toggleDropdownButtonStyle; + var __result__ = __DropDownToggle__2?.Invoke(null, __params__); + toggled = (bool)(__params__[0]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static int AdvancedPopup(int selectedIndex, string[] displayedOptions, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = selectedIndex; + __params__[1] = displayedOptions; + __params__[2] = options; + var __result__ = __AdvancedPopup?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int AdvancedPopup(int selectedIndex, string[] displayedOptions, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = selectedIndex; + __params__[1] = displayedOptions; + __params__[2] = style; + __params__[3] = options; + var __result__ = __AdvancedPopup__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int AdvancedLazyPopup(string displayedOption, int selectedIndex, Delegate displayedOptionsFunc, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = displayedOption; + __params__[1] = selectedIndex; + __params__[2] = displayedOptionsFunc; + __params__[3] = style; + __params__[4] = options; + var __result__ = __AdvancedLazyPopup?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static System.Enum EnumMaskPopup(UnityEngine.GUIContent label, System.Enum selected, out int changedFlags, out bool changedToValue, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = selected; + __params__[2] = null; + __params__[3] = null; + __params__[4] = style; + __params__[5] = options; + var __result__ = __EnumMaskPopup?.Invoke(null, __params__); + changedFlags = (int)(__params__[2]); + changedToValue = (bool)(__params__[3]); + __pool__.Return(__params__); + return __result__ != null ? (System.Enum)(__result__) : default; + } + + public static float AngularDial(UnityEngine.GUIContent label, float angle, UnityEngine.Texture thumbTexture, UnityEngine.GUIStyle background, UnityEngine.GUIStyle thumb, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = angle; + __params__[2] = thumbTexture; + __params__[3] = background; + __params__[4] = thumb; + __params__[5] = options; + var __result__ = __AngularDial?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static UnityEngine.Gradient GradientField(UnityEditor.SerializedProperty value, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = value; + __params__[1] = options; + var __result__ = __GradientField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Gradient)(__result__) : default; + } + + public static UnityEngine.Gradient GradientField(string label, UnityEditor.SerializedProperty value, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = value; + __params__[2] = options; + var __result__ = __GradientField__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Gradient)(__result__) : default; + } + + public static UnityEngine.Gradient GradientField(UnityEngine.GUIContent label, UnityEditor.SerializedProperty value, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = value; + __params__[2] = options; + var __result__ = __GradientField__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Gradient)(__result__) : default; + } + + public static UnityEngine.Color32 HexColorTextField(UnityEngine.GUIContent label, UnityEngine.Color32 color, bool showAlpha, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = color; + __params__[2] = showAlpha; + __params__[3] = options; + var __result__ = __HexColorTextField?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Color32)(__result__) : default; + } + + public static UnityEngine.Color32 HexColorTextField(UnityEngine.GUIContent label, UnityEngine.Color32 color, bool showAlpha, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = color; + __params__[2] = showAlpha; + __params__[3] = style; + __params__[4] = options; + var __result__ = __HexColorTextField__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Color32)(__result__) : default; + } + + public static bool IconButton(int id, UnityEngine.GUIContent content, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = id; + __params__[1] = content; + __params__[2] = style; + __params__[3] = options; + var __result__ = __IconButton?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void GameViewSizePopup(UnityEditor.GameViewSizeGroupType groupType, int selectedIndex, object gameView, UnityEngine.GUIStyle style, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = groupType; + __params__[1] = selectedIndex; + __params__[2] = gameView; + __params__[3] = style; + __params__[4] = options; + __GameViewSizePopup?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void SortingLayerField(UnityEngine.GUIContent label, UnityEditor.SerializedProperty layerID, UnityEngine.GUIStyle style, UnityEngine.GUIStyle labelStyle) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = layerID; + __params__[2] = style; + __params__[3] = labelStyle; + __SortingLayerField__2?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void SliderWithTexture(UnityEngine.GUIContent label, UnityEditor.SerializedProperty property, float sliderMin, float sliderMax, float power, UnityEngine.Texture2D sliderBackground, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(7); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = property; + __params__[2] = sliderMin; + __params__[3] = sliderMax; + __params__[4] = power; + __params__[5] = sliderBackground; + __params__[6] = options; + __SliderWithTexture?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static float SliderWithTexture(UnityEngine.GUIContent label, float sliderValue, float sliderMin, float sliderMax, string formatString, UnityEngine.Texture2D sliderBackground, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(7); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = sliderValue; + __params__[2] = sliderMin; + __params__[3] = sliderMax; + __params__[4] = formatString; + __params__[5] = sliderBackground; + __params__[6] = options; + var __result__ = __SliderWithTexture__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float SliderWithTexture(UnityEngine.GUIContent label, float sliderValue, float sliderMin, float sliderMax, string formatString, float textFieldMin, float textFieldMax, UnityEngine.Texture2D sliderBackground, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(9); + var __params__ = __pool__.Rent(); + __params__[0] = label; + __params__[1] = sliderValue; + __params__[2] = sliderMin; + __params__[3] = sliderMax; + __params__[4] = formatString; + __params__[5] = textFieldMin; + __params__[6] = textFieldMax; + __params__[7] = sliderBackground; + __params__[8] = options; + var __result__ = __SliderWithTexture__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static void TargetChoiceField(UnityEditor.SerializedProperty property, UnityEngine.GUIContent label, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = property; + __params__[1] = label; + __params__[2] = options; + __TargetChoiceField?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void TargetChoiceField(UnityEditor.SerializedProperty property, UnityEngine.GUIContent label, Delegate func, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = property; + __params__[1] = label; + __params__[2] = func; + __params__[3] = options; + __TargetChoiceField__2?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static bool EditorToolbar(UnityEngine.GUIContent content, T selected, object tools, out T clicked) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = content; + __params__[1] = selected; + __params__[2] = tools; + __params__[3] = null; + var __result__ = __EditorToolbar?.Invoke(null, __params__); + clicked = (T)(__params__[3]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public UnityEditor_EditorGUILayout(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + public UnityEditor.EditorGUILayout __super__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.EditorGUILayout)(__self__); + } + + private static FieldInfo ___s_LastRect; + private static FieldInfo __s_LastRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LastRect ??= __type__?.GetField("s_LastRect", (BindingFlags)(-1)); + } + + private static FieldInfo ___kPlatformTabWidth; + private static FieldInfo __kPlatformTabWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kPlatformTabWidth ??= __type__?.GetField("kPlatformTabWidth", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_SelectedDefault; + private static FieldInfo __s_SelectedDefault + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_SelectedDefault ??= __type__?.GetField("s_SelectedDefault", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_TabOnlyOne; + private static FieldInfo __s_TabOnlyOne + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_TabOnlyOne ??= __type__?.GetField("s_TabOnlyOne", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_TabFirst; + private static FieldInfo __s_TabFirst + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_TabFirst ??= __type__?.GetField("s_TabFirst", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_TabMiddle; + private static FieldInfo __s_TabMiddle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_TabMiddle ??= __type__?.GetField("s_TabMiddle", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_TabLast; + private static FieldInfo __s_TabLast + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_TabLast ??= __type__?.GetField("s_TabLast", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ButtonArrays; + private static FieldInfo __s_ButtonArrays + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ButtonArrays ??= __type__?.GetField("s_ButtonArrays", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_BoolArrays; + private static FieldInfo __s_BoolArrays + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_BoolArrays ??= __type__?.GetField("s_BoolArrays", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_CustomEditorTools; + private static FieldInfo __s_CustomEditorTools + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_CustomEditorTools ??= __type__?.GetField("s_CustomEditorTools", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_CustomEditorContexts; + private static FieldInfo __s_CustomEditorContexts + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_CustomEditorContexts ??= __type__?.GetField("s_CustomEditorContexts", (BindingFlags)(-1)); + } + + private static PropertyInfo ___kLabelFloatMinW; + private static PropertyInfo __kLabelFloatMinW + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kLabelFloatMinW ??= __type__?.GetProperty("kLabelFloatMinW", (BindingFlags)(-1)); + } + + private static PropertyInfo ___kLabelFloatMaxW; + private static PropertyInfo __kLabelFloatMaxW + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kLabelFloatMaxW ??= __type__?.GetProperty("kLabelFloatMaxW", (BindingFlags)(-1)); + } + + private static MethodInfo ___DelayedTextField; + private static MethodInfo __DelayedTextField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DelayedTextField ??= __type__?.GetMethodInfoByParameterTypeNames("DelayedTextField", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___ToolbarSearchField; + private static MethodInfo __ToolbarSearchField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ToolbarSearchField ??= __type__?.GetMethodInfoByParameterTypeNames("ToolbarSearchField", "System.String", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___ToolbarSearchField__2; + private static MethodInfo __ToolbarSearchField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ToolbarSearchField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("ToolbarSearchField", "System.String", "System.String[]", "System.Int32&", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___KeyEventField; + private static MethodInfo __KeyEventField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___KeyEventField ??= __type__?.GetMethodInfoByParameterTypeNames("KeyEventField", "UnityEngine.Event", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___VUMeterHorizontal; + private static MethodInfo __VUMeterHorizontal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___VUMeterHorizontal ??= __type__?.GetMethodInfoByParameterTypeNames("VUMeterHorizontal", "System.Single", "System.Single", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___VUMeterHorizontal__2; + private static MethodInfo __VUMeterHorizontal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___VUMeterHorizontal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("VUMeterHorizontal", "System.Single", "UnityEditor.EditorGUI+VUMeter+SmoothingData&", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___Slider; + private static MethodInfo __Slider + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Slider ??= __type__?.GetMethodInfoByParameterTypeNames("Slider", "UnityEngine.GUIContent", "System.Single", "System.Single", "System.Single", "System.Single", "System.Single", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___GetSliderParts; + private static MethodInfo __GetSliderParts + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSliderParts ??= __type__?.GetMethodInfoByParameterTypeNames("GetSliderParts", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle&", "UnityEngine.GUIStyle&", "UnityEngine.GUIStyle&"); + } + + private static MethodInfo ___GetHorizontalSliderParts; + private static MethodInfo __GetHorizontalSliderParts + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetHorizontalSliderParts ??= __type__?.GetMethodInfoByParameterTypeNames("GetHorizontalSliderParts", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle&", "UnityEngine.GUIStyle&", "UnityEngine.GUIStyle&"); + } + + private static MethodInfo ___GetVerticalSliderParts; + private static MethodInfo __GetVerticalSliderParts + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetVerticalSliderParts ??= __type__?.GetMethodInfoByParameterTypeNames("GetVerticalSliderParts", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle&", "UnityEngine.GUIStyle&", "UnityEngine.GUIStyle&"); + } + + private static MethodInfo ___Slider__2; + private static MethodInfo __Slider__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Slider__2 ??= __type__?.GetMethodInfoByParameterTypeNames("Slider", "UnityEngine.GUIContent", "System.Single", "System.Single", "System.Single", "System.Single", "System.Single", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___Slider__3; + private static MethodInfo __Slider__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Slider__3 ??= __type__?.GetMethodInfoByParameterTypeNames("Slider", "UnityEngine.GUIContent", "System.Single", "System.Single", "System.Single", "System.Single", "System.Single", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle", "UnityEngine.Texture2D", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___Slider__4; + private static MethodInfo __Slider__4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Slider__4 ??= __type__?.GetMethodInfoByParameterTypeNames("Slider", "UnityEditor.SerializedProperty", "System.Single", "System.Single", "System.Single", "System.Single", "UnityEngine.GUIContent", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___PowerSlider; + private static MethodInfo __PowerSlider + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PowerSlider ??= __type__?.GetMethodInfoByParameterTypeNames("PowerSlider", "System.String", "System.Single", "System.Single", "System.Single", "System.Single", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___PowerSlider__2; + private static MethodInfo __PowerSlider__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PowerSlider__2 ??= __type__?.GetMethodInfoByParameterTypeNames("PowerSlider", "UnityEngine.GUIContent", "System.Single", "System.Single", "System.Single", "System.Single", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___IntSlider; + private static MethodInfo __IntSlider + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IntSlider ??= __type__?.GetMethodInfoByParameterTypeNames("IntSlider", "System.Int32", "System.Int32", "System.Int32", "System.Single", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___IntSlider__2; + private static MethodInfo __IntSlider__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IntSlider__2 ??= __type__?.GetMethodInfoByParameterTypeNames("IntSlider", "System.Int32", "System.Int32", "System.Int32", "System.Single", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle", "UnityEngine.Texture2D", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___Popup; + private static MethodInfo __Popup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Popup ??= __type__?.GetMethodInfoByParameterTypeNames("Popup", "UnityEngine.GUIContent", "System.Int32", "System.String[]", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___Popup__2; + private static MethodInfo __Popup__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Popup__2 ??= __type__?.GetMethodInfoByParameterTypeNames("Popup", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent[]", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___Popup__3; + private static MethodInfo __Popup__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Popup__3 ??= __type__?.GetMethodInfoByParameterTypeNames("Popup", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent[]", "UnityEngine.GUIContent", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___ObjectField; + private static MethodInfo __ObjectField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ObjectField ??= __type__?.GetMethodInfoByParameterTypeNames("ObjectField", "UnityEditor.SerializedProperty", "System.Type", "UnityEngine.GUIContent", "UnityEditor.EditorGUI+ObjectFieldValidator", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___MiniThumbnailObjectField; + private static MethodInfo __MiniThumbnailObjectField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MiniThumbnailObjectField ??= __type__?.GetMethodInfoByParameterTypeNames("MiniThumbnailObjectField", "UnityEngine.GUIContent", "UnityEngine.Object", "System.Type", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___LinkedVector3Field; + private static MethodInfo __LinkedVector3Field + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LinkedVector3Field ??= __type__?.GetMethodInfoByParameterTypeNames("LinkedVector3Field", "UnityEngine.GUIContent", "UnityEngine.Vector3", "System.Boolean&", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___LinkedVector3Field__2; + private static MethodInfo __LinkedVector3Field__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LinkedVector3Field__2 ??= __type__?.GetMethodInfoByParameterTypeNames("LinkedVector3Field", "UnityEngine.GUIContent", "UnityEngine.Vector3", "UnityEngine.Vector3", "System.Boolean&", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___PropertiesField; + private static MethodInfo __PropertiesField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PropertiesField ??= __type__?.GetMethodInfoByParameterTypeNames("PropertiesField", "UnityEngine.GUIContent", "UnityEditor.SerializedProperty[]", "UnityEngine.GUIContent[]", "System.Single", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___CycleButton; + private static MethodInfo __CycleButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CycleButton ??= __type__?.GetMethodInfoByParameterTypeNames("CycleButton", "System.Int32", "UnityEngine.GUIContent[]", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___ToggleTitlebar; + private static MethodInfo __ToggleTitlebar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ToggleTitlebar ??= __type__?.GetMethodInfoByParameterTypeNames("ToggleTitlebar", "System.Boolean", "UnityEngine.GUIContent", "System.Boolean&"); + } + + private static MethodInfo ___ToggleTitlebar__2; + private static MethodInfo __ToggleTitlebar__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ToggleTitlebar__2 ??= __type__?.GetMethodInfoByParameterTypeNames("ToggleTitlebar", "System.Boolean", "UnityEngine.GUIContent", "UnityEditor.SerializedProperty"); + } + + private static MethodInfo ___FoldoutTitlebar; + private static MethodInfo __FoldoutTitlebar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FoldoutTitlebar ??= __type__?.GetMethodInfoByParameterTypeNames("FoldoutTitlebar", "System.Boolean", "UnityEngine.GUIContent", "System.Boolean"); + } + + private static MethodInfo ___FoldoutTitlebar__2; + private static MethodInfo __FoldoutTitlebar__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FoldoutTitlebar__2 ??= __type__?.GetMethodInfoByParameterTypeNames("FoldoutTitlebar", "System.Boolean", "UnityEngine.GUIContent", "System.Boolean", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___FoldoutInternal; + private static MethodInfo __FoldoutInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FoldoutInternal ??= __type__?.GetMethodInfoByParameterTypeNames("FoldoutInternal", "System.Boolean", "UnityEngine.GUIContent", "System.Boolean", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___LayerMaskField; + private static MethodInfo __LayerMaskField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LayerMaskField ??= __type__?.GetMethodInfoByParameterTypeNames("LayerMaskField", "System.UInt32", "UnityEngine.GUIContent", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___LayerMaskField__2; + private static MethodInfo __LayerMaskField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LayerMaskField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("LayerMaskField", "UnityEngine.LayerMask", "UnityEngine.GUIContent", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___LayerMaskField__3; + private static MethodInfo __LayerMaskField__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LayerMaskField__3 ??= __type__?.GetMethodInfoByParameterTypeNames("LayerMaskField", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___PrefixLabelInternal; + private static MethodInfo __PrefixLabelInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PrefixLabelInternal ??= __type__?.GetMethodInfoByParameterTypeNames("PrefixLabelInternal", "UnityEngine.GUIContent", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___BeginHorizontal; + private static MethodInfo __BeginHorizontal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginHorizontal ??= __type__?.GetMethodInfoByParameterTypeNames("BeginHorizontal", "UnityEngine.GUIContent", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___BeginVertical; + private static MethodInfo __BeginVertical + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginVertical ??= __type__?.GetMethodInfoByParameterTypeNames("BeginVertical", "UnityEngine.GUIContent", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___BeginScrollView; + private static MethodInfo __BeginScrollView + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginScrollView ??= __type__?.GetMethodInfoByParameterTypeNames("BeginScrollView", "UnityEngine.Vector2", "System.Boolean", "System.Boolean", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___BeginVerticalScrollView; + private static MethodInfo __BeginVerticalScrollView + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginVerticalScrollView ??= __type__?.GetMethodInfoByParameterTypeNames("BeginVerticalScrollView", "UnityEngine.Vector2", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___BeginVerticalScrollView__2; + private static MethodInfo __BeginVerticalScrollView__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginVerticalScrollView__2 ??= __type__?.GetMethodInfoByParameterTypeNames("BeginVerticalScrollView", "UnityEngine.Vector2", "System.Boolean", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___BeginHorizontalScrollView; + private static MethodInfo __BeginHorizontalScrollView + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginHorizontalScrollView ??= __type__?.GetMethodInfoByParameterTypeNames("BeginHorizontalScrollView", "UnityEngine.Vector2", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___BeginHorizontalScrollView__2; + private static MethodInfo __BeginHorizontalScrollView__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginHorizontalScrollView__2 ??= __type__?.GetMethodInfoByParameterTypeNames("BeginHorizontalScrollView", "UnityEngine.Vector2", "System.Boolean", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___EndScrollView; + private static MethodInfo __EndScrollView + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EndScrollView ??= __type__?.GetMethodInfoByParameterTypeNames("EndScrollView", "System.Boolean"); + } + + private static MethodInfo ___IsChildrenIncluded; + private static MethodInfo __IsChildrenIncluded + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsChildrenIncluded ??= __type__?.GetMethodInfoByParameterTypeNames("IsChildrenIncluded", "UnityEditor.SerializedProperty"); + } + + private static MethodInfo ___GetSliderRect; + private static MethodInfo __GetSliderRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSliderRect ??= __type__?.GetMethodInfoByParameterTypeNames("GetSliderRect", "System.Boolean", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___GetSliderRect__2; + private static MethodInfo __GetSliderRect__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSliderRect__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GetSliderRect", "System.Boolean", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___GetToggleRect; + private static MethodInfo __GetToggleRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetToggleRect ??= __type__?.GetMethodInfoByParameterTypeNames("GetToggleRect", "System.Boolean", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___BeginPlatformGrouping; + private static MethodInfo __BeginPlatformGrouping + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginPlatformGrouping ??= __type__?.GetMethodInfoByParameterTypeNames("BeginPlatformGrouping", "UnityEditor.Build.BuildPlatform[]", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___GetTabRect; + private static MethodInfo __GetTabRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetTabRect ??= __type__?.GetMethodInfoByParameterTypeNames("GetTabRect", "UnityEngine.Rect", "System.Int32", "System.Int32", "UnityEngine.GUIStyle&"); + } + + private static MethodInfo ___BeginPlatformGrouping__2; + private static MethodInfo __BeginPlatformGrouping__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginPlatformGrouping__2 ??= __type__?.GetMethodInfoByParameterTypeNames("BeginPlatformGrouping", "UnityEditor.Build.BuildPlatform[]", "UnityEngine.GUIContent", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___BeginPlatformGrouping__3; + private static MethodInfo __BeginPlatformGrouping__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginPlatformGrouping__3 ??= __type__?.GetMethodInfoByParameterTypeNames("BeginPlatformGrouping", "UnityEditor.Build.BuildPlatform[]", "UnityEngine.GUIContent", "UnityEngine.GUIStyle", "System.Func`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); + } + + private static MethodInfo ___EndPlatformGrouping; + private static MethodInfo __EndPlatformGrouping + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EndPlatformGrouping ??= __type__?.GetMethodInfoByParameterTypeNames("EndPlatformGrouping"); + } + + private static MethodInfo ___MultiSelectionObjectTitleBar; + private static MethodInfo __MultiSelectionObjectTitleBar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MultiSelectionObjectTitleBar ??= __type__?.GetMethodInfoByParameterTypeNames("MultiSelectionObjectTitleBar", "UnityEngine.Object[]"); + } + + private static MethodInfo ___BitToggleField; + private static MethodInfo __BitToggleField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BitToggleField ??= __type__?.GetMethodInfoByParameterTypeNames("BitToggleField", "System.String", "UnityEditor.SerializedProperty", "System.Int32"); + } + + private static MethodInfo ___SortingLayerField; + private static MethodInfo __SortingLayerField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SortingLayerField ??= __type__?.GetMethodInfoByParameterTypeNames("SortingLayerField", "UnityEngine.GUIContent", "UnityEditor.SerializedProperty", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___TextFieldDropDown; + private static MethodInfo __TextFieldDropDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TextFieldDropDown ??= __type__?.GetMethodInfoByParameterTypeNames("TextFieldDropDown", "System.String", "System.String[]"); + } + + private static MethodInfo ___TextFieldDropDown__2; + private static MethodInfo __TextFieldDropDown__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TextFieldDropDown__2 ??= __type__?.GetMethodInfoByParameterTypeNames("TextFieldDropDown", "UnityEngine.GUIContent", "System.String", "System.String[]"); + } + + private static MethodInfo ___DelayedTextFieldDropDown; + private static MethodInfo __DelayedTextFieldDropDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DelayedTextFieldDropDown ??= __type__?.GetMethodInfoByParameterTypeNames("DelayedTextFieldDropDown", "System.String", "System.String[]"); + } + + private static MethodInfo ___DelayedTextFieldDropDown__2; + private static MethodInfo __DelayedTextFieldDropDown__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DelayedTextFieldDropDown__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DelayedTextFieldDropDown", "UnityEngine.GUIContent", "System.String", "System.String[]"); + } + + private static MethodInfo ___DropDownToggle; + private static MethodInfo __DropDownToggle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DropDownToggle ??= __type__?.GetMethodInfoByParameterTypeNames("DropDownToggle", "System.Boolean&", "UnityEngine.GUIContent", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DropDownToggle__2; + private static MethodInfo __DropDownToggle__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DropDownToggle__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DropDownToggle", "System.Boolean&", "UnityEngine.GUIContent", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___AdvancedPopup; + private static MethodInfo __AdvancedPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AdvancedPopup ??= __type__?.GetMethodInfoByParameterTypeNames("AdvancedPopup", "System.Int32", "System.String[]", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___AdvancedPopup__2; + private static MethodInfo __AdvancedPopup__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AdvancedPopup__2 ??= __type__?.GetMethodInfoByParameterTypeNames("AdvancedPopup", "System.Int32", "System.String[]", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___AdvancedLazyPopup; + private static MethodInfo __AdvancedLazyPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AdvancedLazyPopup ??= __type__?.GetMethodInfoByParameterTypeNames("AdvancedLazyPopup", "System.String", "System.Int32", "System.Func`1[[UnityEditor.Tuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], UnityEditor.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___EnumMaskPopup; + private static MethodInfo __EnumMaskPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EnumMaskPopup ??= __type__?.GetMethodInfoByParameterTypeNames("EnumMaskPopup", "UnityEngine.GUIContent", "System.Enum", "System.Int32&", "System.Boolean&", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___AngularDial; + private static MethodInfo __AngularDial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AngularDial ??= __type__?.GetMethodInfoByParameterTypeNames("AngularDial", "UnityEngine.GUIContent", "System.Single", "UnityEngine.Texture", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___GradientField; + private static MethodInfo __GradientField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GradientField ??= __type__?.GetMethodInfoByParameterTypeNames("GradientField", "UnityEditor.SerializedProperty", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___GradientField__2; + private static MethodInfo __GradientField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GradientField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GradientField", "System.String", "UnityEditor.SerializedProperty", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___GradientField__3; + private static MethodInfo __GradientField__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GradientField__3 ??= __type__?.GetMethodInfoByParameterTypeNames("GradientField", "UnityEngine.GUIContent", "UnityEditor.SerializedProperty", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___HexColorTextField; + private static MethodInfo __HexColorTextField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HexColorTextField ??= __type__?.GetMethodInfoByParameterTypeNames("HexColorTextField", "UnityEngine.GUIContent", "UnityEngine.Color32", "System.Boolean", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___HexColorTextField__2; + private static MethodInfo __HexColorTextField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HexColorTextField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("HexColorTextField", "UnityEngine.GUIContent", "UnityEngine.Color32", "System.Boolean", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___IconButton; + private static MethodInfo __IconButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IconButton ??= __type__?.GetMethodInfoByParameterTypeNames("IconButton", "System.Int32", "UnityEngine.GUIContent", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___GameViewSizePopup; + private static MethodInfo __GameViewSizePopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GameViewSizePopup ??= __type__?.GetMethodInfoByParameterTypeNames("GameViewSizePopup", "UnityEditor.GameViewSizeGroupType", "System.Int32", "UnityEditor.IGameViewSizeMenuUser", "UnityEngine.GUIStyle", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___SortingLayerField__2; + private static MethodInfo __SortingLayerField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SortingLayerField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("SortingLayerField", "UnityEngine.GUIContent", "UnityEditor.SerializedProperty", "UnityEngine.GUIStyle", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___SliderWithTexture; + private static MethodInfo __SliderWithTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SliderWithTexture ??= __type__?.GetMethodInfoByParameterTypeNames("SliderWithTexture", "UnityEngine.GUIContent", "UnityEditor.SerializedProperty", "System.Single", "System.Single", "System.Single", "UnityEngine.Texture2D", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___SliderWithTexture__2; + private static MethodInfo __SliderWithTexture__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SliderWithTexture__2 ??= __type__?.GetMethodInfoByParameterTypeNames("SliderWithTexture", "UnityEngine.GUIContent", "System.Single", "System.Single", "System.Single", "System.String", "UnityEngine.Texture2D", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___SliderWithTexture__3; + private static MethodInfo __SliderWithTexture__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SliderWithTexture__3 ??= __type__?.GetMethodInfoByParameterTypeNames("SliderWithTexture", "UnityEngine.GUIContent", "System.Single", "System.Single", "System.Single", "System.String", "System.Single", "System.Single", "UnityEngine.Texture2D", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___TargetChoiceField; + private static MethodInfo __TargetChoiceField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TargetChoiceField ??= __type__?.GetMethodInfoByParameterTypeNames("TargetChoiceField", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___TargetChoiceField__2; + private static MethodInfo __TargetChoiceField__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TargetChoiceField__2 ??= __type__?.GetMethodInfoByParameterTypeNames("TargetChoiceField", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent", "UnityEditor.TargetChoiceHandler+TargetChoiceMenuFunction", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___EditorToolbar; + private static MethodInfo __EditorToolbar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EditorToolbar ??= __type__?.GetMethodInfoByParameterTypeNames("EditorToolbar", "UnityEngine.GUIContent", "", "", ""); + } + } + public static class UnityEditor_EditorGUILayout_Extension + { + public static UnityEditor_EditorGUILayout ReflectionHelper(this UnityEditor.EditorGUILayout self) => new(self); + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUILayout.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUILayout.cs.meta new file mode 100644 index 0000000..0cf0958 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUILayout.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f1590539b5f24b24caa6f684bbad165a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUIUtility.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUIUtility.cs new file mode 100644 index 0000000..f19962c --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUIUtility.cs @@ -0,0 +1,2233 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_EditorGUIUtility + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.EditorGUIUtility"); + + public delegate bool HeaderItemDelegate(UnityEngine.Rect rectangle, UnityEngine.Object[] targets); + + public static int skinIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__skinIndex?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __skinIndex?.SetValue(null, value); + } + + public static UnityEngine.Material GUITextureBlit2SRGBMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Material)(__GUITextureBlit2SRGBMaterial?.GetValue(null)); + } + + public static UnityEngine.Material GUITextureBlitSceneGUIMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Material)(__GUITextureBlitSceneGUIMaterial?.GetValue(null)); + } + + public static UnityEngine.Texture2D infoIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Texture2D)(__infoIcon?.GetValue(null)); + } + + public static UnityEngine.Texture2D warningIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Texture2D)(__warningIcon?.GetValue(null)); + } + + public static UnityEngine.Texture2D errorIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Texture2D)(__errorIcon?.GetValue(null)); + } + + public static UnityEngine.GUIContent blankContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__blankContent?.GetValue(null)); + } + + public static UnityEngine.GUIStyle whiteTextureStyle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__whiteTextureStyle?.GetValue(null)); + } + + public static object comparisonViewMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__comparisonViewMode?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __comparisonViewMode?.SetValue(null, value); + } + + public static float leftMarginCoord + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__leftMarginCoord?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __leftMarginCoord?.SetValue(null, value); + } + + public static float contextWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__contextWidth?.GetValue(null)); + } + + public static float currentViewWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__currentViewWidth?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __currentViewWidth?.SetValue(null, value); + } + + public static UnityEngine.EventType magnifyGestureEventType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.EventType)(__magnifyGestureEventType?.GetValue(null)); + } + + public static UnityEngine.EventType swipeGestureEventType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.EventType)(__swipeGestureEventType?.GetValue(null)); + } + + public static UnityEngine.EventType rotateGestureEventType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.EventType)(__rotateGestureEventType?.GetValue(null)); + } + + public static UnityEngine.Material s_GUITextureBlit2SRGBMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Material)(__s_GUITextureBlit2SRGBMaterial?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_GUITextureBlit2SRGBMaterial?.SetValue(null, value); + } + + public static UnityEngine.Material s_GUITextureBlitSceneGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Material)(__s_GUITextureBlitSceneGUI?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_GUITextureBlitSceneGUI?.SetValue(null, value); + } + + public static int s_FontIsBold + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_FontIsBold?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_FontIsBold?.SetValue(null, value); + } + + public static int s_LastControlID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_LastControlID?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LastControlID?.SetValue(null, value); + } + + public static float s_LabelWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__s_LabelWidth?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LabelWidth?.SetValue(null, value); + } + + public static object s_InfoIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__s_InfoIcon?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_InfoIcon?.SetValue(null, value); + } + + public static object s_WarningIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__s_WarningIcon?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_WarningIcon?.SetValue(null, value); + } + + public static object s_ErrorIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__s_ErrorIcon?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ErrorIcon?.SetValue(null, value); + } + + public static UnityEngine.GUIStyle s_WhiteTextureStyle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__s_WhiteTextureStyle?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_WhiteTextureStyle?.SetValue(null, value); + } + + public static UnityEngine.GUIStyle s_BasicTextureStyle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__s_BasicTextureStyle?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_BasicTextureStyle?.SetValue(null, value); + } + + public static System.Collections.Hashtable s_TextGUIContents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Hashtable)(__s_TextGUIContents?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_TextGUIContents?.SetValue(null, value); + } + + public static System.Collections.Hashtable s_GUIContents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Hashtable)(__s_GUIContents?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_GUIContents?.SetValue(null, value); + } + + public static System.Collections.Hashtable s_IconGUIContents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Hashtable)(__s_IconGUIContents?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_IconGUIContents?.SetValue(null, value); + } + + public static System.Collections.Hashtable s_SkinnedIcons + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Hashtable)(__s_SkinnedIcons?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_SkinnedIcons?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_ObjectContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_ObjectContent?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ObjectContent?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_Text + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_Text?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_Text?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_Image + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_Image?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_Image?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_TextImage + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_TextImage?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_TextImage?.SetValue(null, value); + } + + public static object kViewBackgroundColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__kViewBackgroundColor?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kViewBackgroundColor?.SetValue(null, value); + } + + public static System.Action contextualPropertyMenu + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Action)(__contextualPropertyMenu__2?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __contextualPropertyMenu__2?.SetValue(null, value); + } + + public static System.Action beginProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Action)(__beginProperty__2?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __beginProperty__2?.SetValue(null, value); + } + + public static System.Collections.IList s_EditorHeaderItemsMethods + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.IList)(__s_EditorHeaderItemsMethods?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_EditorHeaderItemsMethods?.SetValue(null, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static HeaderItemDelegate s_EditorHeaderItemsMethods__GetItem(int i) => (s_EditorHeaderItemsMethods?[i] as Delegate)?.Cast(); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void s_EditorHeaderItemsMethods__SetItem(int i, HeaderItemDelegate value) + { + var __list__ = s_EditorHeaderItemsMethods; + if (__list__ == null) return; + __list__[i] = value?.Cast(__E__s_EditorHeaderItemsMethods); + } + + public static object sliderLabels + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__sliderLabels?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __sliderLabels?.SetValue(null, value); + } + + public static System.Collections.Generic.List k_UserSideSupportedImageExtensions + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Generic.List)(__k_UserSideSupportedImageExtensions?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __k_UserSideSupportedImageExtensions?.SetValue(null, value); + } + + public static object s_ComparisonViewMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__s_ComparisonViewMode?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ComparisonViewMode?.SetValue(null, value); + } + + public static float s_LeftMarginCoord + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__s_LeftMarginCoord?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LeftMarginCoord?.SetValue(null, value); + } + + public static System.Collections.Generic.Stack s_ContextWidthStack + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Generic.Stack)(__s_ContextWidthStack?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ContextWidthStack?.SetValue(null, value); + } + + public static float s_OverriddenViewWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__s_OverriddenViewWidth?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_OverriddenViewWidth?.SetValue(null, value); + } + + public static float s_FieldWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__s_FieldWidth?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_FieldWidth?.SetValue(null, value); + } + + public static string k_LookLikeControlsObsoleteMessage + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__k_LookLikeControlsObsoleteMessage?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __k_LookLikeControlsObsoleteMessage?.SetValue(null, value); + } + + public static UnityEngine.Object GetScript(string scriptClass) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = scriptClass; + var __result__ = __GetScript?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Object)(__result__) : default; + } + + public static UnityEngine.Object GetBuiltinExtraResource(System.Type type, string path) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = type; + __params__[1] = path; + var __result__ = __GetBuiltinExtraResource?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Object)(__result__) : default; + } + + public static Array GetBuiltinResourceList(int classID) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = classID; + var __result__ = __GetBuiltinResourceList?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static UnityEngine.AssetBundle GetEditorAssetBundle() + { + var __result__ = __GetEditorAssetBundle?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (UnityEngine.AssetBundle)(__result__) : default; + } + + public static UnityEngine.AssetBundle ReloadEditorAssetBundle() + { + var __result__ = __ReloadEditorAssetBundle?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (UnityEngine.AssetBundle)(__result__) : default; + } + + public static void SetRenderTextureNoViewport(UnityEngine.RenderTexture rt) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = rt; + __SetRenderTextureNoViewport?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void SetVisibleLayers(int layers) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = layers; + __SetVisibleLayers?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void SetLockedLayers(int layers) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = layers; + __SetLockedLayers?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static bool IsGizmosAllowedForObject(UnityEngine.Object obj) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = obj; + var __result__ = __IsGizmosAllowedForObject?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void SetCurrentViewCursor(UnityEngine.Texture2D texture, UnityEngine.Vector2 hotspot, UnityEditor.MouseCursor type) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = texture; + __params__[1] = hotspot; + __params__[2] = type; + __SetCurrentViewCursor?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void ClearCurrentViewCursor() + { + __ClearCurrentViewCursor?.Invoke(null, System.Array.Empty()); + } + + public static void CleanCache(string text) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = text; + __CleanCache?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void SetSearchIndexOfControlIDList(int index) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = index; + __SetSearchIndexOfControlIDList?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static int GetSearchIndexOfControlIDList() + { + var __result__ = __GetSearchIndexOfControlIDList?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public static bool CanHaveKeyboardFocus(int id) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = id; + var __result__ = __CanHaveKeyboardFocus?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void SetDefaultFont(UnityEngine.Font font) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = font; + __SetDefaultFont?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void RenderPlayModeViewCamerasInternal(UnityEngine.RenderTexture target, int targetDisplay, UnityEngine.Vector2 mousePosition, bool gizmos, bool renderIMGUI) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = target; + __params__[1] = targetDisplay; + __params__[2] = mousePosition; + __params__[3] = gizmos; + __params__[4] = renderIMGUI; + __RenderPlayModeViewCamerasInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void SetupWindowSpaceAndVSyncInternal(UnityEngine.Rect screenRect) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = screenRect; + __SetupWindowSpaceAndVSyncInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Texture2D FindTextureByName(string name) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = name; + var __result__ = __FindTextureByName?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Texture2D)(__result__) : default; + } + + public static UnityEngine.Texture2D FindTextureByType(System.Type type) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = type; + var __result__ = __FindTextureByType?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Texture2D)(__result__) : default; + } + + public static string GetObjectNameWithInfo(UnityEngine.Object obj) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = obj; + var __result__ = __GetObjectNameWithInfo?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static string GetTypeNameWithInfo(string typeName, int instanceID) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = typeName; + __params__[1] = instanceID; + var __result__ = __GetTypeNameWithInfo?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static void Internal_SetupEventValues(object evt) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = evt; + __Internal_SetupEventValues?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Vector2 Internal_GetIconSize() + { + var __result__ = __Internal_GetIconSize?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (UnityEngine.Vector2)(__result__) : default; + } + + public static bool Internal_GetKeyboardRect(int id, out UnityEngine.Rect rect) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = id; + __params__[1] = Activator.CreateInstance(typeof(UnityEngine.Rect)); + var __result__ = __Internal_GetKeyboardRect?.Invoke(null, __params__); + rect = (UnityEngine.Rect)(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void Internal_MoveKeyboardFocus(bool forward) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = forward; + __Internal_MoveKeyboardFocus?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static int Internal_GetNextKeyboardControlID(bool forward) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = forward; + var __result__ = __Internal_GetNextKeyboardControlID?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static void Internal_AddCursorRect(UnityEngine.Rect r, UnityEditor.MouseCursor m, int controlID) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = r; + __params__[1] = m; + __params__[2] = controlID; + __Internal_AddCursorRect?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Material GetPreviewMaterial(object type) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = type; + var __result__ = __GetPreviewMaterial?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Material)(__result__) : default; + } + + public static void RegisterResourceForCleanupOnDomainReload(UnityEngine.Object obj) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = obj; + __RegisterResourceForCleanupOnDomainReload?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void BeginPropertyCallback(UnityEngine.Rect totalRect, UnityEditor.SerializedProperty property) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = totalRect; + __params__[1] = property; + __BeginPropertyCallback?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void ContextualPropertyMenuCallback(UnityEditor.GenericMenu gm, UnityEditor.SerializedProperty prop) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = gm; + __params__[1] = prop; + __ContextualPropertyMenuCallback?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Rect GetCenteredWindowPosition(UnityEngine.Rect parentWindowPosition, UnityEngine.Vector2 size) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = parentWindowPosition; + __params__[1] = size; + var __result__ = __GetCenteredWindowPosition?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static void RepaintCurrentWindow() + { + __RepaintCurrentWindow?.Invoke(null, System.Array.Empty()); + } + + public static bool HasCurrentWindowKeyFocus() + { + var __result__ = __HasCurrentWindowKeyFocus?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public static UnityEngine.Rect DrawEditorHeaderItems(UnityEngine.Rect rectangle, UnityEngine.Object[] targetObjs, float spacing) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = rectangle; + __params__[1] = targetObjs; + __params__[2] = spacing; + var __result__ = __DrawEditorHeaderItems?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static UnityEngine.Texture2D FindTexture(System.Type type) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = type; + var __result__ = __FindTexture?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Texture2D)(__result__) : default; + } + + public static UnityEngine.Texture2D LightenTexture(UnityEngine.Texture2D texture) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = texture; + var __result__ = __LightenTexture?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Texture2D)(__result__) : default; + } + + public static UnityEngine.Color LightenColor(UnityEngine.Color color) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = color; + var __result__ = __LightenColor?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Color)(__result__) : default; + } + + public static UnityEngine.GUIContent TrIconContent(string iconName, string tooltip, bool lightenTexture) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = iconName; + __params__[1] = tooltip; + __params__[2] = lightenTexture; + var __result__ = __TrIconContent?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GUIContent)(__result__) : default; + } + + public static UnityEngine.GUIContent TrIconContent(string tooltip) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = tooltip; + var __result__ = __TrIconContent__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GUIContent)(__result__) : default; + } + + public static UnityEngine.GUIContent TextContent(string textAndTooltip) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = textAndTooltip; + var __result__ = __TextContent?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GUIContent)(__result__) : default; + } + + public static UnityEngine.GUIContent TextContentWithIcon(string textAndTooltip, string icon) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = textAndTooltip; + __params__[1] = icon; + var __result__ = __TextContentWithIcon?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GUIContent)(__result__) : default; + } + + public static UnityEngine.Color GetDefaultBackgroundColor() + { + var __result__ = __GetDefaultBackgroundColor?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (UnityEngine.Color)(__result__) : default; + } + + public static string[] GetNameAndTooltipString(string nameAndTooltip) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = nameAndTooltip; + var __result__ = __GetNameAndTooltipString?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string[])(__result__) : default; + } + + public static UnityEngine.Texture2D LoadIconRequired(string name) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = name; + var __result__ = __LoadIconRequired?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Texture2D)(__result__) : default; + } + + public static UnityEngine.Texture2D LoadIcon(string name) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = name; + var __result__ = __LoadIcon?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Texture2D)(__result__) : default; + } + + public static UnityEngine.Texture2D LoadGeneratedIconOrNormalIcon(string name) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = name; + var __result__ = __LoadGeneratedIconOrNormalIcon?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Texture2D)(__result__) : default; + } + + public static UnityEngine.Texture2D InnerLoadGeneratedIconOrNormalIcon(string name) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = name; + var __result__ = __InnerLoadGeneratedIconOrNormalIcon?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Texture2D)(__result__) : default; + } + + public static UnityEngine.Texture2D LoadIconForSkin(string name, int in_SkinIndex) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = name; + __params__[1] = in_SkinIndex; + var __result__ = __LoadIconForSkin?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Texture2D)(__result__) : default; + } + + public static string GetIconPathFromAttribute(System.Type type) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = type; + var __result__ = __GetIconPathFromAttribute?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static UnityEngine.GUIContent IconContent(string text) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = text; + var __result__ = __IconContent?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GUIContent)(__result__) : default; + } + + public static UnityEngine.GUIContent IconContent(UnityEngine.Texture icon, string text) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = icon; + __params__[1] = text; + var __result__ = __IconContent__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GUIContent)(__result__) : default; + } + + public static void Internal_SwitchSkin() + { + __Internal_SwitchSkin?.Invoke(null, System.Array.Empty()); + } + + public static UnityEngine.GUIContent ObjectContent(UnityEngine.Object obj, System.Type type, int instanceID) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = obj; + __params__[1] = type; + __params__[2] = instanceID; + var __result__ = __ObjectContent?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GUIContent)(__result__) : default; + } + + public static UnityEngine.GUIContent TempContent(string t) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = t; + var __result__ = __TempContent?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GUIContent)(__result__) : default; + } + + public static UnityEngine.GUIContent TempContent(string text, string tip) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = text; + __params__[1] = tip; + var __result__ = __TempContent__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GUIContent)(__result__) : default; + } + + public static UnityEngine.GUIContent TempContent(UnityEngine.Texture i) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = i; + var __result__ = __TempContent__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GUIContent)(__result__) : default; + } + + public static UnityEngine.GUIContent TempContent(string t, UnityEngine.Texture i) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = t; + __params__[1] = i; + var __result__ = __TempContent__4?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GUIContent)(__result__) : default; + } + + public static UnityEngine.GUIContent[] TempContent(string[] texts) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = texts; + var __result__ = __TempContent__5?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GUIContent[])(__result__) : default; + } + + public static UnityEngine.GUIContent[] TempContent(string[] texts, string[] tooltips) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = texts; + __params__[1] = tooltips; + var __result__ = __TempContent__6?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GUIContent[])(__result__) : default; + } + + public static bool HasHolddownKeyModifiers(UnityEngine.Event evt) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = evt; + var __result__ = __HasHolddownKeyModifiers?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static UnityEngine.Texture2D GetHelpIcon(UnityEditor.MessageType type) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = type; + var __result__ = __GetHelpIcon?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Texture2D)(__result__) : default; + } + + public static UnityEngine.GUIStyle GetBasicTextureStyle(UnityEngine.Texture2D tex) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = tex; + var __result__ = __GetBasicTextureStyle?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GUIStyle)(__result__) : default; + } + + public static void NotifyLanguageChanged(UnityEngine.SystemLanguage newLanguage) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = newLanguage; + __NotifyLanguageChanged?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Object Load(string filename, System.Type type) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = filename; + __params__[1] = type; + var __result__ = __Load?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Object)(__result__) : default; + } + + public static void PingObjectFromCPP(int targetInstanceID) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = targetInstanceID; + __PingObjectFromCPP?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void MoveFocusAndScroll(bool forward) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = forward; + __MoveFocusAndScroll?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void RefreshScrollPosition() + { + __RefreshScrollPosition?.Invoke(null, System.Array.Empty()); + } + + public static void ScrollForTabbing(bool forward) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = forward; + __ScrollForTabbing?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void ResetGUIState() + { + __ResetGUIState?.Invoke(null, System.Array.Empty()); + } + + public static void HandleControlID(int id) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = id; + __HandleControlID?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static float CalcContextWidth() + { + var __result__ = __CalcContextWidth?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (float)(__result__) : default; + } + + public static void LockContextWidth() + { + __LockContextWidth?.Invoke(null, System.Array.Empty()); + } + + public static void UnlockContextWidth() + { + __UnlockContextWidth?.Invoke(null, System.Array.Empty()); + } + + public static void SkinChanged() + { + __SkinChanged?.Invoke(null, System.Array.Empty()); + } + + public static UnityEngine.Rect DragZoneRect(UnityEngine.Rect position, bool hasLabel) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = hasLabel; + var __result__ = __DragZoneRect?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static void SetBoldDefaultFont(bool isBold) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = isBold; + __SetBoldDefaultFont?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static bool GetBoldDefaultFont() + { + var __result__ = __GetBoldDefaultFont?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void DrawColorSwatch(UnityEngine.Rect position, UnityEngine.Color color, bool showAlpha) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = color; + __params__[2] = showAlpha; + __DrawColorSwatch?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void DrawColorSwatch(UnityEngine.Rect position, UnityEngine.Color color, bool showAlpha, bool hdr) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = color; + __params__[2] = showAlpha; + __params__[3] = hdr; + __DrawColorSwatch__2?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void DrawRegionSwatch(UnityEngine.Rect position, UnityEditor.SerializedProperty property, UnityEditor.SerializedProperty property2, UnityEngine.Color color, UnityEngine.Color bgColor) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = property; + __params__[2] = property2; + __params__[3] = color; + __params__[4] = bgColor; + __DrawRegionSwatch?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void DrawCurveSwatchInternal(UnityEngine.Rect position, UnityEngine.AnimationCurve curve, UnityEngine.AnimationCurve curve2, UnityEditor.SerializedProperty property, UnityEditor.SerializedProperty property2, UnityEngine.Color color, UnityEngine.Color bgColor, bool useCurveRanges, UnityEngine.Rect curveRanges, UnityEngine.Color topFillColor, UnityEngine.Color bottomFillColor) + { + var __pool__ = FixedArrayPool.Shared(11); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = curve; + __params__[2] = curve2; + __params__[3] = property; + __params__[4] = property2; + __params__[5] = color; + __params__[6] = bgColor; + __params__[7] = useCurveRanges; + __params__[8] = curveRanges; + __params__[9] = topFillColor; + __params__[10] = bottomFillColor; + __DrawCurveSwatchInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Rect HandleHorizontalSplitter(UnityEngine.Rect dragRect, float width, float minLeftSide, float minRightSide) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = dragRect; + __params__[1] = width; + __params__[2] = minLeftSide; + __params__[3] = minRightSide; + var __result__ = __HandleHorizontalSplitter?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static void DrawHorizontalSplitter(UnityEngine.Rect dragRect) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = dragRect; + __DrawHorizontalSplitter?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void SetupObjectSelector(UnityEngine.Object obj, System.Type objType, bool allowSceneObjects, string searchFilter, int controlID) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = obj; + __params__[1] = objType; + __params__[2] = allowSceneObjects; + __params__[3] = searchFilter; + __params__[4] = controlID; + __SetupObjectSelector?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void SetIconSize_Injected(ref UnityEngine.Vector2 size) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = size; + __SetIconSize_Injected?.Invoke(null, __params__); + size = (UnityEngine.Vector2)(__params__[0]); + __pool__.Return(__params__); + } + + public static void SetCurrentViewCursor_Injected(UnityEngine.Texture2D texture, ref UnityEngine.Vector2 hotspot, UnityEditor.MouseCursor type) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = texture; + __params__[1] = hotspot; + __params__[2] = type; + __SetCurrentViewCursor_Injected?.Invoke(null, __params__); + hotspot = (UnityEngine.Vector2)(__params__[1]); + __pool__.Return(__params__); + } + + public static void RenderPlayModeViewCamerasInternal_Injected(UnityEngine.RenderTexture target, int targetDisplay, ref UnityEngine.Vector2 mousePosition, bool gizmos, bool renderIMGUI) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = target; + __params__[1] = targetDisplay; + __params__[2] = mousePosition; + __params__[3] = gizmos; + __params__[4] = renderIMGUI; + __RenderPlayModeViewCamerasInternal_Injected?.Invoke(null, __params__); + mousePosition = (UnityEngine.Vector2)(__params__[2]); + __pool__.Return(__params__); + } + + public static void SetupWindowSpaceAndVSyncInternal_Injected(ref UnityEngine.Rect screenRect) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = screenRect; + __SetupWindowSpaceAndVSyncInternal_Injected?.Invoke(null, __params__); + screenRect = (UnityEngine.Rect)(__params__[0]); + __pool__.Return(__params__); + } + + public static void Internal_GetIconSize_Injected(out UnityEngine.Vector2 ret) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = Activator.CreateInstance(typeof(UnityEngine.Vector2)); + __Internal_GetIconSize_Injected?.Invoke(null, __params__); + ret = (UnityEngine.Vector2)(__params__[0]); + __pool__.Return(__params__); + } + + public static void Internal_AddCursorRect_Injected(ref UnityEngine.Rect r, UnityEditor.MouseCursor m, int controlID) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = r; + __params__[1] = m; + __params__[2] = controlID; + __Internal_AddCursorRect_Injected?.Invoke(null, __params__); + r = (UnityEngine.Rect)(__params__[0]); + __pool__.Return(__params__); + } + + public UnityEditor_EditorGUIUtility(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + public UnityEditor.EditorGUIUtility __super__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.EditorGUIUtility)(__self__); + } + + private static FieldInfo ___s_GUITextureBlit2SRGBMaterial; + private static FieldInfo __s_GUITextureBlit2SRGBMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_GUITextureBlit2SRGBMaterial ??= __type__?.GetField("s_GUITextureBlit2SRGBMaterial", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_GUITextureBlitSceneGUI; + private static FieldInfo __s_GUITextureBlitSceneGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_GUITextureBlitSceneGUI ??= __type__?.GetField("s_GUITextureBlitSceneGUI", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_FontIsBold; + private static FieldInfo __s_FontIsBold + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_FontIsBold ??= __type__?.GetField("s_FontIsBold", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_LastControlID; + private static FieldInfo __s_LastControlID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LastControlID ??= __type__?.GetField("s_LastControlID", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_LabelWidth; + private static FieldInfo __s_LabelWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LabelWidth ??= __type__?.GetField("s_LabelWidth", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_InfoIcon; + private static FieldInfo __s_InfoIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_InfoIcon ??= __type__?.GetField("s_InfoIcon", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_WarningIcon; + private static FieldInfo __s_WarningIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_WarningIcon ??= __type__?.GetField("s_WarningIcon", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ErrorIcon; + private static FieldInfo __s_ErrorIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ErrorIcon ??= __type__?.GetField("s_ErrorIcon", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_WhiteTextureStyle; + private static FieldInfo __s_WhiteTextureStyle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_WhiteTextureStyle ??= __type__?.GetField("s_WhiteTextureStyle", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_BasicTextureStyle; + private static FieldInfo __s_BasicTextureStyle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_BasicTextureStyle ??= __type__?.GetField("s_BasicTextureStyle", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_TextGUIContents; + private static FieldInfo __s_TextGUIContents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_TextGUIContents ??= __type__?.GetField("s_TextGUIContents", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_GUIContents; + private static FieldInfo __s_GUIContents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_GUIContents ??= __type__?.GetField("s_GUIContents", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_IconGUIContents; + private static FieldInfo __s_IconGUIContents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_IconGUIContents ??= __type__?.GetField("s_IconGUIContents", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_SkinnedIcons; + private static FieldInfo __s_SkinnedIcons + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_SkinnedIcons ??= __type__?.GetField("s_SkinnedIcons", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ObjectContent; + private static FieldInfo __s_ObjectContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ObjectContent ??= __type__?.GetField("s_ObjectContent", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_Text; + private static FieldInfo __s_Text + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_Text ??= __type__?.GetField("s_Text", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_Image; + private static FieldInfo __s_Image + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_Image ??= __type__?.GetField("s_Image", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_TextImage; + private static FieldInfo __s_TextImage + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_TextImage ??= __type__?.GetField("s_TextImage", (BindingFlags)(-1)); + } + + private static FieldInfo ___kViewBackgroundColor; + private static FieldInfo __kViewBackgroundColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kViewBackgroundColor ??= __type__?.GetField("kViewBackgroundColor", (BindingFlags)(-1)); + } + + private static FieldInfo ___contextualPropertyMenu__2; + private static FieldInfo __contextualPropertyMenu__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___contextualPropertyMenu__2 ??= __type__?.GetField("contextualPropertyMenu", (BindingFlags)(-1)); + } + + private static FieldInfo ___beginProperty__2; + private static FieldInfo __beginProperty__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___beginProperty__2 ??= __type__?.GetField("beginProperty", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_EditorHeaderItemsMethods; + private static FieldInfo __s_EditorHeaderItemsMethods + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_EditorHeaderItemsMethods ??= __type__?.GetField("s_EditorHeaderItemsMethods", (BindingFlags)(-1)); + } + + private static Type ___E__s_EditorHeaderItemsMethods; + public static Type __E__s_EditorHeaderItemsMethods + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___E__s_EditorHeaderItemsMethods ??= EditorUtils.GetTypeByFullName("UnityEditor.EditorGUIUtility+HeaderItemDelegate"); + } + + private static FieldInfo ___sliderLabels; + private static FieldInfo __sliderLabels + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___sliderLabels ??= __type__?.GetField("sliderLabels", (BindingFlags)(-1)); + } + + private static FieldInfo ___k_UserSideSupportedImageExtensions; + private static FieldInfo __k_UserSideSupportedImageExtensions + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___k_UserSideSupportedImageExtensions ??= __type__?.GetField("k_UserSideSupportedImageExtensions", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ComparisonViewMode; + private static FieldInfo __s_ComparisonViewMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ComparisonViewMode ??= __type__?.GetField("s_ComparisonViewMode", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_LeftMarginCoord; + private static FieldInfo __s_LeftMarginCoord + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LeftMarginCoord ??= __type__?.GetField("s_LeftMarginCoord", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ContextWidthStack; + private static FieldInfo __s_ContextWidthStack + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ContextWidthStack ??= __type__?.GetField("s_ContextWidthStack", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_OverriddenViewWidth; + private static FieldInfo __s_OverriddenViewWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_OverriddenViewWidth ??= __type__?.GetField("s_OverriddenViewWidth", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_FieldWidth; + private static FieldInfo __s_FieldWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_FieldWidth ??= __type__?.GetField("s_FieldWidth", (BindingFlags)(-1)); + } + + private static FieldInfo ___k_LookLikeControlsObsoleteMessage; + private static FieldInfo __k_LookLikeControlsObsoleteMessage + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___k_LookLikeControlsObsoleteMessage ??= __type__?.GetField("k_LookLikeControlsObsoleteMessage", (BindingFlags)(-1)); + } + + private static PropertyInfo ___skinIndex; + private static PropertyInfo __skinIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___skinIndex ??= __type__?.GetProperty("skinIndex", (BindingFlags)(-1)); + } + + private static PropertyInfo ___GUITextureBlit2SRGBMaterial; + private static PropertyInfo __GUITextureBlit2SRGBMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GUITextureBlit2SRGBMaterial ??= __type__?.GetProperty("GUITextureBlit2SRGBMaterial", (BindingFlags)(-1)); + } + + private static PropertyInfo ___GUITextureBlitSceneGUIMaterial; + private static PropertyInfo __GUITextureBlitSceneGUIMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GUITextureBlitSceneGUIMaterial ??= __type__?.GetProperty("GUITextureBlitSceneGUIMaterial", (BindingFlags)(-1)); + } + + private static PropertyInfo ___infoIcon; + private static PropertyInfo __infoIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___infoIcon ??= __type__?.GetProperty("infoIcon", (BindingFlags)(-1)); + } + + private static PropertyInfo ___warningIcon; + private static PropertyInfo __warningIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___warningIcon ??= __type__?.GetProperty("warningIcon", (BindingFlags)(-1)); + } + + private static PropertyInfo ___errorIcon; + private static PropertyInfo __errorIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___errorIcon ??= __type__?.GetProperty("errorIcon", (BindingFlags)(-1)); + } + + private static PropertyInfo ___blankContent; + private static PropertyInfo __blankContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___blankContent ??= __type__?.GetProperty("blankContent", (BindingFlags)(-1)); + } + + private static PropertyInfo ___whiteTextureStyle; + private static PropertyInfo __whiteTextureStyle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___whiteTextureStyle ??= __type__?.GetProperty("whiteTextureStyle", (BindingFlags)(-1)); + } + + private static PropertyInfo ___comparisonViewMode; + private static PropertyInfo __comparisonViewMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___comparisonViewMode ??= __type__?.GetProperty("comparisonViewMode", (BindingFlags)(-1)); + } + + private static PropertyInfo ___leftMarginCoord; + private static PropertyInfo __leftMarginCoord + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___leftMarginCoord ??= __type__?.GetProperty("leftMarginCoord", (BindingFlags)(-1)); + } + + private static PropertyInfo ___contextWidth; + private static PropertyInfo __contextWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___contextWidth ??= __type__?.GetProperty("contextWidth", (BindingFlags)(-1)); + } + + private static PropertyInfo ___currentViewWidth; + private static PropertyInfo __currentViewWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___currentViewWidth ??= __type__?.GetProperty("currentViewWidth", (BindingFlags)(-1)); + } + + private static PropertyInfo ___magnifyGestureEventType; + private static PropertyInfo __magnifyGestureEventType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___magnifyGestureEventType ??= __type__?.GetProperty("magnifyGestureEventType", (BindingFlags)(-1)); + } + + private static PropertyInfo ___swipeGestureEventType; + private static PropertyInfo __swipeGestureEventType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___swipeGestureEventType ??= __type__?.GetProperty("swipeGestureEventType", (BindingFlags)(-1)); + } + + private static PropertyInfo ___rotateGestureEventType; + private static PropertyInfo __rotateGestureEventType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___rotateGestureEventType ??= __type__?.GetProperty("rotateGestureEventType", (BindingFlags)(-1)); + } + + private static MethodInfo ___GetScript; + private static MethodInfo __GetScript + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetScript ??= __type__?.GetMethodInfoByParameterTypeNames("GetScript", "System.String"); + } + + private static MethodInfo ___GetBuiltinExtraResource; + private static MethodInfo __GetBuiltinExtraResource + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetBuiltinExtraResource ??= __type__?.GetMethodInfoByParameterTypeNames("GetBuiltinExtraResource", "System.Type", "System.String"); + } + + private static MethodInfo ___GetBuiltinResourceList; + private static MethodInfo __GetBuiltinResourceList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetBuiltinResourceList ??= __type__?.GetMethodInfoByParameterTypeNames("GetBuiltinResourceList", "System.Int32"); + } + + private static MethodInfo ___GetEditorAssetBundle; + private static MethodInfo __GetEditorAssetBundle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetEditorAssetBundle ??= __type__?.GetMethodInfoByParameterTypeNames("GetEditorAssetBundle"); + } + + private static MethodInfo ___ReloadEditorAssetBundle; + private static MethodInfo __ReloadEditorAssetBundle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ReloadEditorAssetBundle ??= __type__?.GetMethodInfoByParameterTypeNames("ReloadEditorAssetBundle"); + } + + private static MethodInfo ___SetRenderTextureNoViewport; + private static MethodInfo __SetRenderTextureNoViewport + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetRenderTextureNoViewport ??= __type__?.GetMethodInfoByParameterTypeNames("SetRenderTextureNoViewport", "UnityEngine.RenderTexture"); + } + + private static MethodInfo ___SetVisibleLayers; + private static MethodInfo __SetVisibleLayers + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetVisibleLayers ??= __type__?.GetMethodInfoByParameterTypeNames("SetVisibleLayers", "System.Int32"); + } + + private static MethodInfo ___SetLockedLayers; + private static MethodInfo __SetLockedLayers + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetLockedLayers ??= __type__?.GetMethodInfoByParameterTypeNames("SetLockedLayers", "System.Int32"); + } + + private static MethodInfo ___IsGizmosAllowedForObject; + private static MethodInfo __IsGizmosAllowedForObject + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsGizmosAllowedForObject ??= __type__?.GetMethodInfoByParameterTypeNames("IsGizmosAllowedForObject", "UnityEngine.Object"); + } + + private static MethodInfo ___SetCurrentViewCursor; + private static MethodInfo __SetCurrentViewCursor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetCurrentViewCursor ??= __type__?.GetMethodInfoByParameterTypeNames("SetCurrentViewCursor", "UnityEngine.Texture2D", "UnityEngine.Vector2", "UnityEditor.MouseCursor"); + } + + private static MethodInfo ___ClearCurrentViewCursor; + private static MethodInfo __ClearCurrentViewCursor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ClearCurrentViewCursor ??= __type__?.GetMethodInfoByParameterTypeNames("ClearCurrentViewCursor"); + } + + private static MethodInfo ___CleanCache; + private static MethodInfo __CleanCache + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CleanCache ??= __type__?.GetMethodInfoByParameterTypeNames("CleanCache", "System.String"); + } + + private static MethodInfo ___SetSearchIndexOfControlIDList; + private static MethodInfo __SetSearchIndexOfControlIDList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetSearchIndexOfControlIDList ??= __type__?.GetMethodInfoByParameterTypeNames("SetSearchIndexOfControlIDList", "System.Int32"); + } + + private static MethodInfo ___GetSearchIndexOfControlIDList; + private static MethodInfo __GetSearchIndexOfControlIDList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSearchIndexOfControlIDList ??= __type__?.GetMethodInfoByParameterTypeNames("GetSearchIndexOfControlIDList"); + } + + private static MethodInfo ___CanHaveKeyboardFocus; + private static MethodInfo __CanHaveKeyboardFocus + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CanHaveKeyboardFocus ??= __type__?.GetMethodInfoByParameterTypeNames("CanHaveKeyboardFocus", "System.Int32"); + } + + private static MethodInfo ___SetDefaultFont; + private static MethodInfo __SetDefaultFont + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetDefaultFont ??= __type__?.GetMethodInfoByParameterTypeNames("SetDefaultFont", "UnityEngine.Font"); + } + + private static MethodInfo ___RenderPlayModeViewCamerasInternal; + private static MethodInfo __RenderPlayModeViewCamerasInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RenderPlayModeViewCamerasInternal ??= __type__?.GetMethodInfoByParameterTypeNames("RenderPlayModeViewCamerasInternal", "UnityEngine.RenderTexture", "System.Int32", "UnityEngine.Vector2", "System.Boolean", "System.Boolean"); + } + + private static MethodInfo ___SetupWindowSpaceAndVSyncInternal; + private static MethodInfo __SetupWindowSpaceAndVSyncInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetupWindowSpaceAndVSyncInternal ??= __type__?.GetMethodInfoByParameterTypeNames("SetupWindowSpaceAndVSyncInternal", "UnityEngine.Rect"); + } + + private static MethodInfo ___FindTextureByName; + private static MethodInfo __FindTextureByName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FindTextureByName ??= __type__?.GetMethodInfoByParameterTypeNames("FindTextureByName", "System.String"); + } + + private static MethodInfo ___FindTextureByType; + private static MethodInfo __FindTextureByType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FindTextureByType ??= __type__?.GetMethodInfoByParameterTypeNames("FindTextureByType", "System.Type"); + } + + private static MethodInfo ___GetObjectNameWithInfo; + private static MethodInfo __GetObjectNameWithInfo + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetObjectNameWithInfo ??= __type__?.GetMethodInfoByParameterTypeNames("GetObjectNameWithInfo", "UnityEngine.Object"); + } + + private static MethodInfo ___GetTypeNameWithInfo; + private static MethodInfo __GetTypeNameWithInfo + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetTypeNameWithInfo ??= __type__?.GetMethodInfoByParameterTypeNames("GetTypeNameWithInfo", "System.String", "System.Int32"); + } + + private static MethodInfo ___Internal_SetupEventValues; + private static MethodInfo __Internal_SetupEventValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_SetupEventValues ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_SetupEventValues", "System.Object"); + } + + private static MethodInfo ___Internal_GetIconSize; + private static MethodInfo __Internal_GetIconSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_GetIconSize ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_GetIconSize"); + } + + private static MethodInfo ___Internal_GetKeyboardRect; + private static MethodInfo __Internal_GetKeyboardRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_GetKeyboardRect ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_GetKeyboardRect", "System.Int32", "UnityEngine.Rect&"); + } + + private static MethodInfo ___Internal_MoveKeyboardFocus; + private static MethodInfo __Internal_MoveKeyboardFocus + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_MoveKeyboardFocus ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_MoveKeyboardFocus", "System.Boolean"); + } + + private static MethodInfo ___Internal_GetNextKeyboardControlID; + private static MethodInfo __Internal_GetNextKeyboardControlID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_GetNextKeyboardControlID ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_GetNextKeyboardControlID", "System.Boolean"); + } + + private static MethodInfo ___Internal_AddCursorRect; + private static MethodInfo __Internal_AddCursorRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_AddCursorRect ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_AddCursorRect", "UnityEngine.Rect", "UnityEditor.MouseCursor", "System.Int32"); + } + + private static MethodInfo ___GetPreviewMaterial; + private static MethodInfo __GetPreviewMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPreviewMaterial ??= __type__?.GetMethodInfoByParameterTypeNames("GetPreviewMaterial", "UnityEditor.EditorGUIUtility+PreviewType"); + } + + private static MethodInfo ___RegisterResourceForCleanupOnDomainReload; + private static MethodInfo __RegisterResourceForCleanupOnDomainReload + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RegisterResourceForCleanupOnDomainReload ??= __type__?.GetMethodInfoByParameterTypeNames("RegisterResourceForCleanupOnDomainReload", "UnityEngine.Object"); + } + + private static MethodInfo ___BeginPropertyCallback; + private static MethodInfo __BeginPropertyCallback + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginPropertyCallback ??= __type__?.GetMethodInfoByParameterTypeNames("BeginPropertyCallback", "UnityEngine.Rect", "UnityEditor.SerializedProperty"); + } + + private static MethodInfo ___ContextualPropertyMenuCallback; + private static MethodInfo __ContextualPropertyMenuCallback + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ContextualPropertyMenuCallback ??= __type__?.GetMethodInfoByParameterTypeNames("ContextualPropertyMenuCallback", "UnityEditor.GenericMenu", "UnityEditor.SerializedProperty"); + } + + private static MethodInfo ___GetCenteredWindowPosition; + private static MethodInfo __GetCenteredWindowPosition + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetCenteredWindowPosition ??= __type__?.GetMethodInfoByParameterTypeNames("GetCenteredWindowPosition", "UnityEngine.Rect", "UnityEngine.Vector2"); + } + + private static MethodInfo ___RepaintCurrentWindow; + private static MethodInfo __RepaintCurrentWindow + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RepaintCurrentWindow ??= __type__?.GetMethodInfoByParameterTypeNames("RepaintCurrentWindow"); + } + + private static MethodInfo ___HasCurrentWindowKeyFocus; + private static MethodInfo __HasCurrentWindowKeyFocus + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasCurrentWindowKeyFocus ??= __type__?.GetMethodInfoByParameterTypeNames("HasCurrentWindowKeyFocus"); + } + + private static MethodInfo ___DrawEditorHeaderItems; + private static MethodInfo __DrawEditorHeaderItems + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawEditorHeaderItems ??= __type__?.GetMethodInfoByParameterTypeNames("DrawEditorHeaderItems", "UnityEngine.Rect", "UnityEngine.Object[]", "System.Single"); + } + + private static MethodInfo ___FindTexture; + private static MethodInfo __FindTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FindTexture ??= __type__?.GetMethodInfoByParameterTypeNames("FindTexture", "System.Type"); + } + + private static MethodInfo ___LightenTexture; + private static MethodInfo __LightenTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LightenTexture ??= __type__?.GetMethodInfoByParameterTypeNames("LightenTexture", "UnityEngine.Texture2D"); + } + + private static MethodInfo ___LightenColor; + private static MethodInfo __LightenColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LightenColor ??= __type__?.GetMethodInfoByParameterTypeNames("LightenColor", "UnityEngine.Color"); + } + + private static MethodInfo ___TrIconContent; + private static MethodInfo __TrIconContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TrIconContent ??= __type__?.GetMethodInfoByParameterTypeNames("TrIconContent", "System.String", "System.String", "System.Boolean"); + } + + private static MethodInfo ___TrIconContent__2; + private static MethodInfo __TrIconContent__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TrIconContent__2 ??= __type__?.GetMethodInfoByParameterTypeNames("TrIconContent", "System.String"); + } + + private static MethodInfo ___TextContent; + private static MethodInfo __TextContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TextContent ??= __type__?.GetMethodInfoByParameterTypeNames("TextContent", "System.String"); + } + + private static MethodInfo ___TextContentWithIcon; + private static MethodInfo __TextContentWithIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TextContentWithIcon ??= __type__?.GetMethodInfoByParameterTypeNames("TextContentWithIcon", "System.String", "System.String"); + } + + private static MethodInfo ___GetDefaultBackgroundColor; + private static MethodInfo __GetDefaultBackgroundColor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetDefaultBackgroundColor ??= __type__?.GetMethodInfoByParameterTypeNames("GetDefaultBackgroundColor"); + } + + private static MethodInfo ___GetNameAndTooltipString; + private static MethodInfo __GetNameAndTooltipString + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetNameAndTooltipString ??= __type__?.GetMethodInfoByParameterTypeNames("GetNameAndTooltipString", "System.String"); + } + + private static MethodInfo ___LoadIconRequired; + private static MethodInfo __LoadIconRequired + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoadIconRequired ??= __type__?.GetMethodInfoByParameterTypeNames("LoadIconRequired", "System.String"); + } + + private static MethodInfo ___LoadIcon; + private static MethodInfo __LoadIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoadIcon ??= __type__?.GetMethodInfoByParameterTypeNames("LoadIcon", "System.String"); + } + + private static MethodInfo ___LoadGeneratedIconOrNormalIcon; + private static MethodInfo __LoadGeneratedIconOrNormalIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoadGeneratedIconOrNormalIcon ??= __type__?.GetMethodInfoByParameterTypeNames("LoadGeneratedIconOrNormalIcon", "System.String"); + } + + private static MethodInfo ___InnerLoadGeneratedIconOrNormalIcon; + private static MethodInfo __InnerLoadGeneratedIconOrNormalIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___InnerLoadGeneratedIconOrNormalIcon ??= __type__?.GetMethodInfoByParameterTypeNames("InnerLoadGeneratedIconOrNormalIcon", "System.String"); + } + + private static MethodInfo ___LoadIconForSkin; + private static MethodInfo __LoadIconForSkin + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoadIconForSkin ??= __type__?.GetMethodInfoByParameterTypeNames("LoadIconForSkin", "System.String", "System.Int32"); + } + + private static MethodInfo ___GetIconPathFromAttribute; + private static MethodInfo __GetIconPathFromAttribute + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetIconPathFromAttribute ??= __type__?.GetMethodInfoByParameterTypeNames("GetIconPathFromAttribute", "System.Type"); + } + + private static MethodInfo ___IconContent; + private static MethodInfo __IconContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IconContent ??= __type__?.GetMethodInfoByParameterTypeNames("IconContent", "System.String"); + } + + private static MethodInfo ___IconContent__2; + private static MethodInfo __IconContent__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IconContent__2 ??= __type__?.GetMethodInfoByParameterTypeNames("IconContent", "UnityEngine.Texture", "System.String"); + } + + private static MethodInfo ___Internal_SwitchSkin; + private static MethodInfo __Internal_SwitchSkin + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_SwitchSkin ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_SwitchSkin"); + } + + private static MethodInfo ___ObjectContent; + private static MethodInfo __ObjectContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ObjectContent ??= __type__?.GetMethodInfoByParameterTypeNames("ObjectContent", "UnityEngine.Object", "System.Type", "System.Int32"); + } + + private static MethodInfo ___TempContent; + private static MethodInfo __TempContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TempContent ??= __type__?.GetMethodInfoByParameterTypeNames("TempContent", "System.String"); + } + + private static MethodInfo ___TempContent__2; + private static MethodInfo __TempContent__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TempContent__2 ??= __type__?.GetMethodInfoByParameterTypeNames("TempContent", "System.String", "System.String"); + } + + private static MethodInfo ___TempContent__3; + private static MethodInfo __TempContent__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TempContent__3 ??= __type__?.GetMethodInfoByParameterTypeNames("TempContent", "UnityEngine.Texture"); + } + + private static MethodInfo ___TempContent__4; + private static MethodInfo __TempContent__4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TempContent__4 ??= __type__?.GetMethodInfoByParameterTypeNames("TempContent", "System.String", "UnityEngine.Texture"); + } + + private static MethodInfo ___TempContent__5; + private static MethodInfo __TempContent__5 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TempContent__5 ??= __type__?.GetMethodInfoByParameterTypeNames("TempContent", "System.String[]"); + } + + private static MethodInfo ___TempContent__6; + private static MethodInfo __TempContent__6 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TempContent__6 ??= __type__?.GetMethodInfoByParameterTypeNames("TempContent", "System.String[]", "System.String[]"); + } + + private static MethodInfo ___HasHolddownKeyModifiers; + private static MethodInfo __HasHolddownKeyModifiers + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasHolddownKeyModifiers ??= __type__?.GetMethodInfoByParameterTypeNames("HasHolddownKeyModifiers", "UnityEngine.Event"); + } + + private static MethodInfo ___GetHelpIcon; + private static MethodInfo __GetHelpIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetHelpIcon ??= __type__?.GetMethodInfoByParameterTypeNames("GetHelpIcon", "UnityEditor.MessageType"); + } + + private static MethodInfo ___GetBasicTextureStyle; + private static MethodInfo __GetBasicTextureStyle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetBasicTextureStyle ??= __type__?.GetMethodInfoByParameterTypeNames("GetBasicTextureStyle", "UnityEngine.Texture2D"); + } + + private static MethodInfo ___NotifyLanguageChanged; + private static MethodInfo __NotifyLanguageChanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___NotifyLanguageChanged ??= __type__?.GetMethodInfoByParameterTypeNames("NotifyLanguageChanged", "UnityEngine.SystemLanguage"); + } + + private static MethodInfo ___Load; + private static MethodInfo __Load + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Load ??= __type__?.GetMethodInfoByParameterTypeNames("Load", "System.String", "System.Type"); + } + + private static MethodInfo ___PingObjectFromCPP; + private static MethodInfo __PingObjectFromCPP + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PingObjectFromCPP ??= __type__?.GetMethodInfoByParameterTypeNames("PingObjectFromCPP", "System.Int32"); + } + + private static MethodInfo ___MoveFocusAndScroll; + private static MethodInfo __MoveFocusAndScroll + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MoveFocusAndScroll ??= __type__?.GetMethodInfoByParameterTypeNames("MoveFocusAndScroll", "System.Boolean"); + } + + private static MethodInfo ___RefreshScrollPosition; + private static MethodInfo __RefreshScrollPosition + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RefreshScrollPosition ??= __type__?.GetMethodInfoByParameterTypeNames("RefreshScrollPosition"); + } + + private static MethodInfo ___ScrollForTabbing; + private static MethodInfo __ScrollForTabbing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ScrollForTabbing ??= __type__?.GetMethodInfoByParameterTypeNames("ScrollForTabbing", "System.Boolean"); + } + + private static MethodInfo ___ResetGUIState; + private static MethodInfo __ResetGUIState + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ResetGUIState ??= __type__?.GetMethodInfoByParameterTypeNames("ResetGUIState"); + } + + private static MethodInfo ___HandleControlID; + private static MethodInfo __HandleControlID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HandleControlID ??= __type__?.GetMethodInfoByParameterTypeNames("HandleControlID", "System.Int32"); + } + + private static MethodInfo ___CalcContextWidth; + private static MethodInfo __CalcContextWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CalcContextWidth ??= __type__?.GetMethodInfoByParameterTypeNames("CalcContextWidth"); + } + + private static MethodInfo ___LockContextWidth; + private static MethodInfo __LockContextWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LockContextWidth ??= __type__?.GetMethodInfoByParameterTypeNames("LockContextWidth"); + } + + private static MethodInfo ___UnlockContextWidth; + private static MethodInfo __UnlockContextWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UnlockContextWidth ??= __type__?.GetMethodInfoByParameterTypeNames("UnlockContextWidth"); + } + + private static MethodInfo ___SkinChanged; + private static MethodInfo __SkinChanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SkinChanged ??= __type__?.GetMethodInfoByParameterTypeNames("SkinChanged"); + } + + private static MethodInfo ___DragZoneRect; + private static MethodInfo __DragZoneRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DragZoneRect ??= __type__?.GetMethodInfoByParameterTypeNames("DragZoneRect", "UnityEngine.Rect", "System.Boolean"); + } + + private static MethodInfo ___SetBoldDefaultFont; + private static MethodInfo __SetBoldDefaultFont + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetBoldDefaultFont ??= __type__?.GetMethodInfoByParameterTypeNames("SetBoldDefaultFont", "System.Boolean"); + } + + private static MethodInfo ___GetBoldDefaultFont; + private static MethodInfo __GetBoldDefaultFont + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetBoldDefaultFont ??= __type__?.GetMethodInfoByParameterTypeNames("GetBoldDefaultFont"); + } + + private static MethodInfo ___DrawColorSwatch; + private static MethodInfo __DrawColorSwatch + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawColorSwatch ??= __type__?.GetMethodInfoByParameterTypeNames("DrawColorSwatch", "UnityEngine.Rect", "UnityEngine.Color", "System.Boolean"); + } + + private static MethodInfo ___DrawColorSwatch__2; + private static MethodInfo __DrawColorSwatch__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawColorSwatch__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DrawColorSwatch", "UnityEngine.Rect", "UnityEngine.Color", "System.Boolean", "System.Boolean"); + } + + private static MethodInfo ___DrawRegionSwatch; + private static MethodInfo __DrawRegionSwatch + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawRegionSwatch ??= __type__?.GetMethodInfoByParameterTypeNames("DrawRegionSwatch", "UnityEngine.Rect", "UnityEditor.SerializedProperty", "UnityEditor.SerializedProperty", "UnityEngine.Color", "UnityEngine.Color"); + } + + private static MethodInfo ___DrawCurveSwatchInternal; + private static MethodInfo __DrawCurveSwatchInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawCurveSwatchInternal ??= __type__?.GetMethodInfoByParameterTypeNames("DrawCurveSwatchInternal", "UnityEngine.Rect", "UnityEngine.AnimationCurve", "UnityEngine.AnimationCurve", "UnityEditor.SerializedProperty", "UnityEditor.SerializedProperty", "UnityEngine.Color", "UnityEngine.Color", "System.Boolean", "UnityEngine.Rect", "UnityEngine.Color", "UnityEngine.Color"); + } + + private static MethodInfo ___HandleHorizontalSplitter; + private static MethodInfo __HandleHorizontalSplitter + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HandleHorizontalSplitter ??= __type__?.GetMethodInfoByParameterTypeNames("HandleHorizontalSplitter", "UnityEngine.Rect", "System.Single", "System.Single", "System.Single"); + } + + private static MethodInfo ___DrawHorizontalSplitter; + private static MethodInfo __DrawHorizontalSplitter + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawHorizontalSplitter ??= __type__?.GetMethodInfoByParameterTypeNames("DrawHorizontalSplitter", "UnityEngine.Rect"); + } + + private static MethodInfo ___SetupObjectSelector; + private static MethodInfo __SetupObjectSelector + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetupObjectSelector ??= __type__?.GetMethodInfoByParameterTypeNames("SetupObjectSelector", "UnityEngine.Object", "System.Type", "System.Boolean", "System.String", "System.Int32"); + } + + private static MethodInfo ___SetIconSize_Injected; + private static MethodInfo __SetIconSize_Injected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetIconSize_Injected ??= __type__?.GetMethodInfoByParameterTypeNames("SetIconSize_Injected", "UnityEngine.Vector2&"); + } + + private static MethodInfo ___SetCurrentViewCursor_Injected; + private static MethodInfo __SetCurrentViewCursor_Injected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetCurrentViewCursor_Injected ??= __type__?.GetMethodInfoByParameterTypeNames("SetCurrentViewCursor_Injected", "UnityEngine.Texture2D", "UnityEngine.Vector2&", "UnityEditor.MouseCursor"); + } + + private static MethodInfo ___RenderPlayModeViewCamerasInternal_Injected; + private static MethodInfo __RenderPlayModeViewCamerasInternal_Injected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RenderPlayModeViewCamerasInternal_Injected ??= __type__?.GetMethodInfoByParameterTypeNames("RenderPlayModeViewCamerasInternal_Injected", "UnityEngine.RenderTexture", "System.Int32", "UnityEngine.Vector2&", "System.Boolean", "System.Boolean"); + } + + private static MethodInfo ___SetupWindowSpaceAndVSyncInternal_Injected; + private static MethodInfo __SetupWindowSpaceAndVSyncInternal_Injected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetupWindowSpaceAndVSyncInternal_Injected ??= __type__?.GetMethodInfoByParameterTypeNames("SetupWindowSpaceAndVSyncInternal_Injected", "UnityEngine.Rect&"); + } + + private static MethodInfo ___Internal_GetIconSize_Injected; + private static MethodInfo __Internal_GetIconSize_Injected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_GetIconSize_Injected ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_GetIconSize_Injected", "UnityEngine.Vector2&"); + } + + private static MethodInfo ___Internal_AddCursorRect_Injected; + private static MethodInfo __Internal_AddCursorRect_Injected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_AddCursorRect_Injected ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_AddCursorRect_Injected", "UnityEngine.Rect&", "UnityEditor.MouseCursor", "System.Int32"); + } + } + public static class UnityEditor_EditorGUIUtility_Extension + { + public static UnityEditor_EditorGUIUtility ReflectionHelper(this UnityEditor.EditorGUIUtility self) => new(self); + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUIUtility.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUIUtility.cs.meta new file mode 100644 index 0000000..573089d --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUIUtility.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2ff640f4da5d1ed4286934a180fc20d8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUI_RecycledTextEditor.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUI_RecycledTextEditor.cs new file mode 100644 index 0000000..524f8e1 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUI_RecycledTextEditor.cs @@ -0,0 +1,125 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_EditorGUI_RecycledTextEditor + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.EditorGUI+RecycledTextEditor"); + + + public static bool s_ActuallyEditing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__s_ActuallyEditing?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ActuallyEditing?.SetValue(null, value); + } + + public static bool s_AllowContextCutOrPaste + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__s_AllowContextCutOrPaste?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_AllowContextCutOrPaste?.SetValue(null, value); + } + + public UnityEngine.IMECompositionMode m_IMECompositionModeBackup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.IMECompositionMode)(__m_IMECompositionModeBackup?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_IMECompositionModeBackup?.SetValue(__self__, value); + } + + public bool IsEditingControl(int id) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = id; + var __result__ = __IsEditingControl?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public void BeginEditing(int id, string newText, UnityEngine.Rect _position, UnityEngine.GUIStyle _style, bool _multiline, bool passwordField) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = id; + __params__[1] = newText; + __params__[2] = _position; + __params__[3] = _style; + __params__[4] = _multiline; + __params__[5] = passwordField; + __BeginEditing?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void EndEditing() + { + __EndEditing?.Invoke(__self__, System.Array.Empty()); + } + + public UnityEditor_EditorGUI_RecycledTextEditor(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + public UnityEngine.TextEditor __super__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.TextEditor)(__self__); + } + + private static FieldInfo ___s_ActuallyEditing; + private static FieldInfo __s_ActuallyEditing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ActuallyEditing ??= __type__?.GetField("s_ActuallyEditing", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_AllowContextCutOrPaste; + private static FieldInfo __s_AllowContextCutOrPaste + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_AllowContextCutOrPaste ??= __type__?.GetField("s_AllowContextCutOrPaste", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_IMECompositionModeBackup; + private static FieldInfo __m_IMECompositionModeBackup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_IMECompositionModeBackup ??= __type__?.GetField("m_IMECompositionModeBackup", (BindingFlags)(-1)); + } + + private static MethodInfo ___IsEditingControl; + private static MethodInfo __IsEditingControl + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsEditingControl ??= __type__?.GetMethodInfoByParameterTypeNames("IsEditingControl", "System.Int32"); + } + + private static MethodInfo ___BeginEditing; + private static MethodInfo __BeginEditing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginEditing ??= __type__?.GetMethodInfoByParameterTypeNames("BeginEditing", "System.Int32", "System.String", "UnityEngine.Rect", "UnityEngine.GUIStyle", "System.Boolean", "System.Boolean"); + } + + private static MethodInfo ___EndEditing; + private static MethodInfo __EndEditing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EndEditing ??= __type__?.GetMethodInfoByParameterTypeNames("EndEditing"); + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUI_RecycledTextEditor.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUI_RecycledTextEditor.cs.meta new file mode 100644 index 0000000..5527dae --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorGUI_RecycledTextEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5bc1e1c4341cb1c41baa309eead58a67 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorStyles.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorStyles.cs new file mode 100644 index 0000000..24975c6 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorStyles.cs @@ -0,0 +1,2508 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_EditorStyles + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.EditorStyles"); + + + public static UnityEngine.GUIStyle boldTextField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__boldTextField?.GetValue(null)); + } + + public static UnityEngine.GUIStyle objectFieldButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__objectFieldButton?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toggleMixed + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toggleMixed?.GetValue(null)); + } + + public static UnityEngine.GUIStyle titlebarFoldout + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__titlebarFoldout?.GetValue(null)); + } + + public static UnityEngine.GUIStyle optionsButtonStyle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__optionsButtonStyle?.GetValue(null)); + } + + public static UnityEngine.GUIStyle textFieldDropDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__textFieldDropDown?.GetValue(null)); + } + + public static UnityEngine.GUIStyle textFieldDropDownText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__textFieldDropDownText?.GetValue(null)); + } + + public static UnityEngine.GUIStyle overrideMargin + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__overrideMargin?.GetValue(null)); + } + + public static UnityEngine.GUIStyle contentToolbar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__contentToolbar?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarButtonLeft + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarButtonLeft?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarButtonRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarButtonRight?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarPopupLeft + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarPopupLeft?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarPopupRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarPopupRight?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarDropDownLeft + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarDropDownLeft?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarDropDownRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarDropDownRight?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarDropDownToggle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarDropDownToggle?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarDropDownToggleButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarDropDownToggleButton?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarDropDownToggleRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarDropDownToggleRight?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarCreateAddNewDropDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarCreateAddNewDropDown?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarLabel?.GetValue(null)); + } + + public static UnityEngine.GUIStyle defaultContentMargins + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__defaultContentMargins?.GetValue(null)); + } + + public static UnityEngine.GUIStyle frameBox + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__frameBox?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarSearchFieldPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarSearchFieldPopup?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarSearchFieldWithJumpSynced + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarSearchFieldWithJumpSynced?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarSearchFieldWithJumpPopupSynced + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarSearchFieldWithJumpPopupSynced?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarSearchFieldWithJump + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarSearchFieldWithJump?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarSearchFieldWithJumpPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarSearchFieldWithJumpPopup?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarSearchFieldJumpButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarSearchFieldJumpButton?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarSearchFieldCancelButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarSearchFieldCancelButton?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarSearchFieldCancelButtonEmpty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarSearchFieldCancelButtonEmpty?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarSearchFieldCancelButtonWithJump + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarSearchFieldCancelButtonWithJump?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarSearchFieldCancelButtonWithJumpEmpty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarSearchFieldCancelButtonWithJumpEmpty?.GetValue(null)); + } + + public static UnityEngine.GUIStyle colorPickerBox + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__colorPickerBox?.GetValue(null)); + } + + public static UnityEngine.GUIStyle viewBackground + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__viewBackground?.GetValue(null)); + } + + public static UnityEngine.GUIStyle inspectorBig + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__inspectorBig?.GetValue(null)); + } + + public static UnityEngine.GUIStyle inspectorTitlebar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__inspectorTitlebar?.GetValue(null)); + } + + public static UnityEngine.GUIStyle inspectorTitlebarFlat + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__inspectorTitlebarFlat?.GetValue(null)); + } + + public static UnityEngine.GUIStyle inspectorTitlebarText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__inspectorTitlebarText?.GetValue(null)); + } + + public static UnityEngine.GUIStyle foldoutSelected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__foldoutSelected?.GetValue(null)); + } + + public static UnityEngine.GUIStyle tooltip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__tooltip?.GetValue(null)); + } + + public static UnityEngine.GUIStyle notificationText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__notificationText?.GetValue(null)); + } + + public static UnityEngine.GUIStyle notificationBackground + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__notificationBackground?.GetValue(null)); + } + + public static UnityEngine.GUIStyle assetLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__assetLabel?.GetValue(null)); + } + + public static UnityEngine.GUIStyle assetLabelPartial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__assetLabelPartial?.GetValue(null)); + } + + public static UnityEngine.GUIStyle assetLabelIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__assetLabelIcon?.GetValue(null)); + } + + public static UnityEngine.GUIStyle searchField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__searchField?.GetValue(null)); + } + + public static UnityEngine.GUIStyle searchFieldCancelButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__searchFieldCancelButton?.GetValue(null)); + } + + public static UnityEngine.GUIStyle searchFieldCancelButtonEmpty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__searchFieldCancelButtonEmpty?.GetValue(null)); + } + + public static UnityEngine.GUIStyle toolbarSlider + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__toolbarSlider?.GetValue(null)); + } + + public static UnityEngine.GUIStyle minMaxHorizontalSliderThumb + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__minMaxHorizontalSliderThumb?.GetValue(null)); + } + + public static UnityEngine.GUIStyle dropDownList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__dropDownList?.GetValue(null)); + } + + public static UnityEngine.GUIStyle dropDownToggleButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__dropDownToggleButton?.GetValue(null)); + } + + public static UnityEngine.GUIStyle minMaxStateDropdown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__minMaxStateDropdown?.GetValue(null)); + } + + public static UnityEngine.GUIStyle progressBarBack + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__progressBarBack?.GetValue(null)); + } + + public static UnityEngine.GUIStyle progressBarBar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__progressBarBar?.GetValue(null)); + } + + public static UnityEngine.GUIStyle progressBarText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__progressBarText?.GetValue(null)); + } + + public static UnityEngine.GUIStyle scrollViewAlt + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__scrollViewAlt?.GetValue(null)); + } + + public static UnityEngine.Vector2 knobSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Vector2)(__knobSize?.GetValue(null)); + } + + public static UnityEngine.Vector2 miniKnobSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Vector2)(__miniKnobSize?.GetValue(null)); + } + + public static int kInspectorPaddingLeft + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__kInspectorPaddingLeft?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kInspectorPaddingLeft?.SetValue(null, value); + } + + public static int kInspectorPaddingRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__kInspectorPaddingRight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kInspectorPaddingRight?.SetValue(null, value); + } + + public static int kInspectorPaddingTop + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__kInspectorPaddingTop?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kInspectorPaddingTop?.SetValue(null, value); + } + + public UnityEngine.GUIStyle m_Label + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_Label?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Label?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_MiniLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_MiniLabel?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MiniLabel?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_LargeLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_LargeLabel?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LargeLabel?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_BoldLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_BoldLabel?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_BoldLabel?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_MiniBoldLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_MiniBoldLabel?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MiniBoldLabel?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_CenteredGreyMiniLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_CenteredGreyMiniLabel?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_CenteredGreyMiniLabel?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_WordWrappedMiniLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_WordWrappedMiniLabel?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_WordWrappedMiniLabel?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_WordWrappedLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_WordWrappedLabel?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_WordWrappedLabel?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_LinkLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_LinkLabel?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LinkLabel?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_WhiteLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_WhiteLabel?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_WhiteLabel?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_WhiteMiniLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_WhiteMiniLabel?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_WhiteMiniLabel?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_WhiteLargeLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_WhiteLargeLabel?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_WhiteLargeLabel?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_WhiteBoldLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_WhiteBoldLabel?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_WhiteBoldLabel?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_RadioButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_RadioButton?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_RadioButton?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_MiniButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_MiniButton?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MiniButton?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_MiniButtonLeft + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_MiniButtonLeft?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MiniButtonLeft?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_MiniButtonMid + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_MiniButtonMid?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MiniButtonMid?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_MiniButtonRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_MiniButtonRight?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MiniButtonRight?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_MiniPullDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_MiniPullDown?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MiniPullDown?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_TextField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_TextField?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TextField?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_BoldTextField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_BoldTextField?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_BoldTextField?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_TextArea + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_TextArea?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TextArea?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_MiniTextField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_MiniTextField?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MiniTextField?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_NumberField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_NumberField?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_NumberField?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_Popup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_Popup?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Popup?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ObjectField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ObjectField?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ObjectField?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ObjectFieldButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ObjectFieldButton?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ObjectFieldButton?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ObjectFieldThumb + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ObjectFieldThumb?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ObjectFieldThumb?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ObjectFieldMiniThumb + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ObjectFieldMiniThumb?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ObjectFieldMiniThumb?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ColorField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ColorField?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ColorField?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_LayerMaskField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_LayerMaskField?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LayerMaskField?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_Toggle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_Toggle?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Toggle?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToggleMixed + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToggleMixed?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToggleMixed?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_Foldout + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_Foldout?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Foldout?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_TitlebarFoldout + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_TitlebarFoldout?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TitlebarFoldout?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_FoldoutPreDrop + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_FoldoutPreDrop?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_FoldoutPreDrop?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_FoldoutHeader + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_FoldoutHeader?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_FoldoutHeader?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_FoldoutHeaderIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_FoldoutHeaderIcon?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_FoldoutHeaderIcon?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_OptionsButtonStyle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_OptionsButtonStyle?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_OptionsButtonStyle?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToggleGroup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToggleGroup?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToggleGroup?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_TextFieldDropDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_TextFieldDropDown?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TextFieldDropDown?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_TextFieldDropDownText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_TextFieldDropDownText?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TextFieldDropDownText?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_OverrideMargin + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_OverrideMargin?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_OverrideMargin?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_Toolbar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_Toolbar?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Toolbar?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ContentToolbar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ContentToolbar?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ContentToolbar?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarButton?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarButton?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarButtonLeft + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarButtonLeft?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarButtonLeft?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarButtonRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarButtonRight?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarButtonRight?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarPopup?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarPopup?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarPopupLeft + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarPopupLeft?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarPopupLeft?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarPopupRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarPopupRight?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarPopupRight?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarDropDownLeft + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarDropDownLeft?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarDropDownLeft?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarDropDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarDropDown?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarDropDown?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarDropDownRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarDropDownRight?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarDropDownRight?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarDropDownToggle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarDropDownToggle?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarDropDownToggle?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarDropDownToggleButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarDropDownToggleButton?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarDropDownToggleButton?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarDropDownToggleRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarDropDownToggleRight?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarDropDownToggleRight?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarCreateAddNewDropDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarCreateAddNewDropDown?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarCreateAddNewDropDown?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarTextField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarTextField?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarTextField?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarLabel?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarLabel?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_InspectorDefaultMargins + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_InspectorDefaultMargins?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_InspectorDefaultMargins?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_InspectorFullWidthMargins + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_InspectorFullWidthMargins?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_InspectorFullWidthMargins?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_DefaultContentMargins + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_DefaultContentMargins?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_DefaultContentMargins?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_FrameBox + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_FrameBox?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_FrameBox?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_HelpBox + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_HelpBox?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_HelpBox?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarSearchField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarSearchField?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarSearchField?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarSearchFieldPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarSearchFieldPopup?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarSearchFieldPopup?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarSearchFieldWithJumpSynced + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarSearchFieldWithJumpSynced?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarSearchFieldWithJumpSynced?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarSearchFieldWithJumpPopupSynced + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarSearchFieldWithJumpPopupSynced?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarSearchFieldWithJumpPopupSynced?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarSearchFieldWithJump + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarSearchFieldWithJump?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarSearchFieldWithJump?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarSearchFieldWithJumpPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarSearchFieldWithJumpPopup?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarSearchFieldWithJumpPopup?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarSearchFieldJumpButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarSearchFieldJumpButton?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarSearchFieldJumpButton?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarSearchFieldCancelButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarSearchFieldCancelButton?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarSearchFieldCancelButton?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarSearchFieldCancelButtonEmpty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarSearchFieldCancelButtonEmpty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarSearchFieldCancelButtonEmpty?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarSearchFieldCancelButtonWithJump + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarSearchFieldCancelButtonWithJump?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarSearchFieldCancelButtonWithJump?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarSearchFieldCancelButtonWithJumpEmpty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarSearchFieldCancelButtonWithJumpEmpty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarSearchFieldCancelButtonWithJumpEmpty?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ColorPickerBox + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ColorPickerBox?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ColorPickerBox?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ViewBg + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ViewBg?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ViewBg?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_InspectorBig + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_InspectorBig?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_InspectorBig?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_InspectorTitlebar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_InspectorTitlebar?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_InspectorTitlebar?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_InspectorTitlebarFlat + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_InspectorTitlebarFlat?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_InspectorTitlebarFlat?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_InspectorTitlebarText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_InspectorTitlebarText?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_InspectorTitlebarText?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_FoldoutSelected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_FoldoutSelected?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_FoldoutSelected?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_IconButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_IconButton?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_IconButton?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_Tooltip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_Tooltip?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Tooltip?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_NotificationText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_NotificationText?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_NotificationText?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_NotificationBackground + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_NotificationBackground?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_NotificationBackground?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_AssetLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_AssetLabel?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AssetLabel?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_AssetLabelPartial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_AssetLabelPartial?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AssetLabelPartial?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_AssetLabelIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_AssetLabelIcon?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AssetLabelIcon?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_SearchField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_SearchField?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SearchField?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_SearchFieldCancelButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_SearchFieldCancelButton?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SearchFieldCancelButton?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_SearchFieldCancelButtonEmpty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_SearchFieldCancelButtonEmpty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SearchFieldCancelButtonEmpty?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_SelectionRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_SelectionRect?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SelectionRect?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ToolbarSlider + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ToolbarSlider?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ToolbarSlider?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_MinMaxHorizontalSliderThumb + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_MinMaxHorizontalSliderThumb?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MinMaxHorizontalSliderThumb?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_DropDownList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_DropDownList?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_DropDownList?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_DropDownToggleButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_DropDownToggleButton?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_DropDownToggleButton?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_MinMaxStateDropdown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_MinMaxStateDropdown?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MinMaxStateDropdown?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ProgressBarBar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ProgressBarBar?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ProgressBarBar?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ProgressBarText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ProgressBarText?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ProgressBarText?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ProgressBarBack + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ProgressBarBack?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ProgressBarBack?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ScrollViewAlt + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ScrollViewAlt?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ScrollViewAlt?.SetValue(__self__, value); + } + + public UnityEngine.Vector2 m_KnobSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Vector2)(__m_KnobSize?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_KnobSize?.SetValue(__self__, value); + } + + public UnityEngine.Vector2 m_MiniKnobSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Vector2)(__m_MiniKnobSize?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MiniKnobSize?.SetValue(__self__, value); + } + + public static UnityEditor.EditorStyles s_Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.EditorStyles)(__s_Current?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_Current?.SetValue(null, value); + } + + public static UnityEditor.EditorStyles[] s_CachedStyles + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.EditorStyles[])(__s_CachedStyles?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_CachedStyles?.SetValue(null, value); + } + + public static void UpdateSkinCache() + { + __UpdateSkinCache?.Invoke(null, System.Array.Empty()); + } + + public static void UpdateSkinCache(int skinIndex) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = skinIndex; + __UpdateSkinCache__2?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public void InitSharedStyles() + { + __InitSharedStyles?.Invoke(__self__, System.Array.Empty()); + } + + public UnityEngine.GUIStyle GetStyle(string styleName) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = styleName; + var __result__ = __GetStyle?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GUIStyle)(__result__) : default; + } + + public UnityEditor_EditorStyles(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + public UnityEditor.EditorStyles __super__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.EditorStyles)(__self__); + } + + private static FieldInfo ___kInspectorPaddingLeft; + private static FieldInfo __kInspectorPaddingLeft + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kInspectorPaddingLeft ??= __type__?.GetField("kInspectorPaddingLeft", (BindingFlags)(-1)); + } + + private static FieldInfo ___kInspectorPaddingRight; + private static FieldInfo __kInspectorPaddingRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kInspectorPaddingRight ??= __type__?.GetField("kInspectorPaddingRight", (BindingFlags)(-1)); + } + + private static FieldInfo ___kInspectorPaddingTop; + private static FieldInfo __kInspectorPaddingTop + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kInspectorPaddingTop ??= __type__?.GetField("kInspectorPaddingTop", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Label; + private static FieldInfo __m_Label + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Label ??= __type__?.GetField("m_Label", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MiniLabel; + private static FieldInfo __m_MiniLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MiniLabel ??= __type__?.GetField("m_MiniLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LargeLabel; + private static FieldInfo __m_LargeLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LargeLabel ??= __type__?.GetField("m_LargeLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_BoldLabel; + private static FieldInfo __m_BoldLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_BoldLabel ??= __type__?.GetField("m_BoldLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MiniBoldLabel; + private static FieldInfo __m_MiniBoldLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MiniBoldLabel ??= __type__?.GetField("m_MiniBoldLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_CenteredGreyMiniLabel; + private static FieldInfo __m_CenteredGreyMiniLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_CenteredGreyMiniLabel ??= __type__?.GetField("m_CenteredGreyMiniLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_WordWrappedMiniLabel; + private static FieldInfo __m_WordWrappedMiniLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_WordWrappedMiniLabel ??= __type__?.GetField("m_WordWrappedMiniLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_WordWrappedLabel; + private static FieldInfo __m_WordWrappedLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_WordWrappedLabel ??= __type__?.GetField("m_WordWrappedLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LinkLabel; + private static FieldInfo __m_LinkLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LinkLabel ??= __type__?.GetField("m_LinkLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_WhiteLabel; + private static FieldInfo __m_WhiteLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_WhiteLabel ??= __type__?.GetField("m_WhiteLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_WhiteMiniLabel; + private static FieldInfo __m_WhiteMiniLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_WhiteMiniLabel ??= __type__?.GetField("m_WhiteMiniLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_WhiteLargeLabel; + private static FieldInfo __m_WhiteLargeLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_WhiteLargeLabel ??= __type__?.GetField("m_WhiteLargeLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_WhiteBoldLabel; + private static FieldInfo __m_WhiteBoldLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_WhiteBoldLabel ??= __type__?.GetField("m_WhiteBoldLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_RadioButton; + private static FieldInfo __m_RadioButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_RadioButton ??= __type__?.GetField("m_RadioButton", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MiniButton; + private static FieldInfo __m_MiniButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MiniButton ??= __type__?.GetField("m_MiniButton", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MiniButtonLeft; + private static FieldInfo __m_MiniButtonLeft + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MiniButtonLeft ??= __type__?.GetField("m_MiniButtonLeft", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MiniButtonMid; + private static FieldInfo __m_MiniButtonMid + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MiniButtonMid ??= __type__?.GetField("m_MiniButtonMid", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MiniButtonRight; + private static FieldInfo __m_MiniButtonRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MiniButtonRight ??= __type__?.GetField("m_MiniButtonRight", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MiniPullDown; + private static FieldInfo __m_MiniPullDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MiniPullDown ??= __type__?.GetField("m_MiniPullDown", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TextField; + private static FieldInfo __m_TextField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TextField ??= __type__?.GetField("m_TextField", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_BoldTextField; + private static FieldInfo __m_BoldTextField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_BoldTextField ??= __type__?.GetField("m_BoldTextField", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TextArea; + private static FieldInfo __m_TextArea + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TextArea ??= __type__?.GetField("m_TextArea", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MiniTextField; + private static FieldInfo __m_MiniTextField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MiniTextField ??= __type__?.GetField("m_MiniTextField", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_NumberField; + private static FieldInfo __m_NumberField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_NumberField ??= __type__?.GetField("m_NumberField", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Popup; + private static FieldInfo __m_Popup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Popup ??= __type__?.GetField("m_Popup", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ObjectField; + private static FieldInfo __m_ObjectField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ObjectField ??= __type__?.GetField("m_ObjectField", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ObjectFieldButton; + private static FieldInfo __m_ObjectFieldButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ObjectFieldButton ??= __type__?.GetField("m_ObjectFieldButton", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ObjectFieldThumb; + private static FieldInfo __m_ObjectFieldThumb + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ObjectFieldThumb ??= __type__?.GetField("m_ObjectFieldThumb", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ObjectFieldMiniThumb; + private static FieldInfo __m_ObjectFieldMiniThumb + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ObjectFieldMiniThumb ??= __type__?.GetField("m_ObjectFieldMiniThumb", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ColorField; + private static FieldInfo __m_ColorField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ColorField ??= __type__?.GetField("m_ColorField", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LayerMaskField; + private static FieldInfo __m_LayerMaskField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LayerMaskField ??= __type__?.GetField("m_LayerMaskField", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Toggle; + private static FieldInfo __m_Toggle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Toggle ??= __type__?.GetField("m_Toggle", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToggleMixed; + private static FieldInfo __m_ToggleMixed + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToggleMixed ??= __type__?.GetField("m_ToggleMixed", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Foldout; + private static FieldInfo __m_Foldout + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Foldout ??= __type__?.GetField("m_Foldout", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TitlebarFoldout; + private static FieldInfo __m_TitlebarFoldout + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TitlebarFoldout ??= __type__?.GetField("m_TitlebarFoldout", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_FoldoutPreDrop; + private static FieldInfo __m_FoldoutPreDrop + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_FoldoutPreDrop ??= __type__?.GetField("m_FoldoutPreDrop", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_FoldoutHeader; + private static FieldInfo __m_FoldoutHeader + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_FoldoutHeader ??= __type__?.GetField("m_FoldoutHeader", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_FoldoutHeaderIcon; + private static FieldInfo __m_FoldoutHeaderIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_FoldoutHeaderIcon ??= __type__?.GetField("m_FoldoutHeaderIcon", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_OptionsButtonStyle; + private static FieldInfo __m_OptionsButtonStyle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_OptionsButtonStyle ??= __type__?.GetField("m_OptionsButtonStyle", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToggleGroup; + private static FieldInfo __m_ToggleGroup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToggleGroup ??= __type__?.GetField("m_ToggleGroup", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TextFieldDropDown; + private static FieldInfo __m_TextFieldDropDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TextFieldDropDown ??= __type__?.GetField("m_TextFieldDropDown", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TextFieldDropDownText; + private static FieldInfo __m_TextFieldDropDownText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TextFieldDropDownText ??= __type__?.GetField("m_TextFieldDropDownText", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_OverrideMargin; + private static FieldInfo __m_OverrideMargin + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_OverrideMargin ??= __type__?.GetField("m_OverrideMargin", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Toolbar; + private static FieldInfo __m_Toolbar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Toolbar ??= __type__?.GetField("m_Toolbar", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ContentToolbar; + private static FieldInfo __m_ContentToolbar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ContentToolbar ??= __type__?.GetField("m_ContentToolbar", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarButton; + private static FieldInfo __m_ToolbarButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarButton ??= __type__?.GetField("m_ToolbarButton", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarButtonLeft; + private static FieldInfo __m_ToolbarButtonLeft + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarButtonLeft ??= __type__?.GetField("m_ToolbarButtonLeft", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarButtonRight; + private static FieldInfo __m_ToolbarButtonRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarButtonRight ??= __type__?.GetField("m_ToolbarButtonRight", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarPopup; + private static FieldInfo __m_ToolbarPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarPopup ??= __type__?.GetField("m_ToolbarPopup", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarPopupLeft; + private static FieldInfo __m_ToolbarPopupLeft + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarPopupLeft ??= __type__?.GetField("m_ToolbarPopupLeft", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarPopupRight; + private static FieldInfo __m_ToolbarPopupRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarPopupRight ??= __type__?.GetField("m_ToolbarPopupRight", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarDropDownLeft; + private static FieldInfo __m_ToolbarDropDownLeft + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarDropDownLeft ??= __type__?.GetField("m_ToolbarDropDownLeft", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarDropDown; + private static FieldInfo __m_ToolbarDropDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarDropDown ??= __type__?.GetField("m_ToolbarDropDown", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarDropDownRight; + private static FieldInfo __m_ToolbarDropDownRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarDropDownRight ??= __type__?.GetField("m_ToolbarDropDownRight", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarDropDownToggle; + private static FieldInfo __m_ToolbarDropDownToggle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarDropDownToggle ??= __type__?.GetField("m_ToolbarDropDownToggle", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarDropDownToggleButton; + private static FieldInfo __m_ToolbarDropDownToggleButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarDropDownToggleButton ??= __type__?.GetField("m_ToolbarDropDownToggleButton", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarDropDownToggleRight; + private static FieldInfo __m_ToolbarDropDownToggleRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarDropDownToggleRight ??= __type__?.GetField("m_ToolbarDropDownToggleRight", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarCreateAddNewDropDown; + private static FieldInfo __m_ToolbarCreateAddNewDropDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarCreateAddNewDropDown ??= __type__?.GetField("m_ToolbarCreateAddNewDropDown", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarTextField; + private static FieldInfo __m_ToolbarTextField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarTextField ??= __type__?.GetField("m_ToolbarTextField", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarLabel; + private static FieldInfo __m_ToolbarLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarLabel ??= __type__?.GetField("m_ToolbarLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_InspectorDefaultMargins; + private static FieldInfo __m_InspectorDefaultMargins + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_InspectorDefaultMargins ??= __type__?.GetField("m_InspectorDefaultMargins", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_InspectorFullWidthMargins; + private static FieldInfo __m_InspectorFullWidthMargins + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_InspectorFullWidthMargins ??= __type__?.GetField("m_InspectorFullWidthMargins", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_DefaultContentMargins; + private static FieldInfo __m_DefaultContentMargins + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_DefaultContentMargins ??= __type__?.GetField("m_DefaultContentMargins", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_FrameBox; + private static FieldInfo __m_FrameBox + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_FrameBox ??= __type__?.GetField("m_FrameBox", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_HelpBox; + private static FieldInfo __m_HelpBox + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_HelpBox ??= __type__?.GetField("m_HelpBox", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarSearchField; + private static FieldInfo __m_ToolbarSearchField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarSearchField ??= __type__?.GetField("m_ToolbarSearchField", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarSearchFieldPopup; + private static FieldInfo __m_ToolbarSearchFieldPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarSearchFieldPopup ??= __type__?.GetField("m_ToolbarSearchFieldPopup", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarSearchFieldWithJumpSynced; + private static FieldInfo __m_ToolbarSearchFieldWithJumpSynced + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarSearchFieldWithJumpSynced ??= __type__?.GetField("m_ToolbarSearchFieldWithJumpSynced", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarSearchFieldWithJumpPopupSynced; + private static FieldInfo __m_ToolbarSearchFieldWithJumpPopupSynced + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarSearchFieldWithJumpPopupSynced ??= __type__?.GetField("m_ToolbarSearchFieldWithJumpPopupSynced", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarSearchFieldWithJump; + private static FieldInfo __m_ToolbarSearchFieldWithJump + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarSearchFieldWithJump ??= __type__?.GetField("m_ToolbarSearchFieldWithJump", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarSearchFieldWithJumpPopup; + private static FieldInfo __m_ToolbarSearchFieldWithJumpPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarSearchFieldWithJumpPopup ??= __type__?.GetField("m_ToolbarSearchFieldWithJumpPopup", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarSearchFieldJumpButton; + private static FieldInfo __m_ToolbarSearchFieldJumpButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarSearchFieldJumpButton ??= __type__?.GetField("m_ToolbarSearchFieldJumpButton", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarSearchFieldCancelButton; + private static FieldInfo __m_ToolbarSearchFieldCancelButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarSearchFieldCancelButton ??= __type__?.GetField("m_ToolbarSearchFieldCancelButton", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarSearchFieldCancelButtonEmpty; + private static FieldInfo __m_ToolbarSearchFieldCancelButtonEmpty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarSearchFieldCancelButtonEmpty ??= __type__?.GetField("m_ToolbarSearchFieldCancelButtonEmpty", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarSearchFieldCancelButtonWithJump; + private static FieldInfo __m_ToolbarSearchFieldCancelButtonWithJump + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarSearchFieldCancelButtonWithJump ??= __type__?.GetField("m_ToolbarSearchFieldCancelButtonWithJump", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarSearchFieldCancelButtonWithJumpEmpty; + private static FieldInfo __m_ToolbarSearchFieldCancelButtonWithJumpEmpty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarSearchFieldCancelButtonWithJumpEmpty ??= __type__?.GetField("m_ToolbarSearchFieldCancelButtonWithJumpEmpty", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ColorPickerBox; + private static FieldInfo __m_ColorPickerBox + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ColorPickerBox ??= __type__?.GetField("m_ColorPickerBox", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ViewBg; + private static FieldInfo __m_ViewBg + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ViewBg ??= __type__?.GetField("m_ViewBg", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_InspectorBig; + private static FieldInfo __m_InspectorBig + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_InspectorBig ??= __type__?.GetField("m_InspectorBig", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_InspectorTitlebar; + private static FieldInfo __m_InspectorTitlebar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_InspectorTitlebar ??= __type__?.GetField("m_InspectorTitlebar", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_InspectorTitlebarFlat; + private static FieldInfo __m_InspectorTitlebarFlat + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_InspectorTitlebarFlat ??= __type__?.GetField("m_InspectorTitlebarFlat", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_InspectorTitlebarText; + private static FieldInfo __m_InspectorTitlebarText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_InspectorTitlebarText ??= __type__?.GetField("m_InspectorTitlebarText", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_FoldoutSelected; + private static FieldInfo __m_FoldoutSelected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_FoldoutSelected ??= __type__?.GetField("m_FoldoutSelected", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_IconButton; + private static FieldInfo __m_IconButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_IconButton ??= __type__?.GetField("m_IconButton", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Tooltip; + private static FieldInfo __m_Tooltip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Tooltip ??= __type__?.GetField("m_Tooltip", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_NotificationText; + private static FieldInfo __m_NotificationText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_NotificationText ??= __type__?.GetField("m_NotificationText", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_NotificationBackground; + private static FieldInfo __m_NotificationBackground + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_NotificationBackground ??= __type__?.GetField("m_NotificationBackground", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AssetLabel; + private static FieldInfo __m_AssetLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AssetLabel ??= __type__?.GetField("m_AssetLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AssetLabelPartial; + private static FieldInfo __m_AssetLabelPartial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AssetLabelPartial ??= __type__?.GetField("m_AssetLabelPartial", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AssetLabelIcon; + private static FieldInfo __m_AssetLabelIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AssetLabelIcon ??= __type__?.GetField("m_AssetLabelIcon", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SearchField; + private static FieldInfo __m_SearchField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SearchField ??= __type__?.GetField("m_SearchField", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SearchFieldCancelButton; + private static FieldInfo __m_SearchFieldCancelButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SearchFieldCancelButton ??= __type__?.GetField("m_SearchFieldCancelButton", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SearchFieldCancelButtonEmpty; + private static FieldInfo __m_SearchFieldCancelButtonEmpty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SearchFieldCancelButtonEmpty ??= __type__?.GetField("m_SearchFieldCancelButtonEmpty", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SelectionRect; + private static FieldInfo __m_SelectionRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SelectionRect ??= __type__?.GetField("m_SelectionRect", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ToolbarSlider; + private static FieldInfo __m_ToolbarSlider + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ToolbarSlider ??= __type__?.GetField("m_ToolbarSlider", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MinMaxHorizontalSliderThumb; + private static FieldInfo __m_MinMaxHorizontalSliderThumb + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MinMaxHorizontalSliderThumb ??= __type__?.GetField("m_MinMaxHorizontalSliderThumb", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_DropDownList; + private static FieldInfo __m_DropDownList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_DropDownList ??= __type__?.GetField("m_DropDownList", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_DropDownToggleButton; + private static FieldInfo __m_DropDownToggleButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_DropDownToggleButton ??= __type__?.GetField("m_DropDownToggleButton", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MinMaxStateDropdown; + private static FieldInfo __m_MinMaxStateDropdown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MinMaxStateDropdown ??= __type__?.GetField("m_MinMaxStateDropdown", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ProgressBarBar; + private static FieldInfo __m_ProgressBarBar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ProgressBarBar ??= __type__?.GetField("m_ProgressBarBar", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ProgressBarText; + private static FieldInfo __m_ProgressBarText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ProgressBarText ??= __type__?.GetField("m_ProgressBarText", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ProgressBarBack; + private static FieldInfo __m_ProgressBarBack + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ProgressBarBack ??= __type__?.GetField("m_ProgressBarBack", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ScrollViewAlt; + private static FieldInfo __m_ScrollViewAlt + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ScrollViewAlt ??= __type__?.GetField("m_ScrollViewAlt", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_KnobSize; + private static FieldInfo __m_KnobSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_KnobSize ??= __type__?.GetField("m_KnobSize", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MiniKnobSize; + private static FieldInfo __m_MiniKnobSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MiniKnobSize ??= __type__?.GetField("m_MiniKnobSize", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_Current; + private static FieldInfo __s_Current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_Current ??= __type__?.GetField("s_Current", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_CachedStyles; + private static FieldInfo __s_CachedStyles + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_CachedStyles ??= __type__?.GetField("s_CachedStyles", (BindingFlags)(-1)); + } + + private static PropertyInfo ___boldTextField; + private static PropertyInfo __boldTextField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___boldTextField ??= __type__?.GetProperty("boldTextField", (BindingFlags)(-1)); + } + + private static PropertyInfo ___objectFieldButton; + private static PropertyInfo __objectFieldButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___objectFieldButton ??= __type__?.GetProperty("objectFieldButton", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toggleMixed; + private static PropertyInfo __toggleMixed + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toggleMixed ??= __type__?.GetProperty("toggleMixed", (BindingFlags)(-1)); + } + + private static PropertyInfo ___titlebarFoldout; + private static PropertyInfo __titlebarFoldout + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___titlebarFoldout ??= __type__?.GetProperty("titlebarFoldout", (BindingFlags)(-1)); + } + + private static PropertyInfo ___optionsButtonStyle; + private static PropertyInfo __optionsButtonStyle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___optionsButtonStyle ??= __type__?.GetProperty("optionsButtonStyle", (BindingFlags)(-1)); + } + + private static PropertyInfo ___textFieldDropDown; + private static PropertyInfo __textFieldDropDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___textFieldDropDown ??= __type__?.GetProperty("textFieldDropDown", (BindingFlags)(-1)); + } + + private static PropertyInfo ___textFieldDropDownText; + private static PropertyInfo __textFieldDropDownText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___textFieldDropDownText ??= __type__?.GetProperty("textFieldDropDownText", (BindingFlags)(-1)); + } + + private static PropertyInfo ___overrideMargin; + private static PropertyInfo __overrideMargin + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___overrideMargin ??= __type__?.GetProperty("overrideMargin", (BindingFlags)(-1)); + } + + private static PropertyInfo ___contentToolbar; + private static PropertyInfo __contentToolbar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___contentToolbar ??= __type__?.GetProperty("contentToolbar", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarButtonLeft; + private static PropertyInfo __toolbarButtonLeft + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarButtonLeft ??= __type__?.GetProperty("toolbarButtonLeft", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarButtonRight; + private static PropertyInfo __toolbarButtonRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarButtonRight ??= __type__?.GetProperty("toolbarButtonRight", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarPopupLeft; + private static PropertyInfo __toolbarPopupLeft + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarPopupLeft ??= __type__?.GetProperty("toolbarPopupLeft", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarPopupRight; + private static PropertyInfo __toolbarPopupRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarPopupRight ??= __type__?.GetProperty("toolbarPopupRight", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarDropDownLeft; + private static PropertyInfo __toolbarDropDownLeft + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarDropDownLeft ??= __type__?.GetProperty("toolbarDropDownLeft", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarDropDownRight; + private static PropertyInfo __toolbarDropDownRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarDropDownRight ??= __type__?.GetProperty("toolbarDropDownRight", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarDropDownToggle; + private static PropertyInfo __toolbarDropDownToggle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarDropDownToggle ??= __type__?.GetProperty("toolbarDropDownToggle", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarDropDownToggleButton; + private static PropertyInfo __toolbarDropDownToggleButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarDropDownToggleButton ??= __type__?.GetProperty("toolbarDropDownToggleButton", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarDropDownToggleRight; + private static PropertyInfo __toolbarDropDownToggleRight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarDropDownToggleRight ??= __type__?.GetProperty("toolbarDropDownToggleRight", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarCreateAddNewDropDown; + private static PropertyInfo __toolbarCreateAddNewDropDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarCreateAddNewDropDown ??= __type__?.GetProperty("toolbarCreateAddNewDropDown", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarLabel; + private static PropertyInfo __toolbarLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarLabel ??= __type__?.GetProperty("toolbarLabel", (BindingFlags)(-1)); + } + + private static PropertyInfo ___defaultContentMargins; + private static PropertyInfo __defaultContentMargins + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___defaultContentMargins ??= __type__?.GetProperty("defaultContentMargins", (BindingFlags)(-1)); + } + + private static PropertyInfo ___frameBox; + private static PropertyInfo __frameBox + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___frameBox ??= __type__?.GetProperty("frameBox", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarSearchFieldPopup; + private static PropertyInfo __toolbarSearchFieldPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarSearchFieldPopup ??= __type__?.GetProperty("toolbarSearchFieldPopup", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarSearchFieldWithJumpSynced; + private static PropertyInfo __toolbarSearchFieldWithJumpSynced + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarSearchFieldWithJumpSynced ??= __type__?.GetProperty("toolbarSearchFieldWithJumpSynced", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarSearchFieldWithJumpPopupSynced; + private static PropertyInfo __toolbarSearchFieldWithJumpPopupSynced + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarSearchFieldWithJumpPopupSynced ??= __type__?.GetProperty("toolbarSearchFieldWithJumpPopupSynced", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarSearchFieldWithJump; + private static PropertyInfo __toolbarSearchFieldWithJump + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarSearchFieldWithJump ??= __type__?.GetProperty("toolbarSearchFieldWithJump", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarSearchFieldWithJumpPopup; + private static PropertyInfo __toolbarSearchFieldWithJumpPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarSearchFieldWithJumpPopup ??= __type__?.GetProperty("toolbarSearchFieldWithJumpPopup", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarSearchFieldJumpButton; + private static PropertyInfo __toolbarSearchFieldJumpButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarSearchFieldJumpButton ??= __type__?.GetProperty("toolbarSearchFieldJumpButton", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarSearchFieldCancelButton; + private static PropertyInfo __toolbarSearchFieldCancelButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarSearchFieldCancelButton ??= __type__?.GetProperty("toolbarSearchFieldCancelButton", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarSearchFieldCancelButtonEmpty; + private static PropertyInfo __toolbarSearchFieldCancelButtonEmpty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarSearchFieldCancelButtonEmpty ??= __type__?.GetProperty("toolbarSearchFieldCancelButtonEmpty", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarSearchFieldCancelButtonWithJump; + private static PropertyInfo __toolbarSearchFieldCancelButtonWithJump + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarSearchFieldCancelButtonWithJump ??= __type__?.GetProperty("toolbarSearchFieldCancelButtonWithJump", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarSearchFieldCancelButtonWithJumpEmpty; + private static PropertyInfo __toolbarSearchFieldCancelButtonWithJumpEmpty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarSearchFieldCancelButtonWithJumpEmpty ??= __type__?.GetProperty("toolbarSearchFieldCancelButtonWithJumpEmpty", (BindingFlags)(-1)); + } + + private static PropertyInfo ___colorPickerBox; + private static PropertyInfo __colorPickerBox + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___colorPickerBox ??= __type__?.GetProperty("colorPickerBox", (BindingFlags)(-1)); + } + + private static PropertyInfo ___viewBackground; + private static PropertyInfo __viewBackground + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___viewBackground ??= __type__?.GetProperty("viewBackground", (BindingFlags)(-1)); + } + + private static PropertyInfo ___inspectorBig; + private static PropertyInfo __inspectorBig + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___inspectorBig ??= __type__?.GetProperty("inspectorBig", (BindingFlags)(-1)); + } + + private static PropertyInfo ___inspectorTitlebar; + private static PropertyInfo __inspectorTitlebar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___inspectorTitlebar ??= __type__?.GetProperty("inspectorTitlebar", (BindingFlags)(-1)); + } + + private static PropertyInfo ___inspectorTitlebarFlat; + private static PropertyInfo __inspectorTitlebarFlat + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___inspectorTitlebarFlat ??= __type__?.GetProperty("inspectorTitlebarFlat", (BindingFlags)(-1)); + } + + private static PropertyInfo ___inspectorTitlebarText; + private static PropertyInfo __inspectorTitlebarText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___inspectorTitlebarText ??= __type__?.GetProperty("inspectorTitlebarText", (BindingFlags)(-1)); + } + + private static PropertyInfo ___foldoutSelected; + private static PropertyInfo __foldoutSelected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___foldoutSelected ??= __type__?.GetProperty("foldoutSelected", (BindingFlags)(-1)); + } + + private static PropertyInfo ___tooltip; + private static PropertyInfo __tooltip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___tooltip ??= __type__?.GetProperty("tooltip", (BindingFlags)(-1)); + } + + private static PropertyInfo ___notificationText; + private static PropertyInfo __notificationText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___notificationText ??= __type__?.GetProperty("notificationText", (BindingFlags)(-1)); + } + + private static PropertyInfo ___notificationBackground; + private static PropertyInfo __notificationBackground + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___notificationBackground ??= __type__?.GetProperty("notificationBackground", (BindingFlags)(-1)); + } + + private static PropertyInfo ___assetLabel; + private static PropertyInfo __assetLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___assetLabel ??= __type__?.GetProperty("assetLabel", (BindingFlags)(-1)); + } + + private static PropertyInfo ___assetLabelPartial; + private static PropertyInfo __assetLabelPartial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___assetLabelPartial ??= __type__?.GetProperty("assetLabelPartial", (BindingFlags)(-1)); + } + + private static PropertyInfo ___assetLabelIcon; + private static PropertyInfo __assetLabelIcon + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___assetLabelIcon ??= __type__?.GetProperty("assetLabelIcon", (BindingFlags)(-1)); + } + + private static PropertyInfo ___searchField; + private static PropertyInfo __searchField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___searchField ??= __type__?.GetProperty("searchField", (BindingFlags)(-1)); + } + + private static PropertyInfo ___searchFieldCancelButton; + private static PropertyInfo __searchFieldCancelButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___searchFieldCancelButton ??= __type__?.GetProperty("searchFieldCancelButton", (BindingFlags)(-1)); + } + + private static PropertyInfo ___searchFieldCancelButtonEmpty; + private static PropertyInfo __searchFieldCancelButtonEmpty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___searchFieldCancelButtonEmpty ??= __type__?.GetProperty("searchFieldCancelButtonEmpty", (BindingFlags)(-1)); + } + + private static PropertyInfo ___toolbarSlider; + private static PropertyInfo __toolbarSlider + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___toolbarSlider ??= __type__?.GetProperty("toolbarSlider", (BindingFlags)(-1)); + } + + private static PropertyInfo ___minMaxHorizontalSliderThumb; + private static PropertyInfo __minMaxHorizontalSliderThumb + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___minMaxHorizontalSliderThumb ??= __type__?.GetProperty("minMaxHorizontalSliderThumb", (BindingFlags)(-1)); + } + + private static PropertyInfo ___dropDownList; + private static PropertyInfo __dropDownList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___dropDownList ??= __type__?.GetProperty("dropDownList", (BindingFlags)(-1)); + } + + private static PropertyInfo ___dropDownToggleButton; + private static PropertyInfo __dropDownToggleButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___dropDownToggleButton ??= __type__?.GetProperty("dropDownToggleButton", (BindingFlags)(-1)); + } + + private static PropertyInfo ___minMaxStateDropdown; + private static PropertyInfo __minMaxStateDropdown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___minMaxStateDropdown ??= __type__?.GetProperty("minMaxStateDropdown", (BindingFlags)(-1)); + } + + private static PropertyInfo ___progressBarBack; + private static PropertyInfo __progressBarBack + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___progressBarBack ??= __type__?.GetProperty("progressBarBack", (BindingFlags)(-1)); + } + + private static PropertyInfo ___progressBarBar; + private static PropertyInfo __progressBarBar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___progressBarBar ??= __type__?.GetProperty("progressBarBar", (BindingFlags)(-1)); + } + + private static PropertyInfo ___progressBarText; + private static PropertyInfo __progressBarText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___progressBarText ??= __type__?.GetProperty("progressBarText", (BindingFlags)(-1)); + } + + private static PropertyInfo ___scrollViewAlt; + private static PropertyInfo __scrollViewAlt + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___scrollViewAlt ??= __type__?.GetProperty("scrollViewAlt", (BindingFlags)(-1)); + } + + private static PropertyInfo ___knobSize; + private static PropertyInfo __knobSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___knobSize ??= __type__?.GetProperty("knobSize", (BindingFlags)(-1)); + } + + private static PropertyInfo ___miniKnobSize; + private static PropertyInfo __miniKnobSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___miniKnobSize ??= __type__?.GetProperty("miniKnobSize", (BindingFlags)(-1)); + } + + private static MethodInfo ___UpdateSkinCache; + private static MethodInfo __UpdateSkinCache + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UpdateSkinCache ??= __type__?.GetMethodInfoByParameterTypeNames("UpdateSkinCache"); + } + + private static MethodInfo ___UpdateSkinCache__2; + private static MethodInfo __UpdateSkinCache__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UpdateSkinCache__2 ??= __type__?.GetMethodInfoByParameterTypeNames("UpdateSkinCache", "System.Int32"); + } + + private static MethodInfo ___InitSharedStyles; + private static MethodInfo __InitSharedStyles + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___InitSharedStyles ??= __type__?.GetMethodInfoByParameterTypeNames("InitSharedStyles"); + } + + private static MethodInfo ___GetStyle; + private static MethodInfo __GetStyle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetStyle ??= __type__?.GetMethodInfoByParameterTypeNames("GetStyle", "System.String"); + } + } + public static class UnityEditor_EditorStyles_Extension + { + public static UnityEditor_EditorStyles ReflectionHelper(this UnityEditor.EditorStyles self) => new(self); + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorStyles.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorStyles.cs.meta new file mode 100644 index 0000000..5d6e33f --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorStyles.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2d7307db1d8438244bd31626ae530402 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorWindow.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorWindow.cs new file mode 100644 index 0000000..c016399 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorWindow.cs @@ -0,0 +1,1329 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_EditorWindow + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.EditorWindow"); + + + public UnityEngine.UIElements.VisualElement baseRootVisualElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.UIElements.VisualElement)(__baseRootVisualElement?.GetValue(__self__)); + } + + public bool liveReloadPreferenceDefault + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__liveReloadPreferenceDefault?.GetValue(__self__)); + } + + public bool isUIToolkitWindow + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__isUIToolkitWindow?.GetValue(__self__)); + } + + public object overlayCanvas + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__overlayCanvas?.GetValue(__self__)); + } + + public object viewDataDictionary + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__viewDataDictionary?.GetValue(__self__)); + } + + public bool disableInputEvents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__disableInputEvents?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __disableInputEvents?.SetValue(__self__, value); + } + + public bool hasUnsavedChanges + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__hasUnsavedChanges?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __hasUnsavedChanges?.SetValue(__self__, value); + } + + public string saveChangesMessage + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__saveChangesMessage?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __saveChangesMessage?.SetValue(__self__, value); + } + + public int antiAliasing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__antiAliasing?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __antiAliasing?.SetValue(__self__, value); + } + + public bool m_AutoRepaintOnSceneChange + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_AutoRepaintOnSceneChange?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AutoRepaintOnSceneChange?.SetValue(__self__, value); + } + + public UnityEngine.Vector2 m_MinSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Vector2)(__m_MinSize?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MinSize?.SetValue(__self__, value); + } + + public UnityEngine.Vector2 m_MaxSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Vector2)(__m_MaxSize?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MaxSize?.SetValue(__self__, value); + } + + public UnityEngine.GUIContent m_TitleContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__m_TitleContent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TitleContent?.SetValue(__self__, value); + } + + public int m_DepthBufferBits + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__m_DepthBufferBits?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_DepthBufferBits?.SetValue(__self__, value); + } + + public int m_AntiAliasing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__m_AntiAliasing?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AntiAliasing?.SetValue(__self__, value); + } + + public UnityEngine.Rect m_Pos + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Rect)(__m_Pos?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Pos?.SetValue(__self__, value); + } + + public UnityEngine.UIElements.VisualElement m_UIRootElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.UIElements.VisualElement)(__m_UIRootElement?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_UIRootElement?.SetValue(__self__, value); + } + + public object m_ViewDataDictionary + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_ViewDataDictionary?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ViewDataDictionary?.SetValue(__self__, value); + } + + public object m_OverlayCanvas + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_OverlayCanvas?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_OverlayCanvas?.SetValue(__self__, value); + } + + public bool m_OverlaysInitialized + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_OverlaysInitialized?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_OverlaysInitialized?.SetValue(__self__, value); + } + + public bool m_EnableViewDataPersistence + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_EnableViewDataPersistence?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_EnableViewDataPersistence?.SetValue(__self__, value); + } + + public bool m_RequestedViewDataSave + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_RequestedViewDataSave?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_RequestedViewDataSave?.SetValue(__self__, value); + } + + public static System.Action s_UpdateWindowMenuListingOff + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Action)(__s_UpdateWindowMenuListingOff?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_UpdateWindowMenuListingOff?.SetValue(null, value); + } + + public UnityEngine.Rect m_GameViewRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Rect)(__m_GameViewRect?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_GameViewRect?.SetValue(__self__, value); + } + + public UnityEngine.Rect m_GameViewClippedRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Rect)(__m_GameViewClippedRect?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_GameViewClippedRect?.SetValue(__self__, value); + } + + public UnityEngine.Vector2 m_GameViewTargetSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Vector2)(__m_GameViewTargetSize?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_GameViewTargetSize?.SetValue(__self__, value); + } + + public bool m_IsPlayModeView + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_IsPlayModeView?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_IsPlayModeView?.SetValue(__self__, value); + } + + public object m_EventInterests + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_EventInterests?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_EventInterests?.SetValue(__self__, value); + } + + public bool m_DisableInputEvents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_DisableInputEvents?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_DisableInputEvents?.SetValue(__self__, value); + } + + public object m_Parent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_Parent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Parent?.SetValue(__self__, value); + } + + public static double kWarningFadeoutWait + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (double)(__kWarningFadeoutWait?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kWarningFadeoutWait?.SetValue(null, value); + } + + public static double kWarningFadeoutTime + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (double)(__kWarningFadeoutTime?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kWarningFadeoutTime?.SetValue(null, value); + } + + public UnityEngine.GUIContent m_Notification + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__m_Notification?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Notification?.SetValue(__self__, value); + } + + public UnityEngine.Vector2 m_NotificationSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Vector2)(__m_NotificationSize?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_NotificationSize?.SetValue(__self__, value); + } + + public float m_FadeoutTime + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__m_FadeoutTime?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_FadeoutTime?.SetValue(__self__, value); + } + + public bool m_HasUnsavedChanges + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_HasUnsavedChanges?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_HasUnsavedChanges?.SetValue(__self__, value); + } + + public static object s_ShortcutContext + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__s_ShortcutContext?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ShortcutContext?.SetValue(null, value); + } + + public static void Internal_MakeModal(object win) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = win; + __Internal_MakeModal?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public void SaveViewData() + { + __SaveViewData?.Invoke(__self__, System.Array.Empty()); + } + + public void SaveViewDataToDisk() + { + __SaveViewDataToDisk?.Invoke(__self__, System.Array.Empty()); + } + + public object GetViewDataDictionary() + { + var __result__ = __GetViewDataDictionary?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (object)(__result__) : default; + } + + public void DisableViewDataPersistence() + { + __DisableViewDataPersistence?.Invoke(__self__, System.Array.Empty()); + } + + public void ClearPersistentViewData() + { + __ClearPersistentViewData?.Invoke(__self__, System.Array.Empty()); + } + + public void OnResized() + { + __OnResized?.Invoke(__self__, System.Array.Empty()); + } + + public void OnBackgroundViewResized(UnityEngine.Rect pos) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = pos; + __OnBackgroundViewResized?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void CheckForWindowRepaint() + { + __CheckForWindowRepaint?.Invoke(__self__, System.Array.Empty()); + } + + public UnityEngine.GUIContent GetLocalizedTitleContent() + { + var __result__ = __GetLocalizedTitleContent?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (UnityEngine.GUIContent)(__result__) : default; + } + + public static UnityEngine.GUIContent GetLocalizedTitleContentFromType(System.Type t) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = t; + var __result__ = __GetLocalizedTitleContentFromType?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GUIContent)(__result__) : default; + } + + public static UnityEditor.EditorWindowTitleAttribute GetEditorWindowTitleAttribute(System.Type t) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = t; + var __result__ = __GetEditorWindowTitleAttribute?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEditor.EditorWindowTitleAttribute)(__result__) : default; + } + + public void DrawNotification() + { + __DrawNotification?.Invoke(__self__, System.Array.Empty()); + } + + public void OnMaximized() + { + __OnMaximized?.Invoke(__self__, System.Array.Empty()); + } + + public bool CanMaximize() + { + var __result__ = __CanMaximize?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public int GetNumTabs() + { + var __result__ = __GetNumTabs?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public bool ShowNextTabIfPossible() + { + var __result__ = __ShowNextTabIfPossible?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public bool IsSelectedTab() + { + var __result__ = __IsSelectedTab?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void MakeParentsSettingsMatchMe() + { + __MakeParentsSettingsMatchMe?.Invoke(__self__, System.Array.Empty()); + } + + public void ShowTooltip() + { + __ShowTooltip?.Invoke(__self__, System.Array.Empty()); + } + + public void MakeModal() + { + __MakeModal?.Invoke(__self__, System.Array.Empty()); + } + + public void ShowPopupWithMode(object mode, bool giveFocus) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = mode; + __params__[1] = giveFocus; + __ShowPopupWithMode?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void ShowWithMode(object mode) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = mode; + __ShowWithMode?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void ShowAsDropDown(UnityEngine.Rect buttonRect, UnityEngine.Vector2 windowSize, Array locationPriorityOrder) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = buttonRect; + __params__[1] = windowSize; + __params__[2] = locationPriorityOrder; + __ShowAsDropDown?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void ShowAsDropDown(UnityEngine.Rect buttonRect, UnityEngine.Vector2 windowSize, Array locationPriorityOrder, object mode) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = buttonRect; + __params__[1] = windowSize; + __params__[2] = locationPriorityOrder; + __params__[3] = mode; + __ShowAsDropDown__2?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void ShowAsDropDown(UnityEngine.Rect buttonRect, UnityEngine.Vector2 windowSize, Array locationPriorityOrder, object mode, bool giveFocus) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = buttonRect; + __params__[1] = windowSize; + __params__[2] = locationPriorityOrder; + __params__[3] = mode; + __params__[4] = giveFocus; + __ShowAsDropDown__3?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public UnityEngine.Rect ShowAsDropDownFitToScreen(UnityEngine.Rect buttonRect, UnityEngine.Vector2 windowSize, Array locationPriorityOrder) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = buttonRect; + __params__[1] = windowSize; + __params__[2] = locationPriorityOrder; + var __result__ = __ShowAsDropDownFitToScreen?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public static UnityEditor.EditorWindow GetWindowPrivate(System.Type t, bool utility, string title, bool focus) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = t; + __params__[1] = utility; + __params__[2] = title; + __params__[3] = focus; + var __result__ = __GetWindowPrivate?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEditor.EditorWindow)(__result__) : default; + } + + public void RemoveFromDockArea() + { + __RemoveFromDockArea?.Invoke(__self__, System.Array.Empty()); + } + + public static UnityEditor.EditorWindow GetWindowWithRectPrivate(System.Type t, UnityEngine.Rect rect, bool utility, string title) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = t; + __params__[1] = rect; + __params__[2] = utility; + __params__[3] = title; + var __result__ = __GetWindowWithRectPrivate?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEditor.EditorWindow)(__result__) : default; + } + + public static T GetWindowDontShow() + { + var __result__ = __GetWindowDontShow?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (T)(__result__) : default; + } + + public void RepaintImmediately() + { + __RepaintImmediately?.Invoke(__self__, System.Array.Empty()); + } + + public void SetParentGameViewDimensions(UnityEngine.Rect rect, UnityEngine.Rect clippedRect, UnityEngine.Vector2 targetSize) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = clippedRect; + __params__[2] = targetSize; + __SetParentGameViewDimensions?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void SetPlayModeViewSize(UnityEngine.Vector2 targetSize) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = targetSize; + __SetPlayModeViewSize?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void SetMainPlayModeViewSize(UnityEngine.Vector2 targetSize) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = targetSize; + __SetMainPlayModeViewSize?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void SetDisplayViewSize(int displayId, UnityEngine.Vector2 targetSize) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = displayId; + __params__[1] = targetSize; + __SetDisplayViewSize?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public UnityEngine.Vector2 GetDisplayViewSize(int displayId) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = displayId; + var __result__ = __GetDisplayViewSize?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector2)(__result__) : default; + } + + public void SetPlayModeView(bool value) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = value; + __SetPlayModeView?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void __internalAwake() + { + ____internalAwake?.Invoke(__self__, System.Array.Empty()); + } + + public static void Initialize() + { + __Initialize?.Invoke(null, System.Array.Empty()); + } + + public void OnDisableINTERNAL() + { + __OnDisableINTERNAL?.Invoke(__self__, System.Array.Empty()); + } + + public static void CreateNewWindowForEditorWindow(UnityEditor.EditorWindow window, bool loadPosition, bool showImmediately, bool setFocus) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = window; + __params__[1] = loadPosition; + __params__[2] = showImmediately; + __params__[3] = setFocus; + __CreateNewWindowForEditorWindow?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public void AddSceneTab() + { + __AddSceneTab?.Invoke(__self__, System.Array.Empty()); + } + + public void AddGameTab() + { + __AddGameTab?.Invoke(__self__, System.Array.Empty()); + } + + public static void UpdateWindowMenuListing() + { + __UpdateWindowMenuListing?.Invoke(null, System.Array.Empty()); + } + + public static void BuildWindowMenuListing() + { + __BuildWindowMenuListing?.Invoke(null, System.Array.Empty()); + } + + public static UnityEngine.UIElements.VisualElement CreateRoot() + { + var __result__ = __CreateRoot?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (UnityEngine.UIElements.VisualElement)(__result__) : default; + } + + public static void ToggleAllOverlays(UnityEditor.ShortcutManagement.ShortcutArguments args) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = args; + __ToggleAllOverlays?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void HideOverlay(UnityEditor.ShortcutManagement.ShortcutArguments args) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = args; + __HideOverlay?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void ShowOverlayMenu(UnityEditor.ShortcutManagement.ShortcutArguments args) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = args; + __ShowOverlayMenu?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public void OnBackingScaleFactorChangedInternal() + { + __OnBackingScaleFactorChangedInternal?.Invoke(__self__, System.Array.Empty()); + } + + public void OnBackingScaleFactorChanged() + { + __OnBackingScaleFactorChanged?.Invoke(__self__, System.Array.Empty()); + } + + public UnityEditor_EditorWindow(object __self__) => this.__self__ = __self__ as UnityEngine.Object; + public UnityEngine.Object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + public UnityEditor.EditorWindow __super__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.EditorWindow)(__self__); + } + + private static FieldInfo ___m_AutoRepaintOnSceneChange; + private static FieldInfo __m_AutoRepaintOnSceneChange + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AutoRepaintOnSceneChange ??= __type__?.GetField("m_AutoRepaintOnSceneChange", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MinSize; + private static FieldInfo __m_MinSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MinSize ??= __type__?.GetField("m_MinSize", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MaxSize; + private static FieldInfo __m_MaxSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MaxSize ??= __type__?.GetField("m_MaxSize", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TitleContent; + private static FieldInfo __m_TitleContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TitleContent ??= __type__?.GetField("m_TitleContent", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_DepthBufferBits; + private static FieldInfo __m_DepthBufferBits + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_DepthBufferBits ??= __type__?.GetField("m_DepthBufferBits", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AntiAliasing; + private static FieldInfo __m_AntiAliasing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AntiAliasing ??= __type__?.GetField("m_AntiAliasing", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Pos; + private static FieldInfo __m_Pos + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Pos ??= __type__?.GetField("m_Pos", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_UIRootElement; + private static FieldInfo __m_UIRootElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_UIRootElement ??= __type__?.GetField("m_UIRootElement", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ViewDataDictionary; + private static FieldInfo __m_ViewDataDictionary + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ViewDataDictionary ??= __type__?.GetField("m_ViewDataDictionary", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_OverlayCanvas; + private static FieldInfo __m_OverlayCanvas + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_OverlayCanvas ??= __type__?.GetField("m_OverlayCanvas", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_OverlaysInitialized; + private static FieldInfo __m_OverlaysInitialized + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_OverlaysInitialized ??= __type__?.GetField("m_OverlaysInitialized", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_EnableViewDataPersistence; + private static FieldInfo __m_EnableViewDataPersistence + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_EnableViewDataPersistence ??= __type__?.GetField("m_EnableViewDataPersistence", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_RequestedViewDataSave; + private static FieldInfo __m_RequestedViewDataSave + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_RequestedViewDataSave ??= __type__?.GetField("m_RequestedViewDataSave", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_UpdateWindowMenuListingOff; + private static FieldInfo __s_UpdateWindowMenuListingOff + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_UpdateWindowMenuListingOff ??= __type__?.GetField("s_UpdateWindowMenuListingOff", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_GameViewRect; + private static FieldInfo __m_GameViewRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_GameViewRect ??= __type__?.GetField("m_GameViewRect", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_GameViewClippedRect; + private static FieldInfo __m_GameViewClippedRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_GameViewClippedRect ??= __type__?.GetField("m_GameViewClippedRect", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_GameViewTargetSize; + private static FieldInfo __m_GameViewTargetSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_GameViewTargetSize ??= __type__?.GetField("m_GameViewTargetSize", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_IsPlayModeView; + private static FieldInfo __m_IsPlayModeView + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_IsPlayModeView ??= __type__?.GetField("m_IsPlayModeView", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_EventInterests; + private static FieldInfo __m_EventInterests + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_EventInterests ??= __type__?.GetField("m_EventInterests", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_DisableInputEvents; + private static FieldInfo __m_DisableInputEvents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_DisableInputEvents ??= __type__?.GetField("m_DisableInputEvents", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Parent; + private static FieldInfo __m_Parent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Parent ??= __type__?.GetField("m_Parent", (BindingFlags)(-1)); + } + + private static FieldInfo ___kWarningFadeoutWait; + private static FieldInfo __kWarningFadeoutWait + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kWarningFadeoutWait ??= __type__?.GetField("kWarningFadeoutWait", (BindingFlags)(-1)); + } + + private static FieldInfo ___kWarningFadeoutTime; + private static FieldInfo __kWarningFadeoutTime + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kWarningFadeoutTime ??= __type__?.GetField("kWarningFadeoutTime", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Notification; + private static FieldInfo __m_Notification + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Notification ??= __type__?.GetField("m_Notification", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_NotificationSize; + private static FieldInfo __m_NotificationSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_NotificationSize ??= __type__?.GetField("m_NotificationSize", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_FadeoutTime; + private static FieldInfo __m_FadeoutTime + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_FadeoutTime ??= __type__?.GetField("m_FadeoutTime", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_HasUnsavedChanges; + private static FieldInfo __m_HasUnsavedChanges + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_HasUnsavedChanges ??= __type__?.GetField("m_HasUnsavedChanges", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ShortcutContext; + private static FieldInfo __s_ShortcutContext + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ShortcutContext ??= __type__?.GetField("s_ShortcutContext", (BindingFlags)(-1)); + } + + private static PropertyInfo ___baseRootVisualElement; + private static PropertyInfo __baseRootVisualElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___baseRootVisualElement ??= __type__?.GetProperty("baseRootVisualElement", (BindingFlags)(-1)); + } + + private static PropertyInfo ___liveReloadPreferenceDefault; + private static PropertyInfo __liveReloadPreferenceDefault + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___liveReloadPreferenceDefault ??= __type__?.GetProperty("liveReloadPreferenceDefault", (BindingFlags)(-1)); + } + + private static PropertyInfo ___isUIToolkitWindow; + private static PropertyInfo __isUIToolkitWindow + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___isUIToolkitWindow ??= __type__?.GetProperty("isUIToolkitWindow", (BindingFlags)(-1)); + } + + private static PropertyInfo ___overlayCanvas; + private static PropertyInfo __overlayCanvas + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___overlayCanvas ??= __type__?.GetProperty("overlayCanvas", (BindingFlags)(-1)); + } + + private static PropertyInfo ___viewDataDictionary; + private static PropertyInfo __viewDataDictionary + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___viewDataDictionary ??= __type__?.GetProperty("viewDataDictionary", (BindingFlags)(-1)); + } + + private static PropertyInfo ___disableInputEvents; + private static PropertyInfo __disableInputEvents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___disableInputEvents ??= __type__?.GetProperty("disableInputEvents", (BindingFlags)(-1)); + } + + private static PropertyInfo ___hasUnsavedChanges; + private static PropertyInfo __hasUnsavedChanges + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___hasUnsavedChanges ??= __type__?.GetProperty("hasUnsavedChanges", (BindingFlags)(-1)); + } + + private static PropertyInfo ___saveChangesMessage; + private static PropertyInfo __saveChangesMessage + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___saveChangesMessage ??= __type__?.GetProperty("saveChangesMessage", (BindingFlags)(-1)); + } + + private static PropertyInfo ___antiAliasing; + private static PropertyInfo __antiAliasing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___antiAliasing ??= __type__?.GetProperty("antiAliasing", (BindingFlags)(-1)); + } + + private static MethodInfo ___Internal_MakeModal; + private static MethodInfo __Internal_MakeModal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_MakeModal ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_MakeModal", "UnityEditor.ContainerWindow"); + } + + private static MethodInfo ___SaveViewData; + private static MethodInfo __SaveViewData + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SaveViewData ??= __type__?.GetMethodInfoByParameterTypeNames("SaveViewData"); + } + + private static MethodInfo ___SaveViewDataToDisk; + private static MethodInfo __SaveViewDataToDisk + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SaveViewDataToDisk ??= __type__?.GetMethodInfoByParameterTypeNames("SaveViewDataToDisk"); + } + + private static MethodInfo ___GetViewDataDictionary; + private static MethodInfo __GetViewDataDictionary + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetViewDataDictionary ??= __type__?.GetMethodInfoByParameterTypeNames("GetViewDataDictionary"); + } + + private static MethodInfo ___DisableViewDataPersistence; + private static MethodInfo __DisableViewDataPersistence + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DisableViewDataPersistence ??= __type__?.GetMethodInfoByParameterTypeNames("DisableViewDataPersistence"); + } + + private static MethodInfo ___ClearPersistentViewData; + private static MethodInfo __ClearPersistentViewData + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ClearPersistentViewData ??= __type__?.GetMethodInfoByParameterTypeNames("ClearPersistentViewData"); + } + + private static MethodInfo ___OnResized; + private static MethodInfo __OnResized + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnResized ??= __type__?.GetMethodInfoByParameterTypeNames("OnResized"); + } + + private static MethodInfo ___OnBackgroundViewResized; + private static MethodInfo __OnBackgroundViewResized + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnBackgroundViewResized ??= __type__?.GetMethodInfoByParameterTypeNames("OnBackgroundViewResized", "UnityEngine.Rect"); + } + + private static MethodInfo ___CheckForWindowRepaint; + private static MethodInfo __CheckForWindowRepaint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CheckForWindowRepaint ??= __type__?.GetMethodInfoByParameterTypeNames("CheckForWindowRepaint"); + } + + private static MethodInfo ___GetLocalizedTitleContent; + private static MethodInfo __GetLocalizedTitleContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetLocalizedTitleContent ??= __type__?.GetMethodInfoByParameterTypeNames("GetLocalizedTitleContent"); + } + + private static MethodInfo ___GetLocalizedTitleContentFromType; + private static MethodInfo __GetLocalizedTitleContentFromType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetLocalizedTitleContentFromType ??= __type__?.GetMethodInfoByParameterTypeNames("GetLocalizedTitleContentFromType", "System.Type"); + } + + private static MethodInfo ___GetEditorWindowTitleAttribute; + private static MethodInfo __GetEditorWindowTitleAttribute + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetEditorWindowTitleAttribute ??= __type__?.GetMethodInfoByParameterTypeNames("GetEditorWindowTitleAttribute", "System.Type"); + } + + private static MethodInfo ___DrawNotification; + private static MethodInfo __DrawNotification + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawNotification ??= __type__?.GetMethodInfoByParameterTypeNames("DrawNotification"); + } + + private static MethodInfo ___OnMaximized; + private static MethodInfo __OnMaximized + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnMaximized ??= __type__?.GetMethodInfoByParameterTypeNames("OnMaximized"); + } + + private static MethodInfo ___CanMaximize; + private static MethodInfo __CanMaximize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CanMaximize ??= __type__?.GetMethodInfoByParameterTypeNames("CanMaximize"); + } + + private static MethodInfo ___GetNumTabs; + private static MethodInfo __GetNumTabs + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetNumTabs ??= __type__?.GetMethodInfoByParameterTypeNames("GetNumTabs"); + } + + private static MethodInfo ___ShowNextTabIfPossible; + private static MethodInfo __ShowNextTabIfPossible + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShowNextTabIfPossible ??= __type__?.GetMethodInfoByParameterTypeNames("ShowNextTabIfPossible"); + } + + private static MethodInfo ___IsSelectedTab; + private static MethodInfo __IsSelectedTab + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsSelectedTab ??= __type__?.GetMethodInfoByParameterTypeNames("IsSelectedTab"); + } + + private static MethodInfo ___MakeParentsSettingsMatchMe; + private static MethodInfo __MakeParentsSettingsMatchMe + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MakeParentsSettingsMatchMe ??= __type__?.GetMethodInfoByParameterTypeNames("MakeParentsSettingsMatchMe"); + } + + private static MethodInfo ___ShowTooltip; + private static MethodInfo __ShowTooltip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShowTooltip ??= __type__?.GetMethodInfoByParameterTypeNames("ShowTooltip"); + } + + private static MethodInfo ___MakeModal; + private static MethodInfo __MakeModal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MakeModal ??= __type__?.GetMethodInfoByParameterTypeNames("MakeModal"); + } + + private static MethodInfo ___ShowPopupWithMode; + private static MethodInfo __ShowPopupWithMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShowPopupWithMode ??= __type__?.GetMethodInfoByParameterTypeNames("ShowPopupWithMode", "UnityEditor.ShowMode", "System.Boolean"); + } + + private static MethodInfo ___ShowWithMode; + private static MethodInfo __ShowWithMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShowWithMode ??= __type__?.GetMethodInfoByParameterTypeNames("ShowWithMode", "UnityEditor.ShowMode"); + } + + private static MethodInfo ___ShowAsDropDown; + private static MethodInfo __ShowAsDropDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShowAsDropDown ??= __type__?.GetMethodInfoByParameterTypeNames("ShowAsDropDown", "UnityEngine.Rect", "UnityEngine.Vector2", "UnityEditor.PopupLocation[]"); + } + + private static MethodInfo ___ShowAsDropDown__2; + private static MethodInfo __ShowAsDropDown__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShowAsDropDown__2 ??= __type__?.GetMethodInfoByParameterTypeNames("ShowAsDropDown", "UnityEngine.Rect", "UnityEngine.Vector2", "UnityEditor.PopupLocation[]", "UnityEditor.ShowMode"); + } + + private static MethodInfo ___ShowAsDropDown__3; + private static MethodInfo __ShowAsDropDown__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShowAsDropDown__3 ??= __type__?.GetMethodInfoByParameterTypeNames("ShowAsDropDown", "UnityEngine.Rect", "UnityEngine.Vector2", "UnityEditor.PopupLocation[]", "UnityEditor.ShowMode", "System.Boolean"); + } + + private static MethodInfo ___ShowAsDropDownFitToScreen; + private static MethodInfo __ShowAsDropDownFitToScreen + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShowAsDropDownFitToScreen ??= __type__?.GetMethodInfoByParameterTypeNames("ShowAsDropDownFitToScreen", "UnityEngine.Rect", "UnityEngine.Vector2", "UnityEditor.PopupLocation[]"); + } + + private static MethodInfo ___GetWindowPrivate; + private static MethodInfo __GetWindowPrivate + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetWindowPrivate ??= __type__?.GetMethodInfoByParameterTypeNames("GetWindowPrivate", "System.Type", "System.Boolean", "System.String", "System.Boolean"); + } + + private static MethodInfo ___RemoveFromDockArea; + private static MethodInfo __RemoveFromDockArea + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RemoveFromDockArea ??= __type__?.GetMethodInfoByParameterTypeNames("RemoveFromDockArea"); + } + + private static MethodInfo ___GetWindowWithRectPrivate; + private static MethodInfo __GetWindowWithRectPrivate + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetWindowWithRectPrivate ??= __type__?.GetMethodInfoByParameterTypeNames("GetWindowWithRectPrivate", "System.Type", "UnityEngine.Rect", "System.Boolean", "System.String"); + } + + private static MethodInfo ___GetWindowDontShow; + private static MethodInfo __GetWindowDontShow + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetWindowDontShow ??= __type__?.GetMethodInfoByParameterTypeNames("GetWindowDontShow"); + } + + private static MethodInfo ___RepaintImmediately; + private static MethodInfo __RepaintImmediately + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RepaintImmediately ??= __type__?.GetMethodInfoByParameterTypeNames("RepaintImmediately"); + } + + private static MethodInfo ___SetParentGameViewDimensions; + private static MethodInfo __SetParentGameViewDimensions + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetParentGameViewDimensions ??= __type__?.GetMethodInfoByParameterTypeNames("SetParentGameViewDimensions", "UnityEngine.Rect", "UnityEngine.Rect", "UnityEngine.Vector2"); + } + + private static MethodInfo ___SetPlayModeViewSize; + private static MethodInfo __SetPlayModeViewSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetPlayModeViewSize ??= __type__?.GetMethodInfoByParameterTypeNames("SetPlayModeViewSize", "UnityEngine.Vector2"); + } + + private static MethodInfo ___SetMainPlayModeViewSize; + private static MethodInfo __SetMainPlayModeViewSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetMainPlayModeViewSize ??= __type__?.GetMethodInfoByParameterTypeNames("SetMainPlayModeViewSize", "UnityEngine.Vector2"); + } + + private static MethodInfo ___SetDisplayViewSize; + private static MethodInfo __SetDisplayViewSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetDisplayViewSize ??= __type__?.GetMethodInfoByParameterTypeNames("SetDisplayViewSize", "System.Int32", "UnityEngine.Vector2"); + } + + private static MethodInfo ___GetDisplayViewSize; + private static MethodInfo __GetDisplayViewSize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetDisplayViewSize ??= __type__?.GetMethodInfoByParameterTypeNames("GetDisplayViewSize", "System.Int32"); + } + + private static MethodInfo ___SetPlayModeView; + private static MethodInfo __SetPlayModeView + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetPlayModeView ??= __type__?.GetMethodInfoByParameterTypeNames("SetPlayModeView", "System.Boolean"); + } + + private static MethodInfo _____internalAwake; + private static MethodInfo ____internalAwake + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _____internalAwake ??= __type__?.GetMethodInfoByParameterTypeNames("__internalAwake"); + } + + private static MethodInfo ___Initialize; + private static MethodInfo __Initialize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Initialize ??= __type__?.GetMethodInfoByParameterTypeNames("Initialize"); + } + + private static MethodInfo ___OnDisableINTERNAL; + private static MethodInfo __OnDisableINTERNAL + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnDisableINTERNAL ??= __type__?.GetMethodInfoByParameterTypeNames("OnDisableINTERNAL"); + } + + private static MethodInfo ___CreateNewWindowForEditorWindow; + private static MethodInfo __CreateNewWindowForEditorWindow + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CreateNewWindowForEditorWindow ??= __type__?.GetMethodInfoByParameterTypeNames("CreateNewWindowForEditorWindow", "UnityEditor.EditorWindow", "System.Boolean", "System.Boolean", "System.Boolean"); + } + + private static MethodInfo ___AddSceneTab; + private static MethodInfo __AddSceneTab + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AddSceneTab ??= __type__?.GetMethodInfoByParameterTypeNames("AddSceneTab"); + } + + private static MethodInfo ___AddGameTab; + private static MethodInfo __AddGameTab + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AddGameTab ??= __type__?.GetMethodInfoByParameterTypeNames("AddGameTab"); + } + + private static MethodInfo ___UpdateWindowMenuListing; + private static MethodInfo __UpdateWindowMenuListing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UpdateWindowMenuListing ??= __type__?.GetMethodInfoByParameterTypeNames("UpdateWindowMenuListing"); + } + + private static MethodInfo ___BuildWindowMenuListing; + private static MethodInfo __BuildWindowMenuListing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BuildWindowMenuListing ??= __type__?.GetMethodInfoByParameterTypeNames("BuildWindowMenuListing"); + } + + private static MethodInfo ___CreateRoot; + private static MethodInfo __CreateRoot + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CreateRoot ??= __type__?.GetMethodInfoByParameterTypeNames("CreateRoot"); + } + + private static MethodInfo ___ToggleAllOverlays; + private static MethodInfo __ToggleAllOverlays + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ToggleAllOverlays ??= __type__?.GetMethodInfoByParameterTypeNames("ToggleAllOverlays", "UnityEditor.ShortcutManagement.ShortcutArguments"); + } + + private static MethodInfo ___HideOverlay; + private static MethodInfo __HideOverlay + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HideOverlay ??= __type__?.GetMethodInfoByParameterTypeNames("HideOverlay", "UnityEditor.ShortcutManagement.ShortcutArguments"); + } + + private static MethodInfo ___ShowOverlayMenu; + private static MethodInfo __ShowOverlayMenu + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShowOverlayMenu ??= __type__?.GetMethodInfoByParameterTypeNames("ShowOverlayMenu", "UnityEditor.ShortcutManagement.ShortcutArguments"); + } + + private static MethodInfo ___OnBackingScaleFactorChangedInternal; + private static MethodInfo __OnBackingScaleFactorChangedInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnBackingScaleFactorChangedInternal ??= __type__?.GetMethodInfoByParameterTypeNames("OnBackingScaleFactorChangedInternal"); + } + + private static MethodInfo ___OnBackingScaleFactorChanged; + private static MethodInfo __OnBackingScaleFactorChanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnBackingScaleFactorChanged ??= __type__?.GetMethodInfoByParameterTypeNames("OnBackingScaleFactorChanged"); + } + } + public static class UnityEditor_EditorWindow_Extension + { + public static UnityEditor_EditorWindow ReflectionHelper(this UnityEditor.EditorWindow self) => new(self); + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorWindow.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorWindow.cs.meta new file mode 100644 index 0000000..db49724 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EditorWindow.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e7c0bd4261367a947ad195fb8332c090 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EventManipulationHandler.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EventManipulationHandler.cs new file mode 100644 index 0000000..4fc6708 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EventManipulationHandler.cs @@ -0,0 +1,401 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_EventManipulationHandler + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.EventManipulationHandler"); + + + public UnityEngine.Rect[] m_EventRects + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Rect[])(__m_EventRects?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_EventRects?.SetValue(__self__, value); + } + + public static UnityEngine.AnimationEvent[] m_EventsAtMouseDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.AnimationEvent[])(__m_EventsAtMouseDown?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_EventsAtMouseDown?.SetValue(null, value); + } + + public static float[] m_EventTimes + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float[])(__m_EventTimes?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_EventTimes?.SetValue(null, value); + } + + public int m_HoverEvent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__m_HoverEvent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_HoverEvent?.SetValue(__self__, value); + } + + public string m_InstantTooltipText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__m_InstantTooltipText?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_InstantTooltipText?.SetValue(__self__, value); + } + + public UnityEngine.Vector2 m_InstantTooltipPoint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Vector2)(__m_InstantTooltipPoint?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_InstantTooltipPoint?.SetValue(__self__, value); + } + + public bool[] m_EventsSelected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool[])(__m_EventsSelected?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_EventsSelected?.SetValue(__self__, value); + } + + public Array m_Events + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (Array)(__m_Events?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Events?.SetValue(__self__, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public UnityEditor_AnimationWindowEvent m_Events__GetItem(int i) => new UnityEditor_AnimationWindowEvent(m_Events?.GetValue(i)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void m_Events__SetItem(int i, UnityEditor_AnimationWindowEvent value) => m_Events?.SetValue(value.__self__, i); + + public object m_Timeline + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_Timeline?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Timeline?.SetValue(__self__, value); + } + + public void SelectEvent(UnityEngine.AnimationEvent[] events, int index, UnityEditor_AnimationClipInfoProperties clipInfo) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = events; + __params__[1] = index; + __params__[2] = clipInfo.__self__; + __SelectEvent?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public bool HandleEventManipulation(UnityEngine.Rect rect, ref UnityEngine.AnimationEvent[] events, UnityEditor_AnimationClipInfoProperties clipInfo, float currentTime) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = events; + __params__[2] = clipInfo.__self__; + __params__[3] = currentTime; + var __result__ = __HandleEventManipulation?.Invoke(__self__, __params__); + events = (UnityEngine.AnimationEvent[])(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public void CreateContextMenu(UnityEditor_AnimationClipInfoProperties info, float time, int eventIndex, bool[] selectedEvents) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = info.__self__; + __params__[1] = time; + __params__[2] = eventIndex; + __params__[3] = selectedEvents; + __CreateContextMenu?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void EventLineContextMenuAdd(object obj) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = obj; + __EventLineContextMenuAdd?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void EventLineContextMenuDelete(object obj) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = obj; + __EventLineContextMenuDelete?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public static void EventLineContextMenuCopy(object obj) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = obj; + __EventLineContextMenuCopy?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public void EventLineContextMenuPaste(object obj) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = obj; + __EventLineContextMenuPaste?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void CheckRectsOnMouseMove(UnityEngine.Rect eventLineRect, UnityEngine.AnimationEvent[] events, UnityEngine.Rect[] hitRects) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = eventLineRect; + __params__[1] = events; + __params__[2] = hitRects; + __CheckRectsOnMouseMove?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void Draw(UnityEngine.Rect window) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = window; + __Draw?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public bool DeleteEvents(ref UnityEngine.AnimationEvent[] eventList, bool[] deleteIndices) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = eventList; + __params__[1] = deleteIndices; + var __result__ = __DeleteEvents?.Invoke(__self__, __params__); + eventList = (UnityEngine.AnimationEvent[])(__params__[0]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool PasteEvents(ref UnityEngine.AnimationEvent[] eventList, ref bool[] selected, float time) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = eventList; + __params__[1] = selected; + __params__[2] = time; + var __result__ = __PasteEvents?.Invoke(null, __params__); + eventList = (UnityEngine.AnimationEvent[])(__params__[0]); + selected = (bool[])(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public void EditEvents(UnityEditor_AnimationClipInfoProperties clipInfo, bool[] selectedIndices) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = clipInfo.__self__; + __params__[1] = selectedIndices; + __EditEvents?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void UpdateEvents(UnityEditor_AnimationClipInfoProperties clipInfo) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = clipInfo.__self__; + __UpdateEvents?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public UnityEditor_EventManipulationHandler(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + + private static FieldInfo ___m_EventRects; + private static FieldInfo __m_EventRects + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_EventRects ??= __type__?.GetField("m_EventRects", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_EventsAtMouseDown; + private static FieldInfo __m_EventsAtMouseDown + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_EventsAtMouseDown ??= __type__?.GetField("m_EventsAtMouseDown", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_EventTimes; + private static FieldInfo __m_EventTimes + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_EventTimes ??= __type__?.GetField("m_EventTimes", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_HoverEvent; + private static FieldInfo __m_HoverEvent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_HoverEvent ??= __type__?.GetField("m_HoverEvent", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_InstantTooltipText; + private static FieldInfo __m_InstantTooltipText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_InstantTooltipText ??= __type__?.GetField("m_InstantTooltipText", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_InstantTooltipPoint; + private static FieldInfo __m_InstantTooltipPoint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_InstantTooltipPoint ??= __type__?.GetField("m_InstantTooltipPoint", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_EventsSelected; + private static FieldInfo __m_EventsSelected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_EventsSelected ??= __type__?.GetField("m_EventsSelected", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Events; + private static FieldInfo __m_Events + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Events ??= __type__?.GetField("m_Events", (BindingFlags)(-1)); + } + + private static Type ___E__m_Events; + public static Type __E__m_Events + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___E__m_Events ??= EditorUtils.GetTypeByFullName("UnityEditor.AnimationWindowEvent"); + } + + private static FieldInfo ___m_Timeline; + private static FieldInfo __m_Timeline + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Timeline ??= __type__?.GetField("m_Timeline", (BindingFlags)(-1)); + } + + private static MethodInfo ___SelectEvent; + private static MethodInfo __SelectEvent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SelectEvent ??= __type__?.GetMethodInfoByParameterTypeNames("SelectEvent", "UnityEngine.AnimationEvent[]", "System.Int32", "UnityEditor.AnimationClipInfoProperties"); + } + + private static MethodInfo ___HandleEventManipulation; + private static MethodInfo __HandleEventManipulation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HandleEventManipulation ??= __type__?.GetMethodInfoByParameterTypeNames("HandleEventManipulation", "UnityEngine.Rect", "UnityEngine.AnimationEvent[]&", "UnityEditor.AnimationClipInfoProperties", "System.Single"); + } + + private static MethodInfo ___CreateContextMenu; + private static MethodInfo __CreateContextMenu + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CreateContextMenu ??= __type__?.GetMethodInfoByParameterTypeNames("CreateContextMenu", "UnityEditor.AnimationClipInfoProperties", "System.Single", "System.Int32", "System.Boolean[]"); + } + + private static MethodInfo ___EventLineContextMenuAdd; + private static MethodInfo __EventLineContextMenuAdd + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EventLineContextMenuAdd ??= __type__?.GetMethodInfoByParameterTypeNames("EventLineContextMenuAdd", "System.Object"); + } + + private static MethodInfo ___EventLineContextMenuDelete; + private static MethodInfo __EventLineContextMenuDelete + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EventLineContextMenuDelete ??= __type__?.GetMethodInfoByParameterTypeNames("EventLineContextMenuDelete", "System.Object"); + } + + private static MethodInfo ___EventLineContextMenuCopy; + private static MethodInfo __EventLineContextMenuCopy + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EventLineContextMenuCopy ??= __type__?.GetMethodInfoByParameterTypeNames("EventLineContextMenuCopy", "System.Object"); + } + + private static MethodInfo ___EventLineContextMenuPaste; + private static MethodInfo __EventLineContextMenuPaste + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EventLineContextMenuPaste ??= __type__?.GetMethodInfoByParameterTypeNames("EventLineContextMenuPaste", "System.Object"); + } + + private static MethodInfo ___CheckRectsOnMouseMove; + private static MethodInfo __CheckRectsOnMouseMove + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CheckRectsOnMouseMove ??= __type__?.GetMethodInfoByParameterTypeNames("CheckRectsOnMouseMove", "UnityEngine.Rect", "UnityEngine.AnimationEvent[]", "UnityEngine.Rect[]"); + } + + private static MethodInfo ___Draw; + private static MethodInfo __Draw + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Draw ??= __type__?.GetMethodInfoByParameterTypeNames("Draw", "UnityEngine.Rect"); + } + + private static MethodInfo ___DeleteEvents; + private static MethodInfo __DeleteEvents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DeleteEvents ??= __type__?.GetMethodInfoByParameterTypeNames("DeleteEvents", "UnityEngine.AnimationEvent[]&", "System.Boolean[]"); + } + + private static MethodInfo ___PasteEvents; + private static MethodInfo __PasteEvents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PasteEvents ??= __type__?.GetMethodInfoByParameterTypeNames("PasteEvents", "UnityEngine.AnimationEvent[]&", "System.Boolean[]&", "System.Single"); + } + + private static MethodInfo ___EditEvents; + private static MethodInfo __EditEvents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EditEvents ??= __type__?.GetMethodInfoByParameterTypeNames("EditEvents", "UnityEditor.AnimationClipInfoProperties", "System.Boolean[]"); + } + + private static MethodInfo ___UpdateEvents; + private static MethodInfo __UpdateEvents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UpdateEvents ??= __type__?.GetMethodInfoByParameterTypeNames("UpdateEvents", "UnityEditor.AnimationClipInfoProperties"); + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EventManipulationHandler.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EventManipulationHandler.cs.meta new file mode 100644 index 0000000..073e2e9 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_EventManipulationHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fb686b9af69c31544b58a9bc63b68dac +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_GUISlideGroup.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_GUISlideGroup.cs new file mode 100644 index 0000000..1d36bb7 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_GUISlideGroup.cs @@ -0,0 +1,189 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_GUISlideGroup + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.GUISlideGroup"); + + + public static UnityEditor_GUISlideGroup current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_GUISlideGroup(__current?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __current?.SetValue(null, value.__self__); + } + + public System.Collections.Generic.Dictionary animIDs + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Generic.Dictionary)(__animIDs?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __animIDs?.SetValue(__self__, value); + } + + public static float kLerp + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kLerp?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kLerp?.SetValue(null, value); + } + + public static float kSnap + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kSnap?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kSnap?.SetValue(null, value); + } + + public void Begin() + { + __Begin?.Invoke(__self__, System.Array.Empty()); + } + + public void End() + { + __End?.Invoke(__self__, System.Array.Empty()); + } + + public void Reset() + { + __Reset?.Invoke(__self__, System.Array.Empty()); + } + + public UnityEngine.Rect BeginHorizontal(int id, UnityEngine.GUILayoutOption[] options) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = id; + __params__[1] = options; + var __result__ = __BeginHorizontal?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public void EndHorizontal() + { + __EndHorizontal?.Invoke(__self__, System.Array.Empty()); + } + + public UnityEngine.Rect GetRect(int id, UnityEngine.Rect r) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = id; + __params__[1] = r; + var __result__ = __GetRect?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public UnityEngine.Rect GetRect(int id, UnityEngine.Rect r, out bool changed) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = id; + __params__[1] = r; + __params__[2] = null; + var __result__ = __GetRect__2?.Invoke(__self__, __params__); + changed = (bool)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public UnityEditor_GUISlideGroup(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + + private static FieldInfo ___current; + private static FieldInfo __current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___current ??= __type__?.GetField("current", (BindingFlags)(-1)); + } + + private static FieldInfo ___animIDs; + private static FieldInfo __animIDs + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___animIDs ??= __type__?.GetField("animIDs", (BindingFlags)(-1)); + } + + private static FieldInfo ___kLerp; + private static FieldInfo __kLerp + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kLerp ??= __type__?.GetField("kLerp", (BindingFlags)(-1)); + } + + private static FieldInfo ___kSnap; + private static FieldInfo __kSnap + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kSnap ??= __type__?.GetField("kSnap", (BindingFlags)(-1)); + } + + private static MethodInfo ___Begin; + private static MethodInfo __Begin + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Begin ??= __type__?.GetMethodInfoByParameterTypeNames("Begin"); + } + + private static MethodInfo ___End; + private static MethodInfo __End + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___End ??= __type__?.GetMethodInfoByParameterTypeNames("End"); + } + + private static MethodInfo ___Reset; + private static MethodInfo __Reset + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Reset ??= __type__?.GetMethodInfoByParameterTypeNames("Reset"); + } + + private static MethodInfo ___BeginHorizontal; + private static MethodInfo __BeginHorizontal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginHorizontal ??= __type__?.GetMethodInfoByParameterTypeNames("BeginHorizontal", "System.Int32", "UnityEngine.GUILayoutOption[]"); + } + + private static MethodInfo ___EndHorizontal; + private static MethodInfo __EndHorizontal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EndHorizontal ??= __type__?.GetMethodInfoByParameterTypeNames("EndHorizontal"); + } + + private static MethodInfo ___GetRect; + private static MethodInfo __GetRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetRect ??= __type__?.GetMethodInfoByParameterTypeNames("GetRect", "System.Int32", "UnityEngine.Rect"); + } + + private static MethodInfo ___GetRect__2; + private static MethodInfo __GetRect__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetRect__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GetRect", "System.Int32", "UnityEngine.Rect", "System.Boolean&"); + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_GUISlideGroup.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_GUISlideGroup.cs.meta new file mode 100644 index 0000000..b6637f9 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_GUISlideGroup.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7abdc056e9a00a049b74a1a7bf80748a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_LogEntries.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_LogEntries.cs new file mode 100644 index 0000000..343f79c --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_LogEntries.cs @@ -0,0 +1,336 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_LogEntries + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.LogEntries"); + + + public static int consoleFlags + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__consoleFlags?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __consoleFlags?.SetValue(null, value); + } + + public static void RowGotDoubleClicked(int index) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = index; + __RowGotDoubleClicked?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void OpenFileOnSpecificLineAndColumn(string filePath, int line, int column) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = filePath; + __params__[1] = line; + __params__[2] = column; + __OpenFileOnSpecificLineAndColumn?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static string GetStatusText() + { + var __result__ = __GetStatusText?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (string)(__result__) : default; + } + + public static int GetStatusMask() + { + var __result__ = __GetStatusMask?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public static int StartGettingEntries() + { + var __result__ = __StartGettingEntries?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public static void SetConsoleFlag(int bit, bool value) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = bit; + __params__[1] = value; + __SetConsoleFlag?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void SetFilteringText(string filteringText) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = filteringText; + __SetFilteringText?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static string GetFilteringText() + { + var __result__ = __GetFilteringText?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (string)(__result__) : default; + } + + public static void EndGettingEntries() + { + __EndGettingEntries?.Invoke(null, System.Array.Empty()); + } + + public static int GetCount() + { + var __result__ = __GetCount?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public static void GetCountsByType(ref int errorCount, ref int warningCount, ref int logCount) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = errorCount; + __params__[1] = warningCount; + __params__[2] = logCount; + __GetCountsByType?.Invoke(null, __params__); + errorCount = (int)(__params__[0]); + warningCount = (int)(__params__[1]); + logCount = (int)(__params__[2]); + __pool__.Return(__params__); + } + + public static void GetLinesAndModeFromEntryInternal(int row, int numberOfLines, ref int mask, out string outString) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = row; + __params__[1] = numberOfLines; + __params__[2] = mask; + __params__[3] = Activator.CreateInstance(typeof(string)); + __GetLinesAndModeFromEntryInternal?.Invoke(null, __params__); + mask = (int)(__params__[2]); + outString = (string)(__params__[3]); + __pool__.Return(__params__); + } + + public static bool GetEntryInternal(int row, out UnityEditor_LogEntry outputEntry) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = row; + __params__[1] = Activator.CreateInstance(UnityEditor_LogEntry.__type__); + var __result__ = __GetEntryInternal?.Invoke(null, __params__); + outputEntry = new UnityEditor_LogEntry(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static int GetEntryCount(int row) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = row; + var __result__ = __GetEntryCount?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static void Clear() + { + __Clear?.Invoke(null, System.Array.Empty()); + } + + public static int GetStatusViewErrorIndex() + { + var __result__ = __GetStatusViewErrorIndex?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public static void ClickStatusBar(int count) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = count; + __ClickStatusBar?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void AddMessageWithDoubleClickCallback(UnityEditor_LogEntry outputEntry) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = outputEntry.__self__; + __AddMessageWithDoubleClickCallback?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static int GetEntryRowIndex(int globalIndex) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = globalIndex; + var __result__ = __GetEntryRowIndex?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public UnityEditor_LogEntries(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + + private static PropertyInfo ___consoleFlags; + private static PropertyInfo __consoleFlags + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___consoleFlags ??= __type__?.GetProperty("consoleFlags", (BindingFlags)(-1)); + } + + private static MethodInfo ___RowGotDoubleClicked; + private static MethodInfo __RowGotDoubleClicked + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RowGotDoubleClicked ??= __type__?.GetMethodInfoByParameterTypeNames("RowGotDoubleClicked", "System.Int32"); + } + + private static MethodInfo ___OpenFileOnSpecificLineAndColumn; + private static MethodInfo __OpenFileOnSpecificLineAndColumn + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OpenFileOnSpecificLineAndColumn ??= __type__?.GetMethodInfoByParameterTypeNames("OpenFileOnSpecificLineAndColumn", "System.String", "System.Int32", "System.Int32"); + } + + private static MethodInfo ___GetStatusText; + private static MethodInfo __GetStatusText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetStatusText ??= __type__?.GetMethodInfoByParameterTypeNames("GetStatusText"); + } + + private static MethodInfo ___GetStatusMask; + private static MethodInfo __GetStatusMask + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetStatusMask ??= __type__?.GetMethodInfoByParameterTypeNames("GetStatusMask"); + } + + private static MethodInfo ___StartGettingEntries; + private static MethodInfo __StartGettingEntries + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___StartGettingEntries ??= __type__?.GetMethodInfoByParameterTypeNames("StartGettingEntries"); + } + + private static MethodInfo ___SetConsoleFlag; + private static MethodInfo __SetConsoleFlag + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetConsoleFlag ??= __type__?.GetMethodInfoByParameterTypeNames("SetConsoleFlag", "System.Int32", "System.Boolean"); + } + + private static MethodInfo ___SetFilteringText; + private static MethodInfo __SetFilteringText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetFilteringText ??= __type__?.GetMethodInfoByParameterTypeNames("SetFilteringText", "System.String"); + } + + private static MethodInfo ___GetFilteringText; + private static MethodInfo __GetFilteringText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetFilteringText ??= __type__?.GetMethodInfoByParameterTypeNames("GetFilteringText"); + } + + private static MethodInfo ___EndGettingEntries; + private static MethodInfo __EndGettingEntries + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EndGettingEntries ??= __type__?.GetMethodInfoByParameterTypeNames("EndGettingEntries"); + } + + private static MethodInfo ___GetCount; + private static MethodInfo __GetCount + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetCount ??= __type__?.GetMethodInfoByParameterTypeNames("GetCount"); + } + + private static MethodInfo ___GetCountsByType; + private static MethodInfo __GetCountsByType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetCountsByType ??= __type__?.GetMethodInfoByParameterTypeNames("GetCountsByType", "System.Int32&", "System.Int32&", "System.Int32&"); + } + + private static MethodInfo ___GetLinesAndModeFromEntryInternal; + private static MethodInfo __GetLinesAndModeFromEntryInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetLinesAndModeFromEntryInternal ??= __type__?.GetMethodInfoByParameterTypeNames("GetLinesAndModeFromEntryInternal", "System.Int32", "System.Int32", "System.Int32&", "System.String&"); + } + + private static MethodInfo ___GetEntryInternal; + private static MethodInfo __GetEntryInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetEntryInternal ??= __type__?.GetMethodInfoByParameterTypeNames("GetEntryInternal", "System.Int32", "UnityEditor.LogEntry"); + } + + private static MethodInfo ___GetEntryCount; + private static MethodInfo __GetEntryCount + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetEntryCount ??= __type__?.GetMethodInfoByParameterTypeNames("GetEntryCount", "System.Int32"); + } + + private static MethodInfo ___Clear; + private static MethodInfo __Clear + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Clear ??= __type__?.GetMethodInfoByParameterTypeNames("Clear"); + } + + private static MethodInfo ___GetStatusViewErrorIndex; + private static MethodInfo __GetStatusViewErrorIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetStatusViewErrorIndex ??= __type__?.GetMethodInfoByParameterTypeNames("GetStatusViewErrorIndex"); + } + + private static MethodInfo ___ClickStatusBar; + private static MethodInfo __ClickStatusBar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ClickStatusBar ??= __type__?.GetMethodInfoByParameterTypeNames("ClickStatusBar", "System.Int32"); + } + + private static MethodInfo ___AddMessageWithDoubleClickCallback; + private static MethodInfo __AddMessageWithDoubleClickCallback + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AddMessageWithDoubleClickCallback ??= __type__?.GetMethodInfoByParameterTypeNames("AddMessageWithDoubleClickCallback", "UnityEditor.LogEntry"); + } + + private static MethodInfo ___GetEntryRowIndex; + private static MethodInfo __GetEntryRowIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetEntryRowIndex ??= __type__?.GetMethodInfoByParameterTypeNames("GetEntryRowIndex", "System.Int32"); + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_LogEntries.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_LogEntries.cs.meta new file mode 100644 index 0000000..6f3f269 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_LogEntries.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b0a3abc4a9963934b999319d8f25b529 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_LogEntry.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_LogEntry.cs new file mode 100644 index 0000000..4769e51 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_LogEntry.cs @@ -0,0 +1,191 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_LogEntry + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.LogEntry"); + + + public string message + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__message?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __message?.SetValue(__self__, value); + } + + public string file + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__file?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __file?.SetValue(__self__, value); + } + + public int line + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__line?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __line?.SetValue(__self__, value); + } + + public int column + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__column?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __column?.SetValue(__self__, value); + } + + public int mode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__mode?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __mode?.SetValue(__self__, value); + } + + public int instanceID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__instanceID?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __instanceID?.SetValue(__self__, value); + } + + public int identifier + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__identifier?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __identifier?.SetValue(__self__, value); + } + + public int globalLineIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__globalLineIndex?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __globalLineIndex?.SetValue(__self__, value); + } + + public int callstackTextStartUTF8 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__callstackTextStartUTF8?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __callstackTextStartUTF8?.SetValue(__self__, value); + } + + public int callstackTextStartUTF16 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__callstackTextStartUTF16?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __callstackTextStartUTF16?.SetValue(__self__, value); + } + + public static void RemoveLogEntriesByMode(int mode) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = mode; + __RemoveLogEntriesByMode?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public UnityEditor_LogEntry(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + + private static FieldInfo ___message; + private static FieldInfo __message + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___message ??= __type__?.GetField("message", (BindingFlags)(-1)); + } + + private static FieldInfo ___file; + private static FieldInfo __file + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___file ??= __type__?.GetField("file", (BindingFlags)(-1)); + } + + private static FieldInfo ___line; + private static FieldInfo __line + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___line ??= __type__?.GetField("line", (BindingFlags)(-1)); + } + + private static FieldInfo ___column; + private static FieldInfo __column + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___column ??= __type__?.GetField("column", (BindingFlags)(-1)); + } + + private static FieldInfo ___mode; + private static FieldInfo __mode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___mode ??= __type__?.GetField("mode", (BindingFlags)(-1)); + } + + private static FieldInfo ___instanceID; + private static FieldInfo __instanceID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___instanceID ??= __type__?.GetField("instanceID", (BindingFlags)(-1)); + } + + private static FieldInfo ___identifier; + private static FieldInfo __identifier + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___identifier ??= __type__?.GetField("identifier", (BindingFlags)(-1)); + } + + private static FieldInfo ___globalLineIndex; + private static FieldInfo __globalLineIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___globalLineIndex ??= __type__?.GetField("globalLineIndex", (BindingFlags)(-1)); + } + + private static FieldInfo ___callstackTextStartUTF8; + private static FieldInfo __callstackTextStartUTF8 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___callstackTextStartUTF8 ??= __type__?.GetField("callstackTextStartUTF8", (BindingFlags)(-1)); + } + + private static FieldInfo ___callstackTextStartUTF16; + private static FieldInfo __callstackTextStartUTF16 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___callstackTextStartUTF16 ??= __type__?.GetField("callstackTextStartUTF16", (BindingFlags)(-1)); + } + + private static MethodInfo ___RemoveLogEntriesByMode; + private static MethodInfo __RemoveLogEntriesByMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RemoveLogEntriesByMode ??= __type__?.GetMethodInfoByParameterTypeNames("RemoveLogEntriesByMode", "System.Int32"); + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_LogEntry.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_LogEntry.cs.meta new file mode 100644 index 0000000..9af5fc3 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_LogEntry.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 35947bfe550e2b7438d293897d535227 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_MaterialEditor.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_MaterialEditor.cs new file mode 100644 index 0000000..132de80 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_MaterialEditor.cs @@ -0,0 +1,1677 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_MaterialEditor + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.MaterialEditor"); + + public delegate void MaterialPropertyCallbackFunction(UnityEditor.GenericMenu menu, UnityEditor.MaterialProperty property, UnityEngine.Renderer[] renderers); + + public UnityEngine.Renderer rendererForAnimationMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Renderer)(__rendererForAnimationMode?.GetValue(__self__)); + } + + public bool isPrefabAsset + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__isPrefabAsset?.GetValue(__self__)); + } + + public static System.Collections.Generic.List s_MaterialEditors + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Generic.List)(__s_MaterialEditors?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_MaterialEditors?.SetValue(null, value); + } + + public bool m_CheckSetup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_CheckSetup?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_CheckSetup?.SetValue(__self__, value); + } + + public static int s_ControlHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_ControlHash?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ControlHash?.SetValue(null, value); + } + + public static float kSpacingUnderTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kSpacingUnderTexture?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kSpacingUnderTexture?.SetValue(null, value); + } + + public static float kMiniWarningMessageHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kMiniWarningMessageHeight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kMiniWarningMessageHeight?.SetValue(null, value); + } + + public UnityEngine.MaterialPropertyBlock m_PropertyBlock + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.MaterialPropertyBlock)(__m_PropertyBlock?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_PropertyBlock?.SetValue(__self__, value); + } + + public UnityEngine.Shader m_Shader + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Shader)(__m_Shader?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Shader?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_EnableInstancing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_EnableInstancing?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_EnableInstancing?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_DoubleSidedGI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_DoubleSidedGI?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_DoubleSidedGI?.SetValue(__self__, value); + } + + public string m_InfoMessage + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__m_InfoMessage?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_InfoMessage?.SetValue(__self__, value); + } + + public UnityEngine.Vector2 m_PreviewDir + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Vector2)(__m_PreviewDir?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_PreviewDir?.SetValue(__self__, value); + } + + public int m_SelectedMesh + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__m_SelectedMesh?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SelectedMesh?.SetValue(__self__, value); + } + + public int m_TimeUpdate + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__m_TimeUpdate?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TimeUpdate?.SetValue(__self__, value); + } + + public int m_LightMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__m_LightMode?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LightMode?.SetValue(__self__, value); + } + + public static UnityEngine.GUIContent s_TilingText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_TilingText?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_TilingText?.SetValue(null, value); + } + + public static UnityEngine.GUIContent s_OffsetText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__s_OffsetText?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_OffsetText?.SetValue(null, value); + } + + public static string kDefaultMaterialPreviewMesh + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__kDefaultMaterialPreviewMesh?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kDefaultMaterialPreviewMesh?.SetValue(null, value); + } + + public UnityEditor.ShaderGUI m_CustomShaderGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.ShaderGUI)(__m_CustomShaderGUI?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_CustomShaderGUI?.SetValue(__self__, value); + } + + public string m_CustomEditorClassName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__m_CustomEditorClassName?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_CustomEditorClassName?.SetValue(__self__, value); + } + + public bool m_InsidePropertiesGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_InsidePropertiesGUI?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_InsidePropertiesGUI?.SetValue(__self__, value); + } + + public UnityEngine.Renderer[] m_RenderersForAnimationMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Renderer[])(__m_RenderersForAnimationMode?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_RenderersForAnimationMode?.SetValue(__self__, value); + } + + public UnityEngine.Component m_MeshRendererComp + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Component)(__m_MeshRendererComp?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MeshRendererComp?.SetValue(__self__, value); + } + + public static object s_AnimatedCheckStack + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__s_AnimatedCheckStack?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_AnimatedCheckStack?.SetValue(null, value); + } + + public static MaterialPropertyCallbackFunction contextualPropertyMenu + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (__contextualPropertyMenu?.GetValue(null) as Delegate)?.Cast(); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __contextualPropertyMenu?.SetValue(null, value?.Cast(__contextualPropertyMenu.FieldType)); + } + + public object m_ReflectionProbePicker + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_ReflectionProbePicker?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ReflectionProbePicker?.SetValue(__self__, value); + } + + public UnityEngine.Rendering.TextureDimension m_DesiredTexdim + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Rendering.TextureDimension)(__m_DesiredTexdim?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_DesiredTexdim?.SetValue(__self__, value); + } + + public static UnityEngine.Mesh[] s_Meshes + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Mesh[])(__s_Meshes?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_Meshes?.SetValue(null, value); + } + + public static UnityEngine.Mesh s_PlaneMesh + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Mesh)(__s_PlaneMesh?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_PlaneMesh?.SetValue(null, value); + } + + public static UnityEngine.GUIContent[] s_MeshIcons + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent[])(__s_MeshIcons?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_MeshIcons?.SetValue(null, value); + } + + public static UnityEngine.GUIContent[] s_LightIcons + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent[])(__s_LightIcons?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LightIcons?.SetValue(null, value); + } + + public static UnityEngine.GUIContent[] s_TimeIcons + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent[])(__s_TimeIcons?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_TimeIcons?.SetValue(null, value); + } + + public static UnityEditor.PreviewRenderUtility s_PreviewRenderUtility + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.PreviewRenderUtility)(__s_PreviewRenderUtility?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_PreviewRenderUtility?.SetValue(null, value); + } + + public static int s_NumberOfEditors + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_NumberOfEditors?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_NumberOfEditors?.SetValue(null, value); + } + + public UnityEngine.Material s_OriginalMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Material)(__s_OriginalMaterial?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_OriginalMaterial?.SetValue(__self__, value); + } + + public static UnityEngine.Renderer s_previousDraggedUponRenderer + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Renderer)(__s_previousDraggedUponRenderer?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_previousDraggedUponRenderer?.SetValue(null, value); + } + + public static UnityEngine.Material[] s_previousMaterialValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Material[])(__s_previousMaterialValue?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_previousMaterialValue?.SetValue(null, value); + } + + public static bool s_previousAlreadyHadPrefabModification + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__s_previousAlreadyHadPrefabModification?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_previousAlreadyHadPrefabModification?.SetValue(null, value); + } + + public static float kSpaceBetweenFlexibleAreaAndField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kSpaceBetweenFlexibleAreaAndField?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kSpaceBetweenFlexibleAreaAndField?.SetValue(null, value); + } + + public static float kQueuePopupWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kQueuePopupWidth?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kQueuePopupWidth?.SetValue(null, value); + } + + public static float kCustomQueuePopupWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kCustomQueuePopupWidth?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kCustomQueuePopupWidth?.SetValue(null, value); + } + + public static object GetPreviewType(UnityEngine.Material mat) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = mat; + var __result__ = __GetPreviewType?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (object)(__result__) : default; + } + + public static bool DoesPreviewAllowRotation(object type) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = type; + var __result__ = __DoesPreviewAllowRotation?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public bool ShouldEditorBeHidden() + { + var __result__ = __ShouldEditorBeHidden?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void UpdateAllOpenMaterialEditors() + { + __UpdateAllOpenMaterialEditors?.Invoke(__self__, System.Array.Empty()); + } + + public void OnSelectedShaderPopup(object shaderNameObj) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = shaderNameObj; + __OnSelectedShaderPopup?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public bool HasMultipleMixedShaderValues() + { + var __result__ = __HasMultipleMixedShaderValues?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void ShaderPopup(UnityEngine.GUIStyle style) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = style; + __ShaderPopup?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void DetectShaderEditorNeedsUpdate() + { + __DetectShaderEditorNeedsUpdate?.Invoke(__self__, System.Array.Empty()); + } + + public string ParseValidationResult(object validationResult) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = validationResult; + var __result__ = __ParseValidationResult?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public void DetectTextureStackValidationIssues() + { + __DetectTextureStackValidationIssues?.Invoke(__self__, System.Array.Empty()); + } + + public void CheckSetup() + { + __CheckSetup?.Invoke(__self__, System.Array.Empty()); + } + + public void OnAssetStoreInspectorGUI() + { + __OnAssetStoreInspectorGUI?.Invoke(__self__, System.Array.Empty()); + } + + public void OnShaderChanged() + { + __OnShaderChanged?.Invoke(__self__, System.Array.Empty()); + } + + public void OnHeaderGUI() + { + __OnHeaderGUI?.Invoke(__self__, System.Array.Empty()); + } + + public void OnHeaderControlsGUI() + { + __OnHeaderControlsGUI?.Invoke(__self__, System.Array.Empty()); + } + + public float RangePropertyInternal(UnityEditor.MaterialProperty prop, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = prop; + __params__[1] = label; + var __result__ = __RangePropertyInternal?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float RangePropertyInternal(UnityEngine.Rect position, UnityEditor.MaterialProperty prop, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = prop; + __params__[2] = label; + var __result__ = __RangePropertyInternal__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float DoPowerRangeProperty(UnityEngine.Rect position, UnityEditor.MaterialProperty prop, UnityEngine.GUIContent label, float power) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = prop; + __params__[2] = label; + __params__[3] = power; + var __result__ = __DoPowerRangeProperty?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static int DoIntRangeProperty(UnityEngine.Rect position, UnityEditor.MaterialProperty prop, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = prop; + __params__[2] = label; + var __result__ = __DoIntRangeProperty?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public int IntegerPropertyInternal(UnityEditor.MaterialProperty prop, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = prop; + __params__[1] = label; + var __result__ = __IntegerPropertyInternal?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public int IntegerPropertyInternal(UnityEngine.Rect position, UnityEditor.MaterialProperty prop, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = prop; + __params__[2] = label; + var __result__ = __IntegerPropertyInternal__2?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public float FloatPropertyInternal(UnityEditor.MaterialProperty prop, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = prop; + __params__[1] = label; + var __result__ = __FloatPropertyInternal?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static float FloatPropertyInternal(UnityEngine.Rect position, UnityEditor.MaterialProperty prop, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = prop; + __params__[2] = label; + var __result__ = __FloatPropertyInternal__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public UnityEngine.Color ColorPropertyInternal(UnityEditor.MaterialProperty prop, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = prop; + __params__[1] = label; + var __result__ = __ColorPropertyInternal?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Color)(__result__) : default; + } + + public static UnityEngine.Color ColorPropertyInternal(UnityEngine.Rect position, UnityEditor.MaterialProperty prop, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = prop; + __params__[2] = label; + var __result__ = __ColorPropertyInternal__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Color)(__result__) : default; + } + + public static UnityEngine.Vector4 VectorPropertyInternal(in UnityEngine.Rect position, in UnityEditor.MaterialProperty prop, in UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = prop; + __params__[2] = label; + var __result__ = __VectorPropertyInternal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector4)(__result__) : default; + } + + public UnityEngine.Texture TexturePropertyBody(UnityEngine.Rect position, UnityEditor.MaterialProperty prop) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = prop; + var __result__ = __TexturePropertyBody?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Texture)(__result__) : default; + } + + public static UnityEngine.Vector4 TextureScaleOffsetProperty(UnityEngine.Rect position, UnityEngine.Vector4 scaleOffset, int mixedValueMask, bool partOfTexturePropertyControl) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = scaleOffset; + __params__[2] = mixedValueMask; + __params__[3] = partOfTexturePropertyControl; + var __result__ = __TextureScaleOffsetProperty?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector4)(__result__) : default; + } + + public static float GetTextureFieldHeight() + { + var __result__ = __GetTextureFieldHeight?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (float)(__result__) : default; + } + + public UnityEngine.Rect GetPropertyRect(UnityEditor.MaterialProperty prop, UnityEngine.GUIContent label, bool ignoreDrawer) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = prop; + __params__[1] = label; + __params__[2] = ignoreDrawer; + var __result__ = __GetPropertyRect?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public UnityEngine.Rect GetPropertyRect(UnityEditor.MaterialProperty prop, string label, bool ignoreDrawer) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = prop; + __params__[1] = label; + __params__[2] = ignoreDrawer; + var __result__ = __GetPropertyRect__2?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public void DoPropertyContextMenu(UnityEditor.MaterialProperty prop) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = prop; + __DoPropertyContextMenu?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.MaterialGlobalIlluminationFlags GetGlobalIlluminationFlags(UnityEngine.MaterialGlobalIlluminationFlags flags) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = flags; + var __result__ = __GetGlobalIlluminationFlags?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.MaterialGlobalIlluminationFlags)(__result__) : default; + } + + public void ShaderPropertyInternal(UnityEngine.Rect position, UnityEditor.MaterialProperty prop, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = prop; + __params__[2] = label; + __ShaderPropertyInternal?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void DefaultShaderPropertyInternal(UnityEditor.MaterialProperty prop, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = prop; + __params__[1] = label; + __DefaultShaderPropertyInternal?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void DefaultShaderPropertyInternal(UnityEngine.Rect position, UnityEditor.MaterialProperty prop, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __params__[1] = prop; + __params__[2] = label; + __DefaultShaderPropertyInternal__2?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public static UnityEngine.Renderer[] GetAssociatedRenderersFromInspector() + { + var __result__ = __GetAssociatedRenderersFromInspector?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (UnityEngine.Renderer[])(__result__) : default; + } + + public static UnityEngine.Renderer[] GetAssociatedRenderersFromEditors(System.Collections.Generic.IEnumerable editors) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = editors; + var __result__ = __GetAssociatedRenderersFromEditors?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Renderer[])(__result__) : default; + } + + public static UnityEngine.Renderer PrepareMaterialPropertiesForAnimationMode(UnityEditor.MaterialProperty[] properties, UnityEngine.Renderer renderer, bool isMaterialEditable) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = properties; + __params__[1] = renderer; + __params__[2] = isMaterialEditable; + var __result__ = __PrepareMaterialPropertiesForAnimationMode?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Renderer)(__result__) : default; + } + + public static UnityEngine.Renderer[] PrepareMaterialPropertiesForAnimationMode(UnityEditor.MaterialProperty[] properties, UnityEngine.Renderer[] renderers, bool isMaterialEditable) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = properties; + __params__[1] = renderers; + __params__[2] = isMaterialEditable; + var __result__ = __PrepareMaterialPropertiesForAnimationMode__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Renderer[])(__result__) : default; + } + + public bool IsMaterialEditor(string customEditorName) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = customEditorName; + var __result__ = __IsMaterialEditor?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public void CreateCustomShaderEditorIfNeeded(UnityEngine.Shader shader) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = shader; + __CreateCustomShaderEditorIfNeeded?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public static void BeginNoApplyMaterialPropertyDrawers() + { + __BeginNoApplyMaterialPropertyDrawers?.Invoke(null, System.Array.Empty()); + } + + public static void EndNoApplyMaterialPropertyDrawers() + { + __EndNoApplyMaterialPropertyDrawers?.Invoke(null, System.Array.Empty()); + } + + public static void ApplyMaterialPropertyDrawersFromNative(UnityEngine.Material material) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = material; + __ApplyMaterialPropertyDrawersFromNative?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public UnityEngine.Object TextureValidator(UnityEngine.Object[] references, System.Type objType, UnityEditor.SerializedProperty property, object options) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = references; + __params__[1] = objType; + __params__[2] = property; + __params__[3] = options; + var __result__ = __TextureValidator?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Object)(__result__) : default; + } + + public void Init() + { + __Init?.Invoke(__self__, System.Array.Empty()); + } + + public bool DoReflectionProbePicker(out UnityEngine.Rect buttonRect) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = null; + var __result__ = __DoReflectionProbePicker?.Invoke(__self__, __params__); + buttonRect = (UnityEngine.Rect)(__params__[0]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public void StreamRenderResources() + { + __StreamRenderResources?.Invoke(__self__, System.Array.Empty()); + } + + public void DoRenderPreview(UnityEditor.PreviewRenderUtility previewRenderUtility, bool overridePreviewMesh) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = previewRenderUtility; + __params__[1] = overridePreviewMesh; + __DoRenderPreview?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public static UnityEditor.PreviewRenderUtility GetPreviewRendererUtility() + { + var __result__ = __GetPreviewRendererUtility?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (UnityEditor.PreviewRenderUtility)(__result__) : default; + } + + public static void CleanUpPreviewRenderUtility() + { + __CleanUpPreviewRenderUtility?.Invoke(null, System.Array.Empty()); + } + + public void OnSceneDrag(UnityEditor.SceneView sceneView, int index) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = sceneView; + __params__[1] = index; + __OnSceneDrag?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public static void TryRevertDragChanges() + { + __TryRevertDragChanges?.Invoke(null, System.Array.Empty()); + } + + public static void ClearDragMaterialRendering() + { + __ClearDragMaterialRendering?.Invoke(null, System.Array.Empty()); + } + + public void HandleSkybox(UnityEngine.GameObject go, UnityEngine.Event evt) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = go; + __params__[1] = evt; + __HandleSkybox?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public static void HandleRenderer(UnityEngine.Renderer r, int materialIndex, UnityEngine.Material dragMaterial, UnityEngine.EventType eventType, bool alt) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = r; + __params__[1] = materialIndex; + __params__[2] = dragMaterial; + __params__[3] = eventType; + __params__[4] = alt; + __HandleRenderer?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public bool HasLargeHeader() + { + var __result__ = __HasLargeHeader?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void OnHeaderIconGUI(UnityEngine.Rect iconRect) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = iconRect; + __OnHeaderIconGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public bool HasMultipleMixedQueueValues() + { + var __result__ = __HasMultipleMixedQueueValues?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public int CalculateClosestQueueIndexToValue(int requestedValue) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = requestedValue; + var __result__ = __CalculateClosestQueueIndexToValue?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public UnityEngine.Rect GetControlRectForSingleLine() + { + var __result__ = __GetControlRectForSingleLine?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (UnityEngine.Rect)(__result__) : default; + } + + public void ExtraPropertyAfterTexture(UnityEngine.Rect r, UnityEditor.MaterialProperty property, bool adjustLabelWidth) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = r; + __params__[1] = property; + __params__[2] = adjustLabelWidth; + __ExtraPropertyAfterTexture?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public static System.Type GetTextureTypeFromDimension(UnityEngine.Rendering.TextureDimension dim) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = dim; + var __result__ = __GetTextureTypeFromDimension?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (System.Type)(__result__) : default; + } + + public UnityEditor_MaterialEditor(object __self__) => this.__self__ = __self__ as UnityEngine.Object; + public UnityEngine.Object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + public UnityEditor.MaterialEditor __super__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.MaterialEditor)(__self__); + } + + private static FieldInfo ___s_MaterialEditors; + private static FieldInfo __s_MaterialEditors + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_MaterialEditors ??= __type__?.GetField("s_MaterialEditors", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_CheckSetup; + private static FieldInfo __m_CheckSetup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_CheckSetup ??= __type__?.GetField("m_CheckSetup", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ControlHash; + private static FieldInfo __s_ControlHash + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ControlHash ??= __type__?.GetField("s_ControlHash", (BindingFlags)(-1)); + } + + private static FieldInfo ___kSpacingUnderTexture; + private static FieldInfo __kSpacingUnderTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kSpacingUnderTexture ??= __type__?.GetField("kSpacingUnderTexture", (BindingFlags)(-1)); + } + + private static FieldInfo ___kMiniWarningMessageHeight; + private static FieldInfo __kMiniWarningMessageHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kMiniWarningMessageHeight ??= __type__?.GetField("kMiniWarningMessageHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_PropertyBlock; + private static FieldInfo __m_PropertyBlock + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_PropertyBlock ??= __type__?.GetField("m_PropertyBlock", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Shader; + private static FieldInfo __m_Shader + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Shader ??= __type__?.GetField("m_Shader", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_EnableInstancing; + private static FieldInfo __m_EnableInstancing + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_EnableInstancing ??= __type__?.GetField("m_EnableInstancing", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_DoubleSidedGI; + private static FieldInfo __m_DoubleSidedGI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_DoubleSidedGI ??= __type__?.GetField("m_DoubleSidedGI", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_InfoMessage; + private static FieldInfo __m_InfoMessage + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_InfoMessage ??= __type__?.GetField("m_InfoMessage", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_PreviewDir; + private static FieldInfo __m_PreviewDir + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_PreviewDir ??= __type__?.GetField("m_PreviewDir", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SelectedMesh; + private static FieldInfo __m_SelectedMesh + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SelectedMesh ??= __type__?.GetField("m_SelectedMesh", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TimeUpdate; + private static FieldInfo __m_TimeUpdate + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TimeUpdate ??= __type__?.GetField("m_TimeUpdate", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LightMode; + private static FieldInfo __m_LightMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LightMode ??= __type__?.GetField("m_LightMode", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_TilingText; + private static FieldInfo __s_TilingText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_TilingText ??= __type__?.GetField("s_TilingText", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_OffsetText; + private static FieldInfo __s_OffsetText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_OffsetText ??= __type__?.GetField("s_OffsetText", (BindingFlags)(-1)); + } + + private static FieldInfo ___kDefaultMaterialPreviewMesh; + private static FieldInfo __kDefaultMaterialPreviewMesh + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kDefaultMaterialPreviewMesh ??= __type__?.GetField("kDefaultMaterialPreviewMesh", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_CustomShaderGUI; + private static FieldInfo __m_CustomShaderGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_CustomShaderGUI ??= __type__?.GetField("m_CustomShaderGUI", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_CustomEditorClassName; + private static FieldInfo __m_CustomEditorClassName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_CustomEditorClassName ??= __type__?.GetField("m_CustomEditorClassName", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_InsidePropertiesGUI; + private static FieldInfo __m_InsidePropertiesGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_InsidePropertiesGUI ??= __type__?.GetField("m_InsidePropertiesGUI", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_RenderersForAnimationMode; + private static FieldInfo __m_RenderersForAnimationMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_RenderersForAnimationMode ??= __type__?.GetField("m_RenderersForAnimationMode", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MeshRendererComp; + private static FieldInfo __m_MeshRendererComp + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MeshRendererComp ??= __type__?.GetField("m_MeshRendererComp", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_AnimatedCheckStack; + private static FieldInfo __s_AnimatedCheckStack + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_AnimatedCheckStack ??= __type__?.GetField("s_AnimatedCheckStack", (BindingFlags)(-1)); + } + + private static FieldInfo ___contextualPropertyMenu; + private static FieldInfo __contextualPropertyMenu + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___contextualPropertyMenu ??= __type__?.GetField("contextualPropertyMenu", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ReflectionProbePicker; + private static FieldInfo __m_ReflectionProbePicker + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ReflectionProbePicker ??= __type__?.GetField("m_ReflectionProbePicker", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_DesiredTexdim; + private static FieldInfo __m_DesiredTexdim + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_DesiredTexdim ??= __type__?.GetField("m_DesiredTexdim", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_Meshes; + private static FieldInfo __s_Meshes + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_Meshes ??= __type__?.GetField("s_Meshes", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_PlaneMesh; + private static FieldInfo __s_PlaneMesh + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_PlaneMesh ??= __type__?.GetField("s_PlaneMesh", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_MeshIcons; + private static FieldInfo __s_MeshIcons + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_MeshIcons ??= __type__?.GetField("s_MeshIcons", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_LightIcons; + private static FieldInfo __s_LightIcons + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LightIcons ??= __type__?.GetField("s_LightIcons", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_TimeIcons; + private static FieldInfo __s_TimeIcons + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_TimeIcons ??= __type__?.GetField("s_TimeIcons", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_PreviewRenderUtility; + private static FieldInfo __s_PreviewRenderUtility + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_PreviewRenderUtility ??= __type__?.GetField("s_PreviewRenderUtility", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_NumberOfEditors; + private static FieldInfo __s_NumberOfEditors + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_NumberOfEditors ??= __type__?.GetField("s_NumberOfEditors", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_OriginalMaterial; + private static FieldInfo __s_OriginalMaterial + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_OriginalMaterial ??= __type__?.GetField("s_OriginalMaterial", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_previousDraggedUponRenderer; + private static FieldInfo __s_previousDraggedUponRenderer + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_previousDraggedUponRenderer ??= __type__?.GetField("s_previousDraggedUponRenderer", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_previousMaterialValue; + private static FieldInfo __s_previousMaterialValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_previousMaterialValue ??= __type__?.GetField("s_previousMaterialValue", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_previousAlreadyHadPrefabModification; + private static FieldInfo __s_previousAlreadyHadPrefabModification + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_previousAlreadyHadPrefabModification ??= __type__?.GetField("s_previousAlreadyHadPrefabModification", (BindingFlags)(-1)); + } + + private static FieldInfo ___kSpaceBetweenFlexibleAreaAndField; + private static FieldInfo __kSpaceBetweenFlexibleAreaAndField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kSpaceBetweenFlexibleAreaAndField ??= __type__?.GetField("kSpaceBetweenFlexibleAreaAndField", (BindingFlags)(-1)); + } + + private static FieldInfo ___kQueuePopupWidth; + private static FieldInfo __kQueuePopupWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kQueuePopupWidth ??= __type__?.GetField("kQueuePopupWidth", (BindingFlags)(-1)); + } + + private static FieldInfo ___kCustomQueuePopupWidth; + private static FieldInfo __kCustomQueuePopupWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kCustomQueuePopupWidth ??= __type__?.GetField("kCustomQueuePopupWidth", (BindingFlags)(-1)); + } + + private static PropertyInfo ___rendererForAnimationMode; + private static PropertyInfo __rendererForAnimationMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___rendererForAnimationMode ??= __type__?.GetProperty("rendererForAnimationMode", (BindingFlags)(-1)); + } + + private static PropertyInfo ___isPrefabAsset; + private static PropertyInfo __isPrefabAsset + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___isPrefabAsset ??= __type__?.GetProperty("isPrefabAsset", (BindingFlags)(-1)); + } + + private static MethodInfo ___GetPreviewType; + private static MethodInfo __GetPreviewType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPreviewType ??= __type__?.GetMethodInfoByParameterTypeNames("GetPreviewType", "UnityEngine.Material"); + } + + private static MethodInfo ___DoesPreviewAllowRotation; + private static MethodInfo __DoesPreviewAllowRotation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoesPreviewAllowRotation ??= __type__?.GetMethodInfoByParameterTypeNames("DoesPreviewAllowRotation", "UnityEditor.MaterialEditor+PreviewType"); + } + + private static MethodInfo ___ShouldEditorBeHidden; + private static MethodInfo __ShouldEditorBeHidden + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShouldEditorBeHidden ??= __type__?.GetMethodInfoByParameterTypeNames("ShouldEditorBeHidden"); + } + + private static MethodInfo ___UpdateAllOpenMaterialEditors; + private static MethodInfo __UpdateAllOpenMaterialEditors + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UpdateAllOpenMaterialEditors ??= __type__?.GetMethodInfoByParameterTypeNames("UpdateAllOpenMaterialEditors"); + } + + private static MethodInfo ___OnSelectedShaderPopup; + private static MethodInfo __OnSelectedShaderPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnSelectedShaderPopup ??= __type__?.GetMethodInfoByParameterTypeNames("OnSelectedShaderPopup", "System.Object"); + } + + private static MethodInfo ___HasMultipleMixedShaderValues; + private static MethodInfo __HasMultipleMixedShaderValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasMultipleMixedShaderValues ??= __type__?.GetMethodInfoByParameterTypeNames("HasMultipleMixedShaderValues"); + } + + private static MethodInfo ___ShaderPopup; + private static MethodInfo __ShaderPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShaderPopup ??= __type__?.GetMethodInfoByParameterTypeNames("ShaderPopup", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___DetectShaderEditorNeedsUpdate; + private static MethodInfo __DetectShaderEditorNeedsUpdate + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DetectShaderEditorNeedsUpdate ??= __type__?.GetMethodInfoByParameterTypeNames("DetectShaderEditorNeedsUpdate"); + } + + private static MethodInfo ___ParseValidationResult; + private static MethodInfo __ParseValidationResult + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ParseValidationResult ??= __type__?.GetMethodInfoByParameterTypeNames("ParseValidationResult", "UnityEngine.Rendering.VirtualTexturing.EditorHelpers+StackValidationResult"); + } + + private static MethodInfo ___DetectTextureStackValidationIssues; + private static MethodInfo __DetectTextureStackValidationIssues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DetectTextureStackValidationIssues ??= __type__?.GetMethodInfoByParameterTypeNames("DetectTextureStackValidationIssues"); + } + + private static MethodInfo ___CheckSetup; + private static MethodInfo __CheckSetup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CheckSetup ??= __type__?.GetMethodInfoByParameterTypeNames("CheckSetup"); + } + + private static MethodInfo ___OnAssetStoreInspectorGUI; + private static MethodInfo __OnAssetStoreInspectorGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnAssetStoreInspectorGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnAssetStoreInspectorGUI"); + } + + private static MethodInfo ___OnShaderChanged; + private static MethodInfo __OnShaderChanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnShaderChanged ??= __type__?.GetMethodInfoByParameterTypeNames("OnShaderChanged"); + } + + private static MethodInfo ___OnHeaderGUI; + private static MethodInfo __OnHeaderGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnHeaderGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnHeaderGUI"); + } + + private static MethodInfo ___OnHeaderControlsGUI; + private static MethodInfo __OnHeaderControlsGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnHeaderControlsGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnHeaderControlsGUI"); + } + + private static MethodInfo ___RangePropertyInternal; + private static MethodInfo __RangePropertyInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RangePropertyInternal ??= __type__?.GetMethodInfoByParameterTypeNames("RangePropertyInternal", "UnityEditor.MaterialProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___RangePropertyInternal__2; + private static MethodInfo __RangePropertyInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RangePropertyInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("RangePropertyInternal", "UnityEngine.Rect", "UnityEditor.MaterialProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___DoPowerRangeProperty; + private static MethodInfo __DoPowerRangeProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoPowerRangeProperty ??= __type__?.GetMethodInfoByParameterTypeNames("DoPowerRangeProperty", "UnityEngine.Rect", "UnityEditor.MaterialProperty", "UnityEngine.GUIContent", "System.Single"); + } + + private static MethodInfo ___DoIntRangeProperty; + private static MethodInfo __DoIntRangeProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoIntRangeProperty ??= __type__?.GetMethodInfoByParameterTypeNames("DoIntRangeProperty", "UnityEngine.Rect", "UnityEditor.MaterialProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___IntegerPropertyInternal; + private static MethodInfo __IntegerPropertyInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IntegerPropertyInternal ??= __type__?.GetMethodInfoByParameterTypeNames("IntegerPropertyInternal", "UnityEditor.MaterialProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___IntegerPropertyInternal__2; + private static MethodInfo __IntegerPropertyInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IntegerPropertyInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("IntegerPropertyInternal", "UnityEngine.Rect", "UnityEditor.MaterialProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___FloatPropertyInternal; + private static MethodInfo __FloatPropertyInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FloatPropertyInternal ??= __type__?.GetMethodInfoByParameterTypeNames("FloatPropertyInternal", "UnityEditor.MaterialProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___FloatPropertyInternal__2; + private static MethodInfo __FloatPropertyInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FloatPropertyInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("FloatPropertyInternal", "UnityEngine.Rect", "UnityEditor.MaterialProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___ColorPropertyInternal; + private static MethodInfo __ColorPropertyInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ColorPropertyInternal ??= __type__?.GetMethodInfoByParameterTypeNames("ColorPropertyInternal", "UnityEditor.MaterialProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___ColorPropertyInternal__2; + private static MethodInfo __ColorPropertyInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ColorPropertyInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("ColorPropertyInternal", "UnityEngine.Rect", "UnityEditor.MaterialProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___VectorPropertyInternal; + private static MethodInfo __VectorPropertyInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___VectorPropertyInternal ??= __type__?.GetMethodInfoByParameterTypeNames("VectorPropertyInternal", "UnityEngine.Rect&", "UnityEditor.MaterialProperty&", "UnityEngine.GUIContent&"); + } + + private static MethodInfo ___TexturePropertyBody; + private static MethodInfo __TexturePropertyBody + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TexturePropertyBody ??= __type__?.GetMethodInfoByParameterTypeNames("TexturePropertyBody", "UnityEngine.Rect", "UnityEditor.MaterialProperty"); + } + + private static MethodInfo ___TextureScaleOffsetProperty; + private static MethodInfo __TextureScaleOffsetProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TextureScaleOffsetProperty ??= __type__?.GetMethodInfoByParameterTypeNames("TextureScaleOffsetProperty", "UnityEngine.Rect", "UnityEngine.Vector4", "System.Int32", "System.Boolean"); + } + + private static MethodInfo ___GetTextureFieldHeight; + private static MethodInfo __GetTextureFieldHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetTextureFieldHeight ??= __type__?.GetMethodInfoByParameterTypeNames("GetTextureFieldHeight"); + } + + private static MethodInfo ___GetPropertyRect; + private static MethodInfo __GetPropertyRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPropertyRect ??= __type__?.GetMethodInfoByParameterTypeNames("GetPropertyRect", "UnityEditor.MaterialProperty", "UnityEngine.GUIContent", "System.Boolean"); + } + + private static MethodInfo ___GetPropertyRect__2; + private static MethodInfo __GetPropertyRect__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPropertyRect__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GetPropertyRect", "UnityEditor.MaterialProperty", "System.String", "System.Boolean"); + } + + private static MethodInfo ___DoPropertyContextMenu; + private static MethodInfo __DoPropertyContextMenu + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoPropertyContextMenu ??= __type__?.GetMethodInfoByParameterTypeNames("DoPropertyContextMenu", "UnityEditor.MaterialProperty"); + } + + private static MethodInfo ___GetGlobalIlluminationFlags; + private static MethodInfo __GetGlobalIlluminationFlags + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetGlobalIlluminationFlags ??= __type__?.GetMethodInfoByParameterTypeNames("GetGlobalIlluminationFlags", "UnityEngine.MaterialGlobalIlluminationFlags"); + } + + private static MethodInfo ___ShaderPropertyInternal; + private static MethodInfo __ShaderPropertyInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShaderPropertyInternal ??= __type__?.GetMethodInfoByParameterTypeNames("ShaderPropertyInternal", "UnityEngine.Rect", "UnityEditor.MaterialProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___DefaultShaderPropertyInternal; + private static MethodInfo __DefaultShaderPropertyInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DefaultShaderPropertyInternal ??= __type__?.GetMethodInfoByParameterTypeNames("DefaultShaderPropertyInternal", "UnityEditor.MaterialProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___DefaultShaderPropertyInternal__2; + private static MethodInfo __DefaultShaderPropertyInternal__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DefaultShaderPropertyInternal__2 ??= __type__?.GetMethodInfoByParameterTypeNames("DefaultShaderPropertyInternal", "UnityEngine.Rect", "UnityEditor.MaterialProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___GetAssociatedRenderersFromInspector; + private static MethodInfo __GetAssociatedRenderersFromInspector + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetAssociatedRenderersFromInspector ??= __type__?.GetMethodInfoByParameterTypeNames("GetAssociatedRenderersFromInspector"); + } + + private static MethodInfo ___GetAssociatedRenderersFromEditors; + private static MethodInfo __GetAssociatedRenderersFromEditors + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetAssociatedRenderersFromEditors ??= __type__?.GetMethodInfoByParameterTypeNames("GetAssociatedRenderersFromEditors", "System.Collections.Generic.IEnumerable`1[[UnityEditor.Editor, UnityEditor.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]"); + } + + private static MethodInfo ___PrepareMaterialPropertiesForAnimationMode; + private static MethodInfo __PrepareMaterialPropertiesForAnimationMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PrepareMaterialPropertiesForAnimationMode ??= __type__?.GetMethodInfoByParameterTypeNames("PrepareMaterialPropertiesForAnimationMode", "UnityEditor.MaterialProperty[]", "UnityEngine.Renderer", "System.Boolean"); + } + + private static MethodInfo ___PrepareMaterialPropertiesForAnimationMode__2; + private static MethodInfo __PrepareMaterialPropertiesForAnimationMode__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PrepareMaterialPropertiesForAnimationMode__2 ??= __type__?.GetMethodInfoByParameterTypeNames("PrepareMaterialPropertiesForAnimationMode", "UnityEditor.MaterialProperty[]", "UnityEngine.Renderer[]", "System.Boolean"); + } + + private static MethodInfo ___IsMaterialEditor; + private static MethodInfo __IsMaterialEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsMaterialEditor ??= __type__?.GetMethodInfoByParameterTypeNames("IsMaterialEditor", "System.String"); + } + + private static MethodInfo ___CreateCustomShaderEditorIfNeeded; + private static MethodInfo __CreateCustomShaderEditorIfNeeded + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CreateCustomShaderEditorIfNeeded ??= __type__?.GetMethodInfoByParameterTypeNames("CreateCustomShaderEditorIfNeeded", "UnityEngine.Shader"); + } + + private static MethodInfo ___BeginNoApplyMaterialPropertyDrawers; + private static MethodInfo __BeginNoApplyMaterialPropertyDrawers + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginNoApplyMaterialPropertyDrawers ??= __type__?.GetMethodInfoByParameterTypeNames("BeginNoApplyMaterialPropertyDrawers"); + } + + private static MethodInfo ___EndNoApplyMaterialPropertyDrawers; + private static MethodInfo __EndNoApplyMaterialPropertyDrawers + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EndNoApplyMaterialPropertyDrawers ??= __type__?.GetMethodInfoByParameterTypeNames("EndNoApplyMaterialPropertyDrawers"); + } + + private static MethodInfo ___ApplyMaterialPropertyDrawersFromNative; + private static MethodInfo __ApplyMaterialPropertyDrawersFromNative + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ApplyMaterialPropertyDrawersFromNative ??= __type__?.GetMethodInfoByParameterTypeNames("ApplyMaterialPropertyDrawersFromNative", "UnityEngine.Material"); + } + + private static MethodInfo ___TextureValidator; + private static MethodInfo __TextureValidator + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TextureValidator ??= __type__?.GetMethodInfoByParameterTypeNames("TextureValidator", "UnityEngine.Object[]", "System.Type", "UnityEditor.SerializedProperty", "UnityEditor.EditorGUI+ObjectFieldValidatorOptions"); + } + + private static MethodInfo ___Init; + private static MethodInfo __Init + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Init ??= __type__?.GetMethodInfoByParameterTypeNames("Init"); + } + + private static MethodInfo ___DoReflectionProbePicker; + private static MethodInfo __DoReflectionProbePicker + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoReflectionProbePicker ??= __type__?.GetMethodInfoByParameterTypeNames("DoReflectionProbePicker", "UnityEngine.Rect&"); + } + + private static MethodInfo ___StreamRenderResources; + private static MethodInfo __StreamRenderResources + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___StreamRenderResources ??= __type__?.GetMethodInfoByParameterTypeNames("StreamRenderResources"); + } + + private static MethodInfo ___DoRenderPreview; + private static MethodInfo __DoRenderPreview + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoRenderPreview ??= __type__?.GetMethodInfoByParameterTypeNames("DoRenderPreview", "UnityEditor.PreviewRenderUtility", "System.Boolean"); + } + + private static MethodInfo ___GetPreviewRendererUtility; + private static MethodInfo __GetPreviewRendererUtility + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPreviewRendererUtility ??= __type__?.GetMethodInfoByParameterTypeNames("GetPreviewRendererUtility"); + } + + private static MethodInfo ___CleanUpPreviewRenderUtility; + private static MethodInfo __CleanUpPreviewRenderUtility + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CleanUpPreviewRenderUtility ??= __type__?.GetMethodInfoByParameterTypeNames("CleanUpPreviewRenderUtility"); + } + + private static MethodInfo ___OnSceneDrag; + private static MethodInfo __OnSceneDrag + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnSceneDrag ??= __type__?.GetMethodInfoByParameterTypeNames("OnSceneDrag", "UnityEditor.SceneView", "System.Int32"); + } + + private static MethodInfo ___TryRevertDragChanges; + private static MethodInfo __TryRevertDragChanges + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TryRevertDragChanges ??= __type__?.GetMethodInfoByParameterTypeNames("TryRevertDragChanges"); + } + + private static MethodInfo ___ClearDragMaterialRendering; + private static MethodInfo __ClearDragMaterialRendering + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ClearDragMaterialRendering ??= __type__?.GetMethodInfoByParameterTypeNames("ClearDragMaterialRendering"); + } + + private static MethodInfo ___HandleSkybox; + private static MethodInfo __HandleSkybox + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HandleSkybox ??= __type__?.GetMethodInfoByParameterTypeNames("HandleSkybox", "UnityEngine.GameObject", "UnityEngine.Event"); + } + + private static MethodInfo ___HandleRenderer; + private static MethodInfo __HandleRenderer + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HandleRenderer ??= __type__?.GetMethodInfoByParameterTypeNames("HandleRenderer", "UnityEngine.Renderer", "System.Int32", "UnityEngine.Material", "UnityEngine.EventType", "System.Boolean"); + } + + private static MethodInfo ___HasLargeHeader; + private static MethodInfo __HasLargeHeader + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasLargeHeader ??= __type__?.GetMethodInfoByParameterTypeNames("HasLargeHeader"); + } + + private static MethodInfo ___OnHeaderIconGUI; + private static MethodInfo __OnHeaderIconGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnHeaderIconGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnHeaderIconGUI", "UnityEngine.Rect"); + } + + private static MethodInfo ___HasMultipleMixedQueueValues; + private static MethodInfo __HasMultipleMixedQueueValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasMultipleMixedQueueValues ??= __type__?.GetMethodInfoByParameterTypeNames("HasMultipleMixedQueueValues"); + } + + private static MethodInfo ___CalculateClosestQueueIndexToValue; + private static MethodInfo __CalculateClosestQueueIndexToValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CalculateClosestQueueIndexToValue ??= __type__?.GetMethodInfoByParameterTypeNames("CalculateClosestQueueIndexToValue", "System.Int32"); + } + + private static MethodInfo ___GetControlRectForSingleLine; + private static MethodInfo __GetControlRectForSingleLine + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetControlRectForSingleLine ??= __type__?.GetMethodInfoByParameterTypeNames("GetControlRectForSingleLine"); + } + + private static MethodInfo ___ExtraPropertyAfterTexture; + private static MethodInfo __ExtraPropertyAfterTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ExtraPropertyAfterTexture ??= __type__?.GetMethodInfoByParameterTypeNames("ExtraPropertyAfterTexture", "UnityEngine.Rect", "UnityEditor.MaterialProperty", "System.Boolean"); + } + + private static MethodInfo ___GetTextureTypeFromDimension; + private static MethodInfo __GetTextureTypeFromDimension + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetTextureTypeFromDimension ??= __type__?.GetMethodInfoByParameterTypeNames("GetTextureTypeFromDimension", "UnityEngine.Rendering.TextureDimension"); + } + } + public static class UnityEditor_MaterialEditor_Extension + { + public static UnityEditor_MaterialEditor ReflectionHelper(this UnityEditor.MaterialEditor self) => new(self); + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_MaterialEditor.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_MaterialEditor.cs.meta new file mode 100644 index 0000000..057fedd --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_MaterialEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: da374e1fa77f6294684a7e2c01250b52 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_ModelImporterClipEditor.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_ModelImporterClipEditor.cs new file mode 100644 index 0000000..2eafbb8 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_ModelImporterClipEditor.cs @@ -0,0 +1,1270 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_ModelImporterClipEditor + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.ModelImporterClipEditor"); + + + public UnityEditor.ModelImporter singleImporter + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.ModelImporter)(__singleImporter?.GetValue(__self__)); + } + + public string selectedClipName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__selectedClipName?.GetValue(__self__)); + } + + public int motionNodeIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__motionNodeIndex?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __motionNodeIndex?.SetValue(__self__, value); + } + + public int pivotNodeIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__pivotNodeIndex?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __pivotNodeIndex?.SetValue(__self__, value); + } + + public string[] referenceTransformPaths + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string[])(__referenceTransformPaths?.GetValue(__self__)); + } + + public UnityEditor.ModelImporterAnimationType animationType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.ModelImporterAnimationType)(__animationType?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __animationType?.SetValue(__self__, value); + } + + public UnityEditor.ModelImporterGenerateAnimations legacyGenerateAnimations + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.ModelImporterGenerateAnimations)(__legacyGenerateAnimations?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __legacyGenerateAnimations?.SetValue(__self__, value); + } + + public UnityEditor_AnimationClipEditor m_AnimationClipEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_AnimationClipEditor(__m_AnimationClipEditor?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AnimationClipEditor?.SetValue(__self__, value.__self__); + } + + public static string ActiveClipIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__ActiveClipIndex?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __ActiveClipIndex?.SetValue(null, value); + } + + public UnityEditor.SerializedObject m_DefaultClipsSerializedObject + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedObject)(__m_DefaultClipsSerializedObject?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_DefaultClipsSerializedObject?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_AnimationType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_AnimationType?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AnimationType?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_ImportAnimation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_ImportAnimation?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ImportAnimation?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_ClipAnimations + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_ClipAnimations?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ClipAnimations?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_BakeSimulation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_BakeSimulation?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_BakeSimulation?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_ResampleCurves + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_ResampleCurves?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ResampleCurves?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_AnimationCompression + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_AnimationCompression?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AnimationCompression?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_AnimationRotationError + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_AnimationRotationError?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AnimationRotationError?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_AnimationPositionError + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_AnimationPositionError?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AnimationPositionError?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_AnimationScaleError + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_AnimationScaleError?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AnimationScaleError?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_AnimationWrapMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_AnimationWrapMode?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AnimationWrapMode?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_LegacyGenerateAnimations + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_LegacyGenerateAnimations?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LegacyGenerateAnimations?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_ImportAnimatedCustomProperties + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_ImportAnimatedCustomProperties?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ImportAnimatedCustomProperties?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_ImportConstraints + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_ImportConstraints?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ImportConstraints?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_MotionNodeName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_MotionNodeName?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MotionNodeName?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_RemoveConstantScaleCurves + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_RemoveConstantScaleCurves?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_RemoveConstantScaleCurves?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_RigImportErrors + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_RigImportErrors?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_RigImportErrors?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_RigImportWarnings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_RigImportWarnings?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_RigImportWarnings?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_AnimationImportErrors + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_AnimationImportErrors?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AnimationImportErrors?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_AnimationImportWarnings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_AnimationImportWarnings?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AnimationImportWarnings?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_AnimationRetargetingWarnings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_AnimationRetargetingWarnings?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AnimationRetargetingWarnings?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_AnimationDoRetargetingWarnings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_AnimationDoRetargetingWarnings?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AnimationDoRetargetingWarnings?.SetValue(__self__, value); + } + + public string m_Errors + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__m_Errors?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Errors?.SetValue(__self__, value); + } + + public string m_Warnings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__m_Warnings?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Warnings?.SetValue(__self__, value); + } + + public string m_RigWarnings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__m_RigWarnings?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_RigWarnings?.SetValue(__self__, value); + } + + public string m_RetargetWarnings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__m_RetargetWarnings?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_RetargetWarnings?.SetValue(__self__, value); + } + + public UnityEngine.GUIContent[] m_MotionNodeList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent[])(__m_MotionNodeList?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MotionNodeList?.SetValue(__self__, value); + } + + public static bool s_MotionNodeFoldout + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__s_MotionNodeFoldout?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_MotionNodeFoldout?.SetValue(null, value); + } + + public static bool s_ImportMessageFoldout + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__s_ImportMessageFoldout?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ImportMessageFoldout?.SetValue(null, value); + } + + public UnityEditorInternal.ReorderableList m_ClipList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditorInternal.ReorderableList)(__m_ClipList?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ClipList?.SetValue(__self__, value); + } + + public static object styles + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__styles?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __styles?.SetValue(null, value); + } + + public static int kFrameColumnWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__kFrameColumnWidth?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kFrameColumnWidth?.SetValue(null, value); + } + + public UnityEngine.AvatarMask m_Mask + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.AvatarMask)(__m_Mask?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Mask?.SetValue(__self__, value); + } + + public object m_MaskInspector + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_MaskInspector?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MaskInspector?.SetValue(__self__, value); + } + + public static bool m_MaskFoldout + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_MaskFoldout?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MaskFoldout?.SetValue(null, value); + } + + public void OnEnable() + { + __OnEnable?.Invoke(__self__, System.Array.Empty()); + } + + public void SyncClipEditor(UnityEditor_AnimationClipInfoProperties info) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = info.__self__; + __SyncClipEditor?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void SetupDefaultClips() + { + __SetupDefaultClips?.Invoke(__self__, System.Array.Empty()); + } + + public void PatchDefaultClipTakeNamesToSplitClipNames() + { + __PatchDefaultClipTakeNamesToSplitClipNames?.Invoke(__self__, System.Array.Empty()); + } + + public void TransferDefaultClipsToCustomClips() + { + __TransferDefaultClipsToCustomClips?.Invoke(__self__, System.Array.Empty()); + } + + public void OnDestroy() + { + __OnDestroy?.Invoke(__self__, System.Array.Empty()); + } + + public void OnDisable() + { + __OnDisable?.Invoke(__self__, System.Array.Empty()); + } + + public void ResetValues() + { + __ResetValues?.Invoke(__self__, System.Array.Empty()); + } + + public void AnimationClipGUI() + { + __AnimationClipGUI?.Invoke(__self__, System.Array.Empty()); + } + + public void OnInspectorGUI() + { + __OnInspectorGUI?.Invoke(__self__, System.Array.Empty()); + } + + public void AnimationSettings() + { + __AnimationSettings?.Invoke(__self__, System.Array.Empty()); + } + + public void RootMotionNodeSettings() + { + __RootMotionNodeSettings?.Invoke(__self__, System.Array.Empty()); + } + + public void DestroyEditorsAndData() + { + __DestroyEditorsAndData?.Invoke(__self__, System.Array.Empty()); + } + + public void SelectClip(int selected) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = selected; + __SelectClip?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void UpdateList() + { + __UpdateList?.Invoke(__self__, System.Array.Empty()); + } + + public void AddClipInList(UnityEditorInternal.ReorderableList list) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = list; + __AddClipInList?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void RemoveClipInList(UnityEditorInternal.ReorderableList list) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = list; + __RemoveClipInList?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void SelectClipInList(UnityEditorInternal.ReorderableList list) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = list; + __SelectClipInList?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void DrawClipElement(UnityEngine.Rect rect, int index, bool selected, bool focused) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = index; + __params__[2] = selected; + __params__[3] = focused; + __DrawClipElement?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void DrawClipHeader(UnityEngine.Rect rect) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __DrawClipHeader?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void AnimationSplitTable() + { + __AnimationSplitTable?.Invoke(__self__, System.Array.Empty()); + } + + public bool HasPreviewGUI() + { + var __result__ = __HasPreviewGUI?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void OnPreviewSettings() + { + __OnPreviewSettings?.Invoke(__self__, System.Array.Empty()); + } + + public bool IsDeprecatedMultiAnimationRootImport() + { + var __result__ = __IsDeprecatedMultiAnimationRootImport?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void OnInteractivePreviewGUI(UnityEngine.Rect r, UnityEngine.GUIStyle background) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = r; + __params__[1] = background; + __OnInteractivePreviewGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public UnityEditor_AnimationClipInfoProperties GetSelectedClipInfo() + { + var __result__ = __GetSelectedClipInfo?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? new UnityEditor_AnimationClipInfoProperties(__result__) : default; + } + + public string RemoveDuplicateSuffix(string name, out int number) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = name; + __params__[1] = null; + var __result__ = __RemoveDuplicateSuffix?.Invoke(__self__, __params__); + number = (int)(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public string FindNextAvailableName(string baseName, System.Collections.Generic.HashSet allClipNames) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = baseName; + __params__[1] = allClipNames; + var __result__ = __FindNextAvailableName?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public string MakeUniqueClipName(string name, System.Collections.Generic.HashSet allClipNames) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = name; + __params__[1] = allClipNames; + var __result__ = __MakeUniqueClipName?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public void RemoveClip(int index) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = index; + __RemoveClip?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void SetupTakeNameAndFrames(UnityEditor_AnimationClipInfoProperties info, UnityEditor.TakeInfo takeInfo) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = info.__self__; + __params__[1] = takeInfo; + __SetupTakeNameAndFrames?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void AddClip(UnityEditor.TakeInfo takeInfo) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = takeInfo; + __AddClip?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void InitAnimationClipInfoProperties(UnityEditor_AnimationClipInfoProperties info, UnityEditor.TakeInfo takeInfo, string uniqueIdentifier, int clipOffset) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = info.__self__; + __params__[1] = takeInfo; + __params__[2] = uniqueIdentifier; + __params__[3] = clipOffset; + __InitAnimationClipInfoProperties?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void AvatarMaskSettings(UnityEditor_AnimationClipInfoProperties clipInfo) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = clipInfo.__self__; + __AvatarMaskSettings?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void InitMask(UnityEditor_AnimationClipInfoProperties clipInfo) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = clipInfo.__self__; + __InitMask?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void SetTransformMaskFromReference(UnityEditor_AnimationClipInfoProperties clipInfo) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = clipInfo.__self__; + __SetTransformMaskFromReference?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void SetBodyMaskDefaultValues(UnityEditor_AnimationClipInfoProperties clipInfo) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = clipInfo.__self__; + __SetBodyMaskDefaultValues?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void RegisterListeners() + { + __RegisterListeners?.Invoke(__self__, System.Array.Empty()); + } + + public void UnregisterListeners() + { + __UnregisterListeners?.Invoke(__self__, System.Array.Empty()); + } + + public void HandleUndo() + { + __HandleUndo?.Invoke(__self__, System.Array.Empty()); + } + + public void DeserializeClips() + { + __DeserializeClips?.Invoke(__self__, System.Array.Empty()); + } + + public UnityEditor_ModelImporterClipEditor(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + public UnityEditor_BaseAssetImporterTabUI __super__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_BaseAssetImporterTabUI(__self__); + } + + private static FieldInfo ___m_AnimationClipEditor; + private static FieldInfo __m_AnimationClipEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AnimationClipEditor ??= __type__?.GetField("m_AnimationClipEditor", (BindingFlags)(-1)); + } + + private static FieldInfo ___ActiveClipIndex; + private static FieldInfo __ActiveClipIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ActiveClipIndex ??= __type__?.GetField("ActiveClipIndex", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_DefaultClipsSerializedObject; + private static FieldInfo __m_DefaultClipsSerializedObject + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_DefaultClipsSerializedObject ??= __type__?.GetField("m_DefaultClipsSerializedObject", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AnimationType; + private static FieldInfo __m_AnimationType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AnimationType ??= __type__?.GetField("m_AnimationType", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ImportAnimation; + private static FieldInfo __m_ImportAnimation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ImportAnimation ??= __type__?.GetField("m_ImportAnimation", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ClipAnimations; + private static FieldInfo __m_ClipAnimations + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ClipAnimations ??= __type__?.GetField("m_ClipAnimations", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_BakeSimulation; + private static FieldInfo __m_BakeSimulation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_BakeSimulation ??= __type__?.GetField("m_BakeSimulation", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ResampleCurves; + private static FieldInfo __m_ResampleCurves + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ResampleCurves ??= __type__?.GetField("m_ResampleCurves", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AnimationCompression; + private static FieldInfo __m_AnimationCompression + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AnimationCompression ??= __type__?.GetField("m_AnimationCompression", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AnimationRotationError; + private static FieldInfo __m_AnimationRotationError + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AnimationRotationError ??= __type__?.GetField("m_AnimationRotationError", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AnimationPositionError; + private static FieldInfo __m_AnimationPositionError + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AnimationPositionError ??= __type__?.GetField("m_AnimationPositionError", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AnimationScaleError; + private static FieldInfo __m_AnimationScaleError + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AnimationScaleError ??= __type__?.GetField("m_AnimationScaleError", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AnimationWrapMode; + private static FieldInfo __m_AnimationWrapMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AnimationWrapMode ??= __type__?.GetField("m_AnimationWrapMode", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LegacyGenerateAnimations; + private static FieldInfo __m_LegacyGenerateAnimations + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LegacyGenerateAnimations ??= __type__?.GetField("m_LegacyGenerateAnimations", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ImportAnimatedCustomProperties; + private static FieldInfo __m_ImportAnimatedCustomProperties + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ImportAnimatedCustomProperties ??= __type__?.GetField("m_ImportAnimatedCustomProperties", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ImportConstraints; + private static FieldInfo __m_ImportConstraints + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ImportConstraints ??= __type__?.GetField("m_ImportConstraints", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MotionNodeName; + private static FieldInfo __m_MotionNodeName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MotionNodeName ??= __type__?.GetField("m_MotionNodeName", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_RemoveConstantScaleCurves; + private static FieldInfo __m_RemoveConstantScaleCurves + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_RemoveConstantScaleCurves ??= __type__?.GetField("m_RemoveConstantScaleCurves", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_RigImportErrors; + private static FieldInfo __m_RigImportErrors + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_RigImportErrors ??= __type__?.GetField("m_RigImportErrors", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_RigImportWarnings; + private static FieldInfo __m_RigImportWarnings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_RigImportWarnings ??= __type__?.GetField("m_RigImportWarnings", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AnimationImportErrors; + private static FieldInfo __m_AnimationImportErrors + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AnimationImportErrors ??= __type__?.GetField("m_AnimationImportErrors", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AnimationImportWarnings; + private static FieldInfo __m_AnimationImportWarnings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AnimationImportWarnings ??= __type__?.GetField("m_AnimationImportWarnings", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AnimationRetargetingWarnings; + private static FieldInfo __m_AnimationRetargetingWarnings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AnimationRetargetingWarnings ??= __type__?.GetField("m_AnimationRetargetingWarnings", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AnimationDoRetargetingWarnings; + private static FieldInfo __m_AnimationDoRetargetingWarnings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AnimationDoRetargetingWarnings ??= __type__?.GetField("m_AnimationDoRetargetingWarnings", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Errors; + private static FieldInfo __m_Errors + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Errors ??= __type__?.GetField("m_Errors", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Warnings; + private static FieldInfo __m_Warnings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Warnings ??= __type__?.GetField("m_Warnings", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_RigWarnings; + private static FieldInfo __m_RigWarnings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_RigWarnings ??= __type__?.GetField("m_RigWarnings", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_RetargetWarnings; + private static FieldInfo __m_RetargetWarnings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_RetargetWarnings ??= __type__?.GetField("m_RetargetWarnings", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MotionNodeList; + private static FieldInfo __m_MotionNodeList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MotionNodeList ??= __type__?.GetField("m_MotionNodeList", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_MotionNodeFoldout; + private static FieldInfo __s_MotionNodeFoldout + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_MotionNodeFoldout ??= __type__?.GetField("s_MotionNodeFoldout", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_ImportMessageFoldout; + private static FieldInfo __s_ImportMessageFoldout + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ImportMessageFoldout ??= __type__?.GetField("s_ImportMessageFoldout", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ClipList; + private static FieldInfo __m_ClipList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ClipList ??= __type__?.GetField("m_ClipList", (BindingFlags)(-1)); + } + + private static FieldInfo ___styles; + private static FieldInfo __styles + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___styles ??= __type__?.GetField("styles", (BindingFlags)(-1)); + } + + private static FieldInfo ___kFrameColumnWidth; + private static FieldInfo __kFrameColumnWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kFrameColumnWidth ??= __type__?.GetField("kFrameColumnWidth", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Mask; + private static FieldInfo __m_Mask + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Mask ??= __type__?.GetField("m_Mask", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MaskInspector; + private static FieldInfo __m_MaskInspector + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MaskInspector ??= __type__?.GetField("m_MaskInspector", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MaskFoldout; + private static FieldInfo __m_MaskFoldout + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MaskFoldout ??= __type__?.GetField("m_MaskFoldout", (BindingFlags)(-1)); + } + + private static PropertyInfo ___singleImporter; + private static PropertyInfo __singleImporter + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___singleImporter ??= __type__?.GetProperty("singleImporter", (BindingFlags)(-1)); + } + + private static PropertyInfo ___selectedClipName; + private static PropertyInfo __selectedClipName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___selectedClipName ??= __type__?.GetProperty("selectedClipName", (BindingFlags)(-1)); + } + + private static PropertyInfo ___motionNodeIndex; + private static PropertyInfo __motionNodeIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___motionNodeIndex ??= __type__?.GetProperty("motionNodeIndex", (BindingFlags)(-1)); + } + + private static PropertyInfo ___pivotNodeIndex; + private static PropertyInfo __pivotNodeIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___pivotNodeIndex ??= __type__?.GetProperty("pivotNodeIndex", (BindingFlags)(-1)); + } + + private static PropertyInfo ___referenceTransformPaths; + private static PropertyInfo __referenceTransformPaths + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___referenceTransformPaths ??= __type__?.GetProperty("referenceTransformPaths", (BindingFlags)(-1)); + } + + private static PropertyInfo ___animationType; + private static PropertyInfo __animationType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___animationType ??= __type__?.GetProperty("animationType", (BindingFlags)(-1)); + } + + private static PropertyInfo ___legacyGenerateAnimations; + private static PropertyInfo __legacyGenerateAnimations + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___legacyGenerateAnimations ??= __type__?.GetProperty("legacyGenerateAnimations", (BindingFlags)(-1)); + } + + private static MethodInfo ___OnEnable; + private static MethodInfo __OnEnable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnEnable ??= __type__?.GetMethodInfoByParameterTypeNames("OnEnable"); + } + + private static MethodInfo ___SyncClipEditor; + private static MethodInfo __SyncClipEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SyncClipEditor ??= __type__?.GetMethodInfoByParameterTypeNames("SyncClipEditor", "UnityEditor.AnimationClipInfoProperties"); + } + + private static MethodInfo ___SetupDefaultClips; + private static MethodInfo __SetupDefaultClips + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetupDefaultClips ??= __type__?.GetMethodInfoByParameterTypeNames("SetupDefaultClips"); + } + + private static MethodInfo ___PatchDefaultClipTakeNamesToSplitClipNames; + private static MethodInfo __PatchDefaultClipTakeNamesToSplitClipNames + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PatchDefaultClipTakeNamesToSplitClipNames ??= __type__?.GetMethodInfoByParameterTypeNames("PatchDefaultClipTakeNamesToSplitClipNames"); + } + + private static MethodInfo ___TransferDefaultClipsToCustomClips; + private static MethodInfo __TransferDefaultClipsToCustomClips + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TransferDefaultClipsToCustomClips ??= __type__?.GetMethodInfoByParameterTypeNames("TransferDefaultClipsToCustomClips"); + } + + private static MethodInfo ___OnDestroy; + private static MethodInfo __OnDestroy + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnDestroy ??= __type__?.GetMethodInfoByParameterTypeNames("OnDestroy"); + } + + private static MethodInfo ___OnDisable; + private static MethodInfo __OnDisable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnDisable ??= __type__?.GetMethodInfoByParameterTypeNames("OnDisable"); + } + + private static MethodInfo ___ResetValues; + private static MethodInfo __ResetValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ResetValues ??= __type__?.GetMethodInfoByParameterTypeNames("ResetValues"); + } + + private static MethodInfo ___AnimationClipGUI; + private static MethodInfo __AnimationClipGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AnimationClipGUI ??= __type__?.GetMethodInfoByParameterTypeNames("AnimationClipGUI"); + } + + private static MethodInfo ___OnInspectorGUI; + private static MethodInfo __OnInspectorGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnInspectorGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnInspectorGUI"); + } + + private static MethodInfo ___AnimationSettings; + private static MethodInfo __AnimationSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AnimationSettings ??= __type__?.GetMethodInfoByParameterTypeNames("AnimationSettings"); + } + + private static MethodInfo ___RootMotionNodeSettings; + private static MethodInfo __RootMotionNodeSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RootMotionNodeSettings ??= __type__?.GetMethodInfoByParameterTypeNames("RootMotionNodeSettings"); + } + + private static MethodInfo ___DestroyEditorsAndData; + private static MethodInfo __DestroyEditorsAndData + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DestroyEditorsAndData ??= __type__?.GetMethodInfoByParameterTypeNames("DestroyEditorsAndData"); + } + + private static MethodInfo ___SelectClip; + private static MethodInfo __SelectClip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SelectClip ??= __type__?.GetMethodInfoByParameterTypeNames("SelectClip", "System.Int32"); + } + + private static MethodInfo ___UpdateList; + private static MethodInfo __UpdateList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UpdateList ??= __type__?.GetMethodInfoByParameterTypeNames("UpdateList"); + } + + private static MethodInfo ___AddClipInList; + private static MethodInfo __AddClipInList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AddClipInList ??= __type__?.GetMethodInfoByParameterTypeNames("AddClipInList", "UnityEditorInternal.ReorderableList"); + } + + private static MethodInfo ___RemoveClipInList; + private static MethodInfo __RemoveClipInList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RemoveClipInList ??= __type__?.GetMethodInfoByParameterTypeNames("RemoveClipInList", "UnityEditorInternal.ReorderableList"); + } + + private static MethodInfo ___SelectClipInList; + private static MethodInfo __SelectClipInList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SelectClipInList ??= __type__?.GetMethodInfoByParameterTypeNames("SelectClipInList", "UnityEditorInternal.ReorderableList"); + } + + private static MethodInfo ___DrawClipElement; + private static MethodInfo __DrawClipElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawClipElement ??= __type__?.GetMethodInfoByParameterTypeNames("DrawClipElement", "UnityEngine.Rect", "System.Int32", "System.Boolean", "System.Boolean"); + } + + private static MethodInfo ___DrawClipHeader; + private static MethodInfo __DrawClipHeader + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawClipHeader ??= __type__?.GetMethodInfoByParameterTypeNames("DrawClipHeader", "UnityEngine.Rect"); + } + + private static MethodInfo ___AnimationSplitTable; + private static MethodInfo __AnimationSplitTable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AnimationSplitTable ??= __type__?.GetMethodInfoByParameterTypeNames("AnimationSplitTable"); + } + + private static MethodInfo ___HasPreviewGUI; + private static MethodInfo __HasPreviewGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasPreviewGUI ??= __type__?.GetMethodInfoByParameterTypeNames("HasPreviewGUI"); + } + + private static MethodInfo ___OnPreviewSettings; + private static MethodInfo __OnPreviewSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnPreviewSettings ??= __type__?.GetMethodInfoByParameterTypeNames("OnPreviewSettings"); + } + + private static MethodInfo ___IsDeprecatedMultiAnimationRootImport; + private static MethodInfo __IsDeprecatedMultiAnimationRootImport + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsDeprecatedMultiAnimationRootImport ??= __type__?.GetMethodInfoByParameterTypeNames("IsDeprecatedMultiAnimationRootImport"); + } + + private static MethodInfo ___OnInteractivePreviewGUI; + private static MethodInfo __OnInteractivePreviewGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnInteractivePreviewGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnInteractivePreviewGUI", "UnityEngine.Rect", "UnityEngine.GUIStyle"); + } + + private static MethodInfo ___GetSelectedClipInfo; + private static MethodInfo __GetSelectedClipInfo + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSelectedClipInfo ??= __type__?.GetMethodInfoByParameterTypeNames("GetSelectedClipInfo"); + } + + private static MethodInfo ___RemoveDuplicateSuffix; + private static MethodInfo __RemoveDuplicateSuffix + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RemoveDuplicateSuffix ??= __type__?.GetMethodInfoByParameterTypeNames("RemoveDuplicateSuffix", "System.String", "System.Int32&"); + } + + private static MethodInfo ___FindNextAvailableName; + private static MethodInfo __FindNextAvailableName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FindNextAvailableName ??= __type__?.GetMethodInfoByParameterTypeNames("FindNextAvailableName", "System.String", "System.Collections.Generic.HashSet`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); + } + + private static MethodInfo ___MakeUniqueClipName; + private static MethodInfo __MakeUniqueClipName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MakeUniqueClipName ??= __type__?.GetMethodInfoByParameterTypeNames("MakeUniqueClipName", "System.String", "System.Collections.Generic.HashSet`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); + } + + private static MethodInfo ___RemoveClip; + private static MethodInfo __RemoveClip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RemoveClip ??= __type__?.GetMethodInfoByParameterTypeNames("RemoveClip", "System.Int32"); + } + + private static MethodInfo ___SetupTakeNameAndFrames; + private static MethodInfo __SetupTakeNameAndFrames + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetupTakeNameAndFrames ??= __type__?.GetMethodInfoByParameterTypeNames("SetupTakeNameAndFrames", "UnityEditor.AnimationClipInfoProperties", "UnityEditor.TakeInfo"); + } + + private static MethodInfo ___AddClip; + private static MethodInfo __AddClip + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AddClip ??= __type__?.GetMethodInfoByParameterTypeNames("AddClip", "UnityEditor.TakeInfo"); + } + + private static MethodInfo ___InitAnimationClipInfoProperties; + private static MethodInfo __InitAnimationClipInfoProperties + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___InitAnimationClipInfoProperties ??= __type__?.GetMethodInfoByParameterTypeNames("InitAnimationClipInfoProperties", "UnityEditor.AnimationClipInfoProperties", "UnityEditor.TakeInfo", "System.String", "System.Int32"); + } + + private static MethodInfo ___AvatarMaskSettings; + private static MethodInfo __AvatarMaskSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AvatarMaskSettings ??= __type__?.GetMethodInfoByParameterTypeNames("AvatarMaskSettings", "UnityEditor.AnimationClipInfoProperties"); + } + + private static MethodInfo ___InitMask; + private static MethodInfo __InitMask + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___InitMask ??= __type__?.GetMethodInfoByParameterTypeNames("InitMask", "UnityEditor.AnimationClipInfoProperties"); + } + + private static MethodInfo ___SetTransformMaskFromReference; + private static MethodInfo __SetTransformMaskFromReference + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetTransformMaskFromReference ??= __type__?.GetMethodInfoByParameterTypeNames("SetTransformMaskFromReference", "UnityEditor.AnimationClipInfoProperties"); + } + + private static MethodInfo ___SetBodyMaskDefaultValues; + private static MethodInfo __SetBodyMaskDefaultValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetBodyMaskDefaultValues ??= __type__?.GetMethodInfoByParameterTypeNames("SetBodyMaskDefaultValues", "UnityEditor.AnimationClipInfoProperties"); + } + + private static MethodInfo ___RegisterListeners; + private static MethodInfo __RegisterListeners + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RegisterListeners ??= __type__?.GetMethodInfoByParameterTypeNames("RegisterListeners"); + } + + private static MethodInfo ___UnregisterListeners; + private static MethodInfo __UnregisterListeners + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UnregisterListeners ??= __type__?.GetMethodInfoByParameterTypeNames("UnregisterListeners"); + } + + private static MethodInfo ___HandleUndo; + private static MethodInfo __HandleUndo + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HandleUndo ??= __type__?.GetMethodInfoByParameterTypeNames("HandleUndo"); + } + + private static MethodInfo ___DeserializeClips; + private static MethodInfo __DeserializeClips + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DeserializeClips ??= __type__?.GetMethodInfoByParameterTypeNames("DeserializeClips"); + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_ModelImporterClipEditor.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_ModelImporterClipEditor.cs.meta new file mode 100644 index 0000000..b054874 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_ModelImporterClipEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d499717fde33fec4589c2f7a21b60f95 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_ModelImporterClipEditor_ClipInformation.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_ModelImporterClipEditor_ClipInformation.cs new file mode 100644 index 0000000..653b48a --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_ModelImporterClipEditor_ClipInformation.cs @@ -0,0 +1,120 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_ModelImporterClipEditor_ClipInformation + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.ModelImporterClipEditor+ClipInformation"); + + + public UnityEditor.SerializedProperty animationClipProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__animationClipProperty?.GetValue(__self__)); + } + + public UnityEditor_AnimationClipInfoProperties property + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_AnimationClipInfoProperties(__property?.GetValue(__self__)); + } + + public string name + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__name?.GetValue(__self__)); + } + + public string firstFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__firstFrame?.GetValue(__self__)); + } + + public string lastFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__lastFrame?.GetValue(__self__)); + } + + public UnityEditor.SerializedProperty prop + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__prop?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __prop?.SetValue(__self__, value); + } + + public UnityEditor_AnimationClipInfoProperties m_Property + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_AnimationClipInfoProperties(__m_Property?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Property?.SetValue(__self__, value.__self__); + } + + public UnityEditor_ModelImporterClipEditor_ClipInformation(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + + private static FieldInfo ___prop; + private static FieldInfo __prop + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___prop ??= __type__?.GetField("prop", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Property; + private static FieldInfo __m_Property + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Property ??= __type__?.GetField("m_Property", (BindingFlags)(-1)); + } + + private static PropertyInfo ___animationClipProperty; + private static PropertyInfo __animationClipProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___animationClipProperty ??= __type__?.GetProperty("animationClipProperty", (BindingFlags)(-1)); + } + + private static PropertyInfo ___property; + private static PropertyInfo __property + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___property ??= __type__?.GetProperty("property", (BindingFlags)(-1)); + } + + private static PropertyInfo ___name; + private static PropertyInfo __name + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___name ??= __type__?.GetProperty("name", (BindingFlags)(-1)); + } + + private static PropertyInfo ___firstFrame; + private static PropertyInfo __firstFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___firstFrame ??= __type__?.GetProperty("firstFrame", (BindingFlags)(-1)); + } + + private static PropertyInfo ___lastFrame; + private static PropertyInfo __lastFrame + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___lastFrame ??= __type__?.GetProperty("lastFrame", (BindingFlags)(-1)); + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_ModelImporterClipEditor_ClipInformation.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_ModelImporterClipEditor_ClipInformation.cs.meta new file mode 100644 index 0000000..bdddde7 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_ModelImporterClipEditor_ClipInformation.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6fe6c5fabdaaf7c429f260fe525c31cb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_PropertyEditor.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_PropertyEditor.cs new file mode 100644 index 0000000..53dd1bc --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_PropertyEditor.cs @@ -0,0 +1,2457 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_PropertyEditor + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.PropertyEditor"); + + + public UnityEngine.UIElements.VisualElement editorsElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.UIElements.VisualElement)(__editorsElement?.GetValue(__self__)); + } + + public UnityEngine.UIElements.VisualElement previewAndLabelElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.UIElements.VisualElement)(__previewAndLabelElement?.GetValue(__self__)); + } + + public UnityEngine.UIElements.VisualElement versionControlElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.UIElements.VisualElement)(__versionControlElement?.GetValue(__self__)); + } + + public object parent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__parent?.GetValue(__self__)); + } + + public System.Collections.Generic.HashSet editorsWithImportedObjectLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Generic.HashSet)(__editorsWithImportedObjectLabel?.GetValue(__self__)); + } + + public object editorDragging + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__editorDragging?.GetValue(__self__)); + } + + public bool useUIElementsDefaultInspector + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__useUIElementsDefaultInspector?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __useUIElementsDefaultInspector?.SetValue(__self__, value); + } + + public UnityEditor.Editor lastInteractedEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.Editor)(__lastInteractedEditor?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __lastInteractedEditor?.SetValue(__self__, value); + } + + public static UnityEditor_PropertyEditor HoveredPropertyEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_PropertyEditor(__HoveredPropertyEditor?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __HoveredPropertyEditor?.SetValue(null, value.__self__); + } + + public static UnityEditor_PropertyEditor FocusedPropertyEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_PropertyEditor(__FocusedPropertyEditor?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __FocusedPropertyEditor?.SetValue(null, value.__self__); + } + + public UnityEditor.InspectorMode inspectorMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.InspectorMode)(__inspectorMode?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __inspectorMode?.SetValue(__self__, value); + } + + public UnityEditor.ActiveEditorTracker tracker + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.ActiveEditorTracker)(__tracker?.GetValue(__self__)); + } + + public UnityEngine.Rect bottomAreaDropRectangle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Rect)(__bottomAreaDropRectangle?.GetValue(__self__)); + } + + public UnityEngine.Rect scrollViewportRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Rect)(__scrollViewportRect?.GetValue(__self__)); + } + + public static string k_AssetPropertiesMenuItemName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__k_AssetPropertiesMenuItemName?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __k_AssetPropertiesMenuItemName?.SetValue(null, value); + } + + public static string s_MultiEditClassName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__s_MultiEditClassName?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_MultiEditClassName?.SetValue(null, value); + } + + public static string s_EditorListClassName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__s_EditorListClassName?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_EditorListClassName?.SetValue(null, value); + } + + public static string s_AddComponentClassName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__s_AddComponentClassName?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_AddComponentClassName?.SetValue(null, value); + } + + public static string s_HeaderInfoClassName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__s_HeaderInfoClassName?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_HeaderInfoClassName?.SetValue(null, value); + } + + public static string s_FooterInfoClassName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__s_FooterInfoClassName?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_FooterInfoClassName?.SetValue(null, value); + } + + public static string s_MainContainerClassName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__s_MainContainerClassName?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_MainContainerClassName?.SetValue(null, value); + } + + public static float kBottomToolbarHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kBottomToolbarHeight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kBottomToolbarHeight?.SetValue(null, value); + } + + public static float kAddComponentButtonHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kAddComponentButtonHeight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kAddComponentButtonHeight?.SetValue(null, value); + } + + public static float kEditorElementPaddingBottom + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__kEditorElementPaddingBottom?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kEditorElementPaddingBottom?.SetValue(null, value); + } + + public static float k_MinAreaAbovePreview + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__k_MinAreaAbovePreview?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __k_MinAreaAbovePreview?.SetValue(null, value); + } + + public static float k_InspectorPreviewMinHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__k_InspectorPreviewMinHeight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __k_InspectorPreviewMinHeight?.SetValue(null, value); + } + + public static float k_InspectorPreviewMinTotalHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__k_InspectorPreviewMinTotalHeight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __k_InspectorPreviewMinTotalHeight?.SetValue(null, value); + } + + public static int k_MinimumRootVisualHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__k_MinimumRootVisualHeight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __k_MinimumRootVisualHeight?.SetValue(null, value); + } + + public static int k_MinimumWindowWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__k_MinimumWindowWidth?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __k_MinimumWindowWidth?.SetValue(null, value); + } + + public static int k_AutoScrollZoneHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__k_AutoScrollZoneHeight?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __k_AutoScrollZoneHeight?.SetValue(null, value); + } + + public static long delayRepaintWhilePlayingAnimation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (long)(__delayRepaintWhilePlayingAnimation?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __delayRepaintWhilePlayingAnimation?.SetValue(null, value); + } + + public long m_LastUpdateWhilePlayingAnimation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (long)(__m_LastUpdateWhilePlayingAnimation?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LastUpdateWhilePlayingAnimation?.SetValue(__self__, value); + } + + public System.Collections.Generic.List m_ObjectsLockedBeforeSerialization + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Generic.List)(__m_ObjectsLockedBeforeSerialization?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ObjectsLockedBeforeSerialization?.SetValue(__self__, value); + } + + public System.Collections.Generic.List m_InstanceIDsLockedBeforeSerialization + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Generic.List)(__m_InstanceIDsLockedBeforeSerialization?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_InstanceIDsLockedBeforeSerialization?.SetValue(__self__, value); + } + + public object m_PreviewResizer + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_PreviewResizer?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_PreviewResizer?.SetValue(__self__, value); + } + + public object m_LabelGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_LabelGUI?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LabelGUI?.SetValue(__self__, value); + } + + public int m_LastInspectedObjectInstanceID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__m_LastInspectedObjectInstanceID?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LastInspectedObjectInstanceID?.SetValue(__self__, value); + } + + public float m_LastVerticalScrollValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__m_LastVerticalScrollValue?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LastVerticalScrollValue?.SetValue(__self__, value); + } + + public string m_GlobalObjectId + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__m_GlobalObjectId?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_GlobalObjectId?.SetValue(__self__, value); + } + + public UnityEditor.InspectorMode m_InspectorMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.InspectorMode)(__m_InspectorMode?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_InspectorMode?.SetValue(__self__, value); + } + + public UnityEngine.Object m_InspectedObject + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Object)(__m_InspectedObject?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_InspectedObject?.SetValue(__self__, value); + } + + public static UnityEditor_PropertyEditor s_LastPropertyEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_PropertyEditor(__s_LastPropertyEditor?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LastPropertyEditor?.SetValue(null, value.__self__); + } + + public int m_LastInitialEditorInstanceID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__m_LastInitialEditorInstanceID?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_LastInitialEditorInstanceID?.SetValue(__self__, value); + } + + public UnityEngine.Component[] m_ComponentsInPrefabSource + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Component[])(__m_ComponentsInPrefabSource?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ComponentsInPrefabSource?.SetValue(__self__, value); + } + + public System.Collections.Generic.HashSet m_RemovedComponents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Generic.HashSet)(__m_RemovedComponents?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_RemovedComponents?.SetValue(__self__, value); + } + + public System.Collections.Generic.HashSet m_SuppressedComponents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Generic.HashSet)(__m_SuppressedComponents?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SuppressedComponents?.SetValue(__self__, value); + } + + public bool m_ResetKeyboardControl + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_ResetKeyboardControl?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ResetKeyboardControl?.SetValue(__self__, value); + } + + public bool m_OpenAddComponentMenu + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_OpenAddComponentMenu?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_OpenAddComponentMenu?.SetValue(__self__, value); + } + + public UnityEditor.ActiveEditorTracker m_Tracker + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.ActiveEditorTracker)(__m_Tracker?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Tracker?.SetValue(__self__, value); + } + + public object m_AssetBundleNameGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_AssetBundleNameGUI?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AssetBundleNameGUI?.SetValue(__self__, value); + } + + public object m_TypeSelectionList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_TypeSelectionList?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TypeSelectionList?.SetValue(__self__, value); + } + + public double m_lastRenderedTime + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (double)(__m_lastRenderedTime?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_lastRenderedTime?.SetValue(__self__, value); + } + + public System.Collections.IList m_Previews + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.IList)(__m_Previews?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Previews?.SetValue(__self__, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public object m_Previews__GetItem(int i) => (object)(m_Previews?[i]); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void m_Previews__SetItem(int i, object value) + { + var __list__ = m_Previews; + if (__list__ == null) return; + __list__[i] = value; + } + + public System.Collections.Generic.Dictionary> m_PreviewableTypes + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Generic.Dictionary>)(__m_PreviewableTypes?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_PreviewableTypes?.SetValue(__self__, value); + } + + public object m_SelectedPreview + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__m_SelectedPreview?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SelectedPreview?.SetValue(__self__, value); + } + + public UnityEngine.UIElements.VisualElement m_EditorsElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.UIElements.VisualElement)(__m_EditorsElement?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_EditorsElement?.SetValue(__self__, value); + } + + public UnityEngine.UIElements.VisualElement m_RemovedPrefabComponentsElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.UIElements.VisualElement)(__m_RemovedPrefabComponentsElement?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_RemovedPrefabComponentsElement?.SetValue(__self__, value); + } + + public UnityEngine.UIElements.VisualElement m_PreviewAndLabelElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.UIElements.VisualElement)(__m_PreviewAndLabelElement?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_PreviewAndLabelElement?.SetValue(__self__, value); + } + + public UnityEngine.UIElements.VisualElement m_VersionControlElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.UIElements.VisualElement)(__m_VersionControlElement?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_VersionControlElement?.SetValue(__self__, value); + } + + public static System.Collections.IDictionary m_VersionControlBarState + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.IDictionary)(__m_VersionControlBarState?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_VersionControlBarState?.SetValue(null, value); + } + + public UnityEngine.UIElements.VisualElement m_MultiEditLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.UIElements.VisualElement)(__m_MultiEditLabel?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MultiEditLabel?.SetValue(__self__, value); + } + + public UnityEngine.UIElements.ScrollView m_ScrollView + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.UIElements.ScrollView)(__m_ScrollView?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ScrollView?.SetValue(__self__, value); + } + + public bool m_TrackerResetInserted + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_TrackerResetInserted?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TrackerResetInserted?.SetValue(__self__, value); + } + + public bool m_FirstInitialize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_FirstInitialize?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_FirstInitialize?.SetValue(__self__, value); + } + + public float m_PreviousFooterHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__m_PreviousFooterHeight?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_PreviousFooterHeight?.SetValue(__self__, value); + } + + public bool m_PreviousPreviewExpandedState + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_PreviousPreviewExpandedState?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_PreviousPreviewExpandedState?.SetValue(__self__, value); + } + + public bool m_HasPreview + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_HasPreview?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_HasPreview?.SetValue(__self__, value); + } + + public System.Collections.Generic.HashSet m_DrawnSelection + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Generic.HashSet)(__m_DrawnSelection?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_DrawnSelection?.SetValue(__self__, value); + } + + public static UnityEditor.Editor[] s_Editors + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.Editor[])(__s_Editors?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_Editors?.SetValue(null, value); + } + + public void OnDestroy() + { + __OnDestroy?.Invoke(__self__, System.Array.Empty()); + } + + public void OnFocusChanged(bool focus) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = focus; + __OnFocusChanged?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void OnEnable() + { + __OnEnable?.Invoke(__self__, System.Array.Empty()); + } + + public void OnDisable() + { + __OnDisable?.Invoke(__self__, System.Array.Empty()); + } + + public void OnMouseEnter(UnityEngine.UIElements.MouseEnterEvent e) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = e; + __OnMouseEnter?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void OnMouseLeave(UnityEngine.UIElements.MouseLeaveEvent e) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = e; + __OnMouseLeave?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void OnFocusIn(UnityEngine.UIElements.FocusInEvent e) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = e; + __OnFocusIn?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void OnFocusOut(UnityEngine.UIElements.FocusOutEvent e) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = e; + __OnFocusOut?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void OnLostFocus() + { + __OnLostFocus?.Invoke(__self__, System.Array.Empty()); + } + + public bool CloseIfEmpty() + { + var __result__ = __CloseIfEmpty?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void OnInspectorUpdate() + { + __OnInspectorUpdate?.Invoke(__self__, System.Array.Empty()); + } + + public void OnGUI() + { + __OnGUI?.Invoke(__self__, System.Array.Empty()); + } + + public void Update() + { + __Update?.Invoke(__self__, System.Array.Empty()); + } + + public void SetMode(UnityEditor.InspectorMode mode) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = mode; + __SetMode?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void SetTitle(UnityEngine.Object obj) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = obj; + __SetTitle?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void RefreshTitle() + { + __RefreshTitle?.Invoke(__self__, System.Array.Empty()); + } + + public UnityEngine.UIElements.VisualElement FindVisualElementInTreeByClassName(string elementClassName) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = elementClassName; + var __result__ = __FindVisualElementInTreeByClassName?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.UIElements.VisualElement)(__result__) : default; + } + + public static void ClearVersionControlBarState() + { + __ClearVersionControlBarState?.Invoke(null, System.Array.Empty()); + } + + public void LoadVisualTreeFromUxml() + { + __LoadVisualTreeFromUxml?.Invoke(__self__, System.Array.Empty()); + } + + public void OnGeometryChanged(UnityEngine.UIElements.GeometryChangedEvent e) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = e; + __OnGeometryChanged?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void SetUseUIEDefaultInspector() + { + __SetUseUIEDefaultInspector?.Invoke(__self__, System.Array.Empty()); + } + + public void SetDebug() + { + __SetDebug?.Invoke(__self__, System.Array.Empty()); + } + + public void SetNormal() + { + __SetNormal?.Invoke(__self__, System.Array.Empty()); + } + + public void SetDebugInternal() + { + __SetDebugInternal?.Invoke(__self__, System.Array.Empty()); + } + + public void AddDebugItemsToMenu(UnityEditor.GenericMenu menu) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = menu; + __AddDebugItemsToMenu?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void AddItemsToMenu(UnityEditor.GenericMenu menu) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = menu; + __AddItemsToMenu?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void SetTrackerExpandedState(UnityEditor.ActiveEditorTracker tracker, int editorIndex, bool expanded) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = tracker; + __params__[1] = editorIndex; + __params__[2] = expanded; + __SetTrackerExpandedState?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void ExpandAllComponents() + { + __ExpandAllComponents?.Invoke(__self__, System.Array.Empty()); + } + + public bool IsAnyComponentCollapsed() + { + var __result__ = __IsAnyComponentCollapsed?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void CollapseAllComponents() + { + __CollapseAllComponents?.Invoke(__self__, System.Array.Empty()); + } + + public bool IsAnyComponentExpanded() + { + var __result__ = __IsAnyComponentExpanded?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public bool LoadPersistedObject() + { + var __result__ = __LoadPersistedObject?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void CreateTracker() + { + __CreateTracker?.Invoke(__self__, System.Array.Empty()); + } + + public void OnTrackerRebuilt() + { + __OnTrackerRebuilt?.Invoke(__self__, System.Array.Empty()); + } + + public void OnObjectChanged(UnityEditor.ChangeGameObjectOrComponentPropertiesEventArgs args) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = args; + __OnObjectChanged?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void OnObjectChanged(ref UnityEditor.ObjectChangeEventStream stream) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = stream; + __OnObjectChanged__2?.Invoke(__self__, __params__); + stream = (UnityEditor.ObjectChangeEventStream)(__params__[0]); + __pool__.Return(__params__); + } + + public void UpdateWindowObjectNameTitle() + { + __UpdateWindowObjectNameTitle?.Invoke(__self__, System.Array.Empty()); + } + + public void OnUndoRedoPerformed() + { + __OnUndoRedoPerformed?.Invoke(__self__, System.Array.Empty()); + } + + public void ExtractPrefabComponents() + { + __ExtractPrefabComponents?.Invoke(__self__, System.Array.Empty()); + } + + public void CreatePreviewables() + { + __CreatePreviewables?.Invoke(__self__, System.Array.Empty()); + } + + public void ClearPreviewables() + { + __ClearPreviewables?.Invoke(__self__, System.Array.Empty()); + } + + public System.Collections.Generic.Dictionary> GetPreviewableTypes() + { + var __result__ = __GetPreviewableTypes?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (System.Collections.Generic.Dictionary>)(__result__) : default; + } + + public object GetPreviewsForType(UnityEditor.Editor editor) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = editor; + var __result__ = __GetPreviewsForType?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (object)(__result__) : default; + } + + public void ClearTrackerDirtyOnRepaint() + { + __ClearTrackerDirtyOnRepaint?.Invoke(__self__, System.Array.Empty()); + } + + public UnityEngine.UIElements.IMGUIContainer CreateIMGUIContainer(System.Action onGUIHandler, string name) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = onGUIHandler; + __params__[1] = name; + var __result__ = __CreateIMGUIContainer?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.UIElements.IMGUIContainer)(__result__) : default; + } + + public void BeginRebuildContentContainers() + { + __BeginRebuildContentContainers?.Invoke(__self__, System.Array.Empty()); + } + + public void EndRebuildContentContainers() + { + __EndRebuildContentContainers?.Invoke(__self__, System.Array.Empty()); + } + + public void RebuildContentsContainers() + { + __RebuildContentsContainers?.Invoke(__self__, System.Array.Empty()); + } + + public void AutoScroll(UnityEngine.Vector2 mousePosition) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = mousePosition; + __AutoScroll?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void ScrollTo(UnityEngine.Vector2 position) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = position; + __ScrollTo?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void DragOverBottomArea(UnityEngine.UIElements.DragUpdatedEvent dragUpdatedEvent) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = dragUpdatedEvent; + __DragOverBottomArea?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void DragPerformInBottomArea(UnityEngine.UIElements.DragPerformEvent dragPerformedEvent) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = dragPerformedEvent; + __DragPerformInBottomArea?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public UnityEditor.Editor GetLastInteractedEditor() + { + var __result__ = __GetLastInteractedEditor?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (UnityEditor.Editor)(__result__) : default; + } + + public object GetEditorThatControlsPreview(Array editors) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = editors; + var __result__ = __GetEditorThatControlsPreview?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (object)(__result__) : default; + } + + public Array GetEditorsWithPreviews(UnityEditor.Editor[] editors) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = editors; + var __result__ = __GetEditorsWithPreviews?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public UnityEngine.Object GetInspectedObject() + { + var __result__ = __GetInspectedObject?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (UnityEngine.Object)(__result__) : default; + } + + public void ResetKeyboardControl() + { + __ResetKeyboardControl?.Invoke(__self__, System.Array.Empty()); + } + + public static bool HasLabel(UnityEngine.Object target) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = target; + var __result__ = __HasLabel?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool HasLabel(UnityEngine.Object target, string assetPath) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = target; + __params__[1] = assetPath; + var __result__ = __HasLabel__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public UnityEngine.Object[] GetInspectedAssets() + { + var __result__ = __GetInspectedAssets?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (UnityEngine.Object[])(__result__) : default; + } + + public bool BeginDrawPreviewAndLabels() + { + var __result__ = __BeginDrawPreviewAndLabels?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void EndDrawPreviewAndLabels(UnityEngine.Event evt, UnityEngine.Rect rect, UnityEngine.Rect dragRect) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = evt; + __params__[1] = rect; + __params__[2] = dragRect; + __EndDrawPreviewAndLabels?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void DrawPreviewAndLabels() + { + __DrawPreviewAndLabels?.Invoke(__self__, System.Array.Empty()); + } + + public void OnPreviewSelected(object userData, string[] options, int selected) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = userData; + __params__[1] = options; + __params__[2] = selected; + __OnPreviewSelected?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public static void VersionControlBar(UnityEditor.Editor assetEditor) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = assetEditor; + __VersionControlBar?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void VersionControlBar(UnityEditor.Editor[] assetEditors) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = assetEditors; + __VersionControlBar__2?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void VersionControlCheckoutHint(UnityEditor.Editor assetEditor, bool connected) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = assetEditor; + __params__[1] = connected; + __VersionControlCheckoutHint?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void CheckoutForInspector(UnityEngine.Object[] targets) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = targets; + __CheckoutForInspector?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void DoRevertUnchanged(object o) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = o; + __DoRevertUnchanged?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static float VersionControlBarButtons(object presence, UnityEngine.Rect rect, bool connected) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = presence; + __params__[1] = rect; + __params__[2] = connected; + var __result__ = __VersionControlBarButtons?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static bool VersionControlActionDropdownButton(UnityEngine.Rect buttonRect, ref float buttonX, UnityEngine.GUIContent content, UnityEngine.GUIContent[] menuNames, UnityEditor.GenericMenu.MenuFunction2[] menuActions, object context) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = buttonRect; + __params__[1] = buttonX; + __params__[2] = content; + __params__[3] = menuNames; + __params__[4] = menuActions; + __params__[5] = context; + var __result__ = __VersionControlActionDropdownButton?.Invoke(null, __params__); + buttonX = (float)(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool VersionControlActionButton(UnityEngine.Rect buttonRect, ref float buttonX, UnityEngine.GUIContent content) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = buttonRect; + __params__[1] = buttonX; + __params__[2] = content; + var __result__ = __VersionControlActionButton?.Invoke(null, __params__); + buttonX = (float)(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public void DrawEditors(UnityEditor.Editor[] editors) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = editors; + __DrawEditors?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void RestoreVerticalScrollIfNeeded() + { + __RestoreVerticalScrollIfNeeded?.Invoke(__self__, System.Array.Empty()); + } + + public void OnPrefabInstanceUnpacked(UnityEngine.GameObject unpackedPrefabInstance) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = unpackedPrefabInstance; + __OnPrefabInstanceUnpacked?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void AddRemovedPrefabComponentElement(UnityEngine.GameObject targetGameObject, UnityEngine.Component nextInSource, UnityEngine.UIElements.VisualElement element) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = targetGameObject; + __params__[1] = nextInSource; + __params__[2] = element; + __AddRemovedPrefabComponentElement?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public bool ShouldDisplayRemovedComponent(UnityEngine.GameObject go, UnityEngine.Component comp) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = go; + __params__[1] = comp; + var __result__ = __ShouldDisplayRemovedComponent?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void DisplayRemovedComponent(UnityEngine.GameObject go, UnityEngine.Component comp) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = go; + __params__[1] = comp; + __DisplayRemovedComponent?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public bool WasEditorVisible(UnityEditor.Editor[] editors, int editorIndex, UnityEngine.Object target) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = editors; + __params__[1] = editorIndex; + __params__[2] = target; + var __result__ = __WasEditorVisible?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public bool IsMultiEditingSupported(UnityEditor.Editor editor, UnityEngine.Object target) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = editor; + __params__[1] = target; + var __result__ = __IsMultiEditingSupported?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool EditorHasLargeHeader(int editorIndex, UnityEditor.Editor[] trackerActiveEditors) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = editorIndex; + __params__[1] = trackerActiveEditors; + var __result__ = __EditorHasLargeHeader?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public bool ShouldCullEditor(UnityEditor.Editor[] editors, int editorIndex) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = editors; + __params__[1] = editorIndex; + var __result__ = __ShouldCullEditor?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public void DrawSelectionPickerList() + { + __DrawSelectionPickerList?.Invoke(__self__, System.Array.Empty()); + } + + public UnityEditor.AssetImporters.AssetImporterEditor GetAssetImporter(UnityEditor.Editor[] editors) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = editors; + var __result__ = __GetAssetImporter?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEditor.AssetImporters.AssetImporterEditor)(__result__) : default; + } + + public void AddComponentButton(UnityEditor.Editor[] editors) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = editors; + __AddComponentButton?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public bool ReadyToRepaint() + { + var __result__ = __ReadyToRepaint?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void DrawSplitLine(float y) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = y; + __DrawSplitLine?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public System.Collections.IDictionary ProcessEditorElementsToRebuild(UnityEditor.Editor[] editors) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = editors; + var __result__ = __ProcessEditorElementsToRebuild?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (System.Collections.IDictionary)(__result__) : default; + } + + public static bool ValidatePropertyEditorOnSelection() + { + var __result__ = __ValidatePropertyEditorOnSelection?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void OpenPropertyEditorOnSelection() + { + __OpenPropertyEditorOnSelection?.Invoke(null, System.Array.Empty()); + } + + public static UnityEditor_PropertyEditor OpenPropertyEditor(System.Collections.Generic.IList objs) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = objs; + var __result__ = __OpenPropertyEditor?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? new UnityEditor_PropertyEditor(__result__) : default; + } + + public static UnityEditor_PropertyEditor OpenPropertyEditor(UnityEngine.Object obj, bool showWindow) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = obj; + __params__[1] = showWindow; + var __result__ = __OpenPropertyEditor__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? new UnityEditor_PropertyEditor(__result__) : default; + } + + public static void ShowPropertyEditorWindow(UnityEditor_PropertyEditor propertyEditor) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = propertyEditor.__self__; + __ShowPropertyEditorWindow?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void OpenHoveredItemPropertyEditor(UnityEditor.ShortcutManagement.ShortcutArguments args) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = args; + __OpenHoveredItemPropertyEditor?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public UnityEditor_PropertyEditor(object __self__) => this.__self__ = __self__ as UnityEngine.Object; + public UnityEngine.Object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + public UnityEditor.EditorWindow __super__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.EditorWindow)(__self__); + } + + private static FieldInfo ___k_AssetPropertiesMenuItemName; + private static FieldInfo __k_AssetPropertiesMenuItemName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___k_AssetPropertiesMenuItemName ??= __type__?.GetField("k_AssetPropertiesMenuItemName", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_MultiEditClassName; + private static FieldInfo __s_MultiEditClassName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_MultiEditClassName ??= __type__?.GetField("s_MultiEditClassName", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_EditorListClassName; + private static FieldInfo __s_EditorListClassName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_EditorListClassName ??= __type__?.GetField("s_EditorListClassName", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_AddComponentClassName; + private static FieldInfo __s_AddComponentClassName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_AddComponentClassName ??= __type__?.GetField("s_AddComponentClassName", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_HeaderInfoClassName; + private static FieldInfo __s_HeaderInfoClassName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_HeaderInfoClassName ??= __type__?.GetField("s_HeaderInfoClassName", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_FooterInfoClassName; + private static FieldInfo __s_FooterInfoClassName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_FooterInfoClassName ??= __type__?.GetField("s_FooterInfoClassName", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_MainContainerClassName; + private static FieldInfo __s_MainContainerClassName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_MainContainerClassName ??= __type__?.GetField("s_MainContainerClassName", (BindingFlags)(-1)); + } + + private static FieldInfo ___kBottomToolbarHeight; + private static FieldInfo __kBottomToolbarHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kBottomToolbarHeight ??= __type__?.GetField("kBottomToolbarHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___kAddComponentButtonHeight; + private static FieldInfo __kAddComponentButtonHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kAddComponentButtonHeight ??= __type__?.GetField("kAddComponentButtonHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___kEditorElementPaddingBottom; + private static FieldInfo __kEditorElementPaddingBottom + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kEditorElementPaddingBottom ??= __type__?.GetField("kEditorElementPaddingBottom", (BindingFlags)(-1)); + } + + private static FieldInfo ___k_MinAreaAbovePreview; + private static FieldInfo __k_MinAreaAbovePreview + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___k_MinAreaAbovePreview ??= __type__?.GetField("k_MinAreaAbovePreview", (BindingFlags)(-1)); + } + + private static FieldInfo ___k_InspectorPreviewMinHeight; + private static FieldInfo __k_InspectorPreviewMinHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___k_InspectorPreviewMinHeight ??= __type__?.GetField("k_InspectorPreviewMinHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___k_InspectorPreviewMinTotalHeight; + private static FieldInfo __k_InspectorPreviewMinTotalHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___k_InspectorPreviewMinTotalHeight ??= __type__?.GetField("k_InspectorPreviewMinTotalHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___k_MinimumRootVisualHeight; + private static FieldInfo __k_MinimumRootVisualHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___k_MinimumRootVisualHeight ??= __type__?.GetField("k_MinimumRootVisualHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___k_MinimumWindowWidth; + private static FieldInfo __k_MinimumWindowWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___k_MinimumWindowWidth ??= __type__?.GetField("k_MinimumWindowWidth", (BindingFlags)(-1)); + } + + private static FieldInfo ___k_AutoScrollZoneHeight; + private static FieldInfo __k_AutoScrollZoneHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___k_AutoScrollZoneHeight ??= __type__?.GetField("k_AutoScrollZoneHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___delayRepaintWhilePlayingAnimation; + private static FieldInfo __delayRepaintWhilePlayingAnimation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___delayRepaintWhilePlayingAnimation ??= __type__?.GetField("delayRepaintWhilePlayingAnimation", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LastUpdateWhilePlayingAnimation; + private static FieldInfo __m_LastUpdateWhilePlayingAnimation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LastUpdateWhilePlayingAnimation ??= __type__?.GetField("m_LastUpdateWhilePlayingAnimation", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ObjectsLockedBeforeSerialization; + private static FieldInfo __m_ObjectsLockedBeforeSerialization + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ObjectsLockedBeforeSerialization ??= __type__?.GetField("m_ObjectsLockedBeforeSerialization", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_InstanceIDsLockedBeforeSerialization; + private static FieldInfo __m_InstanceIDsLockedBeforeSerialization + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_InstanceIDsLockedBeforeSerialization ??= __type__?.GetField("m_InstanceIDsLockedBeforeSerialization", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_PreviewResizer; + private static FieldInfo __m_PreviewResizer + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_PreviewResizer ??= __type__?.GetField("m_PreviewResizer", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LabelGUI; + private static FieldInfo __m_LabelGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LabelGUI ??= __type__?.GetField("m_LabelGUI", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LastInspectedObjectInstanceID; + private static FieldInfo __m_LastInspectedObjectInstanceID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LastInspectedObjectInstanceID ??= __type__?.GetField("m_LastInspectedObjectInstanceID", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LastVerticalScrollValue; + private static FieldInfo __m_LastVerticalScrollValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LastVerticalScrollValue ??= __type__?.GetField("m_LastVerticalScrollValue", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_GlobalObjectId; + private static FieldInfo __m_GlobalObjectId + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_GlobalObjectId ??= __type__?.GetField("m_GlobalObjectId", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_InspectorMode; + private static FieldInfo __m_InspectorMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_InspectorMode ??= __type__?.GetField("m_InspectorMode", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_InspectedObject; + private static FieldInfo __m_InspectedObject + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_InspectedObject ??= __type__?.GetField("m_InspectedObject", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_LastPropertyEditor; + private static FieldInfo __s_LastPropertyEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LastPropertyEditor ??= __type__?.GetField("s_LastPropertyEditor", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_LastInitialEditorInstanceID; + private static FieldInfo __m_LastInitialEditorInstanceID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_LastInitialEditorInstanceID ??= __type__?.GetField("m_LastInitialEditorInstanceID", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ComponentsInPrefabSource; + private static FieldInfo __m_ComponentsInPrefabSource + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ComponentsInPrefabSource ??= __type__?.GetField("m_ComponentsInPrefabSource", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_RemovedComponents; + private static FieldInfo __m_RemovedComponents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_RemovedComponents ??= __type__?.GetField("m_RemovedComponents", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SuppressedComponents; + private static FieldInfo __m_SuppressedComponents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SuppressedComponents ??= __type__?.GetField("m_SuppressedComponents", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ResetKeyboardControl; + private static FieldInfo __m_ResetKeyboardControl + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ResetKeyboardControl ??= __type__?.GetField("m_ResetKeyboardControl", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_OpenAddComponentMenu; + private static FieldInfo __m_OpenAddComponentMenu + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_OpenAddComponentMenu ??= __type__?.GetField("m_OpenAddComponentMenu", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Tracker; + private static FieldInfo __m_Tracker + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Tracker ??= __type__?.GetField("m_Tracker", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AssetBundleNameGUI; + private static FieldInfo __m_AssetBundleNameGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AssetBundleNameGUI ??= __type__?.GetField("m_AssetBundleNameGUI", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TypeSelectionList; + private static FieldInfo __m_TypeSelectionList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TypeSelectionList ??= __type__?.GetField("m_TypeSelectionList", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_lastRenderedTime; + private static FieldInfo __m_lastRenderedTime + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_lastRenderedTime ??= __type__?.GetField("m_lastRenderedTime", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Previews; + private static FieldInfo __m_Previews + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Previews ??= __type__?.GetField("m_Previews", (BindingFlags)(-1)); + } + + private static Type ___E__m_Previews; + public static Type __E__m_Previews + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___E__m_Previews ??= EditorUtils.GetTypeByFullName("UnityEditor.IPreviewable"); + } + + private static FieldInfo ___m_PreviewableTypes; + private static FieldInfo __m_PreviewableTypes + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_PreviewableTypes ??= __type__?.GetField("m_PreviewableTypes", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SelectedPreview; + private static FieldInfo __m_SelectedPreview + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SelectedPreview ??= __type__?.GetField("m_SelectedPreview", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_EditorsElement; + private static FieldInfo __m_EditorsElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_EditorsElement ??= __type__?.GetField("m_EditorsElement", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_RemovedPrefabComponentsElement; + private static FieldInfo __m_RemovedPrefabComponentsElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_RemovedPrefabComponentsElement ??= __type__?.GetField("m_RemovedPrefabComponentsElement", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_PreviewAndLabelElement; + private static FieldInfo __m_PreviewAndLabelElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_PreviewAndLabelElement ??= __type__?.GetField("m_PreviewAndLabelElement", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_VersionControlElement; + private static FieldInfo __m_VersionControlElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_VersionControlElement ??= __type__?.GetField("m_VersionControlElement", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_VersionControlBarState; + private static FieldInfo __m_VersionControlBarState + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_VersionControlBarState ??= __type__?.GetField("m_VersionControlBarState", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MultiEditLabel; + private static FieldInfo __m_MultiEditLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MultiEditLabel ??= __type__?.GetField("m_MultiEditLabel", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ScrollView; + private static FieldInfo __m_ScrollView + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ScrollView ??= __type__?.GetField("m_ScrollView", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TrackerResetInserted; + private static FieldInfo __m_TrackerResetInserted + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TrackerResetInserted ??= __type__?.GetField("m_TrackerResetInserted", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_FirstInitialize; + private static FieldInfo __m_FirstInitialize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_FirstInitialize ??= __type__?.GetField("m_FirstInitialize", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_PreviousFooterHeight; + private static FieldInfo __m_PreviousFooterHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_PreviousFooterHeight ??= __type__?.GetField("m_PreviousFooterHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_PreviousPreviewExpandedState; + private static FieldInfo __m_PreviousPreviewExpandedState + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_PreviousPreviewExpandedState ??= __type__?.GetField("m_PreviousPreviewExpandedState", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_HasPreview; + private static FieldInfo __m_HasPreview + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_HasPreview ??= __type__?.GetField("m_HasPreview", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_DrawnSelection; + private static FieldInfo __m_DrawnSelection + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_DrawnSelection ??= __type__?.GetField("m_DrawnSelection", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_Editors; + private static FieldInfo __s_Editors + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_Editors ??= __type__?.GetField("s_Editors", (BindingFlags)(-1)); + } + + private static PropertyInfo ___editorsElement; + private static PropertyInfo __editorsElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___editorsElement ??= __type__?.GetProperty("editorsElement", (BindingFlags)(-1)); + } + + private static PropertyInfo ___previewAndLabelElement; + private static PropertyInfo __previewAndLabelElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___previewAndLabelElement ??= __type__?.GetProperty("previewAndLabelElement", (BindingFlags)(-1)); + } + + private static PropertyInfo ___versionControlElement; + private static PropertyInfo __versionControlElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___versionControlElement ??= __type__?.GetProperty("versionControlElement", (BindingFlags)(-1)); + } + + private static PropertyInfo ___parent; + private static PropertyInfo __parent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___parent ??= __type__?.GetProperty("parent", (BindingFlags)(-1)); + } + + private static PropertyInfo ___editorsWithImportedObjectLabel; + private static PropertyInfo __editorsWithImportedObjectLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___editorsWithImportedObjectLabel ??= __type__?.GetProperty("editorsWithImportedObjectLabel", (BindingFlags)(-1)); + } + + private static PropertyInfo ___editorDragging; + private static PropertyInfo __editorDragging + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___editorDragging ??= __type__?.GetProperty("editorDragging", (BindingFlags)(-1)); + } + + private static PropertyInfo ___useUIElementsDefaultInspector; + private static PropertyInfo __useUIElementsDefaultInspector + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___useUIElementsDefaultInspector ??= __type__?.GetProperty("useUIElementsDefaultInspector", (BindingFlags)(-1)); + } + + private static PropertyInfo ___lastInteractedEditor; + private static PropertyInfo __lastInteractedEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___lastInteractedEditor ??= __type__?.GetProperty("lastInteractedEditor", (BindingFlags)(-1)); + } + + private static PropertyInfo ___HoveredPropertyEditor; + private static PropertyInfo __HoveredPropertyEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HoveredPropertyEditor ??= __type__?.GetProperty("HoveredPropertyEditor", (BindingFlags)(-1)); + } + + private static PropertyInfo ___FocusedPropertyEditor; + private static PropertyInfo __FocusedPropertyEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FocusedPropertyEditor ??= __type__?.GetProperty("FocusedPropertyEditor", (BindingFlags)(-1)); + } + + private static PropertyInfo ___inspectorMode; + private static PropertyInfo __inspectorMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___inspectorMode ??= __type__?.GetProperty("inspectorMode", (BindingFlags)(-1)); + } + + private static PropertyInfo ___tracker; + private static PropertyInfo __tracker + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___tracker ??= __type__?.GetProperty("tracker", (BindingFlags)(-1)); + } + + private static PropertyInfo ___bottomAreaDropRectangle; + private static PropertyInfo __bottomAreaDropRectangle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___bottomAreaDropRectangle ??= __type__?.GetProperty("bottomAreaDropRectangle", (BindingFlags)(-1)); + } + + private static PropertyInfo ___scrollViewportRect; + private static PropertyInfo __scrollViewportRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___scrollViewportRect ??= __type__?.GetProperty("scrollViewportRect", (BindingFlags)(-1)); + } + + private static MethodInfo ___OnDestroy; + private static MethodInfo __OnDestroy + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnDestroy ??= __type__?.GetMethodInfoByParameterTypeNames("OnDestroy"); + } + + private static MethodInfo ___OnFocusChanged; + private static MethodInfo __OnFocusChanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnFocusChanged ??= __type__?.GetMethodInfoByParameterTypeNames("OnFocusChanged", "System.Boolean"); + } + + private static MethodInfo ___OnEnable; + private static MethodInfo __OnEnable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnEnable ??= __type__?.GetMethodInfoByParameterTypeNames("OnEnable"); + } + + private static MethodInfo ___OnDisable; + private static MethodInfo __OnDisable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnDisable ??= __type__?.GetMethodInfoByParameterTypeNames("OnDisable"); + } + + private static MethodInfo ___OnMouseEnter; + private static MethodInfo __OnMouseEnter + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnMouseEnter ??= __type__?.GetMethodInfoByParameterTypeNames("OnMouseEnter", "UnityEngine.UIElements.MouseEnterEvent"); + } + + private static MethodInfo ___OnMouseLeave; + private static MethodInfo __OnMouseLeave + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnMouseLeave ??= __type__?.GetMethodInfoByParameterTypeNames("OnMouseLeave", "UnityEngine.UIElements.MouseLeaveEvent"); + } + + private static MethodInfo ___OnFocusIn; + private static MethodInfo __OnFocusIn + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnFocusIn ??= __type__?.GetMethodInfoByParameterTypeNames("OnFocusIn", "UnityEngine.UIElements.FocusInEvent"); + } + + private static MethodInfo ___OnFocusOut; + private static MethodInfo __OnFocusOut + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnFocusOut ??= __type__?.GetMethodInfoByParameterTypeNames("OnFocusOut", "UnityEngine.UIElements.FocusOutEvent"); + } + + private static MethodInfo ___OnLostFocus; + private static MethodInfo __OnLostFocus + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnLostFocus ??= __type__?.GetMethodInfoByParameterTypeNames("OnLostFocus"); + } + + private static MethodInfo ___CloseIfEmpty; + private static MethodInfo __CloseIfEmpty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CloseIfEmpty ??= __type__?.GetMethodInfoByParameterTypeNames("CloseIfEmpty"); + } + + private static MethodInfo ___OnInspectorUpdate; + private static MethodInfo __OnInspectorUpdate + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnInspectorUpdate ??= __type__?.GetMethodInfoByParameterTypeNames("OnInspectorUpdate"); + } + + private static MethodInfo ___OnGUI; + private static MethodInfo __OnGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnGUI"); + } + + private static MethodInfo ___Update; + private static MethodInfo __Update + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Update ??= __type__?.GetMethodInfoByParameterTypeNames("Update"); + } + + private static MethodInfo ___SetMode; + private static MethodInfo __SetMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetMode ??= __type__?.GetMethodInfoByParameterTypeNames("SetMode", "UnityEditor.InspectorMode"); + } + + private static MethodInfo ___SetTitle; + private static MethodInfo __SetTitle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetTitle ??= __type__?.GetMethodInfoByParameterTypeNames("SetTitle", "UnityEngine.Object"); + } + + private static MethodInfo ___RefreshTitle; + private static MethodInfo __RefreshTitle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RefreshTitle ??= __type__?.GetMethodInfoByParameterTypeNames("RefreshTitle"); + } + + private static MethodInfo ___FindVisualElementInTreeByClassName; + private static MethodInfo __FindVisualElementInTreeByClassName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FindVisualElementInTreeByClassName ??= __type__?.GetMethodInfoByParameterTypeNames("FindVisualElementInTreeByClassName", "System.String"); + } + + private static MethodInfo ___ClearVersionControlBarState; + private static MethodInfo __ClearVersionControlBarState + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ClearVersionControlBarState ??= __type__?.GetMethodInfoByParameterTypeNames("ClearVersionControlBarState"); + } + + private static MethodInfo ___LoadVisualTreeFromUxml; + private static MethodInfo __LoadVisualTreeFromUxml + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoadVisualTreeFromUxml ??= __type__?.GetMethodInfoByParameterTypeNames("LoadVisualTreeFromUxml"); + } + + private static MethodInfo ___OnGeometryChanged; + private static MethodInfo __OnGeometryChanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnGeometryChanged ??= __type__?.GetMethodInfoByParameterTypeNames("OnGeometryChanged", "UnityEngine.UIElements.GeometryChangedEvent"); + } + + private static MethodInfo ___SetUseUIEDefaultInspector; + private static MethodInfo __SetUseUIEDefaultInspector + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetUseUIEDefaultInspector ??= __type__?.GetMethodInfoByParameterTypeNames("SetUseUIEDefaultInspector"); + } + + private static MethodInfo ___SetDebug; + private static MethodInfo __SetDebug + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetDebug ??= __type__?.GetMethodInfoByParameterTypeNames("SetDebug"); + } + + private static MethodInfo ___SetNormal; + private static MethodInfo __SetNormal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetNormal ??= __type__?.GetMethodInfoByParameterTypeNames("SetNormal"); + } + + private static MethodInfo ___SetDebugInternal; + private static MethodInfo __SetDebugInternal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetDebugInternal ??= __type__?.GetMethodInfoByParameterTypeNames("SetDebugInternal"); + } + + private static MethodInfo ___AddDebugItemsToMenu; + private static MethodInfo __AddDebugItemsToMenu + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AddDebugItemsToMenu ??= __type__?.GetMethodInfoByParameterTypeNames("AddDebugItemsToMenu", "UnityEditor.GenericMenu"); + } + + private static MethodInfo ___AddItemsToMenu; + private static MethodInfo __AddItemsToMenu + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AddItemsToMenu ??= __type__?.GetMethodInfoByParameterTypeNames("AddItemsToMenu", "UnityEditor.GenericMenu"); + } + + private static MethodInfo ___SetTrackerExpandedState; + private static MethodInfo __SetTrackerExpandedState + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetTrackerExpandedState ??= __type__?.GetMethodInfoByParameterTypeNames("SetTrackerExpandedState", "UnityEditor.ActiveEditorTracker", "System.Int32", "System.Boolean"); + } + + private static MethodInfo ___ExpandAllComponents; + private static MethodInfo __ExpandAllComponents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ExpandAllComponents ??= __type__?.GetMethodInfoByParameterTypeNames("ExpandAllComponents"); + } + + private static MethodInfo ___IsAnyComponentCollapsed; + private static MethodInfo __IsAnyComponentCollapsed + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsAnyComponentCollapsed ??= __type__?.GetMethodInfoByParameterTypeNames("IsAnyComponentCollapsed"); + } + + private static MethodInfo ___CollapseAllComponents; + private static MethodInfo __CollapseAllComponents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CollapseAllComponents ??= __type__?.GetMethodInfoByParameterTypeNames("CollapseAllComponents"); + } + + private static MethodInfo ___IsAnyComponentExpanded; + private static MethodInfo __IsAnyComponentExpanded + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsAnyComponentExpanded ??= __type__?.GetMethodInfoByParameterTypeNames("IsAnyComponentExpanded"); + } + + private static MethodInfo ___LoadPersistedObject; + private static MethodInfo __LoadPersistedObject + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoadPersistedObject ??= __type__?.GetMethodInfoByParameterTypeNames("LoadPersistedObject"); + } + + private static MethodInfo ___CreateTracker; + private static MethodInfo __CreateTracker + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CreateTracker ??= __type__?.GetMethodInfoByParameterTypeNames("CreateTracker"); + } + + private static MethodInfo ___OnTrackerRebuilt; + private static MethodInfo __OnTrackerRebuilt + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnTrackerRebuilt ??= __type__?.GetMethodInfoByParameterTypeNames("OnTrackerRebuilt"); + } + + private static MethodInfo ___OnObjectChanged; + private static MethodInfo __OnObjectChanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnObjectChanged ??= __type__?.GetMethodInfoByParameterTypeNames("OnObjectChanged", "UnityEditor.ChangeGameObjectOrComponentPropertiesEventArgs"); + } + + private static MethodInfo ___OnObjectChanged__2; + private static MethodInfo __OnObjectChanged__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnObjectChanged__2 ??= __type__?.GetMethodInfoByParameterTypeNames("OnObjectChanged", "UnityEditor.ObjectChangeEventStream&"); + } + + private static MethodInfo ___UpdateWindowObjectNameTitle; + private static MethodInfo __UpdateWindowObjectNameTitle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UpdateWindowObjectNameTitle ??= __type__?.GetMethodInfoByParameterTypeNames("UpdateWindowObjectNameTitle"); + } + + private static MethodInfo ___OnUndoRedoPerformed; + private static MethodInfo __OnUndoRedoPerformed + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnUndoRedoPerformed ??= __type__?.GetMethodInfoByParameterTypeNames("OnUndoRedoPerformed"); + } + + private static MethodInfo ___ExtractPrefabComponents; + private static MethodInfo __ExtractPrefabComponents + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ExtractPrefabComponents ??= __type__?.GetMethodInfoByParameterTypeNames("ExtractPrefabComponents"); + } + + private static MethodInfo ___CreatePreviewables; + private static MethodInfo __CreatePreviewables + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CreatePreviewables ??= __type__?.GetMethodInfoByParameterTypeNames("CreatePreviewables"); + } + + private static MethodInfo ___ClearPreviewables; + private static MethodInfo __ClearPreviewables + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ClearPreviewables ??= __type__?.GetMethodInfoByParameterTypeNames("ClearPreviewables"); + } + + private static MethodInfo ___GetPreviewableTypes; + private static MethodInfo __GetPreviewableTypes + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPreviewableTypes ??= __type__?.GetMethodInfoByParameterTypeNames("GetPreviewableTypes"); + } + + private static MethodInfo ___GetPreviewsForType; + private static MethodInfo __GetPreviewsForType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPreviewsForType ??= __type__?.GetMethodInfoByParameterTypeNames("GetPreviewsForType", "UnityEditor.Editor"); + } + + private static MethodInfo ___ClearTrackerDirtyOnRepaint; + private static MethodInfo __ClearTrackerDirtyOnRepaint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ClearTrackerDirtyOnRepaint ??= __type__?.GetMethodInfoByParameterTypeNames("ClearTrackerDirtyOnRepaint"); + } + + private static MethodInfo ___CreateIMGUIContainer; + private static MethodInfo __CreateIMGUIContainer + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CreateIMGUIContainer ??= __type__?.GetMethodInfoByParameterTypeNames("CreateIMGUIContainer", "System.Action", "System.String"); + } + + private static MethodInfo ___BeginRebuildContentContainers; + private static MethodInfo __BeginRebuildContentContainers + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginRebuildContentContainers ??= __type__?.GetMethodInfoByParameterTypeNames("BeginRebuildContentContainers"); + } + + private static MethodInfo ___EndRebuildContentContainers; + private static MethodInfo __EndRebuildContentContainers + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EndRebuildContentContainers ??= __type__?.GetMethodInfoByParameterTypeNames("EndRebuildContentContainers"); + } + + private static MethodInfo ___RebuildContentsContainers; + private static MethodInfo __RebuildContentsContainers + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RebuildContentsContainers ??= __type__?.GetMethodInfoByParameterTypeNames("RebuildContentsContainers"); + } + + private static MethodInfo ___AutoScroll; + private static MethodInfo __AutoScroll + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AutoScroll ??= __type__?.GetMethodInfoByParameterTypeNames("AutoScroll", "UnityEngine.Vector2"); + } + + private static MethodInfo ___ScrollTo; + private static MethodInfo __ScrollTo + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ScrollTo ??= __type__?.GetMethodInfoByParameterTypeNames("ScrollTo", "UnityEngine.Vector2"); + } + + private static MethodInfo ___DragOverBottomArea; + private static MethodInfo __DragOverBottomArea + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DragOverBottomArea ??= __type__?.GetMethodInfoByParameterTypeNames("DragOverBottomArea", "UnityEngine.UIElements.DragUpdatedEvent"); + } + + private static MethodInfo ___DragPerformInBottomArea; + private static MethodInfo __DragPerformInBottomArea + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DragPerformInBottomArea ??= __type__?.GetMethodInfoByParameterTypeNames("DragPerformInBottomArea", "UnityEngine.UIElements.DragPerformEvent"); + } + + private static MethodInfo ___GetLastInteractedEditor; + private static MethodInfo __GetLastInteractedEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetLastInteractedEditor ??= __type__?.GetMethodInfoByParameterTypeNames("GetLastInteractedEditor"); + } + + private static MethodInfo ___GetEditorThatControlsPreview; + private static MethodInfo __GetEditorThatControlsPreview + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetEditorThatControlsPreview ??= __type__?.GetMethodInfoByParameterTypeNames("GetEditorThatControlsPreview", "UnityEditor.IPreviewable[]"); + } + + private static MethodInfo ___GetEditorsWithPreviews; + private static MethodInfo __GetEditorsWithPreviews + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetEditorsWithPreviews ??= __type__?.GetMethodInfoByParameterTypeNames("GetEditorsWithPreviews", "UnityEditor.Editor[]"); + } + + private static MethodInfo ___GetInspectedObject; + private static MethodInfo __GetInspectedObject + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetInspectedObject ??= __type__?.GetMethodInfoByParameterTypeNames("GetInspectedObject"); + } + + private static MethodInfo ___ResetKeyboardControl; + private static MethodInfo __ResetKeyboardControl + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ResetKeyboardControl ??= __type__?.GetMethodInfoByParameterTypeNames("ResetKeyboardControl"); + } + + private static MethodInfo ___HasLabel; + private static MethodInfo __HasLabel + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasLabel ??= __type__?.GetMethodInfoByParameterTypeNames("HasLabel", "UnityEngine.Object"); + } + + private static MethodInfo ___HasLabel__2; + private static MethodInfo __HasLabel__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasLabel__2 ??= __type__?.GetMethodInfoByParameterTypeNames("HasLabel", "UnityEngine.Object", "System.String"); + } + + private static MethodInfo ___GetInspectedAssets; + private static MethodInfo __GetInspectedAssets + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetInspectedAssets ??= __type__?.GetMethodInfoByParameterTypeNames("GetInspectedAssets"); + } + + private static MethodInfo ___BeginDrawPreviewAndLabels; + private static MethodInfo __BeginDrawPreviewAndLabels + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginDrawPreviewAndLabels ??= __type__?.GetMethodInfoByParameterTypeNames("BeginDrawPreviewAndLabels"); + } + + private static MethodInfo ___EndDrawPreviewAndLabels; + private static MethodInfo __EndDrawPreviewAndLabels + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EndDrawPreviewAndLabels ??= __type__?.GetMethodInfoByParameterTypeNames("EndDrawPreviewAndLabels", "UnityEngine.Event", "UnityEngine.Rect", "UnityEngine.Rect"); + } + + private static MethodInfo ___DrawPreviewAndLabels; + private static MethodInfo __DrawPreviewAndLabels + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawPreviewAndLabels ??= __type__?.GetMethodInfoByParameterTypeNames("DrawPreviewAndLabels"); + } + + private static MethodInfo ___OnPreviewSelected; + private static MethodInfo __OnPreviewSelected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnPreviewSelected ??= __type__?.GetMethodInfoByParameterTypeNames("OnPreviewSelected", "System.Object", "System.String[]", "System.Int32"); + } + + private static MethodInfo ___VersionControlBar; + private static MethodInfo __VersionControlBar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___VersionControlBar ??= __type__?.GetMethodInfoByParameterTypeNames("VersionControlBar", "UnityEditor.Editor"); + } + + private static MethodInfo ___VersionControlBar__2; + private static MethodInfo __VersionControlBar__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___VersionControlBar__2 ??= __type__?.GetMethodInfoByParameterTypeNames("VersionControlBar", "UnityEditor.Editor[]"); + } + + private static MethodInfo ___VersionControlCheckoutHint; + private static MethodInfo __VersionControlCheckoutHint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___VersionControlCheckoutHint ??= __type__?.GetMethodInfoByParameterTypeNames("VersionControlCheckoutHint", "UnityEditor.Editor", "System.Boolean"); + } + + private static MethodInfo ___CheckoutForInspector; + private static MethodInfo __CheckoutForInspector + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CheckoutForInspector ??= __type__?.GetMethodInfoByParameterTypeNames("CheckoutForInspector", "UnityEngine.Object[]"); + } + + private static MethodInfo ___DoRevertUnchanged; + private static MethodInfo __DoRevertUnchanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoRevertUnchanged ??= __type__?.GetMethodInfoByParameterTypeNames("DoRevertUnchanged", "System.Object"); + } + + private static MethodInfo ___VersionControlBarButtons; + private static MethodInfo __VersionControlBarButtons + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___VersionControlBarButtons ??= __type__?.GetMethodInfoByParameterTypeNames("VersionControlBarButtons", "UnityEditor.PropertyEditor+VersionControlBarState", "UnityEngine.Rect", "System.Boolean"); + } + + private static MethodInfo ___VersionControlActionDropdownButton; + private static MethodInfo __VersionControlActionDropdownButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___VersionControlActionDropdownButton ??= __type__?.GetMethodInfoByParameterTypeNames("VersionControlActionDropdownButton", "UnityEngine.Rect", "System.Single&", "UnityEngine.GUIContent", "UnityEngine.GUIContent[]", "UnityEditor.GenericMenu+MenuFunction2[]", "System.Object"); + } + + private static MethodInfo ___VersionControlActionButton; + private static MethodInfo __VersionControlActionButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___VersionControlActionButton ??= __type__?.GetMethodInfoByParameterTypeNames("VersionControlActionButton", "UnityEngine.Rect", "System.Single&", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___DrawEditors; + private static MethodInfo __DrawEditors + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawEditors ??= __type__?.GetMethodInfoByParameterTypeNames("DrawEditors", "UnityEditor.Editor[]"); + } + + private static MethodInfo ___RestoreVerticalScrollIfNeeded; + private static MethodInfo __RestoreVerticalScrollIfNeeded + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RestoreVerticalScrollIfNeeded ??= __type__?.GetMethodInfoByParameterTypeNames("RestoreVerticalScrollIfNeeded"); + } + + private static MethodInfo ___OnPrefabInstanceUnpacked; + private static MethodInfo __OnPrefabInstanceUnpacked + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnPrefabInstanceUnpacked ??= __type__?.GetMethodInfoByParameterTypeNames("OnPrefabInstanceUnpacked", "UnityEngine.GameObject"); + } + + private static MethodInfo ___AddRemovedPrefabComponentElement; + private static MethodInfo __AddRemovedPrefabComponentElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AddRemovedPrefabComponentElement ??= __type__?.GetMethodInfoByParameterTypeNames("AddRemovedPrefabComponentElement", "UnityEngine.GameObject", "UnityEngine.Component", "UnityEngine.UIElements.VisualElement"); + } + + private static MethodInfo ___ShouldDisplayRemovedComponent; + private static MethodInfo __ShouldDisplayRemovedComponent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShouldDisplayRemovedComponent ??= __type__?.GetMethodInfoByParameterTypeNames("ShouldDisplayRemovedComponent", "UnityEngine.GameObject", "UnityEngine.Component"); + } + + private static MethodInfo ___DisplayRemovedComponent; + private static MethodInfo __DisplayRemovedComponent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DisplayRemovedComponent ??= __type__?.GetMethodInfoByParameterTypeNames("DisplayRemovedComponent", "UnityEngine.GameObject", "UnityEngine.Component"); + } + + private static MethodInfo ___WasEditorVisible; + private static MethodInfo __WasEditorVisible + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___WasEditorVisible ??= __type__?.GetMethodInfoByParameterTypeNames("WasEditorVisible", "UnityEditor.Editor[]", "System.Int32", "UnityEngine.Object"); + } + + private static MethodInfo ___IsMultiEditingSupported; + private static MethodInfo __IsMultiEditingSupported + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsMultiEditingSupported ??= __type__?.GetMethodInfoByParameterTypeNames("IsMultiEditingSupported", "UnityEditor.Editor", "UnityEngine.Object"); + } + + private static MethodInfo ___EditorHasLargeHeader; + private static MethodInfo __EditorHasLargeHeader + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EditorHasLargeHeader ??= __type__?.GetMethodInfoByParameterTypeNames("EditorHasLargeHeader", "System.Int32", "UnityEditor.Editor[]"); + } + + private static MethodInfo ___ShouldCullEditor; + private static MethodInfo __ShouldCullEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShouldCullEditor ??= __type__?.GetMethodInfoByParameterTypeNames("ShouldCullEditor", "UnityEditor.Editor[]", "System.Int32"); + } + + private static MethodInfo ___DrawSelectionPickerList; + private static MethodInfo __DrawSelectionPickerList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawSelectionPickerList ??= __type__?.GetMethodInfoByParameterTypeNames("DrawSelectionPickerList"); + } + + private static MethodInfo ___GetAssetImporter; + private static MethodInfo __GetAssetImporter + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetAssetImporter ??= __type__?.GetMethodInfoByParameterTypeNames("GetAssetImporter", "UnityEditor.Editor[]"); + } + + private static MethodInfo ___AddComponentButton; + private static MethodInfo __AddComponentButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AddComponentButton ??= __type__?.GetMethodInfoByParameterTypeNames("AddComponentButton", "UnityEditor.Editor[]"); + } + + private static MethodInfo ___ReadyToRepaint; + private static MethodInfo __ReadyToRepaint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ReadyToRepaint ??= __type__?.GetMethodInfoByParameterTypeNames("ReadyToRepaint"); + } + + private static MethodInfo ___DrawSplitLine; + private static MethodInfo __DrawSplitLine + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawSplitLine ??= __type__?.GetMethodInfoByParameterTypeNames("DrawSplitLine", "System.Single"); + } + + private static MethodInfo ___ProcessEditorElementsToRebuild; + private static MethodInfo __ProcessEditorElementsToRebuild + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ProcessEditorElementsToRebuild ??= __type__?.GetMethodInfoByParameterTypeNames("ProcessEditorElementsToRebuild", "UnityEditor.Editor[]"); + } + + private static MethodInfo ___ValidatePropertyEditorOnSelection; + private static MethodInfo __ValidatePropertyEditorOnSelection + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ValidatePropertyEditorOnSelection ??= __type__?.GetMethodInfoByParameterTypeNames("ValidatePropertyEditorOnSelection"); + } + + private static MethodInfo ___OpenPropertyEditorOnSelection; + private static MethodInfo __OpenPropertyEditorOnSelection + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OpenPropertyEditorOnSelection ??= __type__?.GetMethodInfoByParameterTypeNames("OpenPropertyEditorOnSelection"); + } + + private static MethodInfo ___OpenPropertyEditor; + private static MethodInfo __OpenPropertyEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OpenPropertyEditor ??= __type__?.GetMethodInfoByParameterTypeNames("OpenPropertyEditor", "System.Collections.Generic.IList`1[[UnityEngine.Object, UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]"); + } + + private static MethodInfo ___OpenPropertyEditor__2; + private static MethodInfo __OpenPropertyEditor__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OpenPropertyEditor__2 ??= __type__?.GetMethodInfoByParameterTypeNames("OpenPropertyEditor", "UnityEngine.Object", "System.Boolean"); + } + + private static MethodInfo ___ShowPropertyEditorWindow; + private static MethodInfo __ShowPropertyEditorWindow + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShowPropertyEditorWindow ??= __type__?.GetMethodInfoByParameterTypeNames("ShowPropertyEditorWindow", "UnityEditor.PropertyEditor"); + } + + private static MethodInfo ___OpenHoveredItemPropertyEditor; + private static MethodInfo __OpenHoveredItemPropertyEditor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OpenHoveredItemPropertyEditor ??= __type__?.GetMethodInfoByParameterTypeNames("OpenHoveredItemPropertyEditor", "UnityEditor.ShortcutManagement.ShortcutArguments"); + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_PropertyEditor.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_PropertyEditor.cs.meta new file mode 100644 index 0000000..61aeb42 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_PropertyEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b5419be08e989044e88c0c26a56da2ef +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextCore_LowLevel_FontEngineEditorUtilities.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextCore_LowLevel_FontEngineEditorUtilities.cs new file mode 100644 index 0000000..682b9e3 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextCore_LowLevel_FontEngineEditorUtilities.cs @@ -0,0 +1,42 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_TextCore_LowLevel_FontEngineEditorUtilities + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.TextCore.LowLevel.FontEngineEditorUtilities"); + + + public static void SetAtlasTextureIsReadable(UnityEngine.Texture2D texture, bool isReadable) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = texture; + __params__[1] = isReadable; + __SetAtlasTextureIsReadable?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public UnityEditor_TextCore_LowLevel_FontEngineEditorUtilities(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + + private static MethodInfo ___SetAtlasTextureIsReadable; + private static MethodInfo __SetAtlasTextureIsReadable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetAtlasTextureIsReadable ??= __type__?.GetMethodInfoByParameterTypeNames("SetAtlasTextureIsReadable", "UnityEngine.Texture2D", "System.Boolean"); + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextCore_LowLevel_FontEngineEditorUtilities.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextCore_LowLevel_FontEngineEditorUtilities.cs.meta new file mode 100644 index 0000000..d149925 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextCore_LowLevel_FontEngineEditorUtilities.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 199b636c837e74041a21c33491fd0010 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextureImportPlatformSettings.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextureImportPlatformSettings.cs new file mode 100644 index 0000000..7484f44 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextureImportPlatformSettings.cs @@ -0,0 +1,296 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_TextureImportPlatformSettings + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.TextureImportPlatformSettings"); + + + public UnityEditor.TextureImporter[] importers + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.TextureImporter[])(__importers?.GetValue(__self__)); + } + + public UnityEditor_TextureImportPlatformSettingsData model + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_TextureImportPlatformSettingsData(__model?.GetValue(__self__)); + } + + public bool textureTypeHasMultipleDifferentValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__textureTypeHasMultipleDifferentValues?.GetValue(__self__)); + } + + public UnityEditor.TextureImporterType textureType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.TextureImporterType)(__textureType?.GetValue(__self__)); + } + + public UnityEditor.SpriteImportMode spriteImportMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SpriteImportMode)(__spriteImportMode?.GetValue(__self__)); + } + + public UnityEditor.TextureImporter[] m_Importers + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.TextureImporter[])(__m_Importers?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Importers?.SetValue(__self__, value); + } + + public UnityEditor_TextureImporterInspector m_Inspector + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_TextureImporterInspector(__m_Inspector?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Inspector?.SetValue(__self__, value.__self__); + } + + public UnityEditor_TextureImportPlatformSettingsData m_Data + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_TextureImportPlatformSettingsData(__m_Data?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Data?.SetValue(__self__, value.__self__); + } + + public static int[] kAndroidETC2FallbackOverrideValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int[])(__kAndroidETC2FallbackOverrideValues?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kAndroidETC2FallbackOverrideValues?.SetValue(null, value); + } + + public void CacheSerializedProperties(UnityEditor.SerializedProperty platformSettingsArray) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = platformSettingsArray; + __CacheSerializedProperties?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public int GetTargetCount() + { + var __result__ = __GetTargetCount?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public bool ShowPresetSettings() + { + var __result__ = __ShowPresetSettings?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public UnityEditor.TextureImporterSettings GetImporterSettings(int i) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = i; + var __result__ = __GetImporterSettings?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEditor.TextureImporterSettings)(__result__) : default; + } + + public bool IsSourceTextureHDR(int i) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = i; + var __result__ = __IsSourceTextureHDR?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public bool DoesSourceTextureHaveAlpha(int i) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = i; + var __result__ = __DoesSourceTextureHaveAlpha?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public UnityEditor.TextureImporterPlatformSettings GetPlatformTextureSettings(int i, string name) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = i; + __params__[1] = name; + var __result__ = __GetPlatformTextureSettings?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEditor.TextureImporterPlatformSettings)(__result__) : default; + } + + public UnityEditor_BaseTextureImportPlatformSettings GetDefaultImportSettings() + { + var __result__ = __GetDefaultImportSettings?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? new UnityEditor_BaseTextureImportPlatformSettings(__result__) : default; + } + + public void SetPlatformTextureSettings(int i, UnityEditor.TextureImporterPlatformSettings platformSettings) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = i; + __params__[1] = platformSettings; + __SetPlatformTextureSettings?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public UnityEditor_TextureImportPlatformSettings(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + public UnityEditor_BaseTextureImportPlatformSettings __super__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => new UnityEditor_BaseTextureImportPlatformSettings(__self__); + } + + private static FieldInfo ___m_Importers; + private static FieldInfo __m_Importers + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Importers ??= __type__?.GetField("m_Importers", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Inspector; + private static FieldInfo __m_Inspector + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Inspector ??= __type__?.GetField("m_Inspector", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Data; + private static FieldInfo __m_Data + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Data ??= __type__?.GetField("m_Data", (BindingFlags)(-1)); + } + + private static FieldInfo ___kAndroidETC2FallbackOverrideValues; + private static FieldInfo __kAndroidETC2FallbackOverrideValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kAndroidETC2FallbackOverrideValues ??= __type__?.GetField("kAndroidETC2FallbackOverrideValues", (BindingFlags)(-1)); + } + + private static PropertyInfo ___importers; + private static PropertyInfo __importers + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___importers ??= __type__?.GetProperty("importers", (BindingFlags)(-1)); + } + + private static PropertyInfo ___model; + private static PropertyInfo __model + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___model ??= __type__?.GetProperty("model", (BindingFlags)(-1)); + } + + private static PropertyInfo ___textureTypeHasMultipleDifferentValues; + private static PropertyInfo __textureTypeHasMultipleDifferentValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___textureTypeHasMultipleDifferentValues ??= __type__?.GetProperty("textureTypeHasMultipleDifferentValues", (BindingFlags)(-1)); + } + + private static PropertyInfo ___textureType; + private static PropertyInfo __textureType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___textureType ??= __type__?.GetProperty("textureType", (BindingFlags)(-1)); + } + + private static PropertyInfo ___spriteImportMode; + private static PropertyInfo __spriteImportMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___spriteImportMode ??= __type__?.GetProperty("spriteImportMode", (BindingFlags)(-1)); + } + + private static MethodInfo ___CacheSerializedProperties; + private static MethodInfo __CacheSerializedProperties + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CacheSerializedProperties ??= __type__?.GetMethodInfoByParameterTypeNames("CacheSerializedProperties", "UnityEditor.SerializedProperty"); + } + + private static MethodInfo ___GetTargetCount; + private static MethodInfo __GetTargetCount + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetTargetCount ??= __type__?.GetMethodInfoByParameterTypeNames("GetTargetCount"); + } + + private static MethodInfo ___ShowPresetSettings; + private static MethodInfo __ShowPresetSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShowPresetSettings ??= __type__?.GetMethodInfoByParameterTypeNames("ShowPresetSettings"); + } + + private static MethodInfo ___GetImporterSettings; + private static MethodInfo __GetImporterSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetImporterSettings ??= __type__?.GetMethodInfoByParameterTypeNames("GetImporterSettings", "System.Int32"); + } + + private static MethodInfo ___IsSourceTextureHDR; + private static MethodInfo __IsSourceTextureHDR + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsSourceTextureHDR ??= __type__?.GetMethodInfoByParameterTypeNames("IsSourceTextureHDR", "System.Int32"); + } + + private static MethodInfo ___DoesSourceTextureHaveAlpha; + private static MethodInfo __DoesSourceTextureHaveAlpha + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoesSourceTextureHaveAlpha ??= __type__?.GetMethodInfoByParameterTypeNames("DoesSourceTextureHaveAlpha", "System.Int32"); + } + + private static MethodInfo ___GetPlatformTextureSettings; + private static MethodInfo __GetPlatformTextureSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPlatformTextureSettings ??= __type__?.GetMethodInfoByParameterTypeNames("GetPlatformTextureSettings", "System.Int32", "System.String"); + } + + private static MethodInfo ___GetDefaultImportSettings; + private static MethodInfo __GetDefaultImportSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetDefaultImportSettings ??= __type__?.GetMethodInfoByParameterTypeNames("GetDefaultImportSettings"); + } + + private static MethodInfo ___SetPlatformTextureSettings; + private static MethodInfo __SetPlatformTextureSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetPlatformTextureSettings ??= __type__?.GetMethodInfoByParameterTypeNames("SetPlatformTextureSettings", "System.Int32", "UnityEditor.TextureImporterPlatformSettings"); + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextureImportPlatformSettings.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextureImportPlatformSettings.cs.meta new file mode 100644 index 0000000..dd90fed --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextureImportPlatformSettings.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2c0f4354fe96f624d8ffc6f5a3b4aac2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextureImportPlatformSettingsData.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextureImportPlatformSettingsData.cs new file mode 100644 index 0000000..572b8d9 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextureImportPlatformSettingsData.cs @@ -0,0 +1,904 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_TextureImportPlatformSettingsData + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.TextureImportPlatformSettingsData"); + + + public UnityEditor.TextureImporterPlatformSettings platformTextureSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.TextureImporterPlatformSettings)(__platformTextureSettings?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __platformTextureSettings?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty platformTextureSettingsProp + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__platformTextureSettingsProp?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __platformTextureSettingsProp?.SetValue(__self__, value); + } + + public bool overriddenIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__overriddenIsDifferent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __overriddenIsDifferent?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty overriddenProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__overriddenProperty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __overriddenProperty?.SetValue(__self__, value); + } + + public bool allAreOverridden + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__allAreOverridden?.GetValue(__self__)); + } + + public bool isDefault + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__isDefault?.GetValue(__self__)); + } + + public bool maxTextureSizeIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__maxTextureSizeIsDifferent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __maxTextureSizeIsDifferent?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty maxTextureSizeProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__maxTextureSizeProperty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __maxTextureSizeProperty?.SetValue(__self__, value); + } + + public bool resizeAlgorithmIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__resizeAlgorithmIsDifferent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __resizeAlgorithmIsDifferent?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty resizeAlgorithmProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__resizeAlgorithmProperty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __resizeAlgorithmProperty?.SetValue(__self__, value); + } + + public bool textureCompressionIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__textureCompressionIsDifferent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __textureCompressionIsDifferent?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty textureCompressionProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__textureCompressionProperty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __textureCompressionProperty?.SetValue(__self__, value); + } + + public bool compressionQualityIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__compressionQualityIsDifferent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __compressionQualityIsDifferent?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty compressionQualityProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__compressionQualityProperty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __compressionQualityProperty?.SetValue(__self__, value); + } + + public bool crunchedCompressionIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__crunchedCompressionIsDifferent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __crunchedCompressionIsDifferent?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty crunchedCompressionProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__crunchedCompressionProperty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __crunchedCompressionProperty?.SetValue(__self__, value); + } + + public bool textureFormatIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__textureFormatIsDifferent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __textureFormatIsDifferent?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty textureFormatProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__textureFormatProperty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __textureFormatProperty?.SetValue(__self__, value); + } + + public bool allowsAlphaSplitIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__allowsAlphaSplitIsDifferent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __allowsAlphaSplitIsDifferent?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty alphaSplitProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__alphaSplitProperty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __alphaSplitProperty?.SetValue(__self__, value); + } + + public bool androidETC2FallbackOverrideIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__androidETC2FallbackOverrideIsDifferent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __androidETC2FallbackOverrideIsDifferent?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty androidETC2FallbackOverrideProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__androidETC2FallbackOverrideProperty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __androidETC2FallbackOverrideProperty?.SetValue(__self__, value); + } + + public UnityEditor.BuildTarget buildTarget + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.BuildTarget)(__buildTarget?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __buildTarget?.SetValue(__self__, value); + } + + public bool forceMaximumCompressionQuality_BC6H_BC7 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__forceMaximumCompressionQuality_BC6H_BC7?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __forceMaximumCompressionQuality_BC6H_BC7?.SetValue(__self__, value); + } + + public UnityEditor.TextureImporterPlatformSettings m_PlatformSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.TextureImporterPlatformSettings)(__m_PlatformSettings?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_PlatformSettings?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_SerializedPlatformSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_SerializedPlatformSettings?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SerializedPlatformSettings?.SetValue(__self__, value); + } + + public bool m_OverriddenIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_OverriddenIsDifferent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_OverriddenIsDifferent?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_OverriddenProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_OverriddenProperty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_OverriddenProperty?.SetValue(__self__, value); + } + + public bool m_MaxTextureSizeIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_MaxTextureSizeIsDifferent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MaxTextureSizeIsDifferent?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_MaxTextureSizeProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_MaxTextureSizeProperty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MaxTextureSizeProperty?.SetValue(__self__, value); + } + + public bool m_ResizeAlgorithmIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_ResizeAlgorithmIsDifferent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ResizeAlgorithmIsDifferent?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_ResizeAlgorithmProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_ResizeAlgorithmProperty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ResizeAlgorithmProperty?.SetValue(__self__, value); + } + + public bool m_TextureCompressionIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_TextureCompressionIsDifferent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TextureCompressionIsDifferent?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_TextureCompressionProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_TextureCompressionProperty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TextureCompressionProperty?.SetValue(__self__, value); + } + + public bool m_CompressionQualityIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_CompressionQualityIsDifferent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_CompressionQualityIsDifferent?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_CompressionQualityProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_CompressionQualityProperty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_CompressionQualityProperty?.SetValue(__self__, value); + } + + public bool m_CrunchedCompressionIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_CrunchedCompressionIsDifferent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_CrunchedCompressionIsDifferent?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_CrunchedCompressionProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_CrunchedCompressionProperty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_CrunchedCompressionProperty?.SetValue(__self__, value); + } + + public bool m_TextureFormatIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_TextureFormatIsDifferent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TextureFormatIsDifferent?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_TextureFormatProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_TextureFormatProperty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TextureFormatProperty?.SetValue(__self__, value); + } + + public bool m_AlphaSplitIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_AlphaSplitIsDifferent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AlphaSplitIsDifferent?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_AlphaSplitProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_AlphaSplitProperty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AlphaSplitProperty?.SetValue(__self__, value); + } + + public bool m_AndroidETC2FallbackOverrideIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_AndroidETC2FallbackOverrideIsDifferent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AndroidETC2FallbackOverrideIsDifferent?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_AndroidETC2FallbackOverrideProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_AndroidETC2FallbackOverrideProperty?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AndroidETC2FallbackOverrideProperty?.SetValue(__self__, value); + } + + public UnityEditor.BuildTarget m_Target + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.BuildTarget)(__m_Target?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Target?.SetValue(__self__, value); + } + + public bool m_HasChanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_HasChanged?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_HasChanged?.SetValue(__self__, value); + } + + public void SetAndroidETC2FallbackOverrideForAll(UnityEditor.AndroidETC2FallbackOverride value) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = value; + __SetAndroidETC2FallbackOverrideForAll?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void SetChanged(bool value) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = value; + __SetChanged?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public bool HasChanged() + { + var __result__ = __HasChanged?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void SetOverriddenForAll(bool overridden) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = overridden; + __SetOverriddenForAll?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void SetMaxTextureSizeForAll(int maxTextureSize) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = maxTextureSize; + __SetMaxTextureSizeForAll?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void SetResizeAlgorithmForAll(UnityEditor.TextureResizeAlgorithm algorithm) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = algorithm; + __SetResizeAlgorithmForAll?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void SetTextureCompressionForAll(UnityEditor.TextureImporterCompression textureCompression) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = textureCompression; + __SetTextureCompressionForAll?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void SetCompressionQualityForAll(int quality) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = quality; + __SetCompressionQualityForAll?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void SetCrunchedCompressionForAll(bool crunched) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = crunched; + __SetCrunchedCompressionForAll?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void SetTextureFormatForAll(UnityEditor.TextureImporterFormat format) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = format; + __SetTextureFormatForAll?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void GetValidTextureFormatsAndStrings(UnityEditor.TextureImporterType textureType, out int[] formatValues, out string[] formatStrings) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = textureType; + __params__[1] = null; + __params__[2] = null; + __GetValidTextureFormatsAndStrings?.Invoke(__self__, __params__); + formatValues = (int[])(__params__[1]); + formatStrings = (string[])(__params__[2]); + __pool__.Return(__params__); + } + + public void SetAllowsAlphaSplitForAll(bool value) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = value; + __SetAllowsAlphaSplitForAll?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public UnityEditor_TextureImportPlatformSettingsData(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + + private static FieldInfo ___m_PlatformSettings; + private static FieldInfo __m_PlatformSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_PlatformSettings ??= __type__?.GetField("m_PlatformSettings", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SerializedPlatformSettings; + private static FieldInfo __m_SerializedPlatformSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SerializedPlatformSettings ??= __type__?.GetField("m_SerializedPlatformSettings", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_OverriddenIsDifferent; + private static FieldInfo __m_OverriddenIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_OverriddenIsDifferent ??= __type__?.GetField("m_OverriddenIsDifferent", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_OverriddenProperty; + private static FieldInfo __m_OverriddenProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_OverriddenProperty ??= __type__?.GetField("m_OverriddenProperty", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MaxTextureSizeIsDifferent; + private static FieldInfo __m_MaxTextureSizeIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MaxTextureSizeIsDifferent ??= __type__?.GetField("m_MaxTextureSizeIsDifferent", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MaxTextureSizeProperty; + private static FieldInfo __m_MaxTextureSizeProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MaxTextureSizeProperty ??= __type__?.GetField("m_MaxTextureSizeProperty", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ResizeAlgorithmIsDifferent; + private static FieldInfo __m_ResizeAlgorithmIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ResizeAlgorithmIsDifferent ??= __type__?.GetField("m_ResizeAlgorithmIsDifferent", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ResizeAlgorithmProperty; + private static FieldInfo __m_ResizeAlgorithmProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ResizeAlgorithmProperty ??= __type__?.GetField("m_ResizeAlgorithmProperty", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TextureCompressionIsDifferent; + private static FieldInfo __m_TextureCompressionIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TextureCompressionIsDifferent ??= __type__?.GetField("m_TextureCompressionIsDifferent", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TextureCompressionProperty; + private static FieldInfo __m_TextureCompressionProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TextureCompressionProperty ??= __type__?.GetField("m_TextureCompressionProperty", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_CompressionQualityIsDifferent; + private static FieldInfo __m_CompressionQualityIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_CompressionQualityIsDifferent ??= __type__?.GetField("m_CompressionQualityIsDifferent", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_CompressionQualityProperty; + private static FieldInfo __m_CompressionQualityProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_CompressionQualityProperty ??= __type__?.GetField("m_CompressionQualityProperty", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_CrunchedCompressionIsDifferent; + private static FieldInfo __m_CrunchedCompressionIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_CrunchedCompressionIsDifferent ??= __type__?.GetField("m_CrunchedCompressionIsDifferent", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_CrunchedCompressionProperty; + private static FieldInfo __m_CrunchedCompressionProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_CrunchedCompressionProperty ??= __type__?.GetField("m_CrunchedCompressionProperty", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TextureFormatIsDifferent; + private static FieldInfo __m_TextureFormatIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TextureFormatIsDifferent ??= __type__?.GetField("m_TextureFormatIsDifferent", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TextureFormatProperty; + private static FieldInfo __m_TextureFormatProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TextureFormatProperty ??= __type__?.GetField("m_TextureFormatProperty", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AlphaSplitIsDifferent; + private static FieldInfo __m_AlphaSplitIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AlphaSplitIsDifferent ??= __type__?.GetField("m_AlphaSplitIsDifferent", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AlphaSplitProperty; + private static FieldInfo __m_AlphaSplitProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AlphaSplitProperty ??= __type__?.GetField("m_AlphaSplitProperty", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AndroidETC2FallbackOverrideIsDifferent; + private static FieldInfo __m_AndroidETC2FallbackOverrideIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AndroidETC2FallbackOverrideIsDifferent ??= __type__?.GetField("m_AndroidETC2FallbackOverrideIsDifferent", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AndroidETC2FallbackOverrideProperty; + private static FieldInfo __m_AndroidETC2FallbackOverrideProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AndroidETC2FallbackOverrideProperty ??= __type__?.GetField("m_AndroidETC2FallbackOverrideProperty", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Target; + private static FieldInfo __m_Target + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Target ??= __type__?.GetField("m_Target", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_HasChanged; + private static FieldInfo __m_HasChanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_HasChanged ??= __type__?.GetField("m_HasChanged", (BindingFlags)(-1)); + } + + private static PropertyInfo ___platformTextureSettings; + private static PropertyInfo __platformTextureSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___platformTextureSettings ??= __type__?.GetProperty("platformTextureSettings", (BindingFlags)(-1)); + } + + private static PropertyInfo ___platformTextureSettingsProp; + private static PropertyInfo __platformTextureSettingsProp + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___platformTextureSettingsProp ??= __type__?.GetProperty("platformTextureSettingsProp", (BindingFlags)(-1)); + } + + private static PropertyInfo ___overriddenIsDifferent; + private static PropertyInfo __overriddenIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___overriddenIsDifferent ??= __type__?.GetProperty("overriddenIsDifferent", (BindingFlags)(-1)); + } + + private static PropertyInfo ___overriddenProperty; + private static PropertyInfo __overriddenProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___overriddenProperty ??= __type__?.GetProperty("overriddenProperty", (BindingFlags)(-1)); + } + + private static PropertyInfo ___allAreOverridden; + private static PropertyInfo __allAreOverridden + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___allAreOverridden ??= __type__?.GetProperty("allAreOverridden", (BindingFlags)(-1)); + } + + private static PropertyInfo ___isDefault; + private static PropertyInfo __isDefault + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___isDefault ??= __type__?.GetProperty("isDefault", (BindingFlags)(-1)); + } + + private static PropertyInfo ___maxTextureSizeIsDifferent; + private static PropertyInfo __maxTextureSizeIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___maxTextureSizeIsDifferent ??= __type__?.GetProperty("maxTextureSizeIsDifferent", (BindingFlags)(-1)); + } + + private static PropertyInfo ___maxTextureSizeProperty; + private static PropertyInfo __maxTextureSizeProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___maxTextureSizeProperty ??= __type__?.GetProperty("maxTextureSizeProperty", (BindingFlags)(-1)); + } + + private static PropertyInfo ___resizeAlgorithmIsDifferent; + private static PropertyInfo __resizeAlgorithmIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___resizeAlgorithmIsDifferent ??= __type__?.GetProperty("resizeAlgorithmIsDifferent", (BindingFlags)(-1)); + } + + private static PropertyInfo ___resizeAlgorithmProperty; + private static PropertyInfo __resizeAlgorithmProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___resizeAlgorithmProperty ??= __type__?.GetProperty("resizeAlgorithmProperty", (BindingFlags)(-1)); + } + + private static PropertyInfo ___textureCompressionIsDifferent; + private static PropertyInfo __textureCompressionIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___textureCompressionIsDifferent ??= __type__?.GetProperty("textureCompressionIsDifferent", (BindingFlags)(-1)); + } + + private static PropertyInfo ___textureCompressionProperty; + private static PropertyInfo __textureCompressionProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___textureCompressionProperty ??= __type__?.GetProperty("textureCompressionProperty", (BindingFlags)(-1)); + } + + private static PropertyInfo ___compressionQualityIsDifferent; + private static PropertyInfo __compressionQualityIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___compressionQualityIsDifferent ??= __type__?.GetProperty("compressionQualityIsDifferent", (BindingFlags)(-1)); + } + + private static PropertyInfo ___compressionQualityProperty; + private static PropertyInfo __compressionQualityProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___compressionQualityProperty ??= __type__?.GetProperty("compressionQualityProperty", (BindingFlags)(-1)); + } + + private static PropertyInfo ___crunchedCompressionIsDifferent; + private static PropertyInfo __crunchedCompressionIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___crunchedCompressionIsDifferent ??= __type__?.GetProperty("crunchedCompressionIsDifferent", (BindingFlags)(-1)); + } + + private static PropertyInfo ___crunchedCompressionProperty; + private static PropertyInfo __crunchedCompressionProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___crunchedCompressionProperty ??= __type__?.GetProperty("crunchedCompressionProperty", (BindingFlags)(-1)); + } + + private static PropertyInfo ___textureFormatIsDifferent; + private static PropertyInfo __textureFormatIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___textureFormatIsDifferent ??= __type__?.GetProperty("textureFormatIsDifferent", (BindingFlags)(-1)); + } + + private static PropertyInfo ___textureFormatProperty; + private static PropertyInfo __textureFormatProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___textureFormatProperty ??= __type__?.GetProperty("textureFormatProperty", (BindingFlags)(-1)); + } + + private static PropertyInfo ___allowsAlphaSplitIsDifferent; + private static PropertyInfo __allowsAlphaSplitIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___allowsAlphaSplitIsDifferent ??= __type__?.GetProperty("allowsAlphaSplitIsDifferent", (BindingFlags)(-1)); + } + + private static PropertyInfo ___alphaSplitProperty; + private static PropertyInfo __alphaSplitProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___alphaSplitProperty ??= __type__?.GetProperty("alphaSplitProperty", (BindingFlags)(-1)); + } + + private static PropertyInfo ___androidETC2FallbackOverrideIsDifferent; + private static PropertyInfo __androidETC2FallbackOverrideIsDifferent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___androidETC2FallbackOverrideIsDifferent ??= __type__?.GetProperty("androidETC2FallbackOverrideIsDifferent", (BindingFlags)(-1)); + } + + private static PropertyInfo ___androidETC2FallbackOverrideProperty; + private static PropertyInfo __androidETC2FallbackOverrideProperty + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___androidETC2FallbackOverrideProperty ??= __type__?.GetProperty("androidETC2FallbackOverrideProperty", (BindingFlags)(-1)); + } + + private static PropertyInfo ___buildTarget; + private static PropertyInfo __buildTarget + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___buildTarget ??= __type__?.GetProperty("buildTarget", (BindingFlags)(-1)); + } + + private static PropertyInfo ___forceMaximumCompressionQuality_BC6H_BC7; + private static PropertyInfo __forceMaximumCompressionQuality_BC6H_BC7 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___forceMaximumCompressionQuality_BC6H_BC7 ??= __type__?.GetProperty("forceMaximumCompressionQuality_BC6H_BC7", (BindingFlags)(-1)); + } + + private static MethodInfo ___SetAndroidETC2FallbackOverrideForAll; + private static MethodInfo __SetAndroidETC2FallbackOverrideForAll + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetAndroidETC2FallbackOverrideForAll ??= __type__?.GetMethodInfoByParameterTypeNames("SetAndroidETC2FallbackOverrideForAll", "UnityEditor.AndroidETC2FallbackOverride"); + } + + private static MethodInfo ___SetChanged; + private static MethodInfo __SetChanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetChanged ??= __type__?.GetMethodInfoByParameterTypeNames("SetChanged", "System.Boolean"); + } + + private static MethodInfo ___HasChanged; + private static MethodInfo __HasChanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasChanged ??= __type__?.GetMethodInfoByParameterTypeNames("HasChanged"); + } + + private static MethodInfo ___SetOverriddenForAll; + private static MethodInfo __SetOverriddenForAll + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetOverriddenForAll ??= __type__?.GetMethodInfoByParameterTypeNames("SetOverriddenForAll", "System.Boolean"); + } + + private static MethodInfo ___SetMaxTextureSizeForAll; + private static MethodInfo __SetMaxTextureSizeForAll + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetMaxTextureSizeForAll ??= __type__?.GetMethodInfoByParameterTypeNames("SetMaxTextureSizeForAll", "System.Int32"); + } + + private static MethodInfo ___SetResizeAlgorithmForAll; + private static MethodInfo __SetResizeAlgorithmForAll + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetResizeAlgorithmForAll ??= __type__?.GetMethodInfoByParameterTypeNames("SetResizeAlgorithmForAll", "UnityEditor.TextureResizeAlgorithm"); + } + + private static MethodInfo ___SetTextureCompressionForAll; + private static MethodInfo __SetTextureCompressionForAll + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetTextureCompressionForAll ??= __type__?.GetMethodInfoByParameterTypeNames("SetTextureCompressionForAll", "UnityEditor.TextureImporterCompression"); + } + + private static MethodInfo ___SetCompressionQualityForAll; + private static MethodInfo __SetCompressionQualityForAll + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetCompressionQualityForAll ??= __type__?.GetMethodInfoByParameterTypeNames("SetCompressionQualityForAll", "System.Int32"); + } + + private static MethodInfo ___SetCrunchedCompressionForAll; + private static MethodInfo __SetCrunchedCompressionForAll + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetCrunchedCompressionForAll ??= __type__?.GetMethodInfoByParameterTypeNames("SetCrunchedCompressionForAll", "System.Boolean"); + } + + private static MethodInfo ___SetTextureFormatForAll; + private static MethodInfo __SetTextureFormatForAll + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetTextureFormatForAll ??= __type__?.GetMethodInfoByParameterTypeNames("SetTextureFormatForAll", "UnityEditor.TextureImporterFormat"); + } + + private static MethodInfo ___GetValidTextureFormatsAndStrings; + private static MethodInfo __GetValidTextureFormatsAndStrings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetValidTextureFormatsAndStrings ??= __type__?.GetMethodInfoByParameterTypeNames("GetValidTextureFormatsAndStrings", "UnityEditor.TextureImporterType", "System.Int32[]&", "System.String[]&"); + } + + private static MethodInfo ___SetAllowsAlphaSplitForAll; + private static MethodInfo __SetAllowsAlphaSplitForAll + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetAllowsAlphaSplitForAll ??= __type__?.GetMethodInfoByParameterTypeNames("SetAllowsAlphaSplitForAll", "System.Boolean"); + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextureImportPlatformSettingsData.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextureImportPlatformSettingsData.cs.meta new file mode 100644 index 0000000..6b6fda7 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextureImportPlatformSettingsData.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6cc9638869aa7d44ca17118af4501499 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextureImporterInspector.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextureImporterInspector.cs new file mode 100644 index 0000000..ce5d740 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextureImporterInspector.cs @@ -0,0 +1,1778 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEditor_TextureImporterInspector + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEditor.TextureImporterInspector"); + + public delegate void GUIMethod(object guiElements); + + public UnityEditor.TextureImporterType textureType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.TextureImporterType)(__textureType?.GetValue(__self__)); + } + + public bool textureTypeHasMultipleDifferentValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__textureTypeHasMultipleDifferentValues?.GetValue(__self__)); + } + + public bool showImportedObject + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__showImportedObject?.GetValue(__self__)); + } + + public object textureInspector + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__textureInspector?.GetValue(__self__)); + } + + public UnityEditor.SpriteImportMode spriteImportMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SpriteImportMode)(__spriteImportMode?.GetValue(__self__)); + } + + public static string s_DefaultPlatformName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__s_DefaultPlatformName?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_DefaultPlatformName?.SetValue(null, value); + } + + public UnityEditor.SerializedProperty m_TextureType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_TextureType?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TextureType?.SetValue(__self__, value); + } + + public System.Collections.IDictionary m_GUIElementMethods + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.IDictionary)(__m_GUIElementMethods?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_GUIElementMethods?.SetValue(__self__, value); + } + + public System.Collections.IList m_PlatformSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.IList)(__m_PlatformSettings?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_PlatformSettings?.SetValue(__self__, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public UnityEditor_TextureImportPlatformSettings m_PlatformSettings__GetItem(int i) => new UnityEditor_TextureImportPlatformSettings(m_PlatformSettings?[i]); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void m_PlatformSettings__SetItem(int i, UnityEditor_TextureImportPlatformSettings value) + { + var __list__ = m_PlatformSettings; + if (__list__ == null) return; + __list__[i] = value.__self__; + } + + public static UnityEditor.TextureImporterFormat[] kFormatsWithCompressionSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.TextureImporterFormat[])(__kFormatsWithCompressionSettings?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __kFormatsWithCompressionSettings?.SetValue(null, value); + } + + public UnityEditor.AnimatedValues.AnimBool m_ShowBumpGenerationSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.AnimatedValues.AnimBool)(__m_ShowBumpGenerationSettings?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ShowBumpGenerationSettings?.SetValue(__self__, value); + } + + public UnityEditor.AnimatedValues.AnimBool m_ShowCubeMapSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.AnimatedValues.AnimBool)(__m_ShowCubeMapSettings?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ShowCubeMapSettings?.SetValue(__self__, value); + } + + public UnityEditor.AnimatedValues.AnimBool m_ShowElementsAtlasSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.AnimatedValues.AnimBool)(__m_ShowElementsAtlasSettings?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ShowElementsAtlasSettings?.SetValue(__self__, value); + } + + public UnityEditor.AnimatedValues.AnimBool m_ShowGenericSpriteSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.AnimatedValues.AnimBool)(__m_ShowGenericSpriteSettings?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ShowGenericSpriteSettings?.SetValue(__self__, value); + } + + public UnityEditor.AnimatedValues.AnimBool m_ShowMipMapSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.AnimatedValues.AnimBool)(__m_ShowMipMapSettings?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ShowMipMapSettings?.SetValue(__self__, value); + } + + public UnityEditor.AnimatedValues.AnimBool m_ShowSpriteMeshTypeOption + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.AnimatedValues.AnimBool)(__m_ShowSpriteMeshTypeOption?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ShowSpriteMeshTypeOption?.SetValue(__self__, value); + } + + public UnityEngine.GUIContent m_EmptyContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__m_EmptyContent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_EmptyContent?.SetValue(__self__, value); + } + + public int[] m_FilterModeOptions + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int[])(__m_FilterModeOptions?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_FilterModeOptions?.SetValue(__self__, value); + } + + public string m_ImportWarning + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__m_ImportWarning?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ImportWarning?.SetValue(__self__, value); + } + + public static object s_Styles + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (object)(__s_Styles?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_Styles?.SetValue(null, value); + } + + public Array m_TextureTypeGUIElements + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (Array)(__m_TextureTypeGUIElements?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TextureTypeGUIElements?.SetValue(__self__, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public object m_TextureTypeGUIElements__GetItem(int i) => (object)(m_TextureTypeGUIElements?.GetValue(i)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void m_TextureTypeGUIElements__SetItem(int i, object value) => m_TextureTypeGUIElements?.SetValue(value, i); + + public System.Collections.IList m_GUIElementsDisplayOrder + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.IList)(__m_GUIElementsDisplayOrder?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_GUIElementsDisplayOrder?.SetValue(__self__, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public object m_GUIElementsDisplayOrder__GetItem(int i) => (object)(m_GUIElementsDisplayOrder?[i]); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void m_GUIElementsDisplayOrder__SetItem(int i, object value) + { + var __list__ = m_GUIElementsDisplayOrder; + if (__list__ == null) return; + __list__[i] = value; + } + + public UnityEditor.SerializedProperty m_AlphaSource + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_AlphaSource?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AlphaSource?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_ConvertToNormalMap + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_ConvertToNormalMap?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ConvertToNormalMap?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_HeightScale + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_HeightScale?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_HeightScale?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_NormalMapFilter + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_NormalMapFilter?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_NormalMapFilter?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_GenerateCubemap + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_GenerateCubemap?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_GenerateCubemap?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_CubemapConvolution + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_CubemapConvolution?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_CubemapConvolution?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_SeamlessCubemap + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_SeamlessCubemap?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SeamlessCubemap?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_BorderMipMap + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_BorderMipMap?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_BorderMipMap?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_MipMapsPreserveCoverage + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_MipMapsPreserveCoverage?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MipMapsPreserveCoverage?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_AlphaTestReferenceValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_AlphaTestReferenceValue?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AlphaTestReferenceValue?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_NPOTScale + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_NPOTScale?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_NPOTScale?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_IsReadable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_IsReadable?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_IsReadable?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_StreamingMipmaps + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_StreamingMipmaps?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_StreamingMipmaps?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_StreamingMipmapsPriority + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_StreamingMipmapsPriority?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_StreamingMipmapsPriority?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_VTOnly + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_VTOnly?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_VTOnly?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_sRGBTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_sRGBTexture?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_sRGBTexture?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_EnableMipMap + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_EnableMipMap?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_EnableMipMap?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_MipMapMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_MipMapMode?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MipMapMode?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_FadeOut + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_FadeOut?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_FadeOut?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_MipMapFadeDistanceStart + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_MipMapFadeDistanceStart?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MipMapFadeDistanceStart?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_MipMapFadeDistanceEnd + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_MipMapFadeDistanceEnd?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MipMapFadeDistanceEnd?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_Aniso + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_Aniso?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Aniso?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_FilterMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_FilterMode?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_FilterMode?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_WrapU + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_WrapU?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_WrapU?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_WrapV + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_WrapV?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_WrapV?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_WrapW + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_WrapW?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_WrapW?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_SpritePackingTag + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_SpritePackingTag?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SpritePackingTag?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_SpritePixelsToUnits + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_SpritePixelsToUnits?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SpritePixelsToUnits?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_SpriteExtrude + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_SpriteExtrude?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SpriteExtrude?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_SpriteMeshType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_SpriteMeshType?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SpriteMeshType?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_Alignment + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_Alignment?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Alignment?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_SpritePivot + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_SpritePivot?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SpritePivot?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_SpriteGenerateFallbackPhysicsShape + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_SpriteGenerateFallbackPhysicsShape?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SpriteGenerateFallbackPhysicsShape?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_AlphaIsTransparency + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_AlphaIsTransparency?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_AlphaIsTransparency?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_IgnorePngGamma + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_IgnorePngGamma?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_IgnorePngGamma?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_PSDRemoveMatte + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_PSDRemoveMatte?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_PSDRemoveMatte?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_TextureShape + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_TextureShape?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TextureShape?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_SpriteMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_SpriteMode?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SpriteMode?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_FlipbookRows + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_FlipbookRows?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_FlipbookRows?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_FlipbookColumns + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_FlipbookColumns?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_FlipbookColumns?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_SingleChannelComponent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_SingleChannelComponent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SingleChannelComponent?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_CookieLightType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_CookieLightType?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_CookieLightType?.SetValue(__self__, value); + } + + public UnityEditor.SerializedProperty m_PlatformSettingsArrProp + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.SerializedProperty)(__m_PlatformSettingsArrProp?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_PlatformSettingsArrProp?.SetValue(__self__, value); + } + + public System.Collections.Generic.List m_TextureTypes + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Generic.List)(__m_TextureTypes?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TextureTypes?.SetValue(__self__, value); + } + + public bool m_ShowAdvanced + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_ShowAdvanced?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ShowAdvanced?.SetValue(__self__, value); + } + + public int m_TextureWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__m_TextureWidth?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TextureWidth?.SetValue(__self__, value); + } + + public int m_TextureHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__m_TextureHeight?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_TextureHeight?.SetValue(__self__, value); + } + + public bool m_IsPOT + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_IsPOT?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_IsPOT?.SetValue(__self__, value); + } + + public bool m_ShowPerAxisWrapModes + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_ShowPerAxisWrapModes?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ShowPerAxisWrapModes?.SetValue(__self__, value); + } + + public void OnDisable() + { + __OnDisable?.Invoke(__self__, System.Array.Empty()); + } + + public static bool IsCompressedDXTTextureFormat(UnityEditor.TextureImporterFormat format) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = format; + var __result__ = __IsCompressedDXTTextureFormat?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public void UpdateImportWarning() + { + __UpdateImportWarning?.Invoke(__self__, System.Array.Empty()); + } + + public void ToggleFromInt(UnityEditor.SerializedProperty property, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = property; + __params__[1] = label; + __ToggleFromInt?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void EnumPopup(UnityEditor.SerializedProperty property, System.Type type, UnityEngine.GUIContent label) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = property; + __params__[1] = type; + __params__[2] = label; + __EnumPopup?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void CacheSerializedProperties() + { + __CacheSerializedProperties?.Invoke(__self__, System.Array.Empty()); + } + + public void InitializeGUI() + { + __InitializeGUI?.Invoke(__self__, System.Array.Empty()); + } + + public void OnEnable() + { + __OnEnable?.Invoke(__self__, System.Array.Empty()); + } + + public void SetSerializedPropertySettings(UnityEditor.TextureImporterSettings settings) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = settings; + __SetSerializedPropertySettings?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public UnityEditor.TextureImporterSettings GetSerializedPropertySettings() + { + var __result__ = __GetSerializedPropertySettings?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (UnityEditor.TextureImporterSettings)(__result__) : default; + } + + public UnityEditor.TextureImporterSettings GetSerializedPropertySettings(UnityEditor.TextureImporterSettings settings) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = settings; + var __result__ = __GetSerializedPropertySettings__2?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEditor.TextureImporterSettings)(__result__) : default; + } + + public void CookieGUI(object guiElements) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = guiElements; + __CookieGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void CubemapMappingGUI(object guiElements) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = guiElements; + __CubemapMappingGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void ElementsAtlasGui(object guiElements) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = guiElements; + __ElementsAtlasGui?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void ColorSpaceGUI(object guiElements) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = guiElements; + __ColorSpaceGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void POTScaleGUI(object guiElements) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = guiElements; + __POTScaleGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void ReadableGUI(object guiElements) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = guiElements; + __ReadableGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void StreamingMipmapsGUI(object guiElements) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = guiElements; + __StreamingMipmapsGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void VTOnlyGUI(object guiElements) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = guiElements; + __VTOnlyGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void AlphaHandlingGUI(object guiElements) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = guiElements; + __AlphaHandlingGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public bool ShouldShowSpriteMeshTypeOption() + { + var __result__ = __ShouldShowSpriteMeshTypeOption?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void SpriteGUI(object guiElements) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = guiElements; + __SpriteGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void MipMapGUI(object guiElements) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = guiElements; + __MipMapGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void PngGammaGUI(object guiElements) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = guiElements; + __PngGammaGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void BumpGUI(object guiElements) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = guiElements; + __BumpGUI?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public bool TargetsHaveNPOTTextures() + { + var __result__ = __TargetsHaveNPOTTextures?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void TextureSettingsGUI() + { + __TextureSettingsGUI?.Invoke(__self__, System.Array.Empty()); + } + + public void OnInspectorGUI() + { + __OnInspectorGUI?.Invoke(__self__, System.Array.Empty()); + } + + public bool ShouldDisplayGUIElement(object guiElements, object guiElement) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = guiElements; + __params__[1] = guiElement; + var __result__ = __ShouldDisplayGUIElement?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public void DoGUIElements(object guiElements, System.Collections.IList guiElementsDisplayOrder) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = guiElements; + __params__[1] = guiElementsDisplayOrder; + __DoGUIElements?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public static bool CountImportersWithAlpha(UnityEngine.Object[] importers, out int count) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = importers; + __params__[1] = null; + var __result__ = __CountImportersWithAlpha?.Invoke(null, __params__); + count = (int)(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool CountImportersWithHDR(UnityEngine.Object[] importers, out int count) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = importers; + __params__[1] = null; + var __result__ = __CountImportersWithHDR?.Invoke(null, __params__); + count = (int)(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public void SetCookieLightTypeDefaults(object cookieLightType) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = cookieLightType; + __SetCookieLightTypeDefaults?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public static string[] BuildTextureStrings(int[] texFormatValues) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = texFormatValues; + var __result__ = __BuildTextureStrings?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string[])(__result__) : default; + } + + public static bool IsFormatRequireCompressionSetting(UnityEditor.TextureImporterFormat format) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = format; + var __result__ = __IsFormatRequireCompressionSetting?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool IsPowerOfTwo(int f) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = f; + var __result__ = __IsPowerOfTwo?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public bool ShouldShowWarningForReadWrite() + { + var __result__ = __ShouldShowWarningForReadWrite?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void BuildTargetList() + { + __BuildTargetList?.Invoke(__self__, System.Array.Empty()); + } + + public bool HasModified() + { + var __result__ = __HasModified?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public void ResetValues() + { + __ResetValues?.Invoke(__self__, System.Array.Empty()); + } + + public void Apply() + { + __Apply?.Invoke(__self__, System.Array.Empty()); + } + + public void DrawPreview(UnityEngine.Rect previewArea) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = previewArea; + __DrawPreview?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public void RefreshPreviewChannelSelection() + { + __RefreshPreviewChannelSelection?.Invoke(__self__, System.Array.Empty()); + } + + public UnityEditor_TextureImporterInspector(object __self__) => this.__self__ = __self__ as UnityEngine.Object; + public UnityEngine.Object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + public UnityEditor.AssetImporters.AssetImporterEditor __super__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEditor.AssetImporters.AssetImporterEditor)(__self__); + } + + private static FieldInfo ___s_DefaultPlatformName; + private static FieldInfo __s_DefaultPlatformName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_DefaultPlatformName ??= __type__?.GetField("s_DefaultPlatformName", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TextureType; + private static FieldInfo __m_TextureType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TextureType ??= __type__?.GetField("m_TextureType", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_GUIElementMethods; + private static FieldInfo __m_GUIElementMethods + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_GUIElementMethods ??= __type__?.GetField("m_GUIElementMethods", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_PlatformSettings; + private static FieldInfo __m_PlatformSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_PlatformSettings ??= __type__?.GetField("m_PlatformSettings", (BindingFlags)(-1)); + } + + private static Type ___E__m_PlatformSettings; + public static Type __E__m_PlatformSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___E__m_PlatformSettings ??= EditorUtils.GetTypeByFullName("UnityEditor.TextureImportPlatformSettings"); + } + + private static FieldInfo ___kFormatsWithCompressionSettings; + private static FieldInfo __kFormatsWithCompressionSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___kFormatsWithCompressionSettings ??= __type__?.GetField("kFormatsWithCompressionSettings", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ShowBumpGenerationSettings; + private static FieldInfo __m_ShowBumpGenerationSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ShowBumpGenerationSettings ??= __type__?.GetField("m_ShowBumpGenerationSettings", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ShowCubeMapSettings; + private static FieldInfo __m_ShowCubeMapSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ShowCubeMapSettings ??= __type__?.GetField("m_ShowCubeMapSettings", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ShowElementsAtlasSettings; + private static FieldInfo __m_ShowElementsAtlasSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ShowElementsAtlasSettings ??= __type__?.GetField("m_ShowElementsAtlasSettings", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ShowGenericSpriteSettings; + private static FieldInfo __m_ShowGenericSpriteSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ShowGenericSpriteSettings ??= __type__?.GetField("m_ShowGenericSpriteSettings", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ShowMipMapSettings; + private static FieldInfo __m_ShowMipMapSettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ShowMipMapSettings ??= __type__?.GetField("m_ShowMipMapSettings", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ShowSpriteMeshTypeOption; + private static FieldInfo __m_ShowSpriteMeshTypeOption + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ShowSpriteMeshTypeOption ??= __type__?.GetField("m_ShowSpriteMeshTypeOption", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_EmptyContent; + private static FieldInfo __m_EmptyContent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_EmptyContent ??= __type__?.GetField("m_EmptyContent", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_FilterModeOptions; + private static FieldInfo __m_FilterModeOptions + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_FilterModeOptions ??= __type__?.GetField("m_FilterModeOptions", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ImportWarning; + private static FieldInfo __m_ImportWarning + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ImportWarning ??= __type__?.GetField("m_ImportWarning", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_Styles; + private static FieldInfo __s_Styles + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_Styles ??= __type__?.GetField("s_Styles", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TextureTypeGUIElements; + private static FieldInfo __m_TextureTypeGUIElements + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TextureTypeGUIElements ??= __type__?.GetField("m_TextureTypeGUIElements", (BindingFlags)(-1)); + } + + private static Type ___E__m_TextureTypeGUIElements; + public static Type __E__m_TextureTypeGUIElements + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___E__m_TextureTypeGUIElements ??= EditorUtils.GetTypeByFullName("UnityEditor.TextureImporterInspector+TextureInspectorTypeGUIProperties"); + } + + private static FieldInfo ___m_GUIElementsDisplayOrder; + private static FieldInfo __m_GUIElementsDisplayOrder + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_GUIElementsDisplayOrder ??= __type__?.GetField("m_GUIElementsDisplayOrder", (BindingFlags)(-1)); + } + + private static Type ___E__m_GUIElementsDisplayOrder; + public static Type __E__m_GUIElementsDisplayOrder + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___E__m_GUIElementsDisplayOrder ??= EditorUtils.GetTypeByFullName("UnityEditor.TextureImporterInspector+TextureInspectorGUIElement"); + } + + private static FieldInfo ___m_AlphaSource; + private static FieldInfo __m_AlphaSource + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AlphaSource ??= __type__?.GetField("m_AlphaSource", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ConvertToNormalMap; + private static FieldInfo __m_ConvertToNormalMap + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ConvertToNormalMap ??= __type__?.GetField("m_ConvertToNormalMap", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_HeightScale; + private static FieldInfo __m_HeightScale + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_HeightScale ??= __type__?.GetField("m_HeightScale", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_NormalMapFilter; + private static FieldInfo __m_NormalMapFilter + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_NormalMapFilter ??= __type__?.GetField("m_NormalMapFilter", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_GenerateCubemap; + private static FieldInfo __m_GenerateCubemap + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_GenerateCubemap ??= __type__?.GetField("m_GenerateCubemap", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_CubemapConvolution; + private static FieldInfo __m_CubemapConvolution + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_CubemapConvolution ??= __type__?.GetField("m_CubemapConvolution", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SeamlessCubemap; + private static FieldInfo __m_SeamlessCubemap + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SeamlessCubemap ??= __type__?.GetField("m_SeamlessCubemap", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_BorderMipMap; + private static FieldInfo __m_BorderMipMap + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_BorderMipMap ??= __type__?.GetField("m_BorderMipMap", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MipMapsPreserveCoverage; + private static FieldInfo __m_MipMapsPreserveCoverage + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MipMapsPreserveCoverage ??= __type__?.GetField("m_MipMapsPreserveCoverage", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AlphaTestReferenceValue; + private static FieldInfo __m_AlphaTestReferenceValue + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AlphaTestReferenceValue ??= __type__?.GetField("m_AlphaTestReferenceValue", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_NPOTScale; + private static FieldInfo __m_NPOTScale + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_NPOTScale ??= __type__?.GetField("m_NPOTScale", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_IsReadable; + private static FieldInfo __m_IsReadable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_IsReadable ??= __type__?.GetField("m_IsReadable", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_StreamingMipmaps; + private static FieldInfo __m_StreamingMipmaps + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_StreamingMipmaps ??= __type__?.GetField("m_StreamingMipmaps", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_StreamingMipmapsPriority; + private static FieldInfo __m_StreamingMipmapsPriority + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_StreamingMipmapsPriority ??= __type__?.GetField("m_StreamingMipmapsPriority", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_VTOnly; + private static FieldInfo __m_VTOnly + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_VTOnly ??= __type__?.GetField("m_VTOnly", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_sRGBTexture; + private static FieldInfo __m_sRGBTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_sRGBTexture ??= __type__?.GetField("m_sRGBTexture", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_EnableMipMap; + private static FieldInfo __m_EnableMipMap + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_EnableMipMap ??= __type__?.GetField("m_EnableMipMap", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MipMapMode; + private static FieldInfo __m_MipMapMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MipMapMode ??= __type__?.GetField("m_MipMapMode", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_FadeOut; + private static FieldInfo __m_FadeOut + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_FadeOut ??= __type__?.GetField("m_FadeOut", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MipMapFadeDistanceStart; + private static FieldInfo __m_MipMapFadeDistanceStart + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MipMapFadeDistanceStart ??= __type__?.GetField("m_MipMapFadeDistanceStart", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MipMapFadeDistanceEnd; + private static FieldInfo __m_MipMapFadeDistanceEnd + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MipMapFadeDistanceEnd ??= __type__?.GetField("m_MipMapFadeDistanceEnd", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Aniso; + private static FieldInfo __m_Aniso + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Aniso ??= __type__?.GetField("m_Aniso", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_FilterMode; + private static FieldInfo __m_FilterMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_FilterMode ??= __type__?.GetField("m_FilterMode", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_WrapU; + private static FieldInfo __m_WrapU + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_WrapU ??= __type__?.GetField("m_WrapU", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_WrapV; + private static FieldInfo __m_WrapV + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_WrapV ??= __type__?.GetField("m_WrapV", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_WrapW; + private static FieldInfo __m_WrapW + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_WrapW ??= __type__?.GetField("m_WrapW", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SpritePackingTag; + private static FieldInfo __m_SpritePackingTag + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SpritePackingTag ??= __type__?.GetField("m_SpritePackingTag", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SpritePixelsToUnits; + private static FieldInfo __m_SpritePixelsToUnits + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SpritePixelsToUnits ??= __type__?.GetField("m_SpritePixelsToUnits", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SpriteExtrude; + private static FieldInfo __m_SpriteExtrude + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SpriteExtrude ??= __type__?.GetField("m_SpriteExtrude", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SpriteMeshType; + private static FieldInfo __m_SpriteMeshType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SpriteMeshType ??= __type__?.GetField("m_SpriteMeshType", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Alignment; + private static FieldInfo __m_Alignment + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Alignment ??= __type__?.GetField("m_Alignment", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SpritePivot; + private static FieldInfo __m_SpritePivot + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SpritePivot ??= __type__?.GetField("m_SpritePivot", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SpriteGenerateFallbackPhysicsShape; + private static FieldInfo __m_SpriteGenerateFallbackPhysicsShape + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SpriteGenerateFallbackPhysicsShape ??= __type__?.GetField("m_SpriteGenerateFallbackPhysicsShape", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_AlphaIsTransparency; + private static FieldInfo __m_AlphaIsTransparency + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_AlphaIsTransparency ??= __type__?.GetField("m_AlphaIsTransparency", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_IgnorePngGamma; + private static FieldInfo __m_IgnorePngGamma + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_IgnorePngGamma ??= __type__?.GetField("m_IgnorePngGamma", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_PSDRemoveMatte; + private static FieldInfo __m_PSDRemoveMatte + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_PSDRemoveMatte ??= __type__?.GetField("m_PSDRemoveMatte", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TextureShape; + private static FieldInfo __m_TextureShape + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TextureShape ??= __type__?.GetField("m_TextureShape", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SpriteMode; + private static FieldInfo __m_SpriteMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SpriteMode ??= __type__?.GetField("m_SpriteMode", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_FlipbookRows; + private static FieldInfo __m_FlipbookRows + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_FlipbookRows ??= __type__?.GetField("m_FlipbookRows", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_FlipbookColumns; + private static FieldInfo __m_FlipbookColumns + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_FlipbookColumns ??= __type__?.GetField("m_FlipbookColumns", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SingleChannelComponent; + private static FieldInfo __m_SingleChannelComponent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SingleChannelComponent ??= __type__?.GetField("m_SingleChannelComponent", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_CookieLightType; + private static FieldInfo __m_CookieLightType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_CookieLightType ??= __type__?.GetField("m_CookieLightType", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_PlatformSettingsArrProp; + private static FieldInfo __m_PlatformSettingsArrProp + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_PlatformSettingsArrProp ??= __type__?.GetField("m_PlatformSettingsArrProp", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TextureTypes; + private static FieldInfo __m_TextureTypes + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TextureTypes ??= __type__?.GetField("m_TextureTypes", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ShowAdvanced; + private static FieldInfo __m_ShowAdvanced + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ShowAdvanced ??= __type__?.GetField("m_ShowAdvanced", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TextureWidth; + private static FieldInfo __m_TextureWidth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TextureWidth ??= __type__?.GetField("m_TextureWidth", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_TextureHeight; + private static FieldInfo __m_TextureHeight + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_TextureHeight ??= __type__?.GetField("m_TextureHeight", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_IsPOT; + private static FieldInfo __m_IsPOT + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_IsPOT ??= __type__?.GetField("m_IsPOT", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ShowPerAxisWrapModes; + private static FieldInfo __m_ShowPerAxisWrapModes + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ShowPerAxisWrapModes ??= __type__?.GetField("m_ShowPerAxisWrapModes", (BindingFlags)(-1)); + } + + private static PropertyInfo ___textureType; + private static PropertyInfo __textureType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___textureType ??= __type__?.GetProperty("textureType", (BindingFlags)(-1)); + } + + private static PropertyInfo ___textureTypeHasMultipleDifferentValues; + private static PropertyInfo __textureTypeHasMultipleDifferentValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___textureTypeHasMultipleDifferentValues ??= __type__?.GetProperty("textureTypeHasMultipleDifferentValues", (BindingFlags)(-1)); + } + + private static PropertyInfo ___showImportedObject; + private static PropertyInfo __showImportedObject + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___showImportedObject ??= __type__?.GetProperty("showImportedObject", (BindingFlags)(-1)); + } + + private static PropertyInfo ___textureInspector; + private static PropertyInfo __textureInspector + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___textureInspector ??= __type__?.GetProperty("textureInspector", (BindingFlags)(-1)); + } + + private static PropertyInfo ___spriteImportMode; + private static PropertyInfo __spriteImportMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___spriteImportMode ??= __type__?.GetProperty("spriteImportMode", (BindingFlags)(-1)); + } + + private static MethodInfo ___OnDisable; + private static MethodInfo __OnDisable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnDisable ??= __type__?.GetMethodInfoByParameterTypeNames("OnDisable"); + } + + private static MethodInfo ___IsCompressedDXTTextureFormat; + private static MethodInfo __IsCompressedDXTTextureFormat + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsCompressedDXTTextureFormat ??= __type__?.GetMethodInfoByParameterTypeNames("IsCompressedDXTTextureFormat", "UnityEditor.TextureImporterFormat"); + } + + private static MethodInfo ___UpdateImportWarning; + private static MethodInfo __UpdateImportWarning + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UpdateImportWarning ??= __type__?.GetMethodInfoByParameterTypeNames("UpdateImportWarning"); + } + + private static MethodInfo ___ToggleFromInt; + private static MethodInfo __ToggleFromInt + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ToggleFromInt ??= __type__?.GetMethodInfoByParameterTypeNames("ToggleFromInt", "UnityEditor.SerializedProperty", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___EnumPopup; + private static MethodInfo __EnumPopup + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EnumPopup ??= __type__?.GetMethodInfoByParameterTypeNames("EnumPopup", "UnityEditor.SerializedProperty", "System.Type", "UnityEngine.GUIContent"); + } + + private static MethodInfo ___CacheSerializedProperties; + private static MethodInfo __CacheSerializedProperties + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CacheSerializedProperties ??= __type__?.GetMethodInfoByParameterTypeNames("CacheSerializedProperties"); + } + + private static MethodInfo ___InitializeGUI; + private static MethodInfo __InitializeGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___InitializeGUI ??= __type__?.GetMethodInfoByParameterTypeNames("InitializeGUI"); + } + + private static MethodInfo ___OnEnable; + private static MethodInfo __OnEnable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnEnable ??= __type__?.GetMethodInfoByParameterTypeNames("OnEnable"); + } + + private static MethodInfo ___SetSerializedPropertySettings; + private static MethodInfo __SetSerializedPropertySettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetSerializedPropertySettings ??= __type__?.GetMethodInfoByParameterTypeNames("SetSerializedPropertySettings", "UnityEditor.TextureImporterSettings"); + } + + private static MethodInfo ___GetSerializedPropertySettings; + private static MethodInfo __GetSerializedPropertySettings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSerializedPropertySettings ??= __type__?.GetMethodInfoByParameterTypeNames("GetSerializedPropertySettings"); + } + + private static MethodInfo ___GetSerializedPropertySettings__2; + private static MethodInfo __GetSerializedPropertySettings__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSerializedPropertySettings__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GetSerializedPropertySettings", "UnityEditor.TextureImporterSettings"); + } + + private static MethodInfo ___CookieGUI; + private static MethodInfo __CookieGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CookieGUI ??= __type__?.GetMethodInfoByParameterTypeNames("CookieGUI", "UnityEditor.TextureImporterInspector+TextureInspectorGUIElement"); + } + + private static MethodInfo ___CubemapMappingGUI; + private static MethodInfo __CubemapMappingGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CubemapMappingGUI ??= __type__?.GetMethodInfoByParameterTypeNames("CubemapMappingGUI", "UnityEditor.TextureImporterInspector+TextureInspectorGUIElement"); + } + + private static MethodInfo ___ElementsAtlasGui; + private static MethodInfo __ElementsAtlasGui + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ElementsAtlasGui ??= __type__?.GetMethodInfoByParameterTypeNames("ElementsAtlasGui", "UnityEditor.TextureImporterInspector+TextureInspectorGUIElement"); + } + + private static MethodInfo ___ColorSpaceGUI; + private static MethodInfo __ColorSpaceGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ColorSpaceGUI ??= __type__?.GetMethodInfoByParameterTypeNames("ColorSpaceGUI", "UnityEditor.TextureImporterInspector+TextureInspectorGUIElement"); + } + + private static MethodInfo ___POTScaleGUI; + private static MethodInfo __POTScaleGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___POTScaleGUI ??= __type__?.GetMethodInfoByParameterTypeNames("POTScaleGUI", "UnityEditor.TextureImporterInspector+TextureInspectorGUIElement"); + } + + private static MethodInfo ___ReadableGUI; + private static MethodInfo __ReadableGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ReadableGUI ??= __type__?.GetMethodInfoByParameterTypeNames("ReadableGUI", "UnityEditor.TextureImporterInspector+TextureInspectorGUIElement"); + } + + private static MethodInfo ___StreamingMipmapsGUI; + private static MethodInfo __StreamingMipmapsGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___StreamingMipmapsGUI ??= __type__?.GetMethodInfoByParameterTypeNames("StreamingMipmapsGUI", "UnityEditor.TextureImporterInspector+TextureInspectorGUIElement"); + } + + private static MethodInfo ___VTOnlyGUI; + private static MethodInfo __VTOnlyGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___VTOnlyGUI ??= __type__?.GetMethodInfoByParameterTypeNames("VTOnlyGUI", "UnityEditor.TextureImporterInspector+TextureInspectorGUIElement"); + } + + private static MethodInfo ___AlphaHandlingGUI; + private static MethodInfo __AlphaHandlingGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AlphaHandlingGUI ??= __type__?.GetMethodInfoByParameterTypeNames("AlphaHandlingGUI", "UnityEditor.TextureImporterInspector+TextureInspectorGUIElement"); + } + + private static MethodInfo ___ShouldShowSpriteMeshTypeOption; + private static MethodInfo __ShouldShowSpriteMeshTypeOption + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShouldShowSpriteMeshTypeOption ??= __type__?.GetMethodInfoByParameterTypeNames("ShouldShowSpriteMeshTypeOption"); + } + + private static MethodInfo ___SpriteGUI; + private static MethodInfo __SpriteGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SpriteGUI ??= __type__?.GetMethodInfoByParameterTypeNames("SpriteGUI", "UnityEditor.TextureImporterInspector+TextureInspectorGUIElement"); + } + + private static MethodInfo ___MipMapGUI; + private static MethodInfo __MipMapGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MipMapGUI ??= __type__?.GetMethodInfoByParameterTypeNames("MipMapGUI", "UnityEditor.TextureImporterInspector+TextureInspectorGUIElement"); + } + + private static MethodInfo ___PngGammaGUI; + private static MethodInfo __PngGammaGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PngGammaGUI ??= __type__?.GetMethodInfoByParameterTypeNames("PngGammaGUI", "UnityEditor.TextureImporterInspector+TextureInspectorGUIElement"); + } + + private static MethodInfo ___BumpGUI; + private static MethodInfo __BumpGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BumpGUI ??= __type__?.GetMethodInfoByParameterTypeNames("BumpGUI", "UnityEditor.TextureImporterInspector+TextureInspectorGUIElement"); + } + + private static MethodInfo ___TargetsHaveNPOTTextures; + private static MethodInfo __TargetsHaveNPOTTextures + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TargetsHaveNPOTTextures ??= __type__?.GetMethodInfoByParameterTypeNames("TargetsHaveNPOTTextures"); + } + + private static MethodInfo ___TextureSettingsGUI; + private static MethodInfo __TextureSettingsGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TextureSettingsGUI ??= __type__?.GetMethodInfoByParameterTypeNames("TextureSettingsGUI"); + } + + private static MethodInfo ___OnInspectorGUI; + private static MethodInfo __OnInspectorGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnInspectorGUI ??= __type__?.GetMethodInfoByParameterTypeNames("OnInspectorGUI"); + } + + private static MethodInfo ___ShouldDisplayGUIElement; + private static MethodInfo __ShouldDisplayGUIElement + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShouldDisplayGUIElement ??= __type__?.GetMethodInfoByParameterTypeNames("ShouldDisplayGUIElement", "UnityEditor.TextureImporterInspector+TextureInspectorGUIElement", "UnityEditor.TextureImporterInspector+TextureInspectorGUIElement"); + } + + private static MethodInfo ___DoGUIElements; + private static MethodInfo __DoGUIElements + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DoGUIElements ??= __type__?.GetMethodInfoByParameterTypeNames("DoGUIElements", "UnityEditor.TextureImporterInspector+TextureInspectorGUIElement", "System.Collections.Generic.List`1[[UnityEditor.TextureImporterInspector+TextureInspectorGUIElement, UnityEditor.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]"); + } + + private static MethodInfo ___CountImportersWithAlpha; + private static MethodInfo __CountImportersWithAlpha + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CountImportersWithAlpha ??= __type__?.GetMethodInfoByParameterTypeNames("CountImportersWithAlpha", "UnityEngine.Object[]", "System.Int32&"); + } + + private static MethodInfo ___CountImportersWithHDR; + private static MethodInfo __CountImportersWithHDR + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CountImportersWithHDR ??= __type__?.GetMethodInfoByParameterTypeNames("CountImportersWithHDR", "UnityEngine.Object[]", "System.Int32&"); + } + + private static MethodInfo ___SetCookieLightTypeDefaults; + private static MethodInfo __SetCookieLightTypeDefaults + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetCookieLightTypeDefaults ??= __type__?.GetMethodInfoByParameterTypeNames("SetCookieLightTypeDefaults", "UnityEditor.TextureImporterCookieLightType"); + } + + private static MethodInfo ___BuildTextureStrings; + private static MethodInfo __BuildTextureStrings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BuildTextureStrings ??= __type__?.GetMethodInfoByParameterTypeNames("BuildTextureStrings", "System.Int32[]"); + } + + private static MethodInfo ___IsFormatRequireCompressionSetting; + private static MethodInfo __IsFormatRequireCompressionSetting + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsFormatRequireCompressionSetting ??= __type__?.GetMethodInfoByParameterTypeNames("IsFormatRequireCompressionSetting", "UnityEditor.TextureImporterFormat"); + } + + private static MethodInfo ___IsPowerOfTwo; + private static MethodInfo __IsPowerOfTwo + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsPowerOfTwo ??= __type__?.GetMethodInfoByParameterTypeNames("IsPowerOfTwo", "System.Int32"); + } + + private static MethodInfo ___ShouldShowWarningForReadWrite; + private static MethodInfo __ShouldShowWarningForReadWrite + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShouldShowWarningForReadWrite ??= __type__?.GetMethodInfoByParameterTypeNames("ShouldShowWarningForReadWrite"); + } + + private static MethodInfo ___BuildTargetList; + private static MethodInfo __BuildTargetList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BuildTargetList ??= __type__?.GetMethodInfoByParameterTypeNames("BuildTargetList"); + } + + private static MethodInfo ___HasModified; + private static MethodInfo __HasModified + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasModified ??= __type__?.GetMethodInfoByParameterTypeNames("HasModified"); + } + + private static MethodInfo ___ResetValues; + private static MethodInfo __ResetValues + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ResetValues ??= __type__?.GetMethodInfoByParameterTypeNames("ResetValues"); + } + + private static MethodInfo ___Apply; + private static MethodInfo __Apply + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Apply ??= __type__?.GetMethodInfoByParameterTypeNames("Apply"); + } + + private static MethodInfo ___DrawPreview; + private static MethodInfo __DrawPreview + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DrawPreview ??= __type__?.GetMethodInfoByParameterTypeNames("DrawPreview", "UnityEngine.Rect"); + } + + private static MethodInfo ___RefreshPreviewChannelSelection; + private static MethodInfo __RefreshPreviewChannelSelection + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RefreshPreviewChannelSelection ??= __type__?.GetMethodInfoByParameterTypeNames("RefreshPreviewChannelSelection"); + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextureImporterInspector.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextureImporterInspector.cs.meta new file mode 100644 index 0000000..78f33ce --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEditor_TextureImporterInspector.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b2b802697a206b941b1ff9930285d630 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_GUISkin.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_GUISkin.cs new file mode 100644 index 0000000..9d8a30f --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_GUISkin.cs @@ -0,0 +1,603 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEngine_GUISkin + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEngine.GUISkin"); + + public delegate void SkinChangedDelegate(); + + public UnityEngine.GUIStyle horizontalSliderThumbExtent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__horizontalSliderThumbExtent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __horizontalSliderThumbExtent?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle sliderMixed + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__sliderMixed?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __sliderMixed?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle verticalSliderThumbExtent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__verticalSliderThumbExtent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __verticalSliderThumbExtent?.SetValue(__self__, value); + } + + public static UnityEngine.GUIStyle error + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__error?.GetValue(null)); + } + + public UnityEngine.Font m_Font + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Font)(__m_Font?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Font?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_box + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_box?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_box?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_button + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_button?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_button?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_toggle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_toggle?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_toggle?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_label + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_label?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_label?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_textField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_textField?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_textField?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_textArea + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_textArea?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_textArea?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_window + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_window?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_window?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_horizontalSlider + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_horizontalSlider?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_horizontalSlider?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_horizontalSliderThumb + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_horizontalSliderThumb?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_horizontalSliderThumb?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_horizontalSliderThumbExtent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_horizontalSliderThumbExtent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_horizontalSliderThumbExtent?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_verticalSlider + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_verticalSlider?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_verticalSlider?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_verticalSliderThumb + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_verticalSliderThumb?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_verticalSliderThumb?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_verticalSliderThumbExtent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_verticalSliderThumbExtent?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_verticalSliderThumbExtent?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_SliderMixed + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_SliderMixed?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SliderMixed?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_horizontalScrollbar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_horizontalScrollbar?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_horizontalScrollbar?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_horizontalScrollbarThumb + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_horizontalScrollbarThumb?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_horizontalScrollbarThumb?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_horizontalScrollbarLeftButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_horizontalScrollbarLeftButton?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_horizontalScrollbarLeftButton?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_horizontalScrollbarRightButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_horizontalScrollbarRightButton?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_horizontalScrollbarRightButton?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_verticalScrollbar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_verticalScrollbar?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_verticalScrollbar?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_verticalScrollbarThumb + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_verticalScrollbarThumb?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_verticalScrollbarThumb?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_verticalScrollbarUpButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_verticalScrollbarUpButton?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_verticalScrollbarUpButton?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_verticalScrollbarDownButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_verticalScrollbarDownButton?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_verticalScrollbarDownButton?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle m_ScrollView + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__m_ScrollView?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_ScrollView?.SetValue(__self__, value); + } + + public UnityEngine.GUIStyle[] m_CustomStyles + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle[])(__m_CustomStyles?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_CustomStyles?.SetValue(__self__, value); + } + + public UnityEngine.GUISettings m_Settings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUISettings)(__m_Settings?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Settings?.SetValue(__self__, value); + } + + public static UnityEngine.GUIStyle ms_Error + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIStyle)(__ms_Error?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __ms_Error?.SetValue(null, value); + } + + public System.Collections.Generic.Dictionary m_Styles + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Generic.Dictionary)(__m_Styles?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Styles?.SetValue(__self__, value); + } + + public static SkinChangedDelegate m_SkinChanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (__m_SkinChanged?.GetValue(null) as Delegate)?.Cast(); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SkinChanged?.SetValue(null, value?.Cast(__m_SkinChanged.FieldType)); + } + + public static UnityEngine.GUISkin current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUISkin)(__current?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __current?.SetValue(null, value); + } + + public void OnEnable() + { + __OnEnable?.Invoke(__self__, System.Array.Empty()); + } + + public static void CleanupRoots() + { + __CleanupRoots?.Invoke(null, System.Array.Empty()); + } + + public void Apply() + { + __Apply?.Invoke(__self__, System.Array.Empty()); + } + + public void BuildStyleCache() + { + __BuildStyleCache?.Invoke(__self__, System.Array.Empty()); + } + + public void MakeCurrent() + { + __MakeCurrent?.Invoke(__self__, System.Array.Empty()); + } + + public UnityEngine_GUISkin(object __self__) => this.__self__ = __self__ as UnityEngine.Object; + public UnityEngine.Object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + public UnityEngine.GUISkin __super__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUISkin)(__self__); + } + + private static FieldInfo ___m_Font; + private static FieldInfo __m_Font + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Font ??= __type__?.GetField("m_Font", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_box; + private static FieldInfo __m_box + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_box ??= __type__?.GetField("m_box", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_button; + private static FieldInfo __m_button + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_button ??= __type__?.GetField("m_button", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_toggle; + private static FieldInfo __m_toggle + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_toggle ??= __type__?.GetField("m_toggle", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_label; + private static FieldInfo __m_label + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_label ??= __type__?.GetField("m_label", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_textField; + private static FieldInfo __m_textField + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_textField ??= __type__?.GetField("m_textField", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_textArea; + private static FieldInfo __m_textArea + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_textArea ??= __type__?.GetField("m_textArea", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_window; + private static FieldInfo __m_window + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_window ??= __type__?.GetField("m_window", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_horizontalSlider; + private static FieldInfo __m_horizontalSlider + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_horizontalSlider ??= __type__?.GetField("m_horizontalSlider", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_horizontalSliderThumb; + private static FieldInfo __m_horizontalSliderThumb + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_horizontalSliderThumb ??= __type__?.GetField("m_horizontalSliderThumb", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_horizontalSliderThumbExtent; + private static FieldInfo __m_horizontalSliderThumbExtent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_horizontalSliderThumbExtent ??= __type__?.GetField("m_horizontalSliderThumbExtent", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_verticalSlider; + private static FieldInfo __m_verticalSlider + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_verticalSlider ??= __type__?.GetField("m_verticalSlider", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_verticalSliderThumb; + private static FieldInfo __m_verticalSliderThumb + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_verticalSliderThumb ??= __type__?.GetField("m_verticalSliderThumb", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_verticalSliderThumbExtent; + private static FieldInfo __m_verticalSliderThumbExtent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_verticalSliderThumbExtent ??= __type__?.GetField("m_verticalSliderThumbExtent", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SliderMixed; + private static FieldInfo __m_SliderMixed + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SliderMixed ??= __type__?.GetField("m_SliderMixed", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_horizontalScrollbar; + private static FieldInfo __m_horizontalScrollbar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_horizontalScrollbar ??= __type__?.GetField("m_horizontalScrollbar", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_horizontalScrollbarThumb; + private static FieldInfo __m_horizontalScrollbarThumb + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_horizontalScrollbarThumb ??= __type__?.GetField("m_horizontalScrollbarThumb", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_horizontalScrollbarLeftButton; + private static FieldInfo __m_horizontalScrollbarLeftButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_horizontalScrollbarLeftButton ??= __type__?.GetField("m_horizontalScrollbarLeftButton", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_horizontalScrollbarRightButton; + private static FieldInfo __m_horizontalScrollbarRightButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_horizontalScrollbarRightButton ??= __type__?.GetField("m_horizontalScrollbarRightButton", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_verticalScrollbar; + private static FieldInfo __m_verticalScrollbar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_verticalScrollbar ??= __type__?.GetField("m_verticalScrollbar", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_verticalScrollbarThumb; + private static FieldInfo __m_verticalScrollbarThumb + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_verticalScrollbarThumb ??= __type__?.GetField("m_verticalScrollbarThumb", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_verticalScrollbarUpButton; + private static FieldInfo __m_verticalScrollbarUpButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_verticalScrollbarUpButton ??= __type__?.GetField("m_verticalScrollbarUpButton", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_verticalScrollbarDownButton; + private static FieldInfo __m_verticalScrollbarDownButton + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_verticalScrollbarDownButton ??= __type__?.GetField("m_verticalScrollbarDownButton", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_ScrollView; + private static FieldInfo __m_ScrollView + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_ScrollView ??= __type__?.GetField("m_ScrollView", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_CustomStyles; + private static FieldInfo __m_CustomStyles + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_CustomStyles ??= __type__?.GetField("m_CustomStyles", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Settings; + private static FieldInfo __m_Settings + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Settings ??= __type__?.GetField("m_Settings", (BindingFlags)(-1)); + } + + private static FieldInfo ___ms_Error; + private static FieldInfo __ms_Error + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ms_Error ??= __type__?.GetField("ms_Error", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Styles; + private static FieldInfo __m_Styles + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Styles ??= __type__?.GetField("m_Styles", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SkinChanged; + private static FieldInfo __m_SkinChanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SkinChanged ??= __type__?.GetField("m_SkinChanged", (BindingFlags)(-1)); + } + + private static FieldInfo ___current; + private static FieldInfo __current + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___current ??= __type__?.GetField("current", (BindingFlags)(-1)); + } + + private static PropertyInfo ___horizontalSliderThumbExtent; + private static PropertyInfo __horizontalSliderThumbExtent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___horizontalSliderThumbExtent ??= __type__?.GetProperty("horizontalSliderThumbExtent", (BindingFlags)(-1)); + } + + private static PropertyInfo ___sliderMixed; + private static PropertyInfo __sliderMixed + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___sliderMixed ??= __type__?.GetProperty("sliderMixed", (BindingFlags)(-1)); + } + + private static PropertyInfo ___verticalSliderThumbExtent; + private static PropertyInfo __verticalSliderThumbExtent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___verticalSliderThumbExtent ??= __type__?.GetProperty("verticalSliderThumbExtent", (BindingFlags)(-1)); + } + + private static PropertyInfo ___error; + private static PropertyInfo __error + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___error ??= __type__?.GetProperty("error", (BindingFlags)(-1)); + } + + private static MethodInfo ___OnEnable; + private static MethodInfo __OnEnable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnEnable ??= __type__?.GetMethodInfoByParameterTypeNames("OnEnable"); + } + + private static MethodInfo ___CleanupRoots; + private static MethodInfo __CleanupRoots + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CleanupRoots ??= __type__?.GetMethodInfoByParameterTypeNames("CleanupRoots"); + } + + private static MethodInfo ___Apply; + private static MethodInfo __Apply + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Apply ??= __type__?.GetMethodInfoByParameterTypeNames("Apply"); + } + + private static MethodInfo ___BuildStyleCache; + private static MethodInfo __BuildStyleCache + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BuildStyleCache ??= __type__?.GetMethodInfoByParameterTypeNames("BuildStyleCache"); + } + + private static MethodInfo ___MakeCurrent; + private static MethodInfo __MakeCurrent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MakeCurrent ??= __type__?.GetMethodInfoByParameterTypeNames("MakeCurrent"); + } + } + public static class UnityEngine_GUISkin_Extension + { + public static UnityEngine_GUISkin ReflectionHelper(this UnityEngine.GUISkin self) => new(self); + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_GUISkin.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_GUISkin.cs.meta new file mode 100644 index 0000000..bb5f61e --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_GUISkin.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 875ed95a2d492aa458135ea9fee6d710 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_GUIUtility.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_GUIUtility.cs new file mode 100644 index 0000000..aa6d3c2 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_GUIUtility.cs @@ -0,0 +1,1148 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEngine_GUIUtility + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEngine.GUIUtility"); + + + public static float pixelsPerPoint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__pixelsPerPoint?.GetValue(null)); + } + + public static int guiDepth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__guiDepth?.GetValue(null)); + } + + public static UnityEngine.Vector2 s_EditorScreenPointOffset + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Vector2)(__s_EditorScreenPointOffset?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_EditorScreenPointOffset?.SetValue(null, value); + } + + public static bool mouseUsed + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__mouseUsed?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __mouseUsed?.SetValue(null, value); + } + + public static bool textFieldInput + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__textFieldInput?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __textFieldInput?.SetValue(null, value); + } + + public static bool manualTex2SRGBEnabled + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__manualTex2SRGBEnabled?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __manualTex2SRGBEnabled?.SetValue(null, value); + } + + public static string compositionString + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__compositionString?.GetValue(null)); + } + + public static UnityEngine.IMECompositionMode imeCompositionMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.IMECompositionMode)(__imeCompositionMode?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __imeCompositionMode?.SetValue(null, value); + } + + public static UnityEngine.Vector2 compositionCursorPos + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Vector2)(__compositionCursorPos?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __compositionCursorPos?.SetValue(null, value); + } + + public static bool guiIsExiting + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__guiIsExiting?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __guiIsExiting?.SetValue(null, value); + } + + public static int s_ControlCount + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_ControlCount?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ControlCount?.SetValue(null, value); + } + + public static int s_SkinMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_SkinMode?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_SkinMode?.SetValue(null, value); + } + + public static int s_OriginalID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__s_OriginalID?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_OriginalID?.SetValue(null, value); + } + + public static System.Action takeCapture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Action)(__takeCapture?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __takeCapture?.SetValue(null, value); + } + + public static System.Action releaseCapture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Action)(__releaseCapture?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __releaseCapture?.SetValue(null, value); + } + + public static System.Func processEvent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Func)(__processEvent?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __processEvent?.SetValue(null, value); + } + + public static System.Action cleanupRoots + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Action)(__cleanupRoots?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __cleanupRoots?.SetValue(null, value); + } + + public static System.Func endContainerGUIFromException + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Func)(__endContainerGUIFromException?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __endContainerGUIFromException?.SetValue(null, value); + } + + public static System.Action guiChanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Action)(__guiChanged?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __guiChanged?.SetValue(null, value); + } + + public static System.Func s_HasCurrentWindowKeyFocusFunc + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Func)(__s_HasCurrentWindowKeyFocusFunc?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_HasCurrentWindowKeyFocusFunc?.SetValue(null, value); + } + + public static int Internal_GetControlID(int hint, UnityEngine.FocusType focusType, UnityEngine.Rect rect) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = hint; + __params__[1] = focusType; + __params__[2] = rect; + var __result__ = __Internal_GetControlID?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static void BeginContainerFromOwner(UnityEngine.ScriptableObject owner) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = owner; + __BeginContainerFromOwner?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void BeginContainer(object objectGUIState) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = objectGUIState; + __BeginContainer?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void Internal_EndContainer() + { + __Internal_EndContainer?.Invoke(null, System.Array.Empty()); + } + + public static int GetPermanentControlID() + { + var __result__ = __GetPermanentControlID?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public static void UpdateUndoName() + { + __UpdateUndoName?.Invoke(null, System.Array.Empty()); + } + + public static int CheckForTabEvent(UnityEngine.Event evt) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = evt; + var __result__ = __CheckForTabEvent?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static void SetKeyboardControlToFirstControlId() + { + __SetKeyboardControlToFirstControlId?.Invoke(null, System.Array.Empty()); + } + + public static void SetKeyboardControlToLastControlId() + { + __SetKeyboardControlToLastControlId?.Invoke(null, System.Array.Empty()); + } + + public static bool HasFocusableControls() + { + var __result__ = __HasFocusableControls?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool OwnsId(int id) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = id; + var __result__ = __OwnsId?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static UnityEngine.Vector3 Internal_MultiplyPoint(UnityEngine.Vector3 point, UnityEngine.Matrix4x4 transform) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = point; + __params__[1] = transform; + var __result__ = __Internal_MultiplyPoint?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector3)(__result__) : default; + } + + public static bool GetChanged() + { + var __result__ = __GetChanged?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void SetChanged(bool changed) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = changed; + __SetChanged?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void SetDidGUIWindowsEatLastEvent(bool value) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = value; + __SetDidGUIWindowsEatLastEvent?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static int Internal_GetHotControl() + { + var __result__ = __Internal_GetHotControl?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public static int Internal_GetKeyboardControl() + { + var __result__ = __Internal_GetKeyboardControl?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public static void Internal_SetHotControl(int value) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = value; + __Internal_SetHotControl?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void Internal_SetKeyboardControl(int value) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = value; + __Internal_SetKeyboardControl?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static object Internal_GetDefaultSkin(int skinMode) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = skinMode; + var __result__ = __Internal_GetDefaultSkin?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (object)(__result__) : default; + } + + public static UnityEngine.Object Internal_GetBuiltinSkin(int skin) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = skin; + var __result__ = __Internal_GetBuiltinSkin?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Object)(__result__) : default; + } + + public static void Internal_ExitGUI() + { + __Internal_ExitGUI?.Invoke(null, System.Array.Empty()); + } + + public static UnityEngine.Vector2 InternalWindowToScreenPoint(UnityEngine.Vector2 windowPoint) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = windowPoint; + var __result__ = __InternalWindowToScreenPoint?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector2)(__result__) : default; + } + + public static UnityEngine.Vector2 InternalScreenToWindowPoint(UnityEngine.Vector2 screenPoint) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = screenPoint; + var __result__ = __InternalScreenToWindowPoint?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.Vector2)(__result__) : default; + } + + public static void MarkGUIChanged() + { + __MarkGUIChanged?.Invoke(null, System.Array.Empty()); + } + + public static void TakeCapture() + { + __TakeCapture?.Invoke(null, System.Array.Empty()); + } + + public static void RemoveCapture() + { + __RemoveCapture?.Invoke(null, System.Array.Empty()); + } + + public static bool HasKeyFocus(int controlID) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = controlID; + var __result__ = __HasKeyFocus?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static UnityEngine.GUISkin GetDefaultSkin(int skinMode) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = skinMode; + var __result__ = __GetDefaultSkin?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GUISkin)(__result__) : default; + } + + public static UnityEngine.GUISkin GetDefaultSkin() + { + var __result__ = __GetDefaultSkin__2?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (UnityEngine.GUISkin)(__result__) : default; + } + + public static UnityEngine.GUISkin GetBuiltinSkin(int skin) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = skin; + var __result__ = __GetBuiltinSkin?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.GUISkin)(__result__) : default; + } + + public static void ProcessEvent(int instanceID, System.IntPtr nativeEventPtr, out bool result) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = instanceID; + __params__[1] = nativeEventPtr; + __params__[2] = null; + __ProcessEvent?.Invoke(null, __params__); + result = (bool)(__params__[2]); + __pool__.Return(__params__); + } + + public static void EndContainer() + { + __EndContainer?.Invoke(null, System.Array.Empty()); + } + + public static void CleanupRoots() + { + __CleanupRoots?.Invoke(null, System.Array.Empty()); + } + + public static void BeginGUI(int skinMode, int instanceID, int useGUILayout) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = skinMode; + __params__[1] = instanceID; + __params__[2] = useGUILayout; + __BeginGUI?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void SetSkin(int skinMode) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = skinMode; + __SetSkin?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void EndGUI(int layoutType) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = layoutType; + __EndGUI?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static bool EndGUIFromException(System.Exception exception) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = exception; + var __result__ = __EndGUIFromException?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool EndContainerGUIFromException(System.Exception exception) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = exception; + var __result__ = __EndContainerGUIFromException?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void ResetGlobalState() + { + __ResetGlobalState?.Invoke(null, System.Array.Empty()); + } + + public static bool IsExitGUIException(System.Exception exception) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = exception; + var __result__ = __IsExitGUIException?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool ShouldRethrowException(System.Exception exception) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = exception; + var __result__ = __ShouldRethrowException?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static void CheckOnGUI() + { + __CheckOnGUI?.Invoke(null, System.Array.Empty()); + } + + public static float RoundToPixelGrid(float v) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = v; + var __result__ = __RoundToPixelGrid?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (float)(__result__) : default; + } + + public static bool HitTest(UnityEngine.Rect rect, UnityEngine.Vector2 point, int offset) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = point; + __params__[2] = offset; + var __result__ = __HitTest?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool HitTest(UnityEngine.Rect rect, UnityEngine.Vector2 point, bool isDirectManipulationDevice) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = point; + __params__[2] = isDirectManipulationDevice; + var __result__ = __HitTest__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool HitTest(UnityEngine.Rect rect, UnityEngine.Event evt) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = evt; + var __result__ = __HitTest__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static int Internal_GetControlID_Injected(int hint, UnityEngine.FocusType focusType, ref UnityEngine.Rect rect) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = hint; + __params__[1] = focusType; + __params__[2] = rect; + var __result__ = __Internal_GetControlID_Injected?.Invoke(null, __params__); + rect = (UnityEngine.Rect)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static void AlignRectToDevice_Injected(ref UnityEngine.Rect rect, out int widthInPixels, out int heightInPixels, out UnityEngine.Rect ret) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = rect; + __params__[1] = Activator.CreateInstance(typeof(int)); + __params__[2] = Activator.CreateInstance(typeof(int)); + __params__[3] = Activator.CreateInstance(typeof(UnityEngine.Rect)); + __AlignRectToDevice_Injected?.Invoke(null, __params__); + rect = (UnityEngine.Rect)(__params__[0]); + widthInPixels = (int)(__params__[1]); + heightInPixels = (int)(__params__[2]); + ret = (UnityEngine.Rect)(__params__[3]); + __pool__.Return(__params__); + } + + public static void Internal_MultiplyPoint_Injected(ref UnityEngine.Vector3 point, ref UnityEngine.Matrix4x4 transform, out UnityEngine.Vector3 ret) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = point; + __params__[1] = transform; + __params__[2] = Activator.CreateInstance(typeof(UnityEngine.Vector3)); + __Internal_MultiplyPoint_Injected?.Invoke(null, __params__); + point = (UnityEngine.Vector3)(__params__[0]); + transform = (UnityEngine.Matrix4x4)(__params__[1]); + ret = (UnityEngine.Vector3)(__params__[2]); + __pool__.Return(__params__); + } + + public static void InternalWindowToScreenPoint_Injected(ref UnityEngine.Vector2 windowPoint, out UnityEngine.Vector2 ret) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = windowPoint; + __params__[1] = Activator.CreateInstance(typeof(UnityEngine.Vector2)); + __InternalWindowToScreenPoint_Injected?.Invoke(null, __params__); + windowPoint = (UnityEngine.Vector2)(__params__[0]); + ret = (UnityEngine.Vector2)(__params__[1]); + __pool__.Return(__params__); + } + + public static void InternalScreenToWindowPoint_Injected(ref UnityEngine.Vector2 screenPoint, out UnityEngine.Vector2 ret) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = screenPoint; + __params__[1] = Activator.CreateInstance(typeof(UnityEngine.Vector2)); + __InternalScreenToWindowPoint_Injected?.Invoke(null, __params__); + screenPoint = (UnityEngine.Vector2)(__params__[0]); + ret = (UnityEngine.Vector2)(__params__[1]); + __pool__.Return(__params__); + } + + public UnityEngine_GUIUtility(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + public UnityEngine.GUIUtility __super__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIUtility)(__self__); + } + + private static FieldInfo ___s_ControlCount; + private static FieldInfo __s_ControlCount + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ControlCount ??= __type__?.GetField("s_ControlCount", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_SkinMode; + private static FieldInfo __s_SkinMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_SkinMode ??= __type__?.GetField("s_SkinMode", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_OriginalID; + private static FieldInfo __s_OriginalID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_OriginalID ??= __type__?.GetField("s_OriginalID", (BindingFlags)(-1)); + } + + private static FieldInfo ___takeCapture; + private static FieldInfo __takeCapture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___takeCapture ??= __type__?.GetField("takeCapture", (BindingFlags)(-1)); + } + + private static FieldInfo ___releaseCapture; + private static FieldInfo __releaseCapture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___releaseCapture ??= __type__?.GetField("releaseCapture", (BindingFlags)(-1)); + } + + private static FieldInfo ___processEvent; + private static FieldInfo __processEvent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___processEvent ??= __type__?.GetField("processEvent", (BindingFlags)(-1)); + } + + private static FieldInfo ___cleanupRoots; + private static FieldInfo __cleanupRoots + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___cleanupRoots ??= __type__?.GetField("cleanupRoots", (BindingFlags)(-1)); + } + + private static FieldInfo ___endContainerGUIFromException; + private static FieldInfo __endContainerGUIFromException + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___endContainerGUIFromException ??= __type__?.GetField("endContainerGUIFromException", (BindingFlags)(-1)); + } + + private static FieldInfo ___guiChanged; + private static FieldInfo __guiChanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___guiChanged ??= __type__?.GetField("guiChanged", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_HasCurrentWindowKeyFocusFunc; + private static FieldInfo __s_HasCurrentWindowKeyFocusFunc + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_HasCurrentWindowKeyFocusFunc ??= __type__?.GetField("s_HasCurrentWindowKeyFocusFunc", (BindingFlags)(-1)); + } + + private static PropertyInfo ___pixelsPerPoint; + private static PropertyInfo __pixelsPerPoint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___pixelsPerPoint ??= __type__?.GetProperty("pixelsPerPoint", (BindingFlags)(-1)); + } + + private static PropertyInfo ___guiDepth; + private static PropertyInfo __guiDepth + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___guiDepth ??= __type__?.GetProperty("guiDepth", (BindingFlags)(-1)); + } + + private static PropertyInfo ___s_EditorScreenPointOffset; + private static PropertyInfo __s_EditorScreenPointOffset + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_EditorScreenPointOffset ??= __type__?.GetProperty("s_EditorScreenPointOffset", (BindingFlags)(-1)); + } + + private static PropertyInfo ___mouseUsed; + private static PropertyInfo __mouseUsed + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___mouseUsed ??= __type__?.GetProperty("mouseUsed", (BindingFlags)(-1)); + } + + private static PropertyInfo ___textFieldInput; + private static PropertyInfo __textFieldInput + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___textFieldInput ??= __type__?.GetProperty("textFieldInput", (BindingFlags)(-1)); + } + + private static PropertyInfo ___manualTex2SRGBEnabled; + private static PropertyInfo __manualTex2SRGBEnabled + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___manualTex2SRGBEnabled ??= __type__?.GetProperty("manualTex2SRGBEnabled", (BindingFlags)(-1)); + } + + private static PropertyInfo ___compositionString; + private static PropertyInfo __compositionString + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___compositionString ??= __type__?.GetProperty("compositionString", (BindingFlags)(-1)); + } + + private static PropertyInfo ___imeCompositionMode; + private static PropertyInfo __imeCompositionMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___imeCompositionMode ??= __type__?.GetProperty("imeCompositionMode", (BindingFlags)(-1)); + } + + private static PropertyInfo ___compositionCursorPos; + private static PropertyInfo __compositionCursorPos + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___compositionCursorPos ??= __type__?.GetProperty("compositionCursorPos", (BindingFlags)(-1)); + } + + private static PropertyInfo ___guiIsExiting; + private static PropertyInfo __guiIsExiting + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___guiIsExiting ??= __type__?.GetProperty("guiIsExiting", (BindingFlags)(-1)); + } + + private static MethodInfo ___Internal_GetControlID; + private static MethodInfo __Internal_GetControlID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_GetControlID ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_GetControlID", "System.Int32", "UnityEngine.FocusType", "UnityEngine.Rect"); + } + + private static MethodInfo ___BeginContainerFromOwner; + private static MethodInfo __BeginContainerFromOwner + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginContainerFromOwner ??= __type__?.GetMethodInfoByParameterTypeNames("BeginContainerFromOwner", "UnityEngine.ScriptableObject"); + } + + private static MethodInfo ___BeginContainer; + private static MethodInfo __BeginContainer + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginContainer ??= __type__?.GetMethodInfoByParameterTypeNames("BeginContainer", "UnityEngine.ObjectGUIState"); + } + + private static MethodInfo ___Internal_EndContainer; + private static MethodInfo __Internal_EndContainer + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_EndContainer ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_EndContainer"); + } + + private static MethodInfo ___GetPermanentControlID; + private static MethodInfo __GetPermanentControlID + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPermanentControlID ??= __type__?.GetMethodInfoByParameterTypeNames("GetPermanentControlID"); + } + + private static MethodInfo ___UpdateUndoName; + private static MethodInfo __UpdateUndoName + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UpdateUndoName ??= __type__?.GetMethodInfoByParameterTypeNames("UpdateUndoName"); + } + + private static MethodInfo ___CheckForTabEvent; + private static MethodInfo __CheckForTabEvent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CheckForTabEvent ??= __type__?.GetMethodInfoByParameterTypeNames("CheckForTabEvent", "UnityEngine.Event"); + } + + private static MethodInfo ___SetKeyboardControlToFirstControlId; + private static MethodInfo __SetKeyboardControlToFirstControlId + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetKeyboardControlToFirstControlId ??= __type__?.GetMethodInfoByParameterTypeNames("SetKeyboardControlToFirstControlId"); + } + + private static MethodInfo ___SetKeyboardControlToLastControlId; + private static MethodInfo __SetKeyboardControlToLastControlId + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetKeyboardControlToLastControlId ??= __type__?.GetMethodInfoByParameterTypeNames("SetKeyboardControlToLastControlId"); + } + + private static MethodInfo ___HasFocusableControls; + private static MethodInfo __HasFocusableControls + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasFocusableControls ??= __type__?.GetMethodInfoByParameterTypeNames("HasFocusableControls"); + } + + private static MethodInfo ___OwnsId; + private static MethodInfo __OwnsId + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OwnsId ??= __type__?.GetMethodInfoByParameterTypeNames("OwnsId", "System.Int32"); + } + + private static MethodInfo ___Internal_MultiplyPoint; + private static MethodInfo __Internal_MultiplyPoint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_MultiplyPoint ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_MultiplyPoint", "UnityEngine.Vector3", "UnityEngine.Matrix4x4"); + } + + private static MethodInfo ___GetChanged; + private static MethodInfo __GetChanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetChanged ??= __type__?.GetMethodInfoByParameterTypeNames("GetChanged"); + } + + private static MethodInfo ___SetChanged; + private static MethodInfo __SetChanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetChanged ??= __type__?.GetMethodInfoByParameterTypeNames("SetChanged", "System.Boolean"); + } + + private static MethodInfo ___SetDidGUIWindowsEatLastEvent; + private static MethodInfo __SetDidGUIWindowsEatLastEvent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetDidGUIWindowsEatLastEvent ??= __type__?.GetMethodInfoByParameterTypeNames("SetDidGUIWindowsEatLastEvent", "System.Boolean"); + } + + private static MethodInfo ___Internal_GetHotControl; + private static MethodInfo __Internal_GetHotControl + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_GetHotControl ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_GetHotControl"); + } + + private static MethodInfo ___Internal_GetKeyboardControl; + private static MethodInfo __Internal_GetKeyboardControl + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_GetKeyboardControl ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_GetKeyboardControl"); + } + + private static MethodInfo ___Internal_SetHotControl; + private static MethodInfo __Internal_SetHotControl + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_SetHotControl ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_SetHotControl", "System.Int32"); + } + + private static MethodInfo ___Internal_SetKeyboardControl; + private static MethodInfo __Internal_SetKeyboardControl + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_SetKeyboardControl ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_SetKeyboardControl", "System.Int32"); + } + + private static MethodInfo ___Internal_GetDefaultSkin; + private static MethodInfo __Internal_GetDefaultSkin + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_GetDefaultSkin ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_GetDefaultSkin", "System.Int32"); + } + + private static MethodInfo ___Internal_GetBuiltinSkin; + private static MethodInfo __Internal_GetBuiltinSkin + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_GetBuiltinSkin ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_GetBuiltinSkin", "System.Int32"); + } + + private static MethodInfo ___Internal_ExitGUI; + private static MethodInfo __Internal_ExitGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_ExitGUI ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_ExitGUI"); + } + + private static MethodInfo ___InternalWindowToScreenPoint; + private static MethodInfo __InternalWindowToScreenPoint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___InternalWindowToScreenPoint ??= __type__?.GetMethodInfoByParameterTypeNames("InternalWindowToScreenPoint", "UnityEngine.Vector2"); + } + + private static MethodInfo ___InternalScreenToWindowPoint; + private static MethodInfo __InternalScreenToWindowPoint + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___InternalScreenToWindowPoint ??= __type__?.GetMethodInfoByParameterTypeNames("InternalScreenToWindowPoint", "UnityEngine.Vector2"); + } + + private static MethodInfo ___MarkGUIChanged; + private static MethodInfo __MarkGUIChanged + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MarkGUIChanged ??= __type__?.GetMethodInfoByParameterTypeNames("MarkGUIChanged"); + } + + private static MethodInfo ___TakeCapture; + private static MethodInfo __TakeCapture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TakeCapture ??= __type__?.GetMethodInfoByParameterTypeNames("TakeCapture"); + } + + private static MethodInfo ___RemoveCapture; + private static MethodInfo __RemoveCapture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RemoveCapture ??= __type__?.GetMethodInfoByParameterTypeNames("RemoveCapture"); + } + + private static MethodInfo ___HasKeyFocus; + private static MethodInfo __HasKeyFocus + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HasKeyFocus ??= __type__?.GetMethodInfoByParameterTypeNames("HasKeyFocus", "System.Int32"); + } + + private static MethodInfo ___GetDefaultSkin; + private static MethodInfo __GetDefaultSkin + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetDefaultSkin ??= __type__?.GetMethodInfoByParameterTypeNames("GetDefaultSkin", "System.Int32"); + } + + private static MethodInfo ___GetDefaultSkin__2; + private static MethodInfo __GetDefaultSkin__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetDefaultSkin__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GetDefaultSkin"); + } + + private static MethodInfo ___GetBuiltinSkin; + private static MethodInfo __GetBuiltinSkin + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetBuiltinSkin ??= __type__?.GetMethodInfoByParameterTypeNames("GetBuiltinSkin", "System.Int32"); + } + + private static MethodInfo ___ProcessEvent; + private static MethodInfo __ProcessEvent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ProcessEvent ??= __type__?.GetMethodInfoByParameterTypeNames("ProcessEvent", "System.Int32", "System.IntPtr", "System.Boolean&"); + } + + private static MethodInfo ___EndContainer; + private static MethodInfo __EndContainer + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EndContainer ??= __type__?.GetMethodInfoByParameterTypeNames("EndContainer"); + } + + private static MethodInfo ___CleanupRoots; + private static MethodInfo __CleanupRoots + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CleanupRoots ??= __type__?.GetMethodInfoByParameterTypeNames("CleanupRoots"); + } + + private static MethodInfo ___BeginGUI; + private static MethodInfo __BeginGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___BeginGUI ??= __type__?.GetMethodInfoByParameterTypeNames("BeginGUI", "System.Int32", "System.Int32", "System.Int32"); + } + + private static MethodInfo ___SetSkin; + private static MethodInfo __SetSkin + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetSkin ??= __type__?.GetMethodInfoByParameterTypeNames("SetSkin", "System.Int32"); + } + + private static MethodInfo ___EndGUI; + private static MethodInfo __EndGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EndGUI ??= __type__?.GetMethodInfoByParameterTypeNames("EndGUI", "System.Int32"); + } + + private static MethodInfo ___EndGUIFromException; + private static MethodInfo __EndGUIFromException + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EndGUIFromException ??= __type__?.GetMethodInfoByParameterTypeNames("EndGUIFromException", "System.Exception"); + } + + private static MethodInfo ___EndContainerGUIFromException; + private static MethodInfo __EndContainerGUIFromException + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EndContainerGUIFromException ??= __type__?.GetMethodInfoByParameterTypeNames("EndContainerGUIFromException", "System.Exception"); + } + + private static MethodInfo ___ResetGlobalState; + private static MethodInfo __ResetGlobalState + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ResetGlobalState ??= __type__?.GetMethodInfoByParameterTypeNames("ResetGlobalState"); + } + + private static MethodInfo ___IsExitGUIException; + private static MethodInfo __IsExitGUIException + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsExitGUIException ??= __type__?.GetMethodInfoByParameterTypeNames("IsExitGUIException", "System.Exception"); + } + + private static MethodInfo ___ShouldRethrowException; + private static MethodInfo __ShouldRethrowException + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ShouldRethrowException ??= __type__?.GetMethodInfoByParameterTypeNames("ShouldRethrowException", "System.Exception"); + } + + private static MethodInfo ___CheckOnGUI; + private static MethodInfo __CheckOnGUI + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___CheckOnGUI ??= __type__?.GetMethodInfoByParameterTypeNames("CheckOnGUI"); + } + + private static MethodInfo ___RoundToPixelGrid; + private static MethodInfo __RoundToPixelGrid + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RoundToPixelGrid ??= __type__?.GetMethodInfoByParameterTypeNames("RoundToPixelGrid", "System.Single"); + } + + private static MethodInfo ___HitTest; + private static MethodInfo __HitTest + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HitTest ??= __type__?.GetMethodInfoByParameterTypeNames("HitTest", "UnityEngine.Rect", "UnityEngine.Vector2", "System.Int32"); + } + + private static MethodInfo ___HitTest__2; + private static MethodInfo __HitTest__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HitTest__2 ??= __type__?.GetMethodInfoByParameterTypeNames("HitTest", "UnityEngine.Rect", "UnityEngine.Vector2", "System.Boolean"); + } + + private static MethodInfo ___HitTest__3; + private static MethodInfo __HitTest__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HitTest__3 ??= __type__?.GetMethodInfoByParameterTypeNames("HitTest", "UnityEngine.Rect", "UnityEngine.Event"); + } + + private static MethodInfo ___Internal_GetControlID_Injected; + private static MethodInfo __Internal_GetControlID_Injected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_GetControlID_Injected ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_GetControlID_Injected", "System.Int32", "UnityEngine.FocusType", "UnityEngine.Rect&"); + } + + private static MethodInfo ___AlignRectToDevice_Injected; + private static MethodInfo __AlignRectToDevice_Injected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___AlignRectToDevice_Injected ??= __type__?.GetMethodInfoByParameterTypeNames("AlignRectToDevice_Injected", "UnityEngine.Rect&", "System.Int32&", "System.Int32&", "UnityEngine.Rect&"); + } + + private static MethodInfo ___Internal_MultiplyPoint_Injected; + private static MethodInfo __Internal_MultiplyPoint_Injected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___Internal_MultiplyPoint_Injected ??= __type__?.GetMethodInfoByParameterTypeNames("Internal_MultiplyPoint_Injected", "UnityEngine.Vector3&", "UnityEngine.Matrix4x4&", "UnityEngine.Vector3&"); + } + + private static MethodInfo ___InternalWindowToScreenPoint_Injected; + private static MethodInfo __InternalWindowToScreenPoint_Injected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___InternalWindowToScreenPoint_Injected ??= __type__?.GetMethodInfoByParameterTypeNames("InternalWindowToScreenPoint_Injected", "UnityEngine.Vector2&", "UnityEngine.Vector2&"); + } + + private static MethodInfo ___InternalScreenToWindowPoint_Injected; + private static MethodInfo __InternalScreenToWindowPoint_Injected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___InternalScreenToWindowPoint_Injected ??= __type__?.GetMethodInfoByParameterTypeNames("InternalScreenToWindowPoint_Injected", "UnityEngine.Vector2&", "UnityEngine.Vector2&"); + } + } + public static class UnityEngine_GUIUtility_Extension + { + public static UnityEngine_GUIUtility ReflectionHelper(this UnityEngine.GUIUtility self) => new(self); + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_GUIUtility.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_GUIUtility.cs.meta new file mode 100644 index 0000000..26b4981 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_GUIUtility.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d37c46e54956fd14599544dd67bb7c31 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_TextCore_LowLevel_FontEngine.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_TextCore_LowLevel_FontEngine.cs new file mode 100644 index 0000000..58ac68e --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_TextCore_LowLevel_FontEngine.cs @@ -0,0 +1,3222 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEngine_TextCore_LowLevel_FontEngine + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEngine.TextCore.LowLevel.FontEngine"); + + + public static bool isProcessingDone + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__isProcessingDone?.GetValue(null)); + } + + public static float generationProgress + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (float)(__generationProgress?.GetValue(null)); + } + + public static UnityEngine.TextCore.Glyph[] s_Glyphs + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.TextCore.Glyph[])(__s_Glyphs?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_Glyphs?.SetValue(null, value); + } + + public static uint[] s_GlyphIndexes_MarshallingArray_A + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (uint[])(__s_GlyphIndexes_MarshallingArray_A?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_GlyphIndexes_MarshallingArray_A?.SetValue(null, value); + } + + public static uint[] s_GlyphIndexes_MarshallingArray_B + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (uint[])(__s_GlyphIndexes_MarshallingArray_B?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_GlyphIndexes_MarshallingArray_B?.SetValue(null, value); + } + + public static Array s_GlyphMarshallingStruct_IN + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (Array)(__s_GlyphMarshallingStruct_IN?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_GlyphMarshallingStruct_IN?.SetValue(null, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static object s_GlyphMarshallingStruct_IN__GetItem(int i) => (object)(s_GlyphMarshallingStruct_IN?.GetValue(i)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void s_GlyphMarshallingStruct_IN__SetItem(int i, object value) => s_GlyphMarshallingStruct_IN?.SetValue(value, i); + + public static Array s_GlyphMarshallingStruct_OUT + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (Array)(__s_GlyphMarshallingStruct_OUT?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_GlyphMarshallingStruct_OUT?.SetValue(null, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static object s_GlyphMarshallingStruct_OUT__GetItem(int i) => (object)(s_GlyphMarshallingStruct_OUT?.GetValue(i)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void s_GlyphMarshallingStruct_OUT__SetItem(int i, object value) => s_GlyphMarshallingStruct_OUT?.SetValue(value, i); + + public static UnityEngine.TextCore.GlyphRect[] s_FreeGlyphRects + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.TextCore.GlyphRect[])(__s_FreeGlyphRects?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_FreeGlyphRects?.SetValue(null, value); + } + + public static UnityEngine.TextCore.GlyphRect[] s_UsedGlyphRects + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.TextCore.GlyphRect[])(__s_UsedGlyphRects?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_UsedGlyphRects?.SetValue(null, value); + } + + public static UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord[] s_SingleAdjustmentRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord[])(__s_SingleAdjustmentRecords_MarshallingArray?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_SingleAdjustmentRecords_MarshallingArray?.SetValue(null, value); + } + + public static Array s_SingleSubstitutionRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (Array)(__s_SingleSubstitutionRecords_MarshallingArray?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_SingleSubstitutionRecords_MarshallingArray?.SetValue(null, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static object s_SingleSubstitutionRecords_MarshallingArray__GetItem(int i) => (object)(s_SingleSubstitutionRecords_MarshallingArray?.GetValue(i)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void s_SingleSubstitutionRecords_MarshallingArray__SetItem(int i, object value) => s_SingleSubstitutionRecords_MarshallingArray?.SetValue(value, i); + + public static Array s_MultipleSubstitutionRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (Array)(__s_MultipleSubstitutionRecords_MarshallingArray?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_MultipleSubstitutionRecords_MarshallingArray?.SetValue(null, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static object s_MultipleSubstitutionRecords_MarshallingArray__GetItem(int i) => (object)(s_MultipleSubstitutionRecords_MarshallingArray?.GetValue(i)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void s_MultipleSubstitutionRecords_MarshallingArray__SetItem(int i, object value) => s_MultipleSubstitutionRecords_MarshallingArray?.SetValue(value, i); + + public static Array s_AlternateSubstitutionRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (Array)(__s_AlternateSubstitutionRecords_MarshallingArray?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_AlternateSubstitutionRecords_MarshallingArray?.SetValue(null, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static object s_AlternateSubstitutionRecords_MarshallingArray__GetItem(int i) => (object)(s_AlternateSubstitutionRecords_MarshallingArray?.GetValue(i)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void s_AlternateSubstitutionRecords_MarshallingArray__SetItem(int i, object value) => s_AlternateSubstitutionRecords_MarshallingArray?.SetValue(value, i); + + public static Array s_LigatureSubstitutionRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (Array)(__s_LigatureSubstitutionRecords_MarshallingArray?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_LigatureSubstitutionRecords_MarshallingArray?.SetValue(null, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static object s_LigatureSubstitutionRecords_MarshallingArray__GetItem(int i) => (object)(s_LigatureSubstitutionRecords_MarshallingArray?.GetValue(i)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void s_LigatureSubstitutionRecords_MarshallingArray__SetItem(int i, object value) => s_LigatureSubstitutionRecords_MarshallingArray?.SetValue(value, i); + + public static Array s_ContextualSubstitutionRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (Array)(__s_ContextualSubstitutionRecords_MarshallingArray?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ContextualSubstitutionRecords_MarshallingArray?.SetValue(null, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static object s_ContextualSubstitutionRecords_MarshallingArray__GetItem(int i) => (object)(s_ContextualSubstitutionRecords_MarshallingArray?.GetValue(i)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void s_ContextualSubstitutionRecords_MarshallingArray__SetItem(int i, object value) => s_ContextualSubstitutionRecords_MarshallingArray?.SetValue(value, i); + + public static Array s_ChainingContextualSubstitutionRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (Array)(__s_ChainingContextualSubstitutionRecords_MarshallingArray?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_ChainingContextualSubstitutionRecords_MarshallingArray?.SetValue(null, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static object s_ChainingContextualSubstitutionRecords_MarshallingArray__GetItem(int i) => (object)(s_ChainingContextualSubstitutionRecords_MarshallingArray?.GetValue(i)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void s_ChainingContextualSubstitutionRecords_MarshallingArray__SetItem(int i, object value) => s_ChainingContextualSubstitutionRecords_MarshallingArray?.SetValue(value, i); + + public static UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[] s_PairAdjustmentRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[])(__s_PairAdjustmentRecords_MarshallingArray?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_PairAdjustmentRecords_MarshallingArray?.SetValue(null, value); + } + + public static Array s_MarkToBaseAdjustmentRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (Array)(__s_MarkToBaseAdjustmentRecords_MarshallingArray?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_MarkToBaseAdjustmentRecords_MarshallingArray?.SetValue(null, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static object s_MarkToBaseAdjustmentRecords_MarshallingArray__GetItem(int i) => (object)(s_MarkToBaseAdjustmentRecords_MarshallingArray?.GetValue(i)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void s_MarkToBaseAdjustmentRecords_MarshallingArray__SetItem(int i, object value) => s_MarkToBaseAdjustmentRecords_MarshallingArray?.SetValue(value, i); + + public static Array s_MarkToMarkAdjustmentRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (Array)(__s_MarkToMarkAdjustmentRecords_MarshallingArray?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_MarkToMarkAdjustmentRecords_MarshallingArray?.SetValue(null, value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static object s_MarkToMarkAdjustmentRecords_MarshallingArray__GetItem(int i) => (object)(s_MarkToMarkAdjustmentRecords_MarshallingArray?.GetValue(i)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void s_MarkToMarkAdjustmentRecords_MarshallingArray__SetItem(int i, object value) => s_MarkToMarkAdjustmentRecords_MarshallingArray?.SetValue(value, i); + + public static System.Collections.Generic.Dictionary s_GlyphLookupDictionary + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.Generic.Dictionary)(__s_GlyphLookupDictionary?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_GlyphLookupDictionary?.SetValue(null, value); + } + + public static int InitializeFontEngine_Internal() + { + var __result__ = __InitializeFontEngine_Internal?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public static int DestroyFontEngine_Internal() + { + var __result__ = __DestroyFontEngine_Internal?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public static void SendCancellationRequest() + { + __SendCancellationRequest?.Invoke(null, System.Array.Empty()); + } + + public static void SendCancellationRequest_Internal() + { + __SendCancellationRequest_Internal?.Invoke(null, System.Array.Empty()); + } + + public static int LoadFontFace_Internal(string filePath) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = filePath; + var __result__ = __LoadFontFace_Internal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int LoadFontFace_With_Size_Internal(string filePath, int pointSize) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = filePath; + __params__[1] = pointSize; + var __result__ = __LoadFontFace_With_Size_Internal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int LoadFontFace_With_Size_And_FaceIndex_Internal(string filePath, int pointSize, int faceIndex) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = filePath; + __params__[1] = pointSize; + __params__[2] = faceIndex; + var __result__ = __LoadFontFace_With_Size_And_FaceIndex_Internal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int LoadFontFace_FromSourceFontFile_Internal(byte[] sourceFontFile) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = sourceFontFile; + var __result__ = __LoadFontFace_FromSourceFontFile_Internal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int LoadFontFace_With_Size_FromSourceFontFile_Internal(byte[] sourceFontFile, int pointSize) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = sourceFontFile; + __params__[1] = pointSize; + var __result__ = __LoadFontFace_With_Size_FromSourceFontFile_Internal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int LoadFontFace_With_Size_And_FaceIndex_FromSourceFontFile_Internal(byte[] sourceFontFile, int pointSize, int faceIndex) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = sourceFontFile; + __params__[1] = pointSize; + __params__[2] = faceIndex; + var __result__ = __LoadFontFace_With_Size_And_FaceIndex_FromSourceFontFile_Internal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int LoadFontFace_FromFont_Internal(UnityEngine.Font font) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = font; + var __result__ = __LoadFontFace_FromFont_Internal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int LoadFontFace_With_Size_FromFont_Internal(UnityEngine.Font font, int pointSize) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = font; + __params__[1] = pointSize; + var __result__ = __LoadFontFace_With_Size_FromFont_Internal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int LoadFontFace_With_Size_and_FaceIndex_FromFont_Internal(UnityEngine.Font font, int pointSize, int faceIndex) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = font; + __params__[1] = pointSize; + __params__[2] = faceIndex; + var __result__ = __LoadFontFace_With_Size_and_FaceIndex_FromFont_Internal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int LoadFontFace_by_FamilyName_and_StyleName_Internal(string familyName, string styleName) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = familyName; + __params__[1] = styleName; + var __result__ = __LoadFontFace_by_FamilyName_and_StyleName_Internal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int LoadFontFace_With_Size_by_FamilyName_and_StyleName_Internal(string familyName, string styleName, int pointSize) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = familyName; + __params__[1] = styleName; + __params__[2] = pointSize; + var __result__ = __LoadFontFace_With_Size_by_FamilyName_and_StyleName_Internal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int UnloadFontFace_Internal() + { + var __result__ = __UnloadFontFace_Internal?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public static int UnloadAllFontFaces_Internal() + { + var __result__ = __UnloadAllFontFaces_Internal?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public static string[] GetSystemFontNames_Internal() + { + var __result__ = __GetSystemFontNames_Internal?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (string[])(__result__) : default; + } + + public static Array GetSystemFontReferences() + { + var __result__ = __GetSystemFontReferences?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (Array)(__result__) : default; + } + + public static bool TryGetSystemFontReference(string familyName, string styleName, out object fontRef) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = familyName; + __params__[1] = styleName; + __params__[2] = null; + var __result__ = __TryGetSystemFontReference?.Invoke(null, __params__); + fontRef = (object)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool TryGetSystemFontReference_Internal(string familyName, string styleName, out object fontRef) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = familyName; + __params__[1] = styleName; + __params__[2] = Activator.CreateInstance(typeof(object)); + var __result__ = __TryGetSystemFontReference_Internal?.Invoke(null, __params__); + fontRef = (object)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static int SetFaceSize_Internal(int pointSize) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = pointSize; + var __result__ = __SetFaceSize_Internal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int GetFaceInfo_Internal(ref UnityEngine.TextCore.FaceInfo faceInfo) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = faceInfo; + var __result__ = __GetFaceInfo_Internal?.Invoke(null, __params__); + faceInfo = (UnityEngine.TextCore.FaceInfo)(__params__[0]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int GetFaceCount() + { + var __result__ = __GetFaceCount?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (int)(__result__) : default; + } + + public static string[] GetFontFaces_Internal() + { + var __result__ = __GetFontFaces_Internal?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (string[])(__result__) : default; + } + + public static uint GetVariantGlyphIndex(uint unicode, uint variantSelectorUnicode) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = unicode; + __params__[1] = variantSelectorUnicode; + var __result__ = __GetVariantGlyphIndex?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (uint)(__result__) : default; + } + + public static uint GetGlyphIndex(uint unicode) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = unicode; + var __result__ = __GetGlyphIndex?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (uint)(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.FontEngineError LoadGlyph(uint unicode, UnityEngine.TextCore.LowLevel.GlyphLoadFlags flags) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = unicode; + __params__[1] = flags; + var __result__ = __LoadGlyph?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.FontEngineError)(__result__) : default; + } + + public static int LoadGlyph_Internal(uint unicode, UnityEngine.TextCore.LowLevel.GlyphLoadFlags loadFlags) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = unicode; + __params__[1] = loadFlags; + var __result__ = __LoadGlyph_Internal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static bool TryGetGlyphWithUnicodeValue_Internal(uint unicode, UnityEngine.TextCore.LowLevel.GlyphLoadFlags loadFlags, ref object glyphStruct) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = unicode; + __params__[1] = loadFlags; + __params__[2] = glyphStruct; + var __result__ = __TryGetGlyphWithUnicodeValue_Internal?.Invoke(null, __params__); + glyphStruct = (object)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool TryGetGlyphWithIndexValue_Internal(uint glyphIndex, UnityEngine.TextCore.LowLevel.GlyphLoadFlags loadFlags, ref object glyphStruct) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndex; + __params__[1] = loadFlags; + __params__[2] = glyphStruct; + var __result__ = __TryGetGlyphWithIndexValue_Internal?.Invoke(null, __params__); + glyphStruct = (object)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool TryPackGlyphInAtlas(UnityEngine.TextCore.Glyph glyph, int padding, UnityEngine.TextCore.LowLevel.GlyphPackingMode packingMode, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode, int width, int height, System.Collections.Generic.List freeGlyphRects, System.Collections.Generic.List usedGlyphRects) + { + var __pool__ = FixedArrayPool.Shared(8); + var __params__ = __pool__.Rent(); + __params__[0] = glyph; + __params__[1] = padding; + __params__[2] = packingMode; + __params__[3] = renderMode; + __params__[4] = width; + __params__[5] = height; + __params__[6] = freeGlyphRects; + __params__[7] = usedGlyphRects; + var __result__ = __TryPackGlyphInAtlas?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool TryPackGlyphInAtlas_Internal(ref object glyph, int padding, UnityEngine.TextCore.LowLevel.GlyphPackingMode packingMode, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode, int width, int height, out UnityEngine.TextCore.GlyphRect[] freeGlyphRects, ref int freeGlyphRectCount, out UnityEngine.TextCore.GlyphRect[] usedGlyphRects, ref int usedGlyphRectCount) + { + var __pool__ = FixedArrayPool.Shared(10); + var __params__ = __pool__.Rent(); + __params__[0] = glyph; + __params__[1] = padding; + __params__[2] = packingMode; + __params__[3] = renderMode; + __params__[4] = width; + __params__[5] = height; + __params__[6] = Activator.CreateInstance(typeof(UnityEngine.TextCore.GlyphRect[])); + __params__[7] = freeGlyphRectCount; + __params__[8] = Activator.CreateInstance(typeof(UnityEngine.TextCore.GlyphRect[])); + __params__[9] = usedGlyphRectCount; + var __result__ = __TryPackGlyphInAtlas_Internal?.Invoke(null, __params__); + glyph = (object)(__params__[0]); + freeGlyphRects = (UnityEngine.TextCore.GlyphRect[])(__params__[6]); + freeGlyphRectCount = (int)(__params__[7]); + usedGlyphRects = (UnityEngine.TextCore.GlyphRect[])(__params__[8]); + usedGlyphRectCount = (int)(__params__[9]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool TryPackGlyphsInAtlas(System.Collections.Generic.List glyphsToAdd, System.Collections.Generic.List glyphsAdded, int padding, UnityEngine.TextCore.LowLevel.GlyphPackingMode packingMode, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode, int width, int height, System.Collections.Generic.List freeGlyphRects, System.Collections.Generic.List usedGlyphRects) + { + var __pool__ = FixedArrayPool.Shared(9); + var __params__ = __pool__.Rent(); + __params__[0] = glyphsToAdd; + __params__[1] = glyphsAdded; + __params__[2] = padding; + __params__[3] = packingMode; + __params__[4] = renderMode; + __params__[5] = width; + __params__[6] = height; + __params__[7] = freeGlyphRects; + __params__[8] = usedGlyphRects; + var __result__ = __TryPackGlyphsInAtlas?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool TryPackGlyphsInAtlas_Internal(out Array glyphsToAdd, ref int glyphsToAddCount, out Array glyphsAdded, ref int glyphsAddedCount, int padding, UnityEngine.TextCore.LowLevel.GlyphPackingMode packingMode, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode, int width, int height, out UnityEngine.TextCore.GlyphRect[] freeGlyphRects, ref int freeGlyphRectCount, out UnityEngine.TextCore.GlyphRect[] usedGlyphRects, ref int usedGlyphRectCount) + { + var __pool__ = FixedArrayPool.Shared(13); + var __params__ = __pool__.Rent(); + __params__[0] = Activator.CreateInstance(typeof(Array)); + __params__[1] = glyphsToAddCount; + __params__[2] = Activator.CreateInstance(typeof(Array)); + __params__[3] = glyphsAddedCount; + __params__[4] = padding; + __params__[5] = packingMode; + __params__[6] = renderMode; + __params__[7] = width; + __params__[8] = height; + __params__[9] = Activator.CreateInstance(typeof(UnityEngine.TextCore.GlyphRect[])); + __params__[10] = freeGlyphRectCount; + __params__[11] = Activator.CreateInstance(typeof(UnityEngine.TextCore.GlyphRect[])); + __params__[12] = usedGlyphRectCount; + var __result__ = __TryPackGlyphsInAtlas_Internal?.Invoke(null, __params__); + glyphsToAdd = (Array)(__params__[0]); + glyphsToAddCount = (int)(__params__[1]); + glyphsAdded = (Array)(__params__[2]); + glyphsAddedCount = (int)(__params__[3]); + freeGlyphRects = (UnityEngine.TextCore.GlyphRect[])(__params__[9]); + freeGlyphRectCount = (int)(__params__[10]); + usedGlyphRects = (UnityEngine.TextCore.GlyphRect[])(__params__[11]); + usedGlyphRectCount = (int)(__params__[12]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.FontEngineError RenderGlyphToTexture(UnityEngine.TextCore.Glyph glyph, int padding, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode, UnityEngine.Texture2D texture) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = glyph; + __params__[1] = padding; + __params__[2] = renderMode; + __params__[3] = texture; + var __result__ = __RenderGlyphToTexture?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.FontEngineError)(__result__) : default; + } + + public static int RenderGlyphToTexture_Internal(object glyphStruct, int padding, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode, UnityEngine.Texture2D texture) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = glyphStruct; + __params__[1] = padding; + __params__[2] = renderMode; + __params__[3] = texture; + var __result__ = __RenderGlyphToTexture_Internal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.FontEngineError RenderGlyphsToTexture(System.Collections.Generic.List glyphs, int padding, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode, UnityEngine.Texture2D texture) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = glyphs; + __params__[1] = padding; + __params__[2] = renderMode; + __params__[3] = texture; + var __result__ = __RenderGlyphsToTexture?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.FontEngineError)(__result__) : default; + } + + public static int RenderGlyphsToTexture_Internal(Array glyphs, int glyphCount, int padding, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode, UnityEngine.Texture2D texture) + { + var __pool__ = FixedArrayPool.Shared(5); + var __params__ = __pool__.Rent(); + __params__[0] = glyphs; + __params__[1] = glyphCount; + __params__[2] = padding; + __params__[3] = renderMode; + __params__[4] = texture; + var __result__ = __RenderGlyphsToTexture_Internal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.FontEngineError RenderGlyphsToTexture(System.Collections.Generic.List glyphs, int padding, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode, byte[] texBuffer, int texWidth, int texHeight) + { + var __pool__ = FixedArrayPool.Shared(6); + var __params__ = __pool__.Rent(); + __params__[0] = glyphs; + __params__[1] = padding; + __params__[2] = renderMode; + __params__[3] = texBuffer; + __params__[4] = texWidth; + __params__[5] = texHeight; + var __result__ = __RenderGlyphsToTexture__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.FontEngineError)(__result__) : default; + } + + public static int RenderGlyphsToTextureBuffer_Internal(Array glyphs, int glyphCount, int padding, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode, out byte[] texBuffer, int texWidth, int texHeight) + { + var __pool__ = FixedArrayPool.Shared(7); + var __params__ = __pool__.Rent(); + __params__[0] = glyphs; + __params__[1] = glyphCount; + __params__[2] = padding; + __params__[3] = renderMode; + __params__[4] = Activator.CreateInstance(typeof(byte[])); + __params__[5] = texWidth; + __params__[6] = texHeight; + var __result__ = __RenderGlyphsToTextureBuffer_Internal?.Invoke(null, __params__); + texBuffer = (byte[])(__params__[4]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.FontEngineError RenderGlyphsToSharedTexture(System.Collections.Generic.List glyphs, int padding, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = glyphs; + __params__[1] = padding; + __params__[2] = renderMode; + var __result__ = __RenderGlyphsToSharedTexture?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.FontEngineError)(__result__) : default; + } + + public static int RenderGlyphsToSharedTexture_Internal(Array glyphs, int glyphCount, int padding, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = glyphs; + __params__[1] = glyphCount; + __params__[2] = padding; + __params__[3] = renderMode; + var __result__ = __RenderGlyphsToSharedTexture_Internal?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static void SetSharedTexture(UnityEngine.Texture2D texture) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = texture; + __SetSharedTexture?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void ReleaseSharedTexture() + { + __ReleaseSharedTexture?.Invoke(null, System.Array.Empty()); + } + + public static void SetTextureUploadMode(bool shouldUploadImmediately) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = shouldUploadImmediately; + __SetTextureUploadMode?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static bool TryAddGlyphToTexture(uint glyphIndex, int padding, UnityEngine.TextCore.LowLevel.GlyphPackingMode packingMode, System.Collections.Generic.List freeGlyphRects, System.Collections.Generic.List usedGlyphRects, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode, UnityEngine.Texture2D texture, out UnityEngine.TextCore.Glyph glyph) + { + var __pool__ = FixedArrayPool.Shared(8); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndex; + __params__[1] = padding; + __params__[2] = packingMode; + __params__[3] = freeGlyphRects; + __params__[4] = usedGlyphRects; + __params__[5] = renderMode; + __params__[6] = texture; + __params__[7] = null; + var __result__ = __TryAddGlyphToTexture?.Invoke(null, __params__); + glyph = (UnityEngine.TextCore.Glyph)(__params__[7]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool TryAddGlyphToTexture_Internal(uint glyphIndex, int padding, UnityEngine.TextCore.LowLevel.GlyphPackingMode packingMode, out UnityEngine.TextCore.GlyphRect[] freeGlyphRects, ref int freeGlyphRectCount, out UnityEngine.TextCore.GlyphRect[] usedGlyphRects, ref int usedGlyphRectCount, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode, UnityEngine.Texture2D texture, out object glyph) + { + var __pool__ = FixedArrayPool.Shared(10); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndex; + __params__[1] = padding; + __params__[2] = packingMode; + __params__[3] = Activator.CreateInstance(typeof(UnityEngine.TextCore.GlyphRect[])); + __params__[4] = freeGlyphRectCount; + __params__[5] = Activator.CreateInstance(typeof(UnityEngine.TextCore.GlyphRect[])); + __params__[6] = usedGlyphRectCount; + __params__[7] = renderMode; + __params__[8] = texture; + __params__[9] = Activator.CreateInstance(typeof(object)); + var __result__ = __TryAddGlyphToTexture_Internal?.Invoke(null, __params__); + freeGlyphRects = (UnityEngine.TextCore.GlyphRect[])(__params__[3]); + freeGlyphRectCount = (int)(__params__[4]); + usedGlyphRects = (UnityEngine.TextCore.GlyphRect[])(__params__[5]); + usedGlyphRectCount = (int)(__params__[6]); + glyph = (object)(__params__[9]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool TryAddGlyphsToTexture(System.Collections.Generic.List glyphsToAdd, System.Collections.Generic.List glyphsAdded, int padding, UnityEngine.TextCore.LowLevel.GlyphPackingMode packingMode, System.Collections.Generic.List freeGlyphRects, System.Collections.Generic.List usedGlyphRects, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode, UnityEngine.Texture2D texture) + { + var __pool__ = FixedArrayPool.Shared(8); + var __params__ = __pool__.Rent(); + __params__[0] = glyphsToAdd; + __params__[1] = glyphsAdded; + __params__[2] = padding; + __params__[3] = packingMode; + __params__[4] = freeGlyphRects; + __params__[5] = usedGlyphRects; + __params__[6] = renderMode; + __params__[7] = texture; + var __result__ = __TryAddGlyphsToTexture?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool TryAddGlyphsToTexture_Internal_MultiThread(out Array glyphsToAdd, ref int glyphsToAddCount, out Array glyphsAdded, ref int glyphsAddedCount, int padding, UnityEngine.TextCore.LowLevel.GlyphPackingMode packingMode, out UnityEngine.TextCore.GlyphRect[] freeGlyphRects, ref int freeGlyphRectCount, out UnityEngine.TextCore.GlyphRect[] usedGlyphRects, ref int usedGlyphRectCount, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode, UnityEngine.Texture2D texture) + { + var __pool__ = FixedArrayPool.Shared(12); + var __params__ = __pool__.Rent(); + __params__[0] = Activator.CreateInstance(typeof(Array)); + __params__[1] = glyphsToAddCount; + __params__[2] = Activator.CreateInstance(typeof(Array)); + __params__[3] = glyphsAddedCount; + __params__[4] = padding; + __params__[5] = packingMode; + __params__[6] = Activator.CreateInstance(typeof(UnityEngine.TextCore.GlyphRect[])); + __params__[7] = freeGlyphRectCount; + __params__[8] = Activator.CreateInstance(typeof(UnityEngine.TextCore.GlyphRect[])); + __params__[9] = usedGlyphRectCount; + __params__[10] = renderMode; + __params__[11] = texture; + var __result__ = __TryAddGlyphsToTexture_Internal_MultiThread?.Invoke(null, __params__); + glyphsToAdd = (Array)(__params__[0]); + glyphsToAddCount = (int)(__params__[1]); + glyphsAdded = (Array)(__params__[2]); + glyphsAddedCount = (int)(__params__[3]); + freeGlyphRects = (UnityEngine.TextCore.GlyphRect[])(__params__[6]); + freeGlyphRectCount = (int)(__params__[7]); + usedGlyphRects = (UnityEngine.TextCore.GlyphRect[])(__params__[8]); + usedGlyphRectCount = (int)(__params__[9]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool TryAddGlyphsToTexture(System.Collections.Generic.List glyphIndexes, int padding, UnityEngine.TextCore.LowLevel.GlyphPackingMode packingMode, System.Collections.Generic.List freeGlyphRects, System.Collections.Generic.List usedGlyphRects, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode, UnityEngine.Texture2D texture, out UnityEngine.TextCore.Glyph[] glyphs) + { + var __pool__ = FixedArrayPool.Shared(8); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + __params__[1] = padding; + __params__[2] = packingMode; + __params__[3] = freeGlyphRects; + __params__[4] = usedGlyphRects; + __params__[5] = renderMode; + __params__[6] = texture; + __params__[7] = null; + var __result__ = __TryAddGlyphsToTexture__2?.Invoke(null, __params__); + glyphs = (UnityEngine.TextCore.Glyph[])(__params__[7]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static bool TryAddGlyphsToTexture_Internal(uint[] glyphIndex, int padding, UnityEngine.TextCore.LowLevel.GlyphPackingMode packingMode, out UnityEngine.TextCore.GlyphRect[] freeGlyphRects, ref int freeGlyphRectCount, out UnityEngine.TextCore.GlyphRect[] usedGlyphRects, ref int usedGlyphRectCount, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode, UnityEngine.Texture2D texture, out Array glyphs, ref int glyphCount) + { + var __pool__ = FixedArrayPool.Shared(11); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndex; + __params__[1] = padding; + __params__[2] = packingMode; + __params__[3] = Activator.CreateInstance(typeof(UnityEngine.TextCore.GlyphRect[])); + __params__[4] = freeGlyphRectCount; + __params__[5] = Activator.CreateInstance(typeof(UnityEngine.TextCore.GlyphRect[])); + __params__[6] = usedGlyphRectCount; + __params__[7] = renderMode; + __params__[8] = texture; + __params__[9] = Activator.CreateInstance(typeof(Array)); + __params__[10] = glyphCount; + var __result__ = __TryAddGlyphsToTexture_Internal?.Invoke(null, __params__); + freeGlyphRects = (UnityEngine.TextCore.GlyphRect[])(__params__[3]); + freeGlyphRectCount = (int)(__params__[4]); + usedGlyphRects = (UnityEngine.TextCore.GlyphRect[])(__params__[5]); + usedGlyphRectCount = (int)(__params__[6]); + glyphs = (Array)(__params__[9]); + glyphCount = (int)(__params__[10]); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public static object GetOpenTypeLayoutTable(object type) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = type; + var __result__ = __GetOpenTypeLayoutTable?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (object)(__result__) : default; + } + + public static Array GetOpenTypeLayoutScripts() + { + var __result__ = __GetOpenTypeLayoutScripts?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetOpenTypeLayoutFeatures() + { + var __result__ = __GetOpenTypeLayoutFeatures?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetOpenTypeLayoutLookups() + { + var __result__ = __GetOpenTypeLayoutLookups?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetOpenTypeFontFeatureList() + { + var __result__ = __GetOpenTypeFontFeatureList?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetAllSingleSubstitutionRecords() + { + var __result__ = __GetAllSingleSubstitutionRecords?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetSingleSubstitutionRecords(int lookupIndex, uint glyphIndex) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndex; + var __result__ = __GetSingleSubstitutionRecords?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetSingleSubstitutionRecords(int lookupIndex, System.Collections.Generic.List glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetSingleSubstitutionRecords__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetSingleSubstitutionRecords(int lookupIndex, uint[] glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetSingleSubstitutionRecords__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static int PopulateSingleSubstitutionRecordMarshallingArray_from_GlyphIndexes(uint[] glyphIndexes, int lookupIndex, out int recordCount) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + __params__[1] = lookupIndex; + __params__[2] = Activator.CreateInstance(typeof(int)); + var __result__ = __PopulateSingleSubstitutionRecordMarshallingArray_from_GlyphIndexes?.Invoke(null, __params__); + recordCount = (int)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int GetSingleSubstitutionRecordsFromMarshallingArray(out Array singleSubstitutionRecords) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = Activator.CreateInstance(typeof(Array)); + var __result__ = __GetSingleSubstitutionRecordsFromMarshallingArray?.Invoke(null, __params__); + singleSubstitutionRecords = (Array)(__params__[0]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static Array GetAllMultipleSubstitutionRecords() + { + var __result__ = __GetAllMultipleSubstitutionRecords?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetMultipleSubstitutionRecords(int lookupIndex, uint glyphIndex) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndex; + var __result__ = __GetMultipleSubstitutionRecords?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetMultipleSubstitutionRecords(int lookupIndex, System.Collections.Generic.List glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetMultipleSubstitutionRecords__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetMultipleSubstitutionRecords(int lookupIndex, uint[] glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetMultipleSubstitutionRecords__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static int PopulateMultipleSubstitutionRecordMarshallingArray_from_GlyphIndexes(uint[] glyphIndexes, int lookupIndex, out int recordCount) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + __params__[1] = lookupIndex; + __params__[2] = Activator.CreateInstance(typeof(int)); + var __result__ = __PopulateMultipleSubstitutionRecordMarshallingArray_from_GlyphIndexes?.Invoke(null, __params__); + recordCount = (int)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int GetMultipleSubstitutionRecordsFromMarshallingArray(out Array substitutionRecords) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = Activator.CreateInstance(typeof(Array)); + var __result__ = __GetMultipleSubstitutionRecordsFromMarshallingArray?.Invoke(null, __params__); + substitutionRecords = (Array)(__params__[0]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static Array GetAllAlternateSubstitutionRecords() + { + var __result__ = __GetAllAlternateSubstitutionRecords?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetAlternateSubstitutionRecords(int lookupIndex, uint glyphIndex) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndex; + var __result__ = __GetAlternateSubstitutionRecords?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetAlternateSubstitutionRecords(int lookupIndex, System.Collections.Generic.List glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetAlternateSubstitutionRecords__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetAlternateSubstitutionRecords(int lookupIndex, uint[] glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetAlternateSubstitutionRecords__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static int PopulateAlternateSubstitutionRecordMarshallingArray_from_GlyphIndexes(uint[] glyphIndexes, int lookupIndex, out int recordCount) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + __params__[1] = lookupIndex; + __params__[2] = Activator.CreateInstance(typeof(int)); + var __result__ = __PopulateAlternateSubstitutionRecordMarshallingArray_from_GlyphIndexes?.Invoke(null, __params__); + recordCount = (int)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int GetAlternateSubstitutionRecordsFromMarshallingArray(out Array singleSubstitutionRecords) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = Activator.CreateInstance(typeof(Array)); + var __result__ = __GetAlternateSubstitutionRecordsFromMarshallingArray?.Invoke(null, __params__); + singleSubstitutionRecords = (Array)(__params__[0]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static Array GetAllLigatureSubstitutionRecords() + { + var __result__ = __GetAllLigatureSubstitutionRecords?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetLigatureSubstitutionRecords(uint glyphIndex) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndex; + var __result__ = __GetLigatureSubstitutionRecords?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetLigatureSubstitutionRecords(System.Collections.Generic.List glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + var __result__ = __GetLigatureSubstitutionRecords__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetLigatureSubstitutionRecords(int lookupIndex, uint glyphIndex) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndex; + var __result__ = __GetLigatureSubstitutionRecords__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetLigatureSubstitutionRecords(int lookupIndex, System.Collections.Generic.List glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetLigatureSubstitutionRecords__4?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetLigatureSubstitutionRecords(uint[] glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + var __result__ = __GetLigatureSubstitutionRecords__5?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetLigatureSubstitutionRecords(int lookupIndex, uint[] glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetLigatureSubstitutionRecords__6?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static int PopulateLigatureSubstitutionRecordMarshallingArray(uint[] glyphIndexes, out int recordCount) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + __params__[1] = Activator.CreateInstance(typeof(int)); + var __result__ = __PopulateLigatureSubstitutionRecordMarshallingArray?.Invoke(null, __params__); + recordCount = (int)(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int PopulateLigatureSubstitutionRecordMarshallingArray_for_LookupIndex(uint[] glyphIndexes, int lookupIndex, out int recordCount) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + __params__[1] = lookupIndex; + __params__[2] = Activator.CreateInstance(typeof(int)); + var __result__ = __PopulateLigatureSubstitutionRecordMarshallingArray_for_LookupIndex?.Invoke(null, __params__); + recordCount = (int)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int GetLigatureSubstitutionRecordsFromMarshallingArray(out Array ligatureSubstitutionRecords) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = Activator.CreateInstance(typeof(Array)); + var __result__ = __GetLigatureSubstitutionRecordsFromMarshallingArray?.Invoke(null, __params__); + ligatureSubstitutionRecords = (Array)(__params__[0]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static Array GetAllContextualSubstitutionRecords() + { + var __result__ = __GetAllContextualSubstitutionRecords?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetContextualSubstitutionRecords(int lookupIndex, uint glyphIndex) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndex; + var __result__ = __GetContextualSubstitutionRecords?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetContextualSubstitutionRecords(int lookupIndex, System.Collections.Generic.List glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetContextualSubstitutionRecords__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetContextualSubstitutionRecords(int lookupIndex, uint[] glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetContextualSubstitutionRecords__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static int PopulateContextualSubstitutionRecordMarshallingArray_from_GlyphIndexes(uint[] glyphIndexes, int lookupIndex, out int recordCount) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + __params__[1] = lookupIndex; + __params__[2] = Activator.CreateInstance(typeof(int)); + var __result__ = __PopulateContextualSubstitutionRecordMarshallingArray_from_GlyphIndexes?.Invoke(null, __params__); + recordCount = (int)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int GetContextualSubstitutionRecordsFromMarshallingArray(out Array substitutionRecords) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = Activator.CreateInstance(typeof(Array)); + var __result__ = __GetContextualSubstitutionRecordsFromMarshallingArray?.Invoke(null, __params__); + substitutionRecords = (Array)(__params__[0]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static Array GetAllChainingContextualSubstitutionRecords() + { + var __result__ = __GetAllChainingContextualSubstitutionRecords?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetChainingContextualSubstitutionRecords(int lookupIndex, uint glyphIndex) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndex; + var __result__ = __GetChainingContextualSubstitutionRecords?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetChainingContextualSubstitutionRecords(int lookupIndex, System.Collections.Generic.List glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetChainingContextualSubstitutionRecords__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetChainingContextualSubstitutionRecords(int lookupIndex, uint[] glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetChainingContextualSubstitutionRecords__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static int PopulateChainingContextualSubstitutionRecordMarshallingArray_from_GlyphIndexes(uint[] glyphIndexes, int lookupIndex, out int recordCount) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + __params__[1] = lookupIndex; + __params__[2] = Activator.CreateInstance(typeof(int)); + var __result__ = __PopulateChainingContextualSubstitutionRecordMarshallingArray_from_GlyphIndexes?.Invoke(null, __params__); + recordCount = (int)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int GetChainingContextualSubstitutionRecordsFromMarshallingArray(out Array substitutionRecords) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = Activator.CreateInstance(typeof(Array)); + var __result__ = __GetChainingContextualSubstitutionRecordsFromMarshallingArray?.Invoke(null, __params__); + substitutionRecords = (Array)(__params__[0]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[] GetGlyphPairAdjustmentTable(uint[] glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + var __result__ = __GetGlyphPairAdjustmentTable?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[])(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[] GetGlyphPairAdjustmentRecords(System.Collections.Generic.List glyphIndexes, out int recordCount) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + __params__[1] = null; + var __result__ = __GetGlyphPairAdjustmentRecords?.Invoke(null, __params__); + recordCount = (int)(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[])(__result__) : default; + } + + public static int PopulatePairAdjustmentRecordMarshallingArray_from_KernTable(uint[] glyphIndexes, out int recordCount) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + __params__[1] = Activator.CreateInstance(typeof(int)); + var __result__ = __PopulatePairAdjustmentRecordMarshallingArray_from_KernTable?.Invoke(null, __params__); + recordCount = (int)(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[] GetGlyphPairAdjustmentRecords(uint glyphIndex, out int recordCount) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndex; + __params__[1] = null; + var __result__ = __GetGlyphPairAdjustmentRecords__2?.Invoke(null, __params__); + recordCount = (int)(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[])(__result__) : default; + } + + public static int PopulatePairAdjustmentRecordMarshallingArray_from_GlyphIndex(uint glyphIndex, out int recordCount) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndex; + __params__[1] = Activator.CreateInstance(typeof(int)); + var __result__ = __PopulatePairAdjustmentRecordMarshallingArray_from_GlyphIndex?.Invoke(null, __params__); + recordCount = (int)(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[] GetGlyphPairAdjustmentRecords(System.Collections.Generic.List newGlyphIndexes, System.Collections.Generic.List allGlyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = newGlyphIndexes; + __params__[1] = allGlyphIndexes; + var __result__ = __GetGlyphPairAdjustmentRecords__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[])(__result__) : default; + } + + public static int PopulatePairAdjustmentRecordMarshallingArray_for_NewlyAddedGlyphIndexes(uint[] newGlyphIndexes, uint[] allGlyphIndexes, out int recordCount) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = newGlyphIndexes; + __params__[1] = allGlyphIndexes; + __params__[2] = Activator.CreateInstance(typeof(int)); + var __result__ = __PopulatePairAdjustmentRecordMarshallingArray_for_NewlyAddedGlyphIndexes?.Invoke(null, __params__); + recordCount = (int)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord GetGlyphPairAdjustmentRecord(uint firstGlyphIndex, uint secondGlyphIndex) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = firstGlyphIndex; + __params__[1] = secondGlyphIndex; + var __result__ = __GetGlyphPairAdjustmentRecord?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord)(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord[] GetSingleAdjustmentRecords(int lookupIndex, uint glyphIndex) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndex; + var __result__ = __GetSingleAdjustmentRecords?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord[])(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord[] GetSingleAdjustmentRecords(int lookupIndex, System.Collections.Generic.List glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetSingleAdjustmentRecords__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord[])(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord[] GetSingleAdjustmentRecords(int lookupIndex, uint[] glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetSingleAdjustmentRecords__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord[])(__result__) : default; + } + + public static int PopulateSingleAdjustmentRecordMarshallingArray_from_GlyphIndexes(uint[] glyphIndexes, int lookupIndex, out int recordCount) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + __params__[1] = lookupIndex; + __params__[2] = Activator.CreateInstance(typeof(int)); + var __result__ = __PopulateSingleAdjustmentRecordMarshallingArray_from_GlyphIndexes?.Invoke(null, __params__); + recordCount = (int)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int GetSingleAdjustmentRecordsFromMarshallingArray(out UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord[] singleSubstitutionRecords) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = Activator.CreateInstance(typeof(UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord[])); + var __result__ = __GetSingleAdjustmentRecordsFromMarshallingArray?.Invoke(null, __params__); + singleSubstitutionRecords = (UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord[])(__params__[0]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[] GetPairAdjustmentRecords(uint glyphIndex) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndex; + var __result__ = __GetPairAdjustmentRecords?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[])(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord GetPairAdjustmentRecord(uint firstGlyphIndex, uint secondGlyphIndex) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = firstGlyphIndex; + __params__[1] = secondGlyphIndex; + var __result__ = __GetPairAdjustmentRecord?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord)(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[] GetAllPairAdjustmentRecords() + { + var __result__ = __GetAllPairAdjustmentRecords?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[])(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[] GetPairAdjustmentRecords(System.Collections.Generic.List glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + var __result__ = __GetPairAdjustmentRecords__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[])(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[] GetPairAdjustmentRecords(int lookupIndex, uint glyphIndex) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndex; + var __result__ = __GetPairAdjustmentRecords__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[])(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[] GetPairAdjustmentRecords(int lookupIndex, System.Collections.Generic.List glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetPairAdjustmentRecords__4?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[])(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[] GetPairAdjustmentRecords(uint[] glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + var __result__ = __GetPairAdjustmentRecords__5?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[])(__result__) : default; + } + + public static UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[] GetPairAdjustmentRecords(int lookupIndex, uint[] glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetPairAdjustmentRecords__6?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[])(__result__) : default; + } + + public static int PopulatePairAdjustmentRecordMarshallingArray(uint[] glyphIndexes, out int recordCount) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + __params__[1] = Activator.CreateInstance(typeof(int)); + var __result__ = __PopulatePairAdjustmentRecordMarshallingArray?.Invoke(null, __params__); + recordCount = (int)(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int PopulatePairAdjustmentRecordMarshallingArray_for_LookupIndex(uint[] glyphIndexes, int lookupIndex, out int recordCount) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + __params__[1] = lookupIndex; + __params__[2] = Activator.CreateInstance(typeof(int)); + var __result__ = __PopulatePairAdjustmentRecordMarshallingArray_for_LookupIndex?.Invoke(null, __params__); + recordCount = (int)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int GetPairAdjustmentRecordsFromMarshallingArray(out UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[] glyphPairAdjustmentRecords) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = Activator.CreateInstance(typeof(UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[])); + var __result__ = __GetPairAdjustmentRecordsFromMarshallingArray?.Invoke(null, __params__); + glyphPairAdjustmentRecords = (UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[])(__params__[0]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static Array GetAllMarkToBaseAdjustmentRecords() + { + var __result__ = __GetAllMarkToBaseAdjustmentRecords?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetMarkToBaseAdjustmentRecords(uint baseGlyphIndex) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = baseGlyphIndex; + var __result__ = __GetMarkToBaseAdjustmentRecords?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static object GetMarkToBaseAdjustmentRecord(uint baseGlyphIndex, uint markGlyphIndex) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = baseGlyphIndex; + __params__[1] = markGlyphIndex; + var __result__ = __GetMarkToBaseAdjustmentRecord?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (object)(__result__) : default; + } + + public static Array GetMarkToBaseAdjustmentRecords(System.Collections.Generic.List glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + var __result__ = __GetMarkToBaseAdjustmentRecords__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetMarkToBaseAdjustmentRecords(int lookupIndex, System.Collections.Generic.List glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetMarkToBaseAdjustmentRecords__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetMarkToBaseAdjustmentRecords(uint[] glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + var __result__ = __GetMarkToBaseAdjustmentRecords__4?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetMarkToBaseAdjustmentRecords(int lookupIndex, uint[] glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetMarkToBaseAdjustmentRecords__5?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static int PopulateMarkToBaseAdjustmentRecordMarshallingArray(uint[] glyphIndexes, out int recordCount) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + __params__[1] = Activator.CreateInstance(typeof(int)); + var __result__ = __PopulateMarkToBaseAdjustmentRecordMarshallingArray?.Invoke(null, __params__); + recordCount = (int)(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int PopulateMarkToBaseAdjustmentRecordMarshallingArray_for_LookupIndex(uint[] glyphIndexes, int lookupIndex, out int recordCount) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + __params__[1] = lookupIndex; + __params__[2] = Activator.CreateInstance(typeof(int)); + var __result__ = __PopulateMarkToBaseAdjustmentRecordMarshallingArray_for_LookupIndex?.Invoke(null, __params__); + recordCount = (int)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int GetMarkToBaseAdjustmentRecordsFromMarshallingArray(out Array adjustmentRecords) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = Activator.CreateInstance(typeof(Array)); + var __result__ = __GetMarkToBaseAdjustmentRecordsFromMarshallingArray?.Invoke(null, __params__); + adjustmentRecords = (Array)(__params__[0]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static Array GetAllMarkToMarkAdjustmentRecords() + { + var __result__ = __GetAllMarkToMarkAdjustmentRecords?.Invoke(null, System.Array.Empty()); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetMarkToMarkAdjustmentRecords(uint baseMarkGlyphIndex) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = baseMarkGlyphIndex; + var __result__ = __GetMarkToMarkAdjustmentRecords?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static object GetMarkToMarkAdjustmentRecord(uint firstGlyphIndex, uint secondGlyphIndex) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = firstGlyphIndex; + __params__[1] = secondGlyphIndex; + var __result__ = __GetMarkToMarkAdjustmentRecord?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (object)(__result__) : default; + } + + public static Array GetMarkToMarkAdjustmentRecords(System.Collections.Generic.List glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + var __result__ = __GetMarkToMarkAdjustmentRecords__2?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetMarkToMarkAdjustmentRecords(int lookupIndex, System.Collections.Generic.List glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetMarkToMarkAdjustmentRecords__3?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetMarkToMarkAdjustmentRecords(uint[] glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + var __result__ = __GetMarkToMarkAdjustmentRecords__4?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static Array GetMarkToMarkAdjustmentRecords(int lookupIndex, uint[] glyphIndexes) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = lookupIndex; + __params__[1] = glyphIndexes; + var __result__ = __GetMarkToMarkAdjustmentRecords__5?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (Array)(__result__) : default; + } + + public static int PopulateMarkToMarkAdjustmentRecordMarshallingArray(uint[] glyphIndexes, out int recordCount) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + __params__[1] = Activator.CreateInstance(typeof(int)); + var __result__ = __PopulateMarkToMarkAdjustmentRecordMarshallingArray?.Invoke(null, __params__); + recordCount = (int)(__params__[1]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int PopulateMarkToMarkAdjustmentRecordMarshallingArray_for_LookupIndex(uint[] glyphIndexes, int lookupIndex, out int recordCount) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndexes; + __params__[1] = lookupIndex; + __params__[2] = Activator.CreateInstance(typeof(int)); + var __result__ = __PopulateMarkToMarkAdjustmentRecordMarshallingArray_for_LookupIndex?.Invoke(null, __params__); + recordCount = (int)(__params__[2]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static int GetMarkToMarkAdjustmentRecordsFromMarshallingArray(out Array adjustmentRecords) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = Activator.CreateInstance(typeof(Array)); + var __result__ = __GetMarkToMarkAdjustmentRecordsFromMarshallingArray?.Invoke(null, __params__); + adjustmentRecords = (Array)(__params__[0]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static void GlyphIndexToMarshallingArray(uint glyphIndex, ref uint[] dstArray) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = glyphIndex; + __params__[1] = dstArray; + __GlyphIndexToMarshallingArray?.Invoke(null, __params__); + dstArray = (uint[])(__params__[1]); + __pool__.Return(__params__); + } + + public static void GenericListToMarshallingArray(ref System.Collections.IList srcList, ref Array dstArray) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = srcList; + __params__[1] = dstArray; + __GenericListToMarshallingArray?.Invoke(null, __params__); + srcList = (System.Collections.IList)(__params__[0]); + dstArray = (Array)(__params__[1]); + __pool__.Return(__params__); + } + + public static void SetMarshallingArraySize(ref Array marshallingArray, int recordCount) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = marshallingArray; + __params__[1] = recordCount; + __SetMarshallingArraySize?.Invoke(null, __params__); + marshallingArray = (Array)(__params__[0]); + __pool__.Return(__params__); + } + + public static void ResetAtlasTexture(UnityEngine.Texture2D texture) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = texture; + __ResetAtlasTexture?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static void RenderBufferToTexture(UnityEngine.Texture2D srcTexture, int padding, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode, UnityEngine.Texture2D dstTexture) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = srcTexture; + __params__[1] = padding; + __params__[2] = renderMode; + __params__[3] = dstTexture; + __RenderBufferToTexture?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public static int RenderGlyphToTexture_Internal_Injected(ref object glyphStruct, int padding, UnityEngine.TextCore.LowLevel.GlyphRenderMode renderMode, UnityEngine.Texture2D texture) + { + var __pool__ = FixedArrayPool.Shared(4); + var __params__ = __pool__.Rent(); + __params__[0] = glyphStruct; + __params__[1] = padding; + __params__[2] = renderMode; + __params__[3] = texture; + var __result__ = __RenderGlyphToTexture_Internal_Injected?.Invoke(null, __params__); + glyphStruct = (object)(__params__[0]); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public static void GetOpenTypeLayoutTable_Injected(object type, out object ret) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = type; + __params__[1] = Activator.CreateInstance(typeof(object)); + __GetOpenTypeLayoutTable_Injected?.Invoke(null, __params__); + ret = (object)(__params__[1]); + __pool__.Return(__params__); + } + + public static void GetGlyphPairAdjustmentRecord_Injected(uint firstGlyphIndex, uint secondGlyphIndex, out UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord ret) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = firstGlyphIndex; + __params__[1] = secondGlyphIndex; + __params__[2] = Activator.CreateInstance(typeof(UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord)); + __GetGlyphPairAdjustmentRecord_Injected?.Invoke(null, __params__); + ret = (UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord)(__params__[2]); + __pool__.Return(__params__); + } + + public static void GetPairAdjustmentRecord_Injected(uint firstGlyphIndex, uint secondGlyphIndex, out UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord ret) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = firstGlyphIndex; + __params__[1] = secondGlyphIndex; + __params__[2] = Activator.CreateInstance(typeof(UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord)); + __GetPairAdjustmentRecord_Injected?.Invoke(null, __params__); + ret = (UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord)(__params__[2]); + __pool__.Return(__params__); + } + + public static void GetMarkToBaseAdjustmentRecord_Injected(uint baseGlyphIndex, uint markGlyphIndex, out object ret) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = baseGlyphIndex; + __params__[1] = markGlyphIndex; + __params__[2] = Activator.CreateInstance(typeof(object)); + __GetMarkToBaseAdjustmentRecord_Injected?.Invoke(null, __params__); + ret = (object)(__params__[2]); + __pool__.Return(__params__); + } + + public static void GetMarkToMarkAdjustmentRecord_Injected(uint firstGlyphIndex, uint secondGlyphIndex, out object ret) + { + var __pool__ = FixedArrayPool.Shared(3); + var __params__ = __pool__.Rent(); + __params__[0] = firstGlyphIndex; + __params__[1] = secondGlyphIndex; + __params__[2] = Activator.CreateInstance(typeof(object)); + __GetMarkToMarkAdjustmentRecord_Injected?.Invoke(null, __params__); + ret = (object)(__params__[2]); + __pool__.Return(__params__); + } + + public UnityEngine_TextCore_LowLevel_FontEngine(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + public UnityEngine.TextCore.LowLevel.FontEngine __super__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.TextCore.LowLevel.FontEngine)(__self__); + } + + private static FieldInfo ___s_Glyphs; + private static FieldInfo __s_Glyphs + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_Glyphs ??= __type__?.GetField("s_Glyphs", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_GlyphIndexes_MarshallingArray_A; + private static FieldInfo __s_GlyphIndexes_MarshallingArray_A + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_GlyphIndexes_MarshallingArray_A ??= __type__?.GetField("s_GlyphIndexes_MarshallingArray_A", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_GlyphIndexes_MarshallingArray_B; + private static FieldInfo __s_GlyphIndexes_MarshallingArray_B + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_GlyphIndexes_MarshallingArray_B ??= __type__?.GetField("s_GlyphIndexes_MarshallingArray_B", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_GlyphMarshallingStruct_IN; + private static FieldInfo __s_GlyphMarshallingStruct_IN + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_GlyphMarshallingStruct_IN ??= __type__?.GetField("s_GlyphMarshallingStruct_IN", (BindingFlags)(-1)); + } + + private static Type ___E__s_GlyphMarshallingStruct_IN; + public static Type __E__s_GlyphMarshallingStruct_IN + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___E__s_GlyphMarshallingStruct_IN ??= EditorUtils.GetTypeByFullName("UnityEngine.TextCore.LowLevel.GlyphMarshallingStruct"); + } + + private static FieldInfo ___s_GlyphMarshallingStruct_OUT; + private static FieldInfo __s_GlyphMarshallingStruct_OUT + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_GlyphMarshallingStruct_OUT ??= __type__?.GetField("s_GlyphMarshallingStruct_OUT", (BindingFlags)(-1)); + } + + private static Type ___E__s_GlyphMarshallingStruct_OUT; + public static Type __E__s_GlyphMarshallingStruct_OUT + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___E__s_GlyphMarshallingStruct_OUT ??= EditorUtils.GetTypeByFullName("UnityEngine.TextCore.LowLevel.GlyphMarshallingStruct"); + } + + private static FieldInfo ___s_FreeGlyphRects; + private static FieldInfo __s_FreeGlyphRects + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_FreeGlyphRects ??= __type__?.GetField("s_FreeGlyphRects", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_UsedGlyphRects; + private static FieldInfo __s_UsedGlyphRects + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_UsedGlyphRects ??= __type__?.GetField("s_UsedGlyphRects", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_SingleAdjustmentRecords_MarshallingArray; + private static FieldInfo __s_SingleAdjustmentRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_SingleAdjustmentRecords_MarshallingArray ??= __type__?.GetField("s_SingleAdjustmentRecords_MarshallingArray", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_SingleSubstitutionRecords_MarshallingArray; + private static FieldInfo __s_SingleSubstitutionRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_SingleSubstitutionRecords_MarshallingArray ??= __type__?.GetField("s_SingleSubstitutionRecords_MarshallingArray", (BindingFlags)(-1)); + } + + private static Type ___E__s_SingleSubstitutionRecords_MarshallingArray; + public static Type __E__s_SingleSubstitutionRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___E__s_SingleSubstitutionRecords_MarshallingArray ??= EditorUtils.GetTypeByFullName("UnityEngine.TextCore.LowLevel.SingleSubstitutionRecord"); + } + + private static FieldInfo ___s_MultipleSubstitutionRecords_MarshallingArray; + private static FieldInfo __s_MultipleSubstitutionRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_MultipleSubstitutionRecords_MarshallingArray ??= __type__?.GetField("s_MultipleSubstitutionRecords_MarshallingArray", (BindingFlags)(-1)); + } + + private static Type ___E__s_MultipleSubstitutionRecords_MarshallingArray; + public static Type __E__s_MultipleSubstitutionRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___E__s_MultipleSubstitutionRecords_MarshallingArray ??= EditorUtils.GetTypeByFullName("UnityEngine.TextCore.LowLevel.MultipleSubstitutionRecord"); + } + + private static FieldInfo ___s_AlternateSubstitutionRecords_MarshallingArray; + private static FieldInfo __s_AlternateSubstitutionRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_AlternateSubstitutionRecords_MarshallingArray ??= __type__?.GetField("s_AlternateSubstitutionRecords_MarshallingArray", (BindingFlags)(-1)); + } + + private static Type ___E__s_AlternateSubstitutionRecords_MarshallingArray; + public static Type __E__s_AlternateSubstitutionRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___E__s_AlternateSubstitutionRecords_MarshallingArray ??= EditorUtils.GetTypeByFullName("UnityEngine.TextCore.LowLevel.AlternateSubstitutionRecord"); + } + + private static FieldInfo ___s_LigatureSubstitutionRecords_MarshallingArray; + private static FieldInfo __s_LigatureSubstitutionRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_LigatureSubstitutionRecords_MarshallingArray ??= __type__?.GetField("s_LigatureSubstitutionRecords_MarshallingArray", (BindingFlags)(-1)); + } + + private static Type ___E__s_LigatureSubstitutionRecords_MarshallingArray; + public static Type __E__s_LigatureSubstitutionRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___E__s_LigatureSubstitutionRecords_MarshallingArray ??= EditorUtils.GetTypeByFullName("UnityEngine.TextCore.LowLevel.LigatureSubstitutionRecord"); + } + + private static FieldInfo ___s_ContextualSubstitutionRecords_MarshallingArray; + private static FieldInfo __s_ContextualSubstitutionRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ContextualSubstitutionRecords_MarshallingArray ??= __type__?.GetField("s_ContextualSubstitutionRecords_MarshallingArray", (BindingFlags)(-1)); + } + + private static Type ___E__s_ContextualSubstitutionRecords_MarshallingArray; + public static Type __E__s_ContextualSubstitutionRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___E__s_ContextualSubstitutionRecords_MarshallingArray ??= EditorUtils.GetTypeByFullName("UnityEngine.TextCore.LowLevel.ContextualSubstitutionRecord"); + } + + private static FieldInfo ___s_ChainingContextualSubstitutionRecords_MarshallingArray; + private static FieldInfo __s_ChainingContextualSubstitutionRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_ChainingContextualSubstitutionRecords_MarshallingArray ??= __type__?.GetField("s_ChainingContextualSubstitutionRecords_MarshallingArray", (BindingFlags)(-1)); + } + + private static Type ___E__s_ChainingContextualSubstitutionRecords_MarshallingArray; + public static Type __E__s_ChainingContextualSubstitutionRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___E__s_ChainingContextualSubstitutionRecords_MarshallingArray ??= EditorUtils.GetTypeByFullName("UnityEngine.TextCore.LowLevel.ChainingContextualSubstitutionRecord"); + } + + private static FieldInfo ___s_PairAdjustmentRecords_MarshallingArray; + private static FieldInfo __s_PairAdjustmentRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_PairAdjustmentRecords_MarshallingArray ??= __type__?.GetField("s_PairAdjustmentRecords_MarshallingArray", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_MarkToBaseAdjustmentRecords_MarshallingArray; + private static FieldInfo __s_MarkToBaseAdjustmentRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_MarkToBaseAdjustmentRecords_MarshallingArray ??= __type__?.GetField("s_MarkToBaseAdjustmentRecords_MarshallingArray", (BindingFlags)(-1)); + } + + private static Type ___E__s_MarkToBaseAdjustmentRecords_MarshallingArray; + public static Type __E__s_MarkToBaseAdjustmentRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___E__s_MarkToBaseAdjustmentRecords_MarshallingArray ??= EditorUtils.GetTypeByFullName("UnityEngine.TextCore.LowLevel.MarkToBaseAdjustmentRecord"); + } + + private static FieldInfo ___s_MarkToMarkAdjustmentRecords_MarshallingArray; + private static FieldInfo __s_MarkToMarkAdjustmentRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_MarkToMarkAdjustmentRecords_MarshallingArray ??= __type__?.GetField("s_MarkToMarkAdjustmentRecords_MarshallingArray", (BindingFlags)(-1)); + } + + private static Type ___E__s_MarkToMarkAdjustmentRecords_MarshallingArray; + public static Type __E__s_MarkToMarkAdjustmentRecords_MarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___E__s_MarkToMarkAdjustmentRecords_MarshallingArray ??= EditorUtils.GetTypeByFullName("UnityEngine.TextCore.LowLevel.MarkToMarkAdjustmentRecord"); + } + + private static FieldInfo ___s_GlyphLookupDictionary; + private static FieldInfo __s_GlyphLookupDictionary + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_GlyphLookupDictionary ??= __type__?.GetField("s_GlyphLookupDictionary", (BindingFlags)(-1)); + } + + private static PropertyInfo ___isProcessingDone; + private static PropertyInfo __isProcessingDone + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___isProcessingDone ??= __type__?.GetProperty("isProcessingDone", (BindingFlags)(-1)); + } + + private static PropertyInfo ___generationProgress; + private static PropertyInfo __generationProgress + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___generationProgress ??= __type__?.GetProperty("generationProgress", (BindingFlags)(-1)); + } + + private static MethodInfo ___InitializeFontEngine_Internal; + private static MethodInfo __InitializeFontEngine_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___InitializeFontEngine_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("InitializeFontEngine_Internal"); + } + + private static MethodInfo ___DestroyFontEngine_Internal; + private static MethodInfo __DestroyFontEngine_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___DestroyFontEngine_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("DestroyFontEngine_Internal"); + } + + private static MethodInfo ___SendCancellationRequest; + private static MethodInfo __SendCancellationRequest + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SendCancellationRequest ??= __type__?.GetMethodInfoByParameterTypeNames("SendCancellationRequest"); + } + + private static MethodInfo ___SendCancellationRequest_Internal; + private static MethodInfo __SendCancellationRequest_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SendCancellationRequest_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("SendCancellationRequest_Internal"); + } + + private static MethodInfo ___LoadFontFace_Internal; + private static MethodInfo __LoadFontFace_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoadFontFace_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("LoadFontFace_Internal", "System.String"); + } + + private static MethodInfo ___LoadFontFace_With_Size_Internal; + private static MethodInfo __LoadFontFace_With_Size_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoadFontFace_With_Size_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("LoadFontFace_With_Size_Internal", "System.String", "System.Int32"); + } + + private static MethodInfo ___LoadFontFace_With_Size_And_FaceIndex_Internal; + private static MethodInfo __LoadFontFace_With_Size_And_FaceIndex_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoadFontFace_With_Size_And_FaceIndex_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("LoadFontFace_With_Size_And_FaceIndex_Internal", "System.String", "System.Int32", "System.Int32"); + } + + private static MethodInfo ___LoadFontFace_FromSourceFontFile_Internal; + private static MethodInfo __LoadFontFace_FromSourceFontFile_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoadFontFace_FromSourceFontFile_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("LoadFontFace_FromSourceFontFile_Internal", "System.Byte[]"); + } + + private static MethodInfo ___LoadFontFace_With_Size_FromSourceFontFile_Internal; + private static MethodInfo __LoadFontFace_With_Size_FromSourceFontFile_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoadFontFace_With_Size_FromSourceFontFile_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("LoadFontFace_With_Size_FromSourceFontFile_Internal", "System.Byte[]", "System.Int32"); + } + + private static MethodInfo ___LoadFontFace_With_Size_And_FaceIndex_FromSourceFontFile_Internal; + private static MethodInfo __LoadFontFace_With_Size_And_FaceIndex_FromSourceFontFile_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoadFontFace_With_Size_And_FaceIndex_FromSourceFontFile_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("LoadFontFace_With_Size_And_FaceIndex_FromSourceFontFile_Internal", "System.Byte[]", "System.Int32", "System.Int32"); + } + + private static MethodInfo ___LoadFontFace_FromFont_Internal; + private static MethodInfo __LoadFontFace_FromFont_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoadFontFace_FromFont_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("LoadFontFace_FromFont_Internal", "UnityEngine.Font"); + } + + private static MethodInfo ___LoadFontFace_With_Size_FromFont_Internal; + private static MethodInfo __LoadFontFace_With_Size_FromFont_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoadFontFace_With_Size_FromFont_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("LoadFontFace_With_Size_FromFont_Internal", "UnityEngine.Font", "System.Int32"); + } + + private static MethodInfo ___LoadFontFace_With_Size_and_FaceIndex_FromFont_Internal; + private static MethodInfo __LoadFontFace_With_Size_and_FaceIndex_FromFont_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoadFontFace_With_Size_and_FaceIndex_FromFont_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("LoadFontFace_With_Size_and_FaceIndex_FromFont_Internal", "UnityEngine.Font", "System.Int32", "System.Int32"); + } + + private static MethodInfo ___LoadFontFace_by_FamilyName_and_StyleName_Internal; + private static MethodInfo __LoadFontFace_by_FamilyName_and_StyleName_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoadFontFace_by_FamilyName_and_StyleName_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("LoadFontFace_by_FamilyName_and_StyleName_Internal", "System.String", "System.String"); + } + + private static MethodInfo ___LoadFontFace_With_Size_by_FamilyName_and_StyleName_Internal; + private static MethodInfo __LoadFontFace_With_Size_by_FamilyName_and_StyleName_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoadFontFace_With_Size_by_FamilyName_and_StyleName_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("LoadFontFace_With_Size_by_FamilyName_and_StyleName_Internal", "System.String", "System.String", "System.Int32"); + } + + private static MethodInfo ___UnloadFontFace_Internal; + private static MethodInfo __UnloadFontFace_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UnloadFontFace_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("UnloadFontFace_Internal"); + } + + private static MethodInfo ___UnloadAllFontFaces_Internal; + private static MethodInfo __UnloadAllFontFaces_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UnloadAllFontFaces_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("UnloadAllFontFaces_Internal"); + } + + private static MethodInfo ___GetSystemFontNames_Internal; + private static MethodInfo __GetSystemFontNames_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSystemFontNames_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("GetSystemFontNames_Internal"); + } + + private static MethodInfo ___GetSystemFontReferences; + private static MethodInfo __GetSystemFontReferences + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSystemFontReferences ??= __type__?.GetMethodInfoByParameterTypeNames("GetSystemFontReferences"); + } + + private static MethodInfo ___TryGetSystemFontReference; + private static MethodInfo __TryGetSystemFontReference + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TryGetSystemFontReference ??= __type__?.GetMethodInfoByParameterTypeNames("TryGetSystemFontReference", "System.String", "System.String", "UnityEngine.TextCore.LowLevel.FontReference&"); + } + + private static MethodInfo ___TryGetSystemFontReference_Internal; + private static MethodInfo __TryGetSystemFontReference_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TryGetSystemFontReference_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("TryGetSystemFontReference_Internal", "System.String", "System.String", "UnityEngine.TextCore.LowLevel.FontReference&"); + } + + private static MethodInfo ___SetFaceSize_Internal; + private static MethodInfo __SetFaceSize_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetFaceSize_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("SetFaceSize_Internal", "System.Int32"); + } + + private static MethodInfo ___GetFaceInfo_Internal; + private static MethodInfo __GetFaceInfo_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetFaceInfo_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("GetFaceInfo_Internal", "UnityEngine.TextCore.FaceInfo&"); + } + + private static MethodInfo ___GetFaceCount; + private static MethodInfo __GetFaceCount + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetFaceCount ??= __type__?.GetMethodInfoByParameterTypeNames("GetFaceCount"); + } + + private static MethodInfo ___GetFontFaces_Internal; + private static MethodInfo __GetFontFaces_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetFontFaces_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("GetFontFaces_Internal"); + } + + private static MethodInfo ___GetVariantGlyphIndex; + private static MethodInfo __GetVariantGlyphIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetVariantGlyphIndex ??= __type__?.GetMethodInfoByParameterTypeNames("GetVariantGlyphIndex", "System.UInt32", "System.UInt32"); + } + + private static MethodInfo ___GetGlyphIndex; + private static MethodInfo __GetGlyphIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetGlyphIndex ??= __type__?.GetMethodInfoByParameterTypeNames("GetGlyphIndex", "System.UInt32"); + } + + private static MethodInfo ___LoadGlyph; + private static MethodInfo __LoadGlyph + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoadGlyph ??= __type__?.GetMethodInfoByParameterTypeNames("LoadGlyph", "System.UInt32", "UnityEngine.TextCore.LowLevel.GlyphLoadFlags"); + } + + private static MethodInfo ___LoadGlyph_Internal; + private static MethodInfo __LoadGlyph_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___LoadGlyph_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("LoadGlyph_Internal", "System.UInt32", "UnityEngine.TextCore.LowLevel.GlyphLoadFlags"); + } + + private static MethodInfo ___TryGetGlyphWithUnicodeValue_Internal; + private static MethodInfo __TryGetGlyphWithUnicodeValue_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TryGetGlyphWithUnicodeValue_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("TryGetGlyphWithUnicodeValue_Internal", "System.UInt32", "UnityEngine.TextCore.LowLevel.GlyphLoadFlags", "UnityEngine.TextCore.LowLevel.GlyphMarshallingStruct&"); + } + + private static MethodInfo ___TryGetGlyphWithIndexValue_Internal; + private static MethodInfo __TryGetGlyphWithIndexValue_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TryGetGlyphWithIndexValue_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("TryGetGlyphWithIndexValue_Internal", "System.UInt32", "UnityEngine.TextCore.LowLevel.GlyphLoadFlags", "UnityEngine.TextCore.LowLevel.GlyphMarshallingStruct&"); + } + + private static MethodInfo ___TryPackGlyphInAtlas; + private static MethodInfo __TryPackGlyphInAtlas + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TryPackGlyphInAtlas ??= __type__?.GetMethodInfoByParameterTypeNames("TryPackGlyphInAtlas", "UnityEngine.TextCore.Glyph", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphPackingMode", "UnityEngine.TextCore.LowLevel.GlyphRenderMode", "System.Int32", "System.Int32", "System.Collections.Generic.List`1[[UnityEngine.TextCore.GlyphRect, UnityEngine.TextCoreFontEngineModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "System.Collections.Generic.List`1[[UnityEngine.TextCore.GlyphRect, UnityEngine.TextCoreFontEngineModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]"); + } + + private static MethodInfo ___TryPackGlyphInAtlas_Internal; + private static MethodInfo __TryPackGlyphInAtlas_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TryPackGlyphInAtlas_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("TryPackGlyphInAtlas_Internal", "UnityEngine.TextCore.LowLevel.GlyphMarshallingStruct&", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphPackingMode", "UnityEngine.TextCore.LowLevel.GlyphRenderMode", "System.Int32", "System.Int32", "UnityEngine.TextCore.GlyphRect[]", "System.Int32&", "UnityEngine.TextCore.GlyphRect[]", "System.Int32&"); + } + + private static MethodInfo ___TryPackGlyphsInAtlas; + private static MethodInfo __TryPackGlyphsInAtlas + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TryPackGlyphsInAtlas ??= __type__?.GetMethodInfoByParameterTypeNames("TryPackGlyphsInAtlas", "System.Collections.Generic.List`1[[UnityEngine.TextCore.Glyph, UnityEngine.TextCoreFontEngineModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "System.Collections.Generic.List`1[[UnityEngine.TextCore.Glyph, UnityEngine.TextCoreFontEngineModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphPackingMode", "UnityEngine.TextCore.LowLevel.GlyphRenderMode", "System.Int32", "System.Int32", "System.Collections.Generic.List`1[[UnityEngine.TextCore.GlyphRect, UnityEngine.TextCoreFontEngineModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "System.Collections.Generic.List`1[[UnityEngine.TextCore.GlyphRect, UnityEngine.TextCoreFontEngineModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]"); + } + + private static MethodInfo ___TryPackGlyphsInAtlas_Internal; + private static MethodInfo __TryPackGlyphsInAtlas_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TryPackGlyphsInAtlas_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("TryPackGlyphsInAtlas_Internal", "UnityEngine.TextCore.LowLevel.GlyphMarshallingStruct[]", "System.Int32&", "UnityEngine.TextCore.LowLevel.GlyphMarshallingStruct[]", "System.Int32&", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphPackingMode", "UnityEngine.TextCore.LowLevel.GlyphRenderMode", "System.Int32", "System.Int32", "UnityEngine.TextCore.GlyphRect[]", "System.Int32&", "UnityEngine.TextCore.GlyphRect[]", "System.Int32&"); + } + + private static MethodInfo ___RenderGlyphToTexture; + private static MethodInfo __RenderGlyphToTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RenderGlyphToTexture ??= __type__?.GetMethodInfoByParameterTypeNames("RenderGlyphToTexture", "UnityEngine.TextCore.Glyph", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphRenderMode", "UnityEngine.Texture2D"); + } + + private static MethodInfo ___RenderGlyphToTexture_Internal; + private static MethodInfo __RenderGlyphToTexture_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RenderGlyphToTexture_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("RenderGlyphToTexture_Internal", "UnityEngine.TextCore.LowLevel.GlyphMarshallingStruct", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphRenderMode", "UnityEngine.Texture2D"); + } + + private static MethodInfo ___RenderGlyphsToTexture; + private static MethodInfo __RenderGlyphsToTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RenderGlyphsToTexture ??= __type__?.GetMethodInfoByParameterTypeNames("RenderGlyphsToTexture", "System.Collections.Generic.List`1[[UnityEngine.TextCore.Glyph, UnityEngine.TextCoreFontEngineModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphRenderMode", "UnityEngine.Texture2D"); + } + + private static MethodInfo ___RenderGlyphsToTexture_Internal; + private static MethodInfo __RenderGlyphsToTexture_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RenderGlyphsToTexture_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("RenderGlyphsToTexture_Internal", "UnityEngine.TextCore.LowLevel.GlyphMarshallingStruct[]", "System.Int32", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphRenderMode", "UnityEngine.Texture2D"); + } + + private static MethodInfo ___RenderGlyphsToTexture__2; + private static MethodInfo __RenderGlyphsToTexture__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RenderGlyphsToTexture__2 ??= __type__?.GetMethodInfoByParameterTypeNames("RenderGlyphsToTexture", "System.Collections.Generic.List`1[[UnityEngine.TextCore.Glyph, UnityEngine.TextCoreFontEngineModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphRenderMode", "System.Byte[]", "System.Int32", "System.Int32"); + } + + private static MethodInfo ___RenderGlyphsToTextureBuffer_Internal; + private static MethodInfo __RenderGlyphsToTextureBuffer_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RenderGlyphsToTextureBuffer_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("RenderGlyphsToTextureBuffer_Internal", "UnityEngine.TextCore.LowLevel.GlyphMarshallingStruct[]", "System.Int32", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphRenderMode", "System.Byte[]", "System.Int32", "System.Int32"); + } + + private static MethodInfo ___RenderGlyphsToSharedTexture; + private static MethodInfo __RenderGlyphsToSharedTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RenderGlyphsToSharedTexture ??= __type__?.GetMethodInfoByParameterTypeNames("RenderGlyphsToSharedTexture", "System.Collections.Generic.List`1[[UnityEngine.TextCore.Glyph, UnityEngine.TextCoreFontEngineModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphRenderMode"); + } + + private static MethodInfo ___RenderGlyphsToSharedTexture_Internal; + private static MethodInfo __RenderGlyphsToSharedTexture_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RenderGlyphsToSharedTexture_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("RenderGlyphsToSharedTexture_Internal", "UnityEngine.TextCore.LowLevel.GlyphMarshallingStruct[]", "System.Int32", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphRenderMode"); + } + + private static MethodInfo ___SetSharedTexture; + private static MethodInfo __SetSharedTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetSharedTexture ??= __type__?.GetMethodInfoByParameterTypeNames("SetSharedTexture", "UnityEngine.Texture2D"); + } + + private static MethodInfo ___ReleaseSharedTexture; + private static MethodInfo __ReleaseSharedTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ReleaseSharedTexture ??= __type__?.GetMethodInfoByParameterTypeNames("ReleaseSharedTexture"); + } + + private static MethodInfo ___SetTextureUploadMode; + private static MethodInfo __SetTextureUploadMode + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetTextureUploadMode ??= __type__?.GetMethodInfoByParameterTypeNames("SetTextureUploadMode", "System.Boolean"); + } + + private static MethodInfo ___TryAddGlyphToTexture; + private static MethodInfo __TryAddGlyphToTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TryAddGlyphToTexture ??= __type__?.GetMethodInfoByParameterTypeNames("TryAddGlyphToTexture", "System.UInt32", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphPackingMode", "System.Collections.Generic.List`1[[UnityEngine.TextCore.GlyphRect, UnityEngine.TextCoreFontEngineModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "System.Collections.Generic.List`1[[UnityEngine.TextCore.GlyphRect, UnityEngine.TextCoreFontEngineModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "UnityEngine.TextCore.LowLevel.GlyphRenderMode", "UnityEngine.Texture2D", "UnityEngine.TextCore.Glyph&"); + } + + private static MethodInfo ___TryAddGlyphToTexture_Internal; + private static MethodInfo __TryAddGlyphToTexture_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TryAddGlyphToTexture_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("TryAddGlyphToTexture_Internal", "System.UInt32", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphPackingMode", "UnityEngine.TextCore.GlyphRect[]", "System.Int32&", "UnityEngine.TextCore.GlyphRect[]", "System.Int32&", "UnityEngine.TextCore.LowLevel.GlyphRenderMode", "UnityEngine.Texture2D", "UnityEngine.TextCore.LowLevel.GlyphMarshallingStruct&"); + } + + private static MethodInfo ___TryAddGlyphsToTexture; + private static MethodInfo __TryAddGlyphsToTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TryAddGlyphsToTexture ??= __type__?.GetMethodInfoByParameterTypeNames("TryAddGlyphsToTexture", "System.Collections.Generic.List`1[[UnityEngine.TextCore.Glyph, UnityEngine.TextCoreFontEngineModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "System.Collections.Generic.List`1[[UnityEngine.TextCore.Glyph, UnityEngine.TextCoreFontEngineModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphPackingMode", "System.Collections.Generic.List`1[[UnityEngine.TextCore.GlyphRect, UnityEngine.TextCoreFontEngineModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "System.Collections.Generic.List`1[[UnityEngine.TextCore.GlyphRect, UnityEngine.TextCoreFontEngineModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "UnityEngine.TextCore.LowLevel.GlyphRenderMode", "UnityEngine.Texture2D"); + } + + private static MethodInfo ___TryAddGlyphsToTexture_Internal_MultiThread; + private static MethodInfo __TryAddGlyphsToTexture_Internal_MultiThread + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TryAddGlyphsToTexture_Internal_MultiThread ??= __type__?.GetMethodInfoByParameterTypeNames("TryAddGlyphsToTexture_Internal_MultiThread", "UnityEngine.TextCore.LowLevel.GlyphMarshallingStruct[]", "System.Int32&", "UnityEngine.TextCore.LowLevel.GlyphMarshallingStruct[]", "System.Int32&", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphPackingMode", "UnityEngine.TextCore.GlyphRect[]", "System.Int32&", "UnityEngine.TextCore.GlyphRect[]", "System.Int32&", "UnityEngine.TextCore.LowLevel.GlyphRenderMode", "UnityEngine.Texture2D"); + } + + private static MethodInfo ___TryAddGlyphsToTexture__2; + private static MethodInfo __TryAddGlyphsToTexture__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TryAddGlyphsToTexture__2 ??= __type__?.GetMethodInfoByParameterTypeNames("TryAddGlyphsToTexture", "System.Collections.Generic.List`1[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphPackingMode", "System.Collections.Generic.List`1[[UnityEngine.TextCore.GlyphRect, UnityEngine.TextCoreFontEngineModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "System.Collections.Generic.List`1[[UnityEngine.TextCore.GlyphRect, UnityEngine.TextCoreFontEngineModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]", "UnityEngine.TextCore.LowLevel.GlyphRenderMode", "UnityEngine.Texture2D", "UnityEngine.TextCore.Glyph[]&"); + } + + private static MethodInfo ___TryAddGlyphsToTexture_Internal; + private static MethodInfo __TryAddGlyphsToTexture_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___TryAddGlyphsToTexture_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("TryAddGlyphsToTexture_Internal", "System.UInt32[]", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphPackingMode", "UnityEngine.TextCore.GlyphRect[]", "System.Int32&", "UnityEngine.TextCore.GlyphRect[]", "System.Int32&", "UnityEngine.TextCore.LowLevel.GlyphRenderMode", "UnityEngine.Texture2D", "UnityEngine.TextCore.LowLevel.GlyphMarshallingStruct[]", "System.Int32&"); + } + + private static MethodInfo ___GetOpenTypeLayoutTable; + private static MethodInfo __GetOpenTypeLayoutTable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetOpenTypeLayoutTable ??= __type__?.GetMethodInfoByParameterTypeNames("GetOpenTypeLayoutTable", "UnityEngine.TextCore.LowLevel.OTL_TableType"); + } + + private static MethodInfo ___GetOpenTypeLayoutScripts; + private static MethodInfo __GetOpenTypeLayoutScripts + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetOpenTypeLayoutScripts ??= __type__?.GetMethodInfoByParameterTypeNames("GetOpenTypeLayoutScripts"); + } + + private static MethodInfo ___GetOpenTypeLayoutFeatures; + private static MethodInfo __GetOpenTypeLayoutFeatures + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetOpenTypeLayoutFeatures ??= __type__?.GetMethodInfoByParameterTypeNames("GetOpenTypeLayoutFeatures"); + } + + private static MethodInfo ___GetOpenTypeLayoutLookups; + private static MethodInfo __GetOpenTypeLayoutLookups + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetOpenTypeLayoutLookups ??= __type__?.GetMethodInfoByParameterTypeNames("GetOpenTypeLayoutLookups"); + } + + private static MethodInfo ___GetOpenTypeFontFeatureList; + private static MethodInfo __GetOpenTypeFontFeatureList + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetOpenTypeFontFeatureList ??= __type__?.GetMethodInfoByParameterTypeNames("GetOpenTypeFontFeatureList"); + } + + private static MethodInfo ___GetAllSingleSubstitutionRecords; + private static MethodInfo __GetAllSingleSubstitutionRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetAllSingleSubstitutionRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetAllSingleSubstitutionRecords"); + } + + private static MethodInfo ___GetSingleSubstitutionRecords; + private static MethodInfo __GetSingleSubstitutionRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSingleSubstitutionRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetSingleSubstitutionRecords", "System.Int32", "System.UInt32"); + } + + private static MethodInfo ___GetSingleSubstitutionRecords__2; + private static MethodInfo __GetSingleSubstitutionRecords__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSingleSubstitutionRecords__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GetSingleSubstitutionRecords", "System.Int32", "System.Collections.Generic.List`1[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); + } + + private static MethodInfo ___GetSingleSubstitutionRecords__3; + private static MethodInfo __GetSingleSubstitutionRecords__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSingleSubstitutionRecords__3 ??= __type__?.GetMethodInfoByParameterTypeNames("GetSingleSubstitutionRecords", "System.Int32", "System.UInt32[]"); + } + + private static MethodInfo ___PopulateSingleSubstitutionRecordMarshallingArray_from_GlyphIndexes; + private static MethodInfo __PopulateSingleSubstitutionRecordMarshallingArray_from_GlyphIndexes + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PopulateSingleSubstitutionRecordMarshallingArray_from_GlyphIndexes ??= __type__?.GetMethodInfoByParameterTypeNames("PopulateSingleSubstitutionRecordMarshallingArray_from_GlyphIndexes", "System.UInt32[]", "System.Int32", "System.Int32&"); + } + + private static MethodInfo ___GetSingleSubstitutionRecordsFromMarshallingArray; + private static MethodInfo __GetSingleSubstitutionRecordsFromMarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSingleSubstitutionRecordsFromMarshallingArray ??= __type__?.GetMethodInfoByParameterTypeNames("GetSingleSubstitutionRecordsFromMarshallingArray", "UnityEngine.TextCore.LowLevel.SingleSubstitutionRecord[]"); + } + + private static MethodInfo ___GetAllMultipleSubstitutionRecords; + private static MethodInfo __GetAllMultipleSubstitutionRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetAllMultipleSubstitutionRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetAllMultipleSubstitutionRecords"); + } + + private static MethodInfo ___GetMultipleSubstitutionRecords; + private static MethodInfo __GetMultipleSubstitutionRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMultipleSubstitutionRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetMultipleSubstitutionRecords", "System.Int32", "System.UInt32"); + } + + private static MethodInfo ___GetMultipleSubstitutionRecords__2; + private static MethodInfo __GetMultipleSubstitutionRecords__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMultipleSubstitutionRecords__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GetMultipleSubstitutionRecords", "System.Int32", "System.Collections.Generic.List`1[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); + } + + private static MethodInfo ___GetMultipleSubstitutionRecords__3; + private static MethodInfo __GetMultipleSubstitutionRecords__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMultipleSubstitutionRecords__3 ??= __type__?.GetMethodInfoByParameterTypeNames("GetMultipleSubstitutionRecords", "System.Int32", "System.UInt32[]"); + } + + private static MethodInfo ___PopulateMultipleSubstitutionRecordMarshallingArray_from_GlyphIndexes; + private static MethodInfo __PopulateMultipleSubstitutionRecordMarshallingArray_from_GlyphIndexes + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PopulateMultipleSubstitutionRecordMarshallingArray_from_GlyphIndexes ??= __type__?.GetMethodInfoByParameterTypeNames("PopulateMultipleSubstitutionRecordMarshallingArray_from_GlyphIndexes", "System.UInt32[]", "System.Int32", "System.Int32&"); + } + + private static MethodInfo ___GetMultipleSubstitutionRecordsFromMarshallingArray; + private static MethodInfo __GetMultipleSubstitutionRecordsFromMarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMultipleSubstitutionRecordsFromMarshallingArray ??= __type__?.GetMethodInfoByParameterTypeNames("GetMultipleSubstitutionRecordsFromMarshallingArray", "UnityEngine.TextCore.LowLevel.MultipleSubstitutionRecord[]"); + } + + private static MethodInfo ___GetAllAlternateSubstitutionRecords; + private static MethodInfo __GetAllAlternateSubstitutionRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetAllAlternateSubstitutionRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetAllAlternateSubstitutionRecords"); + } + + private static MethodInfo ___GetAlternateSubstitutionRecords; + private static MethodInfo __GetAlternateSubstitutionRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetAlternateSubstitutionRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetAlternateSubstitutionRecords", "System.Int32", "System.UInt32"); + } + + private static MethodInfo ___GetAlternateSubstitutionRecords__2; + private static MethodInfo __GetAlternateSubstitutionRecords__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetAlternateSubstitutionRecords__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GetAlternateSubstitutionRecords", "System.Int32", "System.Collections.Generic.List`1[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); + } + + private static MethodInfo ___GetAlternateSubstitutionRecords__3; + private static MethodInfo __GetAlternateSubstitutionRecords__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetAlternateSubstitutionRecords__3 ??= __type__?.GetMethodInfoByParameterTypeNames("GetAlternateSubstitutionRecords", "System.Int32", "System.UInt32[]"); + } + + private static MethodInfo ___PopulateAlternateSubstitutionRecordMarshallingArray_from_GlyphIndexes; + private static MethodInfo __PopulateAlternateSubstitutionRecordMarshallingArray_from_GlyphIndexes + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PopulateAlternateSubstitutionRecordMarshallingArray_from_GlyphIndexes ??= __type__?.GetMethodInfoByParameterTypeNames("PopulateAlternateSubstitutionRecordMarshallingArray_from_GlyphIndexes", "System.UInt32[]", "System.Int32", "System.Int32&"); + } + + private static MethodInfo ___GetAlternateSubstitutionRecordsFromMarshallingArray; + private static MethodInfo __GetAlternateSubstitutionRecordsFromMarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetAlternateSubstitutionRecordsFromMarshallingArray ??= __type__?.GetMethodInfoByParameterTypeNames("GetAlternateSubstitutionRecordsFromMarshallingArray", "UnityEngine.TextCore.LowLevel.AlternateSubstitutionRecord[]"); + } + + private static MethodInfo ___GetAllLigatureSubstitutionRecords; + private static MethodInfo __GetAllLigatureSubstitutionRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetAllLigatureSubstitutionRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetAllLigatureSubstitutionRecords"); + } + + private static MethodInfo ___GetLigatureSubstitutionRecords; + private static MethodInfo __GetLigatureSubstitutionRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetLigatureSubstitutionRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetLigatureSubstitutionRecords", "System.UInt32"); + } + + private static MethodInfo ___GetLigatureSubstitutionRecords__2; + private static MethodInfo __GetLigatureSubstitutionRecords__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetLigatureSubstitutionRecords__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GetLigatureSubstitutionRecords", "System.Collections.Generic.List`1[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); + } + + private static MethodInfo ___GetLigatureSubstitutionRecords__3; + private static MethodInfo __GetLigatureSubstitutionRecords__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetLigatureSubstitutionRecords__3 ??= __type__?.GetMethodInfoByParameterTypeNames("GetLigatureSubstitutionRecords", "System.Int32", "System.UInt32"); + } + + private static MethodInfo ___GetLigatureSubstitutionRecords__4; + private static MethodInfo __GetLigatureSubstitutionRecords__4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetLigatureSubstitutionRecords__4 ??= __type__?.GetMethodInfoByParameterTypeNames("GetLigatureSubstitutionRecords", "System.Int32", "System.Collections.Generic.List`1[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); + } + + private static MethodInfo ___GetLigatureSubstitutionRecords__5; + private static MethodInfo __GetLigatureSubstitutionRecords__5 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetLigatureSubstitutionRecords__5 ??= __type__?.GetMethodInfoByParameterTypeNames("GetLigatureSubstitutionRecords", "System.UInt32[]"); + } + + private static MethodInfo ___GetLigatureSubstitutionRecords__6; + private static MethodInfo __GetLigatureSubstitutionRecords__6 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetLigatureSubstitutionRecords__6 ??= __type__?.GetMethodInfoByParameterTypeNames("GetLigatureSubstitutionRecords", "System.Int32", "System.UInt32[]"); + } + + private static MethodInfo ___PopulateLigatureSubstitutionRecordMarshallingArray; + private static MethodInfo __PopulateLigatureSubstitutionRecordMarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PopulateLigatureSubstitutionRecordMarshallingArray ??= __type__?.GetMethodInfoByParameterTypeNames("PopulateLigatureSubstitutionRecordMarshallingArray", "System.UInt32[]", "System.Int32&"); + } + + private static MethodInfo ___PopulateLigatureSubstitutionRecordMarshallingArray_for_LookupIndex; + private static MethodInfo __PopulateLigatureSubstitutionRecordMarshallingArray_for_LookupIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PopulateLigatureSubstitutionRecordMarshallingArray_for_LookupIndex ??= __type__?.GetMethodInfoByParameterTypeNames("PopulateLigatureSubstitutionRecordMarshallingArray_for_LookupIndex", "System.UInt32[]", "System.Int32", "System.Int32&"); + } + + private static MethodInfo ___GetLigatureSubstitutionRecordsFromMarshallingArray; + private static MethodInfo __GetLigatureSubstitutionRecordsFromMarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetLigatureSubstitutionRecordsFromMarshallingArray ??= __type__?.GetMethodInfoByParameterTypeNames("GetLigatureSubstitutionRecordsFromMarshallingArray", "UnityEngine.TextCore.LowLevel.LigatureSubstitutionRecord[]"); + } + + private static MethodInfo ___GetAllContextualSubstitutionRecords; + private static MethodInfo __GetAllContextualSubstitutionRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetAllContextualSubstitutionRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetAllContextualSubstitutionRecords"); + } + + private static MethodInfo ___GetContextualSubstitutionRecords; + private static MethodInfo __GetContextualSubstitutionRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetContextualSubstitutionRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetContextualSubstitutionRecords", "System.Int32", "System.UInt32"); + } + + private static MethodInfo ___GetContextualSubstitutionRecords__2; + private static MethodInfo __GetContextualSubstitutionRecords__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetContextualSubstitutionRecords__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GetContextualSubstitutionRecords", "System.Int32", "System.Collections.Generic.List`1[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); + } + + private static MethodInfo ___GetContextualSubstitutionRecords__3; + private static MethodInfo __GetContextualSubstitutionRecords__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetContextualSubstitutionRecords__3 ??= __type__?.GetMethodInfoByParameterTypeNames("GetContextualSubstitutionRecords", "System.Int32", "System.UInt32[]"); + } + + private static MethodInfo ___PopulateContextualSubstitutionRecordMarshallingArray_from_GlyphIndexes; + private static MethodInfo __PopulateContextualSubstitutionRecordMarshallingArray_from_GlyphIndexes + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PopulateContextualSubstitutionRecordMarshallingArray_from_GlyphIndexes ??= __type__?.GetMethodInfoByParameterTypeNames("PopulateContextualSubstitutionRecordMarshallingArray_from_GlyphIndexes", "System.UInt32[]", "System.Int32", "System.Int32&"); + } + + private static MethodInfo ___GetContextualSubstitutionRecordsFromMarshallingArray; + private static MethodInfo __GetContextualSubstitutionRecordsFromMarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetContextualSubstitutionRecordsFromMarshallingArray ??= __type__?.GetMethodInfoByParameterTypeNames("GetContextualSubstitutionRecordsFromMarshallingArray", "UnityEngine.TextCore.LowLevel.ContextualSubstitutionRecord[]"); + } + + private static MethodInfo ___GetAllChainingContextualSubstitutionRecords; + private static MethodInfo __GetAllChainingContextualSubstitutionRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetAllChainingContextualSubstitutionRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetAllChainingContextualSubstitutionRecords"); + } + + private static MethodInfo ___GetChainingContextualSubstitutionRecords; + private static MethodInfo __GetChainingContextualSubstitutionRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetChainingContextualSubstitutionRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetChainingContextualSubstitutionRecords", "System.Int32", "System.UInt32"); + } + + private static MethodInfo ___GetChainingContextualSubstitutionRecords__2; + private static MethodInfo __GetChainingContextualSubstitutionRecords__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetChainingContextualSubstitutionRecords__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GetChainingContextualSubstitutionRecords", "System.Int32", "System.Collections.Generic.List`1[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); + } + + private static MethodInfo ___GetChainingContextualSubstitutionRecords__3; + private static MethodInfo __GetChainingContextualSubstitutionRecords__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetChainingContextualSubstitutionRecords__3 ??= __type__?.GetMethodInfoByParameterTypeNames("GetChainingContextualSubstitutionRecords", "System.Int32", "System.UInt32[]"); + } + + private static MethodInfo ___PopulateChainingContextualSubstitutionRecordMarshallingArray_from_GlyphIndexes; + private static MethodInfo __PopulateChainingContextualSubstitutionRecordMarshallingArray_from_GlyphIndexes + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PopulateChainingContextualSubstitutionRecordMarshallingArray_from_GlyphIndexes ??= __type__?.GetMethodInfoByParameterTypeNames("PopulateChainingContextualSubstitutionRecordMarshallingArray_from_GlyphIndexes", "System.UInt32[]", "System.Int32", "System.Int32&"); + } + + private static MethodInfo ___GetChainingContextualSubstitutionRecordsFromMarshallingArray; + private static MethodInfo __GetChainingContextualSubstitutionRecordsFromMarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetChainingContextualSubstitutionRecordsFromMarshallingArray ??= __type__?.GetMethodInfoByParameterTypeNames("GetChainingContextualSubstitutionRecordsFromMarshallingArray", "UnityEngine.TextCore.LowLevel.ChainingContextualSubstitutionRecord[]"); + } + + private static MethodInfo ___GetGlyphPairAdjustmentTable; + private static MethodInfo __GetGlyphPairAdjustmentTable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetGlyphPairAdjustmentTable ??= __type__?.GetMethodInfoByParameterTypeNames("GetGlyphPairAdjustmentTable", "System.UInt32[]"); + } + + private static MethodInfo ___GetGlyphPairAdjustmentRecords; + private static MethodInfo __GetGlyphPairAdjustmentRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetGlyphPairAdjustmentRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetGlyphPairAdjustmentRecords", "System.Collections.Generic.List`1[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", "System.Int32&"); + } + + private static MethodInfo ___PopulatePairAdjustmentRecordMarshallingArray_from_KernTable; + private static MethodInfo __PopulatePairAdjustmentRecordMarshallingArray_from_KernTable + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PopulatePairAdjustmentRecordMarshallingArray_from_KernTable ??= __type__?.GetMethodInfoByParameterTypeNames("PopulatePairAdjustmentRecordMarshallingArray_from_KernTable", "System.UInt32[]", "System.Int32&"); + } + + private static MethodInfo ___GetGlyphPairAdjustmentRecords__2; + private static MethodInfo __GetGlyphPairAdjustmentRecords__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetGlyphPairAdjustmentRecords__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GetGlyphPairAdjustmentRecords", "System.UInt32", "System.Int32&"); + } + + private static MethodInfo ___PopulatePairAdjustmentRecordMarshallingArray_from_GlyphIndex; + private static MethodInfo __PopulatePairAdjustmentRecordMarshallingArray_from_GlyphIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PopulatePairAdjustmentRecordMarshallingArray_from_GlyphIndex ??= __type__?.GetMethodInfoByParameterTypeNames("PopulatePairAdjustmentRecordMarshallingArray_from_GlyphIndex", "System.UInt32", "System.Int32&"); + } + + private static MethodInfo ___GetGlyphPairAdjustmentRecords__3; + private static MethodInfo __GetGlyphPairAdjustmentRecords__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetGlyphPairAdjustmentRecords__3 ??= __type__?.GetMethodInfoByParameterTypeNames("GetGlyphPairAdjustmentRecords", "System.Collections.Generic.List`1[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", "System.Collections.Generic.List`1[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); + } + + private static MethodInfo ___PopulatePairAdjustmentRecordMarshallingArray_for_NewlyAddedGlyphIndexes; + private static MethodInfo __PopulatePairAdjustmentRecordMarshallingArray_for_NewlyAddedGlyphIndexes + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PopulatePairAdjustmentRecordMarshallingArray_for_NewlyAddedGlyphIndexes ??= __type__?.GetMethodInfoByParameterTypeNames("PopulatePairAdjustmentRecordMarshallingArray_for_NewlyAddedGlyphIndexes", "System.UInt32[]", "System.UInt32[]", "System.Int32&"); + } + + private static MethodInfo ___GetGlyphPairAdjustmentRecord; + private static MethodInfo __GetGlyphPairAdjustmentRecord + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetGlyphPairAdjustmentRecord ??= __type__?.GetMethodInfoByParameterTypeNames("GetGlyphPairAdjustmentRecord", "System.UInt32", "System.UInt32"); + } + + private static MethodInfo ___GetSingleAdjustmentRecords; + private static MethodInfo __GetSingleAdjustmentRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSingleAdjustmentRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetSingleAdjustmentRecords", "System.Int32", "System.UInt32"); + } + + private static MethodInfo ___GetSingleAdjustmentRecords__2; + private static MethodInfo __GetSingleAdjustmentRecords__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSingleAdjustmentRecords__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GetSingleAdjustmentRecords", "System.Int32", "System.Collections.Generic.List`1[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); + } + + private static MethodInfo ___GetSingleAdjustmentRecords__3; + private static MethodInfo __GetSingleAdjustmentRecords__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSingleAdjustmentRecords__3 ??= __type__?.GetMethodInfoByParameterTypeNames("GetSingleAdjustmentRecords", "System.Int32", "System.UInt32[]"); + } + + private static MethodInfo ___PopulateSingleAdjustmentRecordMarshallingArray_from_GlyphIndexes; + private static MethodInfo __PopulateSingleAdjustmentRecordMarshallingArray_from_GlyphIndexes + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PopulateSingleAdjustmentRecordMarshallingArray_from_GlyphIndexes ??= __type__?.GetMethodInfoByParameterTypeNames("PopulateSingleAdjustmentRecordMarshallingArray_from_GlyphIndexes", "System.UInt32[]", "System.Int32", "System.Int32&"); + } + + private static MethodInfo ___GetSingleAdjustmentRecordsFromMarshallingArray; + private static MethodInfo __GetSingleAdjustmentRecordsFromMarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetSingleAdjustmentRecordsFromMarshallingArray ??= __type__?.GetMethodInfoByParameterTypeNames("GetSingleAdjustmentRecordsFromMarshallingArray", "UnityEngine.TextCore.LowLevel.GlyphAdjustmentRecord[]"); + } + + private static MethodInfo ___GetPairAdjustmentRecords; + private static MethodInfo __GetPairAdjustmentRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPairAdjustmentRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetPairAdjustmentRecords", "System.UInt32"); + } + + private static MethodInfo ___GetPairAdjustmentRecord; + private static MethodInfo __GetPairAdjustmentRecord + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPairAdjustmentRecord ??= __type__?.GetMethodInfoByParameterTypeNames("GetPairAdjustmentRecord", "System.UInt32", "System.UInt32"); + } + + private static MethodInfo ___GetAllPairAdjustmentRecords; + private static MethodInfo __GetAllPairAdjustmentRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetAllPairAdjustmentRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetAllPairAdjustmentRecords"); + } + + private static MethodInfo ___GetPairAdjustmentRecords__2; + private static MethodInfo __GetPairAdjustmentRecords__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPairAdjustmentRecords__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GetPairAdjustmentRecords", "System.Collections.Generic.List`1[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); + } + + private static MethodInfo ___GetPairAdjustmentRecords__3; + private static MethodInfo __GetPairAdjustmentRecords__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPairAdjustmentRecords__3 ??= __type__?.GetMethodInfoByParameterTypeNames("GetPairAdjustmentRecords", "System.Int32", "System.UInt32"); + } + + private static MethodInfo ___GetPairAdjustmentRecords__4; + private static MethodInfo __GetPairAdjustmentRecords__4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPairAdjustmentRecords__4 ??= __type__?.GetMethodInfoByParameterTypeNames("GetPairAdjustmentRecords", "System.Int32", "System.Collections.Generic.List`1[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); + } + + private static MethodInfo ___GetPairAdjustmentRecords__5; + private static MethodInfo __GetPairAdjustmentRecords__5 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPairAdjustmentRecords__5 ??= __type__?.GetMethodInfoByParameterTypeNames("GetPairAdjustmentRecords", "System.UInt32[]"); + } + + private static MethodInfo ___GetPairAdjustmentRecords__6; + private static MethodInfo __GetPairAdjustmentRecords__6 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPairAdjustmentRecords__6 ??= __type__?.GetMethodInfoByParameterTypeNames("GetPairAdjustmentRecords", "System.Int32", "System.UInt32[]"); + } + + private static MethodInfo ___PopulatePairAdjustmentRecordMarshallingArray; + private static MethodInfo __PopulatePairAdjustmentRecordMarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PopulatePairAdjustmentRecordMarshallingArray ??= __type__?.GetMethodInfoByParameterTypeNames("PopulatePairAdjustmentRecordMarshallingArray", "System.UInt32[]", "System.Int32&"); + } + + private static MethodInfo ___PopulatePairAdjustmentRecordMarshallingArray_for_LookupIndex; + private static MethodInfo __PopulatePairAdjustmentRecordMarshallingArray_for_LookupIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PopulatePairAdjustmentRecordMarshallingArray_for_LookupIndex ??= __type__?.GetMethodInfoByParameterTypeNames("PopulatePairAdjustmentRecordMarshallingArray_for_LookupIndex", "System.UInt32[]", "System.Int32", "System.Int32&"); + } + + private static MethodInfo ___GetPairAdjustmentRecordsFromMarshallingArray; + private static MethodInfo __GetPairAdjustmentRecordsFromMarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPairAdjustmentRecordsFromMarshallingArray ??= __type__?.GetMethodInfoByParameterTypeNames("GetPairAdjustmentRecordsFromMarshallingArray", "UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord[]"); + } + + private static MethodInfo ___GetAllMarkToBaseAdjustmentRecords; + private static MethodInfo __GetAllMarkToBaseAdjustmentRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetAllMarkToBaseAdjustmentRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetAllMarkToBaseAdjustmentRecords"); + } + + private static MethodInfo ___GetMarkToBaseAdjustmentRecords; + private static MethodInfo __GetMarkToBaseAdjustmentRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMarkToBaseAdjustmentRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetMarkToBaseAdjustmentRecords", "System.UInt32"); + } + + private static MethodInfo ___GetMarkToBaseAdjustmentRecord; + private static MethodInfo __GetMarkToBaseAdjustmentRecord + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMarkToBaseAdjustmentRecord ??= __type__?.GetMethodInfoByParameterTypeNames("GetMarkToBaseAdjustmentRecord", "System.UInt32", "System.UInt32"); + } + + private static MethodInfo ___GetMarkToBaseAdjustmentRecords__2; + private static MethodInfo __GetMarkToBaseAdjustmentRecords__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMarkToBaseAdjustmentRecords__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GetMarkToBaseAdjustmentRecords", "System.Collections.Generic.List`1[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); + } + + private static MethodInfo ___GetMarkToBaseAdjustmentRecords__3; + private static MethodInfo __GetMarkToBaseAdjustmentRecords__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMarkToBaseAdjustmentRecords__3 ??= __type__?.GetMethodInfoByParameterTypeNames("GetMarkToBaseAdjustmentRecords", "System.Int32", "System.Collections.Generic.List`1[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); + } + + private static MethodInfo ___GetMarkToBaseAdjustmentRecords__4; + private static MethodInfo __GetMarkToBaseAdjustmentRecords__4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMarkToBaseAdjustmentRecords__4 ??= __type__?.GetMethodInfoByParameterTypeNames("GetMarkToBaseAdjustmentRecords", "System.UInt32[]"); + } + + private static MethodInfo ___GetMarkToBaseAdjustmentRecords__5; + private static MethodInfo __GetMarkToBaseAdjustmentRecords__5 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMarkToBaseAdjustmentRecords__5 ??= __type__?.GetMethodInfoByParameterTypeNames("GetMarkToBaseAdjustmentRecords", "System.Int32", "System.UInt32[]"); + } + + private static MethodInfo ___PopulateMarkToBaseAdjustmentRecordMarshallingArray; + private static MethodInfo __PopulateMarkToBaseAdjustmentRecordMarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PopulateMarkToBaseAdjustmentRecordMarshallingArray ??= __type__?.GetMethodInfoByParameterTypeNames("PopulateMarkToBaseAdjustmentRecordMarshallingArray", "System.UInt32[]", "System.Int32&"); + } + + private static MethodInfo ___PopulateMarkToBaseAdjustmentRecordMarshallingArray_for_LookupIndex; + private static MethodInfo __PopulateMarkToBaseAdjustmentRecordMarshallingArray_for_LookupIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PopulateMarkToBaseAdjustmentRecordMarshallingArray_for_LookupIndex ??= __type__?.GetMethodInfoByParameterTypeNames("PopulateMarkToBaseAdjustmentRecordMarshallingArray_for_LookupIndex", "System.UInt32[]", "System.Int32", "System.Int32&"); + } + + private static MethodInfo ___GetMarkToBaseAdjustmentRecordsFromMarshallingArray; + private static MethodInfo __GetMarkToBaseAdjustmentRecordsFromMarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMarkToBaseAdjustmentRecordsFromMarshallingArray ??= __type__?.GetMethodInfoByParameterTypeNames("GetMarkToBaseAdjustmentRecordsFromMarshallingArray", "UnityEngine.TextCore.LowLevel.MarkToBaseAdjustmentRecord[]"); + } + + private static MethodInfo ___GetAllMarkToMarkAdjustmentRecords; + private static MethodInfo __GetAllMarkToMarkAdjustmentRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetAllMarkToMarkAdjustmentRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetAllMarkToMarkAdjustmentRecords"); + } + + private static MethodInfo ___GetMarkToMarkAdjustmentRecords; + private static MethodInfo __GetMarkToMarkAdjustmentRecords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMarkToMarkAdjustmentRecords ??= __type__?.GetMethodInfoByParameterTypeNames("GetMarkToMarkAdjustmentRecords", "System.UInt32"); + } + + private static MethodInfo ___GetMarkToMarkAdjustmentRecord; + private static MethodInfo __GetMarkToMarkAdjustmentRecord + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMarkToMarkAdjustmentRecord ??= __type__?.GetMethodInfoByParameterTypeNames("GetMarkToMarkAdjustmentRecord", "System.UInt32", "System.UInt32"); + } + + private static MethodInfo ___GetMarkToMarkAdjustmentRecords__2; + private static MethodInfo __GetMarkToMarkAdjustmentRecords__2 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMarkToMarkAdjustmentRecords__2 ??= __type__?.GetMethodInfoByParameterTypeNames("GetMarkToMarkAdjustmentRecords", "System.Collections.Generic.List`1[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); + } + + private static MethodInfo ___GetMarkToMarkAdjustmentRecords__3; + private static MethodInfo __GetMarkToMarkAdjustmentRecords__3 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMarkToMarkAdjustmentRecords__3 ??= __type__?.GetMethodInfoByParameterTypeNames("GetMarkToMarkAdjustmentRecords", "System.Int32", "System.Collections.Generic.List`1[[System.UInt32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"); + } + + private static MethodInfo ___GetMarkToMarkAdjustmentRecords__4; + private static MethodInfo __GetMarkToMarkAdjustmentRecords__4 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMarkToMarkAdjustmentRecords__4 ??= __type__?.GetMethodInfoByParameterTypeNames("GetMarkToMarkAdjustmentRecords", "System.UInt32[]"); + } + + private static MethodInfo ___GetMarkToMarkAdjustmentRecords__5; + private static MethodInfo __GetMarkToMarkAdjustmentRecords__5 + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMarkToMarkAdjustmentRecords__5 ??= __type__?.GetMethodInfoByParameterTypeNames("GetMarkToMarkAdjustmentRecords", "System.Int32", "System.UInt32[]"); + } + + private static MethodInfo ___PopulateMarkToMarkAdjustmentRecordMarshallingArray; + private static MethodInfo __PopulateMarkToMarkAdjustmentRecordMarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PopulateMarkToMarkAdjustmentRecordMarshallingArray ??= __type__?.GetMethodInfoByParameterTypeNames("PopulateMarkToMarkAdjustmentRecordMarshallingArray", "System.UInt32[]", "System.Int32&"); + } + + private static MethodInfo ___PopulateMarkToMarkAdjustmentRecordMarshallingArray_for_LookupIndex; + private static MethodInfo __PopulateMarkToMarkAdjustmentRecordMarshallingArray_for_LookupIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PopulateMarkToMarkAdjustmentRecordMarshallingArray_for_LookupIndex ??= __type__?.GetMethodInfoByParameterTypeNames("PopulateMarkToMarkAdjustmentRecordMarshallingArray_for_LookupIndex", "System.UInt32[]", "System.Int32", "System.Int32&"); + } + + private static MethodInfo ___GetMarkToMarkAdjustmentRecordsFromMarshallingArray; + private static MethodInfo __GetMarkToMarkAdjustmentRecordsFromMarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMarkToMarkAdjustmentRecordsFromMarshallingArray ??= __type__?.GetMethodInfoByParameterTypeNames("GetMarkToMarkAdjustmentRecordsFromMarshallingArray", "UnityEngine.TextCore.LowLevel.MarkToMarkAdjustmentRecord[]"); + } + + private static MethodInfo ___GlyphIndexToMarshallingArray; + private static MethodInfo __GlyphIndexToMarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GlyphIndexToMarshallingArray ??= __type__?.GetMethodInfoByParameterTypeNames("GlyphIndexToMarshallingArray", "System.UInt32", "System.UInt32[]&"); + } + + private static MethodInfo ___GenericListToMarshallingArray; + private static MethodInfo __GenericListToMarshallingArray + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GenericListToMarshallingArray ??= __type__?.GetMethodInfoByParameterTypeNames("GenericListToMarshallingArray", "", ""); + } + + private static MethodInfo ___SetMarshallingArraySize; + private static MethodInfo __SetMarshallingArraySize + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___SetMarshallingArraySize ??= __type__?.GetMethodInfoByParameterTypeNames("SetMarshallingArraySize", "", "System.Int32"); + } + + private static MethodInfo ___ResetAtlasTexture; + private static MethodInfo __ResetAtlasTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ResetAtlasTexture ??= __type__?.GetMethodInfoByParameterTypeNames("ResetAtlasTexture", "UnityEngine.Texture2D"); + } + + private static MethodInfo ___RenderBufferToTexture; + private static MethodInfo __RenderBufferToTexture + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RenderBufferToTexture ??= __type__?.GetMethodInfoByParameterTypeNames("RenderBufferToTexture", "UnityEngine.Texture2D", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphRenderMode", "UnityEngine.Texture2D"); + } + + private static MethodInfo ___RenderGlyphToTexture_Internal_Injected; + private static MethodInfo __RenderGlyphToTexture_Internal_Injected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___RenderGlyphToTexture_Internal_Injected ??= __type__?.GetMethodInfoByParameterTypeNames("RenderGlyphToTexture_Internal_Injected", "UnityEngine.TextCore.LowLevel.GlyphMarshallingStruct&", "System.Int32", "UnityEngine.TextCore.LowLevel.GlyphRenderMode", "UnityEngine.Texture2D"); + } + + private static MethodInfo ___GetOpenTypeLayoutTable_Injected; + private static MethodInfo __GetOpenTypeLayoutTable_Injected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetOpenTypeLayoutTable_Injected ??= __type__?.GetMethodInfoByParameterTypeNames("GetOpenTypeLayoutTable_Injected", "UnityEngine.TextCore.LowLevel.OTL_TableType", "UnityEngine.TextCore.LowLevel.OTL_Table&"); + } + + private static MethodInfo ___GetGlyphPairAdjustmentRecord_Injected; + private static MethodInfo __GetGlyphPairAdjustmentRecord_Injected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetGlyphPairAdjustmentRecord_Injected ??= __type__?.GetMethodInfoByParameterTypeNames("GetGlyphPairAdjustmentRecord_Injected", "System.UInt32", "System.UInt32", "UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord&"); + } + + private static MethodInfo ___GetPairAdjustmentRecord_Injected; + private static MethodInfo __GetPairAdjustmentRecord_Injected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetPairAdjustmentRecord_Injected ??= __type__?.GetMethodInfoByParameterTypeNames("GetPairAdjustmentRecord_Injected", "System.UInt32", "System.UInt32", "UnityEngine.TextCore.LowLevel.GlyphPairAdjustmentRecord&"); + } + + private static MethodInfo ___GetMarkToBaseAdjustmentRecord_Injected; + private static MethodInfo __GetMarkToBaseAdjustmentRecord_Injected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMarkToBaseAdjustmentRecord_Injected ??= __type__?.GetMethodInfoByParameterTypeNames("GetMarkToBaseAdjustmentRecord_Injected", "System.UInt32", "System.UInt32", "UnityEngine.TextCore.LowLevel.MarkToBaseAdjustmentRecord&"); + } + + private static MethodInfo ___GetMarkToMarkAdjustmentRecord_Injected; + private static MethodInfo __GetMarkToMarkAdjustmentRecord_Injected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetMarkToMarkAdjustmentRecord_Injected ??= __type__?.GetMethodInfoByParameterTypeNames("GetMarkToMarkAdjustmentRecord_Injected", "System.UInt32", "System.UInt32", "UnityEngine.TextCore.LowLevel.MarkToMarkAdjustmentRecord&"); + } + } + public static class UnityEngine_TextCore_LowLevel_FontEngine_Extension + { + public static UnityEngine_TextCore_LowLevel_FontEngine ReflectionHelper(this UnityEngine.TextCore.LowLevel.FontEngine self) => new(self); + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_TextCore_LowLevel_FontEngine.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_TextCore_LowLevel_FontEngine.cs.meta new file mode 100644 index 0000000..72766d0 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_TextCore_LowLevel_FontEngine.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7f8855ded85d04b4cb8d480ccd72dbf1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_TextEditor.cs b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_TextEditor.cs new file mode 100644 index 0000000..d7bd505 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_TextEditor.cs @@ -0,0 +1,678 @@ +//This file was automatically generated by kuroneko. +using System; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats.ReflectionHelper +{ + public partial struct UnityEngine_TextEditor + { + + /// + /// + /// + public static Type __type__ { get; } = EditorUtils.GetTypeByFullName("UnityEngine.TextEditor"); + + + public UnityEngine.Rect localPosition + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Rect)(__localPosition?.GetValue(__self__)); + } + + public bool m_HasFocus + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_HasFocus?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_HasFocus?.SetValue(__self__, value); + } + + public UnityEngine.GUIContent m_Content + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.GUIContent)(__m_Content?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Content?.SetValue(__self__, value); + } + + public UnityEngine.Rect m_Position + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.Rect)(__m_Position?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_Position?.SetValue(__self__, value); + } + + public int m_CursorIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__m_CursorIndex?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_CursorIndex?.SetValue(__self__, value); + } + + public int m_SelectIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__m_SelectIndex?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_SelectIndex?.SetValue(__self__, value); + } + + public bool m_RevealCursor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_RevealCursor?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_RevealCursor?.SetValue(__self__, value); + } + + public bool m_MouseDragSelectsWholeWords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_MouseDragSelectsWholeWords?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_MouseDragSelectsWholeWords?.SetValue(__self__, value); + } + + public int m_DblClickInitPos + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__m_DblClickInitPos?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_DblClickInitPos?.SetValue(__self__, value); + } + + public UnityEngine.TextEditor.DblClickSnapping m_DblClickSnap + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.TextEditor.DblClickSnapping)(__m_DblClickSnap?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_DblClickSnap?.SetValue(__self__, value); + } + + public bool m_bJustSelected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (bool)(__m_bJustSelected?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_bJustSelected?.SetValue(__self__, value); + } + + public int m_iAltCursorPos + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__m_iAltCursorPos?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __m_iAltCursorPos?.SetValue(__self__, value); + } + + public string oldText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (string)(__oldText?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __oldText?.SetValue(__self__, value); + } + + public int oldPos + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__oldPos?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __oldPos?.SetValue(__self__, value); + } + + public int oldSelectPos + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (int)(__oldSelectPos?.GetValue(__self__)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __oldSelectPos?.SetValue(__self__, value); + } + + public static System.Collections.IDictionary s_Keyactions + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (System.Collections.IDictionary)(__s_Keyactions?.GetValue(null)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => __s_Keyactions?.SetValue(null, value); + } + + public void ClearCursorPos() + { + __ClearCursorPos?.Invoke(__self__, System.Array.Empty()); + } + + public void GrabGraphicalCursorPos() + { + __GrabGraphicalCursorPos?.Invoke(__self__, System.Array.Empty()); + } + + public bool HandleKeyEvent(UnityEngine.Event e, bool textIsReadOnly) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = e; + __params__[1] = textIsReadOnly; + var __result__ = __HandleKeyEvent?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public int IndexOfEndOfLine(int startIndex) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = startIndex; + var __result__ = __IndexOfEndOfLine?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public void MoveCursorToPosition_Internal(UnityEngine.Vector2 cursorPosition, bool shift) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = cursorPosition; + __params__[1] = shift; + __MoveCursorToPosition_Internal?.Invoke(__self__, __params__); + __pool__.Return(__params__); + } + + public int GetGraphicalLineStart(int p) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = p; + var __result__ = __GetGraphicalLineStart?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public int GetGraphicalLineEnd(int p) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = p; + var __result__ = __GetGraphicalLineEnd?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public int FindNextSeperator(int startPos) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = startPos; + var __result__ = __FindNextSeperator?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public int FindPrevSeperator(int startPos) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = startPos; + var __result__ = __FindPrevSeperator?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public object ClassifyChar(int index) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = index; + var __result__ = __ClassifyChar?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (object)(__result__) : default; + } + + public int FindEndOfPreviousWord(int p) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = p; + var __result__ = __FindEndOfPreviousWord?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public int FindEndOfClassification(int p, object dir) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = p; + __params__[1] = dir; + var __result__ = __FindEndOfClassification?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public void UpdateScrollOffset() + { + __UpdateScrollOffset?.Invoke(__self__, System.Array.Empty()); + } + + public bool PerformOperation(object operation, bool textIsReadOnly) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = operation; + __params__[1] = textIsReadOnly; + var __result__ = __PerformOperation?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public UnityEngine.Rect[] GetHyperlinksRect() + { + var __result__ = __GetHyperlinksRect?.Invoke(__self__, System.Array.Empty()); + return __result__ != null ? (UnityEngine.Rect[])(__result__) : default; + } + + public static string ReplaceNewlinesWithSpaces(string value) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = value; + var __result__ = __ReplaceNewlinesWithSpaces?.Invoke(null, __params__); + __pool__.Return(__params__); + return __result__ != null ? (string)(__result__) : default; + } + + public static void MapKey(string key, object action) + { + var __pool__ = FixedArrayPool.Shared(2); + var __params__ = __pool__.Rent(); + __params__[0] = key; + __params__[1] = action; + __MapKey?.Invoke(null, __params__); + __pool__.Return(__params__); + } + + public void InitKeyActions() + { + __InitKeyActions?.Invoke(__self__, System.Array.Empty()); + } + + public void OnDetectFocusChange() + { + __OnDetectFocusChange?.Invoke(__self__, System.Array.Empty()); + } + + public void OnCursorIndexChange() + { + __OnCursorIndexChange?.Invoke(__self__, System.Array.Empty()); + } + + public void OnSelectIndexChange() + { + __OnSelectIndexChange?.Invoke(__self__, System.Array.Empty()); + } + + public void ClampTextIndex(ref int index) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = index; + __ClampTextIndex?.Invoke(__self__, __params__); + index = (int)(__params__[0]); + __pool__.Return(__params__); + } + + public void EnsureValidCodePointIndex(ref int index) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = index; + __EnsureValidCodePointIndex?.Invoke(__self__, __params__); + index = (int)(__params__[0]); + __pool__.Return(__params__); + } + + public bool IsValidCodePointIndex(int index) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = index; + var __result__ = __IsValidCodePointIndex?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (bool)(__result__) : default; + } + + public int PreviousCodePointIndex(int index) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = index; + var __result__ = __PreviousCodePointIndex?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public int NextCodePointIndex(int index) + { + var __pool__ = FixedArrayPool.Shared(1); + var __params__ = __pool__.Rent(); + __params__[0] = index; + var __result__ = __NextCodePointIndex?.Invoke(__self__, __params__); + __pool__.Return(__params__); + return __result__ != null ? (int)(__result__) : default; + } + + public UnityEngine_TextEditor(object __self__) => this.__self__ = __self__ as object; + public object __self__; + public bool __valid__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => __self__ != null && __type__ != null; + } + public UnityEngine.TextEditor __super__ + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => (UnityEngine.TextEditor)(__self__); + } + + private static FieldInfo ___m_HasFocus; + private static FieldInfo __m_HasFocus + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_HasFocus ??= __type__?.GetField("m_HasFocus", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Content; + private static FieldInfo __m_Content + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Content ??= __type__?.GetField("m_Content", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_Position; + private static FieldInfo __m_Position + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_Position ??= __type__?.GetField("m_Position", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_CursorIndex; + private static FieldInfo __m_CursorIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_CursorIndex ??= __type__?.GetField("m_CursorIndex", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_SelectIndex; + private static FieldInfo __m_SelectIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_SelectIndex ??= __type__?.GetField("m_SelectIndex", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_RevealCursor; + private static FieldInfo __m_RevealCursor + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_RevealCursor ??= __type__?.GetField("m_RevealCursor", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_MouseDragSelectsWholeWords; + private static FieldInfo __m_MouseDragSelectsWholeWords + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_MouseDragSelectsWholeWords ??= __type__?.GetField("m_MouseDragSelectsWholeWords", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_DblClickInitPos; + private static FieldInfo __m_DblClickInitPos + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_DblClickInitPos ??= __type__?.GetField("m_DblClickInitPos", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_DblClickSnap; + private static FieldInfo __m_DblClickSnap + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_DblClickSnap ??= __type__?.GetField("m_DblClickSnap", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_bJustSelected; + private static FieldInfo __m_bJustSelected + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_bJustSelected ??= __type__?.GetField("m_bJustSelected", (BindingFlags)(-1)); + } + + private static FieldInfo ___m_iAltCursorPos; + private static FieldInfo __m_iAltCursorPos + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___m_iAltCursorPos ??= __type__?.GetField("m_iAltCursorPos", (BindingFlags)(-1)); + } + + private static FieldInfo ___oldText; + private static FieldInfo __oldText + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___oldText ??= __type__?.GetField("oldText", (BindingFlags)(-1)); + } + + private static FieldInfo ___oldPos; + private static FieldInfo __oldPos + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___oldPos ??= __type__?.GetField("oldPos", (BindingFlags)(-1)); + } + + private static FieldInfo ___oldSelectPos; + private static FieldInfo __oldSelectPos + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___oldSelectPos ??= __type__?.GetField("oldSelectPos", (BindingFlags)(-1)); + } + + private static FieldInfo ___s_Keyactions; + private static FieldInfo __s_Keyactions + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___s_Keyactions ??= __type__?.GetField("s_Keyactions", (BindingFlags)(-1)); + } + + private static PropertyInfo ___localPosition; + private static PropertyInfo __localPosition + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___localPosition ??= __type__?.GetProperty("localPosition", (BindingFlags)(-1)); + } + + private static MethodInfo ___ClearCursorPos; + private static MethodInfo __ClearCursorPos + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ClearCursorPos ??= __type__?.GetMethodInfoByParameterTypeNames("ClearCursorPos"); + } + + private static MethodInfo ___GrabGraphicalCursorPos; + private static MethodInfo __GrabGraphicalCursorPos + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GrabGraphicalCursorPos ??= __type__?.GetMethodInfoByParameterTypeNames("GrabGraphicalCursorPos"); + } + + private static MethodInfo ___HandleKeyEvent; + private static MethodInfo __HandleKeyEvent + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___HandleKeyEvent ??= __type__?.GetMethodInfoByParameterTypeNames("HandleKeyEvent", "UnityEngine.Event", "System.Boolean"); + } + + private static MethodInfo ___IndexOfEndOfLine; + private static MethodInfo __IndexOfEndOfLine + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IndexOfEndOfLine ??= __type__?.GetMethodInfoByParameterTypeNames("IndexOfEndOfLine", "System.Int32"); + } + + private static MethodInfo ___MoveCursorToPosition_Internal; + private static MethodInfo __MoveCursorToPosition_Internal + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MoveCursorToPosition_Internal ??= __type__?.GetMethodInfoByParameterTypeNames("MoveCursorToPosition_Internal", "UnityEngine.Vector2", "System.Boolean"); + } + + private static MethodInfo ___GetGraphicalLineStart; + private static MethodInfo __GetGraphicalLineStart + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetGraphicalLineStart ??= __type__?.GetMethodInfoByParameterTypeNames("GetGraphicalLineStart", "System.Int32"); + } + + private static MethodInfo ___GetGraphicalLineEnd; + private static MethodInfo __GetGraphicalLineEnd + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetGraphicalLineEnd ??= __type__?.GetMethodInfoByParameterTypeNames("GetGraphicalLineEnd", "System.Int32"); + } + + private static MethodInfo ___FindNextSeperator; + private static MethodInfo __FindNextSeperator + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FindNextSeperator ??= __type__?.GetMethodInfoByParameterTypeNames("FindNextSeperator", "System.Int32"); + } + + private static MethodInfo ___FindPrevSeperator; + private static MethodInfo __FindPrevSeperator + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FindPrevSeperator ??= __type__?.GetMethodInfoByParameterTypeNames("FindPrevSeperator", "System.Int32"); + } + + private static MethodInfo ___ClassifyChar; + private static MethodInfo __ClassifyChar + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ClassifyChar ??= __type__?.GetMethodInfoByParameterTypeNames("ClassifyChar", "System.Int32"); + } + + private static MethodInfo ___FindEndOfPreviousWord; + private static MethodInfo __FindEndOfPreviousWord + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FindEndOfPreviousWord ??= __type__?.GetMethodInfoByParameterTypeNames("FindEndOfPreviousWord", "System.Int32"); + } + + private static MethodInfo ___FindEndOfClassification; + private static MethodInfo __FindEndOfClassification + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___FindEndOfClassification ??= __type__?.GetMethodInfoByParameterTypeNames("FindEndOfClassification", "System.Int32", "UnityEngine.TextEditor+Direction"); + } + + private static MethodInfo ___UpdateScrollOffset; + private static MethodInfo __UpdateScrollOffset + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___UpdateScrollOffset ??= __type__?.GetMethodInfoByParameterTypeNames("UpdateScrollOffset"); + } + + private static MethodInfo ___PerformOperation; + private static MethodInfo __PerformOperation + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PerformOperation ??= __type__?.GetMethodInfoByParameterTypeNames("PerformOperation", "UnityEngine.TextEditor+TextEditOp", "System.Boolean"); + } + + private static MethodInfo ___GetHyperlinksRect; + private static MethodInfo __GetHyperlinksRect + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___GetHyperlinksRect ??= __type__?.GetMethodInfoByParameterTypeNames("GetHyperlinksRect"); + } + + private static MethodInfo ___ReplaceNewlinesWithSpaces; + private static MethodInfo __ReplaceNewlinesWithSpaces + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ReplaceNewlinesWithSpaces ??= __type__?.GetMethodInfoByParameterTypeNames("ReplaceNewlinesWithSpaces", "System.String"); + } + + private static MethodInfo ___MapKey; + private static MethodInfo __MapKey + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___MapKey ??= __type__?.GetMethodInfoByParameterTypeNames("MapKey", "System.String", "UnityEngine.TextEditor+TextEditOp"); + } + + private static MethodInfo ___InitKeyActions; + private static MethodInfo __InitKeyActions + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___InitKeyActions ??= __type__?.GetMethodInfoByParameterTypeNames("InitKeyActions"); + } + + private static MethodInfo ___OnDetectFocusChange; + private static MethodInfo __OnDetectFocusChange + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnDetectFocusChange ??= __type__?.GetMethodInfoByParameterTypeNames("OnDetectFocusChange"); + } + + private static MethodInfo ___OnCursorIndexChange; + private static MethodInfo __OnCursorIndexChange + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnCursorIndexChange ??= __type__?.GetMethodInfoByParameterTypeNames("OnCursorIndexChange"); + } + + private static MethodInfo ___OnSelectIndexChange; + private static MethodInfo __OnSelectIndexChange + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___OnSelectIndexChange ??= __type__?.GetMethodInfoByParameterTypeNames("OnSelectIndexChange"); + } + + private static MethodInfo ___ClampTextIndex; + private static MethodInfo __ClampTextIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___ClampTextIndex ??= __type__?.GetMethodInfoByParameterTypeNames("ClampTextIndex", "System.Int32&"); + } + + private static MethodInfo ___EnsureValidCodePointIndex; + private static MethodInfo __EnsureValidCodePointIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___EnsureValidCodePointIndex ??= __type__?.GetMethodInfoByParameterTypeNames("EnsureValidCodePointIndex", "System.Int32&"); + } + + private static MethodInfo ___IsValidCodePointIndex; + private static MethodInfo __IsValidCodePointIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___IsValidCodePointIndex ??= __type__?.GetMethodInfoByParameterTypeNames("IsValidCodePointIndex", "System.Int32"); + } + + private static MethodInfo ___PreviousCodePointIndex; + private static MethodInfo __PreviousCodePointIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___PreviousCodePointIndex ??= __type__?.GetMethodInfoByParameterTypeNames("PreviousCodePointIndex", "System.Int32"); + } + + private static MethodInfo ___NextCodePointIndex; + private static MethodInfo __NextCodePointIndex + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ___NextCodePointIndex ??= __type__?.GetMethodInfoByParameterTypeNames("NextCodePointIndex", "System.Int32"); + } + } + public static class UnityEngine_TextEditor_Extension + { + public static UnityEngine_TextEditor ReflectionHelper(this UnityEngine.TextEditor self) => new(self); + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_TextEditor.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_TextEditor.cs.meta new file mode 100644 index 0000000..654687e --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/Generated/Wrap_UnityEngine_TextEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a3e652b2f2e54dd4c9a6489a908af59e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook.meta b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook.meta new file mode 100644 index 0000000..ae9f41e --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3476693353cd4064596f479f1788aca0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/HookPool.cs b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/HookPool.cs new file mode 100644 index 0000000..ae82313 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/HookPool.cs @@ -0,0 +1,29 @@ +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using UnityEngine; + +/// +/// Hook 池,防止重复 Hook +/// +public static class HookPool +{ + private static Dictionary _hookers = new Dictionary(); + + public static void AddHooker(MethodBase method, MethodHook hooker) + { + MethodHook preHooker; + if (_hookers.TryGetValue(method, out preHooker)) + { + preHooker.Uninstall(); + _hookers[method] = hooker; + } + else + _hookers.Add(method, hooker); + } + + public static void RemoveHooker(MethodBase method) + { + _hookers.Remove(method); + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/HookPool.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/HookPool.cs.meta new file mode 100644 index 0000000..7503859 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/HookPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6b7421e47f0ae1e4ebb72bf18d1d7d48 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/IL2CPPHelper.cs b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/IL2CPPHelper.cs new file mode 100644 index 0000000..b483d43 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/IL2CPPHelper.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using UnityEngine; + +public static class IL2CPPHelper +{ + public enum Protection + { + PAGE_NOACCESS = 0x01, + PAGE_READONLY = 0x02, + PAGE_READWRITE = 0x04, + PAGE_WRITECOPY = 0x08, + PAGE_EXECUTE = 0x10, + PAGE_EXECUTE_READ = 0x20, + PAGE_EXECUTE_READWRITE = 0x40, + PAGE_EXECUTE_WRITECOPY = 0x80, + PAGE_GUARD = 0x100, + PAGE_NOCACHE = 0x200, + PAGE_WRITECOMBINE = 0x400 + } + +#if UNITY_STANDALONE_WIN + + [DllImport("kernel32")] + public static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, Protection flNewProtect, out uint lpflOldProtect); +#else + // mprotect + public static bool VirtualProtect(IntPtr lpAddress, uint dwSize, Protection flNewProtect, out uint lpflOldProtect) + { + lpflOldProtect = 0; + return false; + } +#endif +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/IL2CPPHelper.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/IL2CPPHelper.cs.meta new file mode 100644 index 0000000..d2b2c6d --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/IL2CPPHelper.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 606e5d1aa707ccb498682917dd9d1684 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/LDasm.cs b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/LDasm.cs new file mode 100644 index 0000000..24fc32f --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/LDasm.cs @@ -0,0 +1,875 @@ +using System; + +namespace DotNetDetour +{ + /// + /// 用于计算汇编指令长度,使用的是BlackBone的LDasm.c中的算法,我把他翻译成C#了 + /// + public unsafe class LDasm + { + const int F_INVALID = 0x01; + const int F_PREFIX = 0x02; + const int F_REX = 0x04; + const int F_MODRM = 0x08; + const int F_SIB = 0x10; + const int F_DISP = 0x20; + const int F_IMM = 0x40; + const int F_RELATIVE = 0x80; + + const int OP_NONE = 0x00; + const int OP_INVALID = 0x80; + + const int OP_DATA_I8 = 0x01; + const int OP_DATA_I16 = 0x02; + const int OP_DATA_I16_I32 = 0x04; + const int OP_DATA_I16_I32_I64 = 0x08; + const int OP_EXTENDED = 0x10; + const int OP_RELATIVE = 0x20; + const int OP_MODRM = 0x40; + const int OP_PREFIX = 0x80; + + struct ldasm_data + { + public byte flags; + public byte rex; + public byte modrm; + public byte sib; + public byte opcd_offset; + public byte opcd_size; + public byte disp_offset; + public byte disp_size; + public byte imm_offset; + public byte imm_size; + } + + static byte[] flags_table = + { + /* 00 */ OP_MODRM, + /* 01 */ OP_MODRM, + /* 02 */ OP_MODRM, + /* 03 */ OP_MODRM, + /* 04 */ OP_DATA_I8, + /* 05 */ OP_DATA_I16_I32, + /* 06 */ OP_NONE, + /* 07 */ OP_NONE, + /* 08 */ OP_MODRM, + /* 09 */ OP_MODRM, + /* 0A */ OP_MODRM, + /* 0B */ OP_MODRM, + /* 0C */ OP_DATA_I8, + /* 0D */ OP_DATA_I16_I32, + /* 0E */ OP_NONE, + /* 0F */ OP_NONE, + + /* 10 */ OP_MODRM, + /* 11 */ OP_MODRM, + /* 12 */ OP_MODRM, + /* 13 */ OP_MODRM, + /* 14 */ OP_DATA_I8, + /* 15 */ OP_DATA_I16_I32, + /* 16 */ OP_NONE, + /* 17 */ OP_NONE, + /* 18 */ OP_MODRM, + /* 19 */ OP_MODRM, + /* 1A */ OP_MODRM, + /* 1B */ OP_MODRM, + /* 1C */ OP_DATA_I8, + /* 1D */ OP_DATA_I16_I32, + /* 1E */ OP_NONE, + /* 1F */ OP_NONE, + + /* 20 */ OP_MODRM, + /* 21 */ OP_MODRM, + /* 22 */ OP_MODRM, + /* 23 */ OP_MODRM, + /* 24 */ OP_DATA_I8, + /* 25 */ OP_DATA_I16_I32, + /* 26 */ OP_PREFIX, + /* 27 */ OP_NONE, + /* 28 */ OP_MODRM, + /* 29 */ OP_MODRM, + /* 2A */ OP_MODRM, + /* 2B */ OP_MODRM, + /* 2C */ OP_DATA_I8, + /* 2D */ OP_DATA_I16_I32, + /* 2E */ OP_PREFIX, + /* 2F */ OP_NONE, + + /* 30 */ OP_MODRM, + /* 31 */ OP_MODRM, + /* 32 */ OP_MODRM, + /* 33 */ OP_MODRM, + /* 34 */ OP_DATA_I8, + /* 35 */ OP_DATA_I16_I32, + /* 36 */ OP_PREFIX, + /* 37 */ OP_NONE, + /* 38 */ OP_MODRM, + /* 39 */ OP_MODRM, + /* 3A */ OP_MODRM, + /* 3B */ OP_MODRM, + /* 3C */ OP_DATA_I8, + /* 3D */ OP_DATA_I16_I32, + /* 3E */ OP_PREFIX, + /* 3F */ OP_NONE, + + /* 40 */ OP_NONE, + /* 41 */ OP_NONE, + /* 42 */ OP_NONE, + /* 43 */ OP_NONE, + /* 44 */ OP_NONE, + /* 45 */ OP_NONE, + /* 46 */ OP_NONE, + /* 47 */ OP_NONE, + /* 48 */ OP_NONE, + /* 49 */ OP_NONE, + /* 4A */ OP_NONE, + /* 4B */ OP_NONE, + /* 4C */ OP_NONE, + /* 4D */ OP_NONE, + /* 4E */ OP_NONE, + /* 4F */ OP_NONE, + + /* 50 */ OP_NONE, + /* 51 */ OP_NONE, + /* 52 */ OP_NONE, + /* 53 */ OP_NONE, + /* 54 */ OP_NONE, + /* 55 */ OP_NONE, + /* 56 */ OP_NONE, + /* 57 */ OP_NONE, + /* 58 */ OP_NONE, + /* 59 */ OP_NONE, + /* 5A */ OP_NONE, + /* 5B */ OP_NONE, + /* 5C */ OP_NONE, + /* 5D */ OP_NONE, + /* 5E */ OP_NONE, + /* 5F */ OP_NONE, + /* 60 */ OP_NONE, + + /* 61 */ OP_NONE, + /* 62 */ OP_MODRM, + /* 63 */ OP_MODRM, + /* 64 */ OP_PREFIX, + /* 65 */ OP_PREFIX, + /* 66 */ OP_PREFIX, + /* 67 */ OP_PREFIX, + /* 68 */ OP_DATA_I16_I32, + /* 69 */ OP_MODRM | OP_DATA_I16_I32, + /* 6A */ OP_DATA_I8, + /* 6B */ OP_MODRM | OP_DATA_I8, + /* 6C */ OP_NONE, + /* 6D */ OP_NONE, + /* 6E */ OP_NONE, + /* 6F */ OP_NONE, + + /* 70 */ OP_RELATIVE | OP_DATA_I8, + /* 71 */ OP_RELATIVE | OP_DATA_I8, + /* 72 */ OP_RELATIVE | OP_DATA_I8, + /* 73 */ OP_RELATIVE | OP_DATA_I8, + /* 74 */ OP_RELATIVE | OP_DATA_I8, + /* 75 */ OP_RELATIVE | OP_DATA_I8, + /* 76 */ OP_RELATIVE | OP_DATA_I8, + /* 77 */ OP_RELATIVE | OP_DATA_I8, + /* 78 */ OP_RELATIVE | OP_DATA_I8, + /* 79 */ OP_RELATIVE | OP_DATA_I8, + /* 7A */ OP_RELATIVE | OP_DATA_I8, + /* 7B */ OP_RELATIVE | OP_DATA_I8, + /* 7C */ OP_RELATIVE | OP_DATA_I8, + /* 7D */ OP_RELATIVE | OP_DATA_I8, + /* 7E */ OP_RELATIVE | OP_DATA_I8, + /* 7F */ OP_RELATIVE | OP_DATA_I8, + + /* 80 */ OP_MODRM | OP_DATA_I8, + /* 81 */ OP_MODRM | OP_DATA_I16_I32, + /* 82 */ OP_MODRM | OP_DATA_I8, + /* 83 */ OP_MODRM | OP_DATA_I8, + /* 84 */ OP_MODRM, + /* 85 */ OP_MODRM, + /* 86 */ OP_MODRM, + /* 87 */ OP_MODRM, + /* 88 */ OP_MODRM, + /* 89 */ OP_MODRM, + /* 8A */ OP_MODRM, + /* 8B */ OP_MODRM, + /* 8C */ OP_MODRM, + /* 8D */ OP_MODRM, + /* 8E */ OP_MODRM, + /* 8F */ OP_MODRM, + + /* 90 */ OP_NONE, + /* 91 */ OP_NONE, + /* 92 */ OP_NONE, + /* 93 */ OP_NONE, + /* 94 */ OP_NONE, + /* 95 */ OP_NONE, + /* 96 */ OP_NONE, + /* 97 */ OP_NONE, + /* 98 */ OP_NONE, + /* 99 */ OP_NONE, + /* 9A */ OP_DATA_I16 | OP_DATA_I16_I32, + /* 9B */ OP_NONE, + /* 9C */ OP_NONE, + /* 9D */ OP_NONE, + /* 9E */ OP_NONE, + /* 9F */ OP_NONE, + + /* A0 */ OP_DATA_I8, + /* A1 */ OP_DATA_I16_I32_I64, + /* A2 */ OP_DATA_I8, + /* A3 */ OP_DATA_I16_I32_I64, + /* A4 */ OP_NONE, + /* A5 */ OP_NONE, + /* A6 */ OP_NONE, + /* A7 */ OP_NONE, + /* A8 */ OP_DATA_I8, + /* A9 */ OP_DATA_I16_I32, + /* AA */ OP_NONE, + /* AB */ OP_NONE, + /* AC */ OP_NONE, + /* AD */ OP_NONE, + /* AE */ OP_NONE, + /* AF */ OP_NONE, + + /* B0 */ OP_DATA_I8, + /* B1 */ OP_DATA_I8, + /* B2 */ OP_DATA_I8, + /* B3 */ OP_DATA_I8, + /* B4 */ OP_DATA_I8, + /* B5 */ OP_DATA_I8, + /* B6 */ OP_DATA_I8, + /* B7 */ OP_DATA_I8, + /* B8 */ OP_DATA_I16_I32_I64, + /* B9 */ OP_DATA_I16_I32_I64, + /* BA */ OP_DATA_I16_I32_I64, + /* BB */ OP_DATA_I16_I32_I64, + /* BC */ OP_DATA_I16_I32_I64, + /* BD */ OP_DATA_I16_I32_I64, + /* BE */ OP_DATA_I16_I32_I64, + /* BF */ OP_DATA_I16_I32_I64, + + /* C0 */ OP_MODRM | OP_DATA_I8, + /* C1 */ OP_MODRM | OP_DATA_I8, + /* C2 */ OP_DATA_I16, + /* C3 */ OP_NONE, + /* C4 */ OP_MODRM, + /* C5 */ OP_MODRM, + /* C6 */ OP_MODRM | OP_DATA_I8, + /* C7 */ OP_MODRM | OP_DATA_I16_I32, + /* C8 */ OP_DATA_I8 | OP_DATA_I16, + /* C9 */ OP_NONE, + /* CA */ OP_DATA_I16, + /* CB */ OP_NONE, + /* CC */ OP_NONE, + /* CD */ OP_DATA_I8, + /* CE */ OP_NONE, + /* CF */ OP_NONE, + + /* D0 */ OP_MODRM, + /* D1 */ OP_MODRM, + /* D2 */ OP_MODRM, + /* D3 */ OP_MODRM, + /* D4 */ OP_DATA_I8, + /* D5 */ OP_DATA_I8, + /* D6 */ OP_NONE, + /* D7 */ OP_NONE, + /* D8 */ OP_MODRM, + /* D9 */ OP_MODRM, + /* DA */ OP_MODRM, + /* DB */ OP_MODRM, + /* DC */ OP_MODRM, + /* DD */ OP_MODRM, + /* DE */ OP_MODRM, + /* DF */ OP_MODRM, + + /* E0 */ OP_RELATIVE | OP_DATA_I8, + /* E1 */ OP_RELATIVE | OP_DATA_I8, + /* E2 */ OP_RELATIVE | OP_DATA_I8, + /* E3 */ OP_RELATIVE | OP_DATA_I8, + /* E4 */ OP_DATA_I8, + /* E5 */ OP_DATA_I8, + /* E6 */ OP_DATA_I8, + /* E7 */ OP_DATA_I8, + /* E8 */ OP_RELATIVE | OP_DATA_I16_I32, + /* E9 */ OP_RELATIVE | OP_DATA_I16_I32, + /* EA */ OP_DATA_I16 | OP_DATA_I16_I32, + /* EB */ OP_RELATIVE | OP_DATA_I8, + /* EC */ OP_NONE, + /* ED */ OP_NONE, + /* EE */ OP_NONE, + /* EF */ OP_NONE, + + /* F0 */ OP_PREFIX, + /* F1 */ OP_NONE, + /* F2 */ OP_PREFIX, + /* F3 */ OP_PREFIX, + /* F4 */ OP_NONE, + /* F5 */ OP_NONE, + /* F6 */ OP_MODRM, + /* F7 */ OP_MODRM, + /* F8 */ OP_NONE, + /* F9 */ OP_NONE, + /* FA */ OP_NONE, + /* FB */ OP_NONE, + /* FC */ OP_NONE, + /* FD */ OP_NONE, + /* FE */ OP_MODRM, + /* FF */ OP_MODRM + }; + + static byte[] flags_table_ex = + { + /* 0F00 */ OP_MODRM, + /* 0F01 */ OP_MODRM, + /* 0F02 */ OP_MODRM, + /* 0F03 */ OP_MODRM, + /* 0F04 */ OP_INVALID, + /* 0F05 */ OP_NONE, + /* 0F06 */ OP_NONE, + /* 0F07 */ OP_NONE, + /* 0F08 */ OP_NONE, + /* 0F09 */ OP_NONE, + /* 0F0A */ OP_INVALID, + /* 0F0B */ OP_NONE, + /* 0F0C */ OP_INVALID, + /* 0F0D */ OP_MODRM, + /* 0F0E */ OP_INVALID, + /* 0F0F */ OP_MODRM | OP_DATA_I8, //3Dnow + + /* 0F10 */ OP_MODRM, + /* 0F11 */ OP_MODRM, + /* 0F12 */ OP_MODRM, + /* 0F13 */ OP_MODRM, + /* 0F14 */ OP_MODRM, + /* 0F15 */ OP_MODRM, + /* 0F16 */ OP_MODRM, + /* 0F17 */ OP_MODRM, + /* 0F18 */ OP_MODRM, + /* 0F19 */ OP_INVALID, + /* 0F1A */ OP_INVALID, + /* 0F1B */ OP_INVALID, + /* 0F1C */ OP_INVALID, + /* 0F1D */ OP_INVALID, + /* 0F1E */ OP_INVALID, + /* 0F1F */ OP_NONE, + + /* 0F20 */ OP_MODRM, + /* 0F21 */ OP_MODRM, + /* 0F22 */ OP_MODRM, + /* 0F23 */ OP_MODRM, + /* 0F24 */ OP_MODRM | OP_EXTENDED, //SSE5 + /* 0F25 */ OP_INVALID, + /* 0F26 */ OP_MODRM, + /* 0F27 */ OP_INVALID, + /* 0F28 */ OP_MODRM, + /* 0F29 */ OP_MODRM, + /* 0F2A */ OP_MODRM, + /* 0F2B */ OP_MODRM, + /* 0F2C */ OP_MODRM, + /* 0F2D */ OP_MODRM, + /* 0F2E */ OP_MODRM, + /* 0F2F */ OP_MODRM, + + /* 0F30 */ OP_NONE, + /* 0F31 */ OP_NONE, + /* 0F32 */ OP_NONE, + /* 0F33 */ OP_NONE, + /* 0F34 */ OP_NONE, + /* 0F35 */ OP_NONE, + /* 0F36 */ OP_INVALID, + /* 0F37 */ OP_NONE, + /* 0F38 */ OP_MODRM | OP_EXTENDED, + /* 0F39 */ OP_INVALID, + /* 0F3A */ OP_MODRM | OP_EXTENDED | OP_DATA_I8, + /* 0F3B */ OP_INVALID, + /* 0F3C */ OP_INVALID, + /* 0F3D */ OP_INVALID, + /* 0F3E */ OP_INVALID, + /* 0F3F */ OP_INVALID, + + /* 0F40 */ OP_MODRM, + /* 0F41 */ OP_MODRM, + /* 0F42 */ OP_MODRM, + /* 0F43 */ OP_MODRM, + /* 0F44 */ OP_MODRM, + /* 0F45 */ OP_MODRM, + /* 0F46 */ OP_MODRM, + /* 0F47 */ OP_MODRM, + /* 0F48 */ OP_MODRM, + /* 0F49 */ OP_MODRM, + /* 0F4A */ OP_MODRM, + /* 0F4B */ OP_MODRM, + /* 0F4C */ OP_MODRM, + /* 0F4D */ OP_MODRM, + /* 0F4E */ OP_MODRM, + /* 0F4F */ OP_MODRM, + + /* 0F50 */ OP_MODRM, + /* 0F51 */ OP_MODRM, + /* 0F52 */ OP_MODRM, + /* 0F53 */ OP_MODRM, + /* 0F54 */ OP_MODRM, + /* 0F55 */ OP_MODRM, + /* 0F56 */ OP_MODRM, + /* 0F57 */ OP_MODRM, + /* 0F58 */ OP_MODRM, + /* 0F59 */ OP_MODRM, + /* 0F5A */ OP_MODRM, + /* 0F5B */ OP_MODRM, + /* 0F5C */ OP_MODRM, + /* 0F5D */ OP_MODRM, + /* 0F5E */ OP_MODRM, + /* 0F5F */ OP_MODRM, + + /* 0F60 */ OP_MODRM, + /* 0F61 */ OP_MODRM, + /* 0F62 */ OP_MODRM, + /* 0F63 */ OP_MODRM, + /* 0F64 */ OP_MODRM, + /* 0F65 */ OP_MODRM, + /* 0F66 */ OP_MODRM, + /* 0F67 */ OP_MODRM, + /* 0F68 */ OP_MODRM, + /* 0F69 */ OP_MODRM, + /* 0F6A */ OP_MODRM, + /* 0F6B */ OP_MODRM, + /* 0F6C */ OP_MODRM, + /* 0F6D */ OP_MODRM, + /* 0F6E */ OP_MODRM, + /* 0F6F */ OP_MODRM, + + /* 0F70 */ OP_MODRM | OP_DATA_I8, + /* 0F71 */ OP_MODRM | OP_DATA_I8, + /* 0F72 */ OP_MODRM | OP_DATA_I8, + /* 0F73 */ OP_MODRM | OP_DATA_I8, + /* 0F74 */ OP_MODRM, + /* 0F75 */ OP_MODRM, + /* 0F76 */ OP_MODRM, + /* 0F77 */ OP_NONE, + /* 0F78 */ OP_MODRM, + /* 0F79 */ OP_MODRM, + /* 0F7A */ OP_INVALID, + /* 0F7B */ OP_INVALID, + /* 0F7C */ OP_MODRM, + /* 0F7D */ OP_MODRM, + /* 0F7E */ OP_MODRM, + /* 0F7F */ OP_MODRM, + + /* 0F80 */ OP_RELATIVE | OP_DATA_I16_I32, + /* 0F81 */ OP_RELATIVE | OP_DATA_I16_I32, + /* 0F82 */ OP_RELATIVE | OP_DATA_I16_I32, + /* 0F83 */ OP_RELATIVE | OP_DATA_I16_I32, + /* 0F84 */ OP_RELATIVE | OP_DATA_I16_I32, + /* 0F85 */ OP_RELATIVE | OP_DATA_I16_I32, + /* 0F86 */ OP_RELATIVE | OP_DATA_I16_I32, + /* 0F87 */ OP_RELATIVE | OP_DATA_I16_I32, + /* 0F88 */ OP_RELATIVE | OP_DATA_I16_I32, + /* 0F89 */ OP_RELATIVE | OP_DATA_I16_I32, + /* 0F8A */ OP_RELATIVE | OP_DATA_I16_I32, + /* 0F8B */ OP_RELATIVE | OP_DATA_I16_I32, + /* 0F8C */ OP_RELATIVE | OP_DATA_I16_I32, + /* 0F8D */ OP_RELATIVE | OP_DATA_I16_I32, + /* 0F8E */ OP_RELATIVE | OP_DATA_I16_I32, + /* 0F8F */ OP_RELATIVE | OP_DATA_I16_I32, + + /* 0F90 */ OP_MODRM, + /* 0F91 */ OP_MODRM, + /* 0F92 */ OP_MODRM, + /* 0F93 */ OP_MODRM, + /* 0F94 */ OP_MODRM, + /* 0F95 */ OP_MODRM, + /* 0F96 */ OP_MODRM, + /* 0F97 */ OP_MODRM, + /* 0F98 */ OP_MODRM, + /* 0F99 */ OP_MODRM, + /* 0F9A */ OP_MODRM, + /* 0F9B */ OP_MODRM, + /* 0F9C */ OP_MODRM, + /* 0F9D */ OP_MODRM, + /* 0F9E */ OP_MODRM, + /* 0F9F */ OP_MODRM, + + /* 0FA0 */ OP_NONE, + /* 0FA1 */ OP_NONE, + /* 0FA2 */ OP_NONE, + /* 0FA3 */ OP_MODRM, + /* 0FA4 */ OP_MODRM | OP_DATA_I8, + /* 0FA5 */ OP_MODRM, + /* 0FA6 */ OP_INVALID, + /* 0FA7 */ OP_INVALID, + /* 0FA8 */ OP_NONE, + /* 0FA9 */ OP_NONE, + /* 0FAA */ OP_NONE, + /* 0FAB */ OP_MODRM, + /* 0FAC */ OP_MODRM | OP_DATA_I8, + /* 0FAD */ OP_MODRM, + /* 0FAE */ OP_MODRM, + /* 0FAF */ OP_MODRM, + + /* 0FB0 */ OP_MODRM, + /* 0FB1 */ OP_MODRM, + /* 0FB2 */ OP_MODRM, + /* 0FB3 */ OP_MODRM, + /* 0FB4 */ OP_MODRM, + /* 0FB5 */ OP_MODRM, + /* 0FB6 */ OP_MODRM, + /* 0FB7 */ OP_MODRM, + /* 0FB8 */ OP_MODRM, + /* 0FB9 */ OP_MODRM, + /* 0FBA */ OP_MODRM | OP_DATA_I8, + /* 0FBB */ OP_MODRM, + /* 0FBC */ OP_MODRM, + /* 0FBD */ OP_MODRM, + /* 0FBE */ OP_MODRM, + /* 0FBF */ OP_MODRM, + + /* 0FC0 */ OP_MODRM, + /* 0FC1 */ OP_MODRM, + /* 0FC2 */ OP_MODRM | OP_DATA_I8, + /* 0FC3 */ OP_MODRM, + /* 0FC4 */ OP_MODRM | OP_DATA_I8, + /* 0FC5 */ OP_MODRM | OP_DATA_I8, + /* 0FC6 */ OP_MODRM | OP_DATA_I8, + /* 0FC7 */ OP_MODRM, + /* 0FC8 */ OP_NONE, + /* 0FC9 */ OP_NONE, + /* 0FCA */ OP_NONE, + /* 0FCB */ OP_NONE, + /* 0FCC */ OP_NONE, + /* 0FCD */ OP_NONE, + /* 0FCE */ OP_NONE, + /* 0FCF */ OP_NONE, + + /* 0FD0 */ OP_MODRM, + /* 0FD1 */ OP_MODRM, + /* 0FD2 */ OP_MODRM, + /* 0FD3 */ OP_MODRM, + /* 0FD4 */ OP_MODRM, + /* 0FD5 */ OP_MODRM, + /* 0FD6 */ OP_MODRM, + /* 0FD7 */ OP_MODRM, + /* 0FD8 */ OP_MODRM, + /* 0FD9 */ OP_MODRM, + /* 0FDA */ OP_MODRM, + /* 0FDB */ OP_MODRM, + /* 0FDC */ OP_MODRM, + /* 0FDD */ OP_MODRM, + /* 0FDE */ OP_MODRM, + /* 0FDF */ OP_MODRM, + + /* 0FE0 */ OP_MODRM, + /* 0FE1 */ OP_MODRM, + /* 0FE2 */ OP_MODRM, + /* 0FE3 */ OP_MODRM, + /* 0FE4 */ OP_MODRM, + /* 0FE5 */ OP_MODRM, + /* 0FE6 */ OP_MODRM, + /* 0FE7 */ OP_MODRM, + /* 0FE8 */ OP_MODRM, + /* 0FE9 */ OP_MODRM, + /* 0FEA */ OP_MODRM, + /* 0FEB */ OP_MODRM, + /* 0FEC */ OP_MODRM, + /* 0FED */ OP_MODRM, + /* 0FEE */ OP_MODRM, + /* 0FEF */ OP_MODRM, + + /* 0FF0 */ OP_MODRM, + /* 0FF1 */ OP_MODRM, + /* 0FF2 */ OP_MODRM, + /* 0FF3 */ OP_MODRM, + /* 0FF4 */ OP_MODRM, + /* 0FF5 */ OP_MODRM, + /* 0FF6 */ OP_MODRM, + /* 0FF7 */ OP_MODRM, + /* 0FF8 */ OP_MODRM, + /* 0FF9 */ OP_MODRM, + /* 0FFA */ OP_MODRM, + /* 0FFB */ OP_MODRM, + /* 0FFC */ OP_MODRM, + /* 0FFD */ OP_MODRM, + /* 0FFE */ OP_MODRM, + /* 0FFF */ OP_INVALID, + }; + + static byte cflags(byte op) + { + return flags_table[op]; + } + + static byte cflags_ex(byte op) + { + return flags_table_ex[op]; + } + + /// + /// 计算大于等于 size 字节的最少指令的长度 + /// + /// + /// + public static uint SizeofMinNumByte(void* code, int size) + { + if (IsAndroidARM()) + { + if (IsIL2CPP()) + return CalcARMThumbMinLen(code, size); + else + return (uint)((size + 3) / 4) * 4; // 此为 jit 模式下的长度 + } + + UInt32 Length; + byte* pOpcode; + UInt32 Result = 0; + ldasm_data data = new ldasm_data(); + bool is64 = IntPtr.Size == 8; + do + { + Length = ldasm(code, data, is64); + + pOpcode = (byte*)code + data.opcd_offset; + Result += Length; + if (Result >= size) + break; + if ((Length == 1) && (*pOpcode == 0xCC)) + break; + + code = (void*)((ulong)code + Length); + + } while (Length>0); + + return Result; + } + + public static bool IsAndroidARM() + { + return UnityEngine.SystemInfo.operatingSystem.Contains("Android") + && UnityEngine.SystemInfo.processorType.Contains("ARM"); + } + + public static bool IsiOS() + { + return UnityEngine.SystemInfo.operatingSystem.ToLower().Contains("ios"); + } + + public static bool IsIL2CPP() + { + bool isIL2CPP = false; + try + { + byte[] ilBody = typeof(LDasm).GetMethod("IsIL2CPP").GetMethodBody().GetILAsByteArray(); + if (ilBody == null || ilBody.Length == 0) + isIL2CPP = true; + } + catch + { + isIL2CPP = true; + } + return isIL2CPP; + } + + /// + /// 计算 thumb 指令长度 + /// + /// + /// + /// + public static uint CalcARMThumbMinLen(void* code, int size) + { + uint len = 0; + + ushort* ins = (ushort*)code; + while (true) + { + if (len >= size) + return len; + + if (((*ins >> 13) & 3) == 3) + { + ins += 2; + len += 4; + } + else + { + ins++; + len += 2; + } + } + } + + static uint ldasm(void* code, ldasm_data ld, bool is64) + { + byte* p = (byte*)code; + byte s, op, f; + byte rexw, pr_66, pr_67; + + s = rexw = pr_66 = pr_67 = 0; + + /* dummy check */ + if ((int)code==0) + return 0; + + /* init output data */ + //memset(ld, 0, sizeof(ldasm_data)); + + /* phase 1: parse prefixies */ + while ((cflags(*p) & OP_PREFIX)!=0) + { + if (*p == 0x66) + pr_66 = 1; + if (*p == 0x67) + pr_67 = 1; + p++; s++; + ld.flags |= F_PREFIX; + if (s == 15) + { + ld.flags |= F_INVALID; + return s; + } + } + + /* parse REX prefix */ + if (is64 && *p >> 4 == 4) + { + ld.rex = *p; + rexw = (byte)((ld.rex >> 3) & 1); + ld.flags |= F_REX; + p++; s++; + } + + /* can be only one REX prefix */ + if (is64 && *p >> 4 == 4) + { + ld.flags |= F_INVALID; + s++; + return s; + } + + /* phase 2: parse opcode */ + ld.opcd_offset = (byte)(p - (byte*)code); + ld.opcd_size = 1; + op = *p++; s++; + + /* is 2 byte opcode? */ + if (op == 0x0F) + { + op = *p++; s++; + ld.opcd_size++; + f = cflags_ex(op); + if ((f & OP_INVALID)!=0) + { + ld.flags |= F_INVALID; + return s; + } + /* for SSE instructions */ + if ((f & OP_EXTENDED)!=0) + { + op = *p++; s++; + ld.opcd_size++; + } + } + else { + f = cflags(op); + /* pr_66 = pr_67 for opcodes A0-A3 */ + if (op >= 0xA0 && op <= 0xA3) + pr_66 = pr_67; + } + + /* phase 3: parse ModR/M, SIB and DISP */ + if ((f & OP_MODRM)!=0) + { + byte mod = (byte)(*p >> 6); + byte ro = (byte)((*p & 0x38) >> 3); + byte rm = (byte)(*p & 7); + + ld.modrm = *p++; s++; + ld.flags |= F_MODRM; + + /* in F6,F7 opcodes immediate data present if R/O == 0 */ + if (op == 0xF6 && (ro == 0 || ro == 1)) + f |= OP_DATA_I8; + if (op == 0xF7 && (ro == 0 || ro == 1)) + f |= OP_DATA_I16_I32_I64; + + /* is SIB byte exist? */ + if (mod != 3 && rm == 4 && !(!is64 && pr_67!=0)) + { + ld.sib = *p++; s++; + ld.flags |= F_SIB; + + /* if base == 5 and mod == 0 */ + if ((ld.sib & 7) == 5 && mod == 0) + { + ld.disp_size = 4; + } + } + + switch (mod) + { + case 0: + if (is64) + { + if (rm == 5) + { + ld.disp_size = 4; + if (is64) + ld.flags |= F_RELATIVE; + } + } + else if (pr_67!=0) + { + if (rm == 6) + ld.disp_size = 2; + } + else { + if (rm == 5) + ld.disp_size = 4; + } + break; + case 1: + ld.disp_size = 1; + break; + case 2: + if (is64) + ld.disp_size = 4; + else if (pr_67!=0) + ld.disp_size = 2; + else + ld.disp_size = 4; + break; + } + + if (ld.disp_size>0) + { + ld.disp_offset = (byte)(p - (byte*)code); + p += ld.disp_size; + s += ld.disp_size; + ld.flags |= F_DISP; + } + } + + /* phase 4: parse immediate data */ + if (rexw!=0 && (f & OP_DATA_I16_I32_I64)!=0) + ld.imm_size = 8; + else if ((f & OP_DATA_I16_I32)!=0 || (f & OP_DATA_I16_I32_I64)!=0) + ld.imm_size = (byte)(4 - (pr_66 << 1)); + + /* if exist, add OP_DATA_I16 and OP_DATA_I8 size */ + ld.imm_size += (byte)(f & 3); + + if ((ld.imm_size)!=0) + { + s += ld.imm_size; + ld.imm_offset = (byte)(p - (byte*)code); + ld.flags |= F_IMM; + if ((f & OP_RELATIVE)!=0) + ld.flags |= F_RELATIVE; + } + + /* instruction is too long */ + if (s > 15) + ld.flags |= F_INVALID; + + return s; + } + } +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/LDasm.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/LDasm.cs.meta new file mode 100644 index 0000000..969a5a1 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/LDasm.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3c561c9729c367e4fbef63f4ec56f268 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/MethodHook.cs b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/MethodHook.cs new file mode 100644 index 0000000..b2d912d --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/MethodHook.cs @@ -0,0 +1,333 @@ +/* + Desc: 一个可以运行时 Hook Mono 方法的工具,让你可以无需修改 UnityEditor.dll 等文件就可以重写其函数功能 + Author: Misaka Mikoto + Github: https://github.com/Misaka-Mikoto-Tech/MonoHook + */ + +using DotNetDetour; +using System; +using System.Diagnostics; +using System.Reflection; +using System.Runtime.InteropServices; +using Unity.Collections.LowLevel.Unsafe; + + +/* +>>>>>>> 原始 UnityEditor.LogEntries.Clear 一型(.net 4.x) +0000000000403A00 < | 55 | push rbp | +0000000000403A01 | 48 8B EC | mov rbp,rsp | +0000000000403A04 | 48 81 EC 80 00 00 00 | sub rsp,80 | +0000000000403A0B | 48 89 65 B0 | mov qword ptr ss:[rbp-50],rsp | +0000000000403A0F | 48 89 6D A8 | mov qword ptr ss:[rbp-58],rbp | +0000000000403A13 | 48 89 5D C8 | mov qword ptr ss:[rbp-38],rbx | << +0000000000403A17 | 48 89 75 D0 | mov qword ptr ss:[rbp-30],rsi | +0000000000403A1B | 48 89 7D D8 | mov qword ptr ss:[rbp-28],rdi | +0000000000403A1F | 4C 89 65 E0 | mov qword ptr ss:[rbp-20],r12 | +0000000000403A23 | 4C 89 6D E8 | mov qword ptr ss:[rbp-18],r13 | +0000000000403A27 | 4C 89 75 F0 | mov qword ptr ss:[rbp-10],r14 | +0000000000403A2B | 4C 89 7D F8 | mov qword ptr ss:[rbp-8],r15 | +0000000000403A2F | 49 BB 00 2D 1E 1A FE 7F 00 00 | mov r11,7FFE1A1E2D00 | +0000000000403A39 | 4C 89 5D B8 | mov qword ptr ss:[rbp-48],r11 | +0000000000403A3D | 49 BB 08 2D 1E 1A FE 7F 00 00 | mov r11,7FFE1A1E2D08 | + + +>>>>>>> 二型(.net 2.x) +0000000000403E8F | 55 | push rbp | +0000000000403E90 | 48 8B EC | mov rbp,rsp | +0000000000403E93 | 48 83 EC 70 | sub rsp,70 | +0000000000403E97 | 48 89 65 C8 | mov qword ptr ss:[rbp-38],rsp | +0000000000403E9B | 48 89 5D B8 | mov qword ptr ss:[rbp-48],rbx | +0000000000403E9F | 48 89 6D C0 | mov qword ptr ss:[rbp-40],rbp | <<(16) +0000000000403EA3 | 48 89 75 F8 | mov qword ptr ss:[rbp-8],rsi | +0000000000403EA7 | 48 89 7D F0 | mov qword ptr ss:[rbp-10],rdi | +0000000000403EAB | 4C 89 65 D0 | mov qword ptr ss:[rbp-30],r12 | +0000000000403EAF | 4C 89 6D D8 | mov qword ptr ss:[rbp-28],r13 | +0000000000403EB3 | 4C 89 75 E0 | mov qword ptr ss:[rbp-20],r14 | +0000000000403EB7 | 4C 89 7D E8 | mov qword ptr ss:[rbp-18],r15 | +0000000000403EBB | 48 83 EC 20 | sub rsp,20 | +0000000000403EBF | 49 BB 18 3F 15 13 FE 7F 00 00 | mov r11,7FFE13153F18 | +0000000000403EC9 | 41 FF D3 | call r11 | +0000000000403ECC | 48 83 C4 20 | add rsp,20 | + + */ + + +/// +/// Hook 类,用来 Hook 某个 C# 方法 +/// +public unsafe class MethodHook +{ + public bool isHooked { get; private set; } + + private MethodBase _targetMethod; // 需要被hook的目标方法 + private MethodBase _replacementMethod; // 被hook后的替代方法 + private MethodBase _proxyMethod; // 目标方法的代理方法(可以通过此方法调用被hook后的原方法) + + private IntPtr _targetPtr; // 目标方法被 jit 后的地址指针 + private IntPtr _replacementPtr; + private IntPtr _proxyPtr; + + private static readonly byte[] s_jmpBuff; + private static readonly byte[] s_jmpBuff_32 = new byte[] // 6 bytes + { + 0x68, 0x00, 0x00, 0x00, 0x00, // push $val + 0xC3 // ret + }; + private static readonly byte[] s_jmpBuff_64 = new byte[] // 14 bytes + { + 0xFF, 0x25, 0x00, 0x00, 0x00, 0x00, // jmp [rip] + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // $val + }; + private static readonly byte[] s_jmpBuff_arm32_arm = new byte[] // 8 bytes + { + 0x04, 0xF0, 0x1F, 0xE5, // LDR PC, [PC, #-4] + 0x00, 0x00, 0x00, 0x00, // $val + }; + private static readonly byte[] s_jmpBuff_arm32_thumb = new byte[] // 38 bytes + { + 0x00, 0xB5, // PUSH {LR} + 0x10, 0xB4, // PUSH {R0} + 0x03, 0xB4, // PUSH {R0, R1} + 0x78, 0x46, // MOV R0, PC + 0x16, 0x30, // ADD R0, #0x16 + 0x00, 0x68, // LDR R0, [R0, #0x00] + 0x69, 0x46, // MOV R1, SP + 0x08, 0x31, // ADD R1, #0x08 + 0x08, 0x60, // STR R0, [R1, #0x00] + 0x79, 0x46, // MOV R1, PC + 0x0E, 0x31, // ADD R1, #0x0E + 0x8E, 0x46, // MOV LR, R1 + 0x01, 0xBC, // POP {R0} + 0x02, 0xBC, // POP {R1} + 0x00, 0xBD, // POP {PC} + 0xC0, 0x46, // NOP + + 0x00, 0x00, 0x00, 0x00, // $val + 0x00, 0xBD, // POP {PC} + }; + private static readonly byte[] s_jmpBuff_arm64 = new byte[] + { + 0x04, 0xF0, 0x1F, 0xE5, // LDR PC, [PC, #-4] + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // $val + }; + private static readonly int s_addrOffset; + + + private byte[] _jmpBuff; + private byte[] _proxyBuff; + + static MethodHook() + { + if (LDasm.IsAndroidARM()) + { + s_addrOffset = 4; + if (IntPtr.Size == 4) + { + s_jmpBuff = s_jmpBuff_arm32_arm; + //if (!LDasm.IsIL2CPP()) + // s_jmpBuff = s_jmpBuff_arm32_arm; + //else + //{ + // s_jmpBuff = s_jmpBuff_arm32_thumb; + // s_addrOffset = 32; + //} + + } + else + s_jmpBuff = s_jmpBuff_arm64; + } + else + { + if (IntPtr.Size == 4) + { + s_jmpBuff = s_jmpBuff_32; + s_addrOffset = 1; + } + else + { + s_jmpBuff = s_jmpBuff_64; + s_addrOffset = 6; + } + } + + } + + /// + /// 创建一个 Hook + /// + /// 需要替换的目标方法 + /// 准备好的替换方法 + /// 如果还需要调用原始目标方法,可以通过此参数的方法调用,如果不需要可以填 null + public MethodHook(MethodBase targetMethod, MethodBase replacementMethod, MethodBase proxyMethod = null) + { + _targetMethod = targetMethod; + _replacementMethod = replacementMethod; + _proxyMethod = proxyMethod; + + _targetPtr = GetFunctionAddr(_targetMethod); + _replacementPtr = GetFunctionAddr(_replacementMethod); + if(proxyMethod != null) + _proxyPtr = GetFunctionAddr(_proxyMethod); + + _jmpBuff = new byte[s_jmpBuff.Length]; + } + + public void Install() + { + if(LDasm.IsiOS()) // iOS 不支持修改 code 所在区域 page + return; + + if (isHooked) + return; + + HookPool.AddHooker(_targetMethod, this); + + InitProxyBuff(); + BackupHeader(); + PatchTargetMethod(); + PatchProxyMethod(); + + isHooked = true; + } + + public void Uninstall() + { + if (!isHooked) + return; + + byte* pTarget = (byte*)_targetPtr.ToPointer(); + for (int i = 0; i < _proxyBuff.Length; i++) + *pTarget++ = _proxyBuff[i]; + + isHooked = false; + HookPool.RemoveHooker(_targetMethod); + } + +#region private + /// + /// 根据具体指令填充 ProxyBuff + /// + /// + private void InitProxyBuff() + { + byte* pTarget = (byte*)_targetPtr.ToPointer(); + + uint requireSize = DotNetDetour.LDasm.SizeofMinNumByte(pTarget, s_jmpBuff.Length); + _proxyBuff = new byte[requireSize]; + EnableAddrModifiable(_targetPtr, requireSize); + } + + /// + /// 备份原始方法头 + /// + private void BackupHeader() + { + byte* pTarget = (byte*)_targetPtr.ToPointer(); + for (int i = 0; i < _proxyBuff.Length; i++) + _proxyBuff[i] = *pTarget++; + } + + // 将原始方法跳转到我们的方法 + private void PatchTargetMethod() + { + Array.Copy(s_jmpBuff, _jmpBuff, _jmpBuff.Length); + fixed (byte* p = &_jmpBuff[s_addrOffset]) + { + if(IntPtr.Size == 4) + *((uint*)p) = (uint)_replacementPtr.ToInt32(); + else + *((ulong*)p) = (ulong)_replacementPtr.ToInt64(); + } + + byte* pTarget = (byte*)_targetPtr.ToPointer(); + + if(pTarget != null) + { + for (int i = 0, imax = _jmpBuff.Length; i < imax; i++) + *pTarget++ = _jmpBuff[i]; + } + + } + + /// + /// 让 Proxy 方法的功能变成跳转向原始方法 + /// + private void PatchProxyMethod() + { + if (_proxyPtr == IntPtr.Zero) + return; + + EnableAddrModifiable(_proxyPtr, (uint)_proxyBuff.Length); + byte * pProxy = (byte*)_proxyPtr.ToPointer(); + for (int i = 0; i < _proxyBuff.Length; i++) // 先填充头 + *pProxy++ = _proxyBuff[i]; + + fixed (byte* p = &_jmpBuff[s_addrOffset]) // 将跳转指向原函数跳过头的位置 + { + if (IntPtr.Size == 4) + * ((uint*)p) = (uint)_targetPtr.ToInt32() + (uint)_proxyBuff.Length; + else + *((ulong*)p) = (ulong)_targetPtr.ToInt64() + (ulong)_proxyBuff.Length; + } + + for (int i = 0; i < _jmpBuff.Length; i++) // 再填充跳转 + *pProxy++ = _jmpBuff[i]; + } + + private void EnableAddrModifiable(IntPtr ptr, uint size) + { + if (!LDasm.IsIL2CPP()) + return; + + uint oldProtect; + bool ret = IL2CPPHelper.VirtualProtect(ptr, size, IL2CPPHelper.Protection.PAGE_EXECUTE_READWRITE, out oldProtect); + Debug.Assert(ret); + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] // 好像在 IL2CPP 里无效 + private struct __ForCopy + { + public long __dummy; + public MethodBase method; + } + /// + /// 获取方法指令地址 + /// + /// + /// + private IntPtr GetFunctionAddr(MethodBase method) + { + if (!LDasm.IsIL2CPP()) + return method.MethodHandle.GetFunctionPointer(); + else + { + __ForCopy __forCopy = new __ForCopy() { method = method }; + + long* ptr = &__forCopy.__dummy; + ptr++; // addr of _forCopy.method + + IntPtr methodAddr = IntPtr.Zero; + if(sizeof(IntPtr) == 8) + { + long methodDataAddr = *(long*)ptr; + byte* ptrData = (byte *)methodDataAddr + sizeof(IntPtr) * 2; // offset of Il2CppReflectionMethod::const MethodInfo *method; + + long methodPtr = 0; + methodPtr = *(long*)ptrData; + methodAddr = new IntPtr(*(long*)methodPtr); // MethodInfo::Il2CppMethodPointer methodPointer; + } + else + { + int methodDataAddr = *(int*)ptr; + byte* ptrData = (byte *)methodDataAddr + sizeof(IntPtr) * 2; // offset of Il2CppReflectionMethod::const MethodInfo *method; + + int methodPtr = 0; + methodPtr = *(int*)ptrData; + methodAddr = new IntPtr(*(int*)methodPtr); + } + return methodAddr; + } + } + +#endregion +} diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/MethodHook.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/MethodHook.cs.meta new file mode 100644 index 0000000..007e62c --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/MethodHook.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bd0b8071cf434d6498160259e3829980 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/MonoHookInstaller.cs b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/MonoHookInstaller.cs new file mode 100644 index 0000000..0aa44e1 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/MonoHookInstaller.cs @@ -0,0 +1,357 @@ +using UnityEngine; +using UnityEditor; +using System; +using System.Reflection; +using System.Text; +using System.Collections.Generic; +using System.Linq; + +namespace NinjaBeats.ReflectionHelper +{ + public enum MonoHookType + { + Method, + Property, + Constructor, + PropertyGet, + PropertySet, + } + + public class MonoHookAttribute : Attribute + { + + public MonoHookType HookType; + public Type[] Parameters; + + public MonoHookAttribute() + { + this.HookType = MonoHookType.Method; + this.Parameters = null; + } + + public MonoHookAttribute(MonoHookType hookType, params Type[] parameters) + { + this.HookType = hookType; + this.Parameters = parameters; + } + } + + public class MonoHookInstallerV2 + { + static readonly string __type__Str = "__type__"; + static readonly string __original__Str = "__original__"; + static readonly string __replace__Str = "__replace__"; + + private MethodHook hook = null; + + private delegate MethodBase GetTargetMethodDelegate(Type originType, Type hookType, MethodInfo __replace__); + + void InitMethod(Type targetType, Type hookType, GetTargetMethodDelegate getter) + { + if (hook != null) + return; + + // 找到被替换成的新方法 + MethodInfo miReplacement = hookType.GetMethod(__replace__Str, (BindingFlags)(-1)); + + // 这个方法是用来调用原始方法的 + MethodInfo miProxy = hookType.GetMethod(__original__Str, (BindingFlags)(-1)); + + // 找到需要 Hook 的方法 + MethodBase miTarget = getter(targetType, hookType, miReplacement); + + if (miTarget == null) + { + Debug.LogErrorFormat("{0} hook failed, method {1} is invalid", targetType?.FullName ?? "?", hookType?.Name ?? "?"); + return; + } + + if (miReplacement.IsStatic != miTarget.IsStatic || miReplacement.IsStatic != miProxy.IsStatic) + { + Debug.LogError($"{targetType.FullName ?? "?"} hook failed, method static is not match"); + return; + } + + // 创建一个 Hook 并 Install 就OK啦, 之后无论哪个代码再调用原始方法都会重定向到 + // 我们写的方法ヾ(゚∀゚ゞ) + hook = new MethodHook(miTarget, miReplacement, miProxy); + hook.Install(); + } + + private static List _MonoHookInstallerList = new(); + + static MethodBase GetTargetMethod(Type originType, Type hookType, MethodInfo __replace__) + { + return originType.GetMethodInfoByParameterTypes(hookType.Name, __replace__.GetParameters().Select(x => x.ParameterType).ToArray()); + } + + static MethodBase GetTargetConstructor(Type originType, Type hookType, MethodInfo __replace__) + { + return originType.GetConstructorInfoByParameterTypes(__replace__.GetParameters().Select(x => x.ParameterType).ToArray()); + } + + static MethodBase GetTargetPropertyGet(Type originType, Type hookType, MethodInfo __replace__) + { + return originType.GetProperty(hookType.Name, (BindingFlags)(-1))?.GetMethod; + } + + static MethodBase GetTargetPropertySet(Type originType, Type hookType, MethodInfo __replace__) + { + return originType.GetProperty(hookType.Name, (BindingFlags)(-1))?.SetMethod; + } + + [InitializeOnLoadMethod] + static void Initalize() + { +#if UNITY_EDITOR_OSX + return; +#endif + EditorPrefs.SetBool("ScriptDebugInfoEnabled", true); + UnityEditor.Compilation.CompilationPipeline.codeOptimization = + UnityEditor.Compilation.CodeOptimization.Debug; + + EditorApplication.update -= OnEditorUpdate; + EditorApplication.update += OnEditorUpdate; + } + + static void OnEditorUpdate() + { + if (UnityEngine_GUISkin.current == null) + return; + + EditorApplication.update -= OnEditorUpdate; + + var list = EditorUtils.ScanAllTypeWithAttributeMark(); + foreach (var info in list) + { + try + { + var installer = new MonoHookInstallerV2(); + + var typeFullName = info.type.GetField(__type__Str, (BindingFlags)(-1))?.GetValue(null) as string; + var targetType = EditorUtils.GetTypeByFullName(typeFullName); + if (targetType == null) + continue; + + switch (info.attr.HookType) + { + case MonoHookType.Method: + installer.InitMethod(targetType, info.type, GetTargetMethod); + break; + case MonoHookType.Constructor: + installer.InitMethod(targetType, info.type, GetTargetConstructor); + break; + case MonoHookType.PropertyGet: + installer.InitMethod(targetType, info.type, GetTargetPropertyGet); + break; + case MonoHookType.PropertySet: + installer.InitMethod(targetType, info.type, GetTargetPropertySet); + break; + } + + _MonoHookInstallerList.Add(installer); + } + catch (Exception e) + { + Debug.LogError(e.Message + "\n" + e.StackTrace); + } + } + } + } + + public class MonoHookInstaller + { + static readonly string PropNameTarget = "__Target"; + static readonly string FuncNameOriginal = "__Original"; + static readonly string FuncNameReplace = "__Replace"; + MethodHook hook = null; + MethodHook hookExtra = null; + + bool CheckSame(MethodInfo method, string name, ParameterInfo[] parameters, Type returnType) + { + if (method.Name != name) + return false; + if (method.ReturnType != returnType) + return false; + + var methodParameters = method.GetParameters(); + if (parameters.Length != methodParameters.Length) + return false; + + for (int i = 0; i < parameters.Length; ++i) + { + if (parameters[i].ParameterType != methodParameters[i].ParameterType) + return false; + } + + return true; + } + + void InitMethod(Type originType, Type hookType) + { + if (hook != null) + return; + + // 找到被替换成的新方法 + MethodInfo miReplacement = hookType.GetMethod(FuncNameReplace, (BindingFlags)(-1)); + var miReplacementParameters = miReplacement.GetParameters(); + + // 这个方法是用来调用原始方法的 + MethodInfo miProxy = hookType.GetMethod(FuncNameOriginal, (BindingFlags)(-1)); + + // 找到需要 Hook 的方法 + MethodInfo miTarget = null; + foreach (var method in originType.GetMethods((BindingFlags)(-1))) + { + if (CheckSame(method, hookType.Name, miReplacementParameters, miReplacement.ReturnType)) + { + miTarget = method; + break; + } + } + + if (miTarget == null) + { + Debug.LogErrorFormat("{0} hook failed, method {1} is invalid", originType?.FullName ?? "?", + hookType?.Name ?? "?"); + return; + } + + // 创建一个 Hook 并 Install 就OK啦, 之后无论哪个代码再调用原始方法都会重定向到 + // 我们写的方法ヾ(゚∀゚ゞ) + hook = new MethodHook(miTarget, miReplacement, miProxy); + hook.Install(); + } + + void InitProperty(Type originType, Type hookType) + { + if (hook != null || hookExtra != null) + return; + + // 找到需要 Hook 的属性 + PropertyInfo piTarget = originType.GetProperty(hookType.Name, (BindingFlags)(-1)); + if (piTarget == null) + { + Debug.LogErrorFormat("{0} hook failed, property {1} is invalid", originType?.FullName ?? "?", + hookType?.Name ?? "?"); + return; + } + + var getMethod = piTarget.GetMethod; + if (getMethod != null) + { + // 找到被替换成的新方法 + MethodInfo miReplacement = hookType.GetMethod(FuncNameReplace + "_Get", (BindingFlags)(-1)); + + // 这个方法是用来调用原始方法的 + MethodInfo miProxy = hookType.GetMethod(FuncNameOriginal + "_Get", (BindingFlags)(-1)); + + if (miReplacement != null && miProxy != null) + { + // 创建一个 Hook 并 Install 就OK啦, 之后无论哪个代码再调用原始方法都会重定向到 + // 我们写的方法ヾ(゚∀゚ゞ) + hook = new MethodHook(getMethod, miReplacement, miProxy); + hook.Install(); + } + } + + var setMethod = piTarget.SetMethod; + if (setMethod != null) + { + // 找到被替换成的新方法 + MethodInfo miReplacement = hookType.GetMethod(FuncNameReplace + "_Set", (BindingFlags)(-1)); + + // 这个方法是用来调用原始方法的 + MethodInfo miProxy = hookType.GetMethod(FuncNameOriginal + "_Set", (BindingFlags)(-1)); + + if (miReplacement != null && miProxy != null) + { + // 创建一个 Hook 并 Install 就OK啦, 之后无论哪个代码再调用原始方法都会重定向到 + // 我们写的方法ヾ(゚∀゚ゞ) + hookExtra = new MethodHook(setMethod, miReplacement, miProxy); + hookExtra.Install(); + } + } + } + + void InitConstructor(Type originType, Type hookType, Type[] parameters) + { + if (hook != null) + return; + + // 找到需要 Hook 的方法 + ConstructorInfo miTarget = originType.GetConstructor(parameters ?? new Type[] { }); + if (miTarget == null) + { + Debug.LogErrorFormat("{0} hook failed, method CheckRectsOnMouseMove is invalid", + originType?.FullName ?? "?"); + return; + } + + // 找到被替换成的新方法 + MethodInfo miReplacement = hookType.GetMethod(FuncNameReplace, (BindingFlags)(-1)); + + // 这个方法是用来调用原始方法的 + MethodInfo miProxy = hookType.GetMethod(FuncNameOriginal, (BindingFlags)(-1)); + + // 创建一个 Hook 并 Install 就OK啦, 之后无论哪个代码再调用原始方法都会重定向到 + // 我们写的方法ヾ(゚∀゚ゞ) + hook = new MethodHook(miTarget, miReplacement, miProxy); + hook.Install(); + } + + static List _MonoHookInstallerList = new List(); + + [InitializeOnLoadMethod] + static void Initalize() + { +#if UNITY_EDITOR_OSX + return; +#endif + EditorPrefs.SetBool("ScriptDebugInfoEnabled", true); + UnityEditor.Compilation.CompilationPipeline.codeOptimization = + UnityEditor.Compilation.CodeOptimization.Debug; + + EditorApplication.update -= OnEditorUpdate; + EditorApplication.update += OnEditorUpdate; + } + + static void OnEditorUpdate() + { + if (UnityEngine_GUISkin.current == null) + return; + + EditorApplication.update -= OnEditorUpdate; + + var list = EditorUtils.ScanAllTypeWithAttributeMark(); + foreach (var info in list) + { + try + { + var installer = new MonoHookInstaller(); + Type targetType = info.type.GetProperty(PropNameTarget, (BindingFlags)(-1))?.GetValue(null) as Type; + if (targetType == null) + continue; + switch (info.attr.HookType) + { + case MonoHookType.Method: + installer.InitMethod(targetType, info.type); + break; + case MonoHookType.Property: + installer.InitProperty(targetType, info.type); + break; + case MonoHookType.Constructor: + installer.InitConstructor(targetType, info.type, info.attr.Parameters); + break; + } + + _MonoHookInstallerList.Add(installer); + } + catch (Exception e) + { + Debug.LogError(e.Message + "\n" + e.StackTrace); + } + } + } + } +} \ No newline at end of file diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/MonoHookInstaller.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/MonoHookInstaller.cs.meta new file mode 100644 index 0000000..314282d --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/MonoHook/MonoHookInstaller.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 259c8913dda7cf34e82643a6997185be +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/ReflectionTool.cs b/Assets/URS/Utils/Editor/ReflectionHelper/ReflectionTool.cs new file mode 100644 index 0000000..256c636 --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/ReflectionTool.cs @@ -0,0 +1,582 @@ +using UnityEngine; +using UnityEditor; +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using NinjaBeats.ReflectionHelper; +using Unity.Jobs; + +namespace NinjaBeats +{ + + public partial class ReflectionTool + { + private static readonly string SelfGeneratePath = Application.dataPath + "/URS/Utils/Editor/ReflectionHelper/Generated"; + private static readonly string CSharpGeneratePath = Application.dataPath + "/Editor/ReflectionHelper/Generated/"; + + private static GenWrapInfo[] s_WrapInfoList => new GenWrapInfo[] + { + // new("TMPro.TMP_FontAsset"), + + new("UnityEngine.GUISkin"), + new("UnityEngine.GUIUtility"), + + new("UnityEditor.AnimationClipEditor"), + new("UnityEditor.AnimationClipInfoProperties"), + new("UnityEditor.AnimationWindowEvent"), + new("UnityEditor.BaseAssetImporterTabUI"), + new("UnityEditor.BaseTextureImportPlatformSettings"), + new("UnityEditor.Build.BuildPlatform"), + new("UnityEditor.Build.BuildPlatforms"), + new("UnityEditor.Editor"), + new("UnityEditor.EditorStyles"), + new("UnityEditor.EditorGUI"), + new("UnityEditor.EditorGUI+RecycledTextEditor"), + new("UnityEditor.EditorGUILayout"), + new("UnityEditor.EditorGUIUtility"), + new("UnityEditor.GUISlideGroup"), + + new("UnityEditor.EventManipulationHandler"), + new("UnityEditor.LogEntries"), + new("UnityEditor.LogEntry"), + new("UnityEditor.MaterialEditor"), + new("UnityEditor.ModelImporterClipEditor"), + new("UnityEditor.ModelImporterClipEditor+ClipInformation"), + new("UnityEditor.TextureImporterInspector"), + new("UnityEditor.TextureImportPlatformSettings"), + new("UnityEditor.TextureImportPlatformSettingsData"), + new("UnityEngine.TextEditor"), + new("UnityEngine.TextCore.LowLevel.FontEngine"), + new("UnityEditor.TextCore.LowLevel.FontEngineEditorUtilities"), + new("UnityEngine.TimeArea"), + + new("UnityEditor.PropertyEditor"), + new("UnityEditor.EditorWindow"), + + // new("NinjaBeats.ReflectionTool+TestClass"), + }; + + private static GenHookInfo[] s_HookInfoList => new GenHookInfo[] + { + new("UnityEditor.EditorUtility", false, "DisplayCustomMenu", new [] + { + typeof(Rect), + typeof(GUIContent[]), + typeof(Func), + typeof(int), + typeof(EditorUtility.SelectMenuItemFunction), + typeof(object), + typeof(bool), + }), + + new("UnityEditor.LogEntries", false, "RowGotDoubleClicked", null), + new("UnityEditor.ConsoleWindow", false, "StacktraceWithHyperlinks", null), + new("UnityEditor.AnimationClipInfoProperties", false, "AddEvent", null), + new("UnityEditor.AnimationClipInfoProperties", false, "SetEvent", null), + new("UnityEditor.AnimationClipInfoProperties", false, "GetEvent", null), + new("UnityEditor.AnimationWindowEventInspector", false, "DoEditRegularParameters", null), + new("UnityEditor.EditorGUIExt", false, "GetIndexUnderMouse", null), + new("UnityEditor.EventManipulationHandler", false, "CheckRectsOnMouseMove", null), + new("UnityEditor.EventManipulationHandler", false, "Draw", null), + new("UnityEditor.ModelImporterClipEditor", false, ".ctor", new [] + { + typeof(UnityEditor.AssetImporters.AssetImporterEditor), + }), + new("UnityEditor.ModelImporterClipEditor", false, "AnimationClipGUI", null), + + new("UnityEditor.EditorGUIUtility", false, "ObjectContent", new[] + { + typeof(UnityEngine.Object), + typeof(Type), + typeof(int), + }), + + }; + + class TestClass + { + private delegate void FuncA(ref int a, out int b); + + private FuncA onFuncA; + private int a = 0; + private int b = 1; + + public void Test() + { + onFuncA?.Invoke(ref a, out b); + } + } + + + [MenuItem("Tools/类型反射生成工具/Generate Wrap")] + static void GenerateWrap() + { + new GenWrapTool().Execute(); + + AssetDatabase.Refresh(); + } + + [MenuItem("Tools/类型反射生成工具/Generate Hook")] + static void GenerateHook() + { + new GenHookTool().Execute(); + + AssetDatabase.Refresh(); + } + + public abstract class GenInfoBase + { + public string typeName; + public bool isCSharpAssembly; + } + + public class GenWrapInfo : GenInfoBase + { + public GenWrapInfo(string typeName) + { + this.typeName = typeName; + this.isCSharpAssembly = false; + } + } + + public class GenHookInfo : GenInfoBase + { + public string methodName; + public Type[] paramTypes; + public GenHookInfo(string typeName, bool isCSharpAssembly, string methodName, Type[] paramTypes) + { + this.typeName = typeName; + this.isCSharpAssembly = isCSharpAssembly; + this.methodName = methodName; + this.paramTypes = paramTypes; + } + } + + + public struct Member + { + public MemberInfo memberInfo; + public string rawName; + public string uniqueName; + public FieldInfo fieldInfo => memberInfo as FieldInfo; + public PropertyInfo propertyInfo => memberInfo as PropertyInfo; + public MethodInfo methodInfo => memberInfo as MethodInfo; + public ConstructorInfo constructorInfo => memberInfo as ConstructorInfo; + public Type delegateInfo => memberInfo as Type; + } + + public class MemberCollection + { + public MemberCollectionGroup ownerGroup; + public Type type; + public bool isCSharpAssembly; + public List fields = new(); + public List properties = new(); + public List methods = new(); + public List constructors = new(); + public List delegates = new(); + public List fieldOrProperties = new(); + + private Dictionary nameCount = new(); + + public MemberCollection(MemberCollectionGroup ownerGroup, Type type, bool isCSharpAssembly) + { + this.ownerGroup = ownerGroup; + this.type = type; + this.isCSharpAssembly = isCSharpAssembly; + } + + private void AddMemberImpl(MemberInfo member) + { + if (member == null) + return; + + if (member.Name.StartsWith('<')) + return; + + Member m = new(); + m.memberInfo = member; + m.rawName = member.Name.Replace('.', '_'); + + if (!nameCount.TryGetValue(m.rawName, out var count)) + count = 0; + count += 1; + nameCount[m.rawName] = count; + + if (count > 1) + m.uniqueName = $"{m.rawName}__{count}"; + else + m.uniqueName = m.rawName; + + switch (member) + { + case FieldInfo fi: + { + if (fi.IsSpecialName) + return; + fields.Add(m); + fieldOrProperties.Add(m); + break; + } + case PropertyInfo: + properties.Add(m); + fieldOrProperties.Add(m); + break; + case MethodInfo mi: + { + if (mi.IsSpecialName) + return; + methods.Add(m); + break; + } + case ConstructorInfo: + constructors.Add(m); + break; + case Type ei: + { + if (ei.Is()) + { + var invoke = ei.GetMethod("Invoke"); + if (invoke != null && invoke.ReturnType.IsRealPublic() && + !invoke.ReturnType.ContainsGenericParameters && + !invoke.GetGenericArguments().Any(x => x.ContainsGenericParameters || !x.IsRealPublic())) + { + delegates.Add(m); + ownerGroup.declaredDelegateTypes.Add(ei); + } + } + break; + } + } + } + + public void AddMember(GenInfoBase info) + { + switch (info) + { + case GenWrapInfo wi: + { + foreach (var m in type.GetMembers((BindingFlags)(-1))) + { + if (m.IsRealPublic()) + continue; + AddMemberImpl(m); + } + break; + } + case GenHookInfo hi: + { + if (hi.paramTypes != null) + { + if (hi.methodName == ".ctor") + { + var method = type.GetConstructorInfoByParameterTypes(hi.paramTypes); + if (method != null) + AddMemberImpl(method); + } + else + { + var method = type.GetMethodInfoByParameterTypes(hi.methodName, hi.paramTypes); + if (method != null) + AddMemberImpl(method); + } + } + else + { + foreach (var method in type.GetMember(hi.methodName, (BindingFlags)(-1)).OfType()) + AddMemberImpl(method); + } + break; + } + } + } + + } + + public class MemberCollectionGroup + { + public List list = new(); + public HashSet declaredTypes = new(); + public HashSet declaredDelegateTypes = new(); + + private MemberCollection GetMemberCollection(string typeName, bool CSharpAssembly) + { + if (string.IsNullOrWhiteSpace(typeName)) + return null; + var result = list.FirstOrDefault(x => x.type.FullName == typeName && x.isCSharpAssembly == CSharpAssembly); + if (result != null) + return result; + + var type = EditorUtils.GetTypeByFullName(typeName); + if (type == null) + return null; + if (type.IsGenericType) + return null; + + result = new(this, type, CSharpAssembly); + list.Add(result); + declaredTypes.Add(type); + return result; + } + + public void AddMember(IEnumerable genInfoList) + { + foreach (var info in genInfoList) + { + var collection = GetMemberCollection(info.typeName, info.isCSharpAssembly); + if (collection == null) + continue; + collection.AddMember(info); + } + } + } + + public abstract class GenToolBase + { + public const string k_SELF = "__self__"; + public const string k_TYPE = "__type__"; + public const string k_SUPER = "__super__"; + public const string k_VALID = "__valid__"; + public const string k_HOOK = "__hook__"; + public const string k_DELEGATE = "__delegate__"; + public const string k_REPLACE = "__replace__"; + public const string k_ORIGINAL = "__original__"; + public const string k_THIS = "__this__"; + public const string k_RESULT = "__result__"; + public const string k_PREFIX = "__"; + public const string k_ELEMENT_PREFIX = "__E"; + + public enum TypeNameMode + { + Public, + Wrap, + Array, + List, + Dictionary, + Object, + Void, + Generic, + Delegate, + WrapDelegate, + } + + public enum RefMode + { + None, + In, + Out, + Ref, + } + + public struct TypeName + { + public string name; + public TypeNameMode mode; + + public string Cast(string value) => mode switch + { + TypeNameMode.Wrap => $"new {name}({value})", + TypeNameMode.WrapDelegate => $"({value} as Delegate)?.Cast<{name}>()", + TypeNameMode.Void => $"{value}", + _ => $"({name})({value})" + }; + + public string CastTo(string value, string type) => mode switch + { + TypeNameMode.Wrap => $"{value}.{k_SELF}", + TypeNameMode.WrapDelegate => $"{value}?.Cast({type})", + TypeNameMode.Void => "", + _ => value + }; + } + + + public struct ParameterTypeName + { + public TypeName typeName; + public ParameterInfo parameter; + public RefMode refMode; + + public string ParameterModifier => parameter.GetParameterModifierStr(); + + public string Cast(string value) => typeName.Cast(value); + + public string GetValue(string value) => typeName.CastTo(value, "null"); + } + + public abstract class GenJobBase + { + private GenToolBase _genTool; + public MemberCollection collection; + + public Type type; + public string typeFullName; + public string typeFlatName; + public bool typeIsStatic; + public bool typeIsUnityObject; + public string objectTypeName; + + public int indent; + public StringBuilder sb; + public string fileName; + + public GenJobBase(GenToolBase genTool, MemberCollection collection) + { + this._genTool = genTool; + this.collection = collection; + + this.type = collection.type; + this.typeFullName = type.FullName; + this.typeFlatName = type.GetTypeDisplayName(true); + this.typeIsStatic = type.IsRealStatic(); + this.typeIsUnityObject = type.Is(); + this.objectTypeName = this.typeIsUnityObject ? "UnityEngine.Object" : "object"; + + this.indent = 0; + this.sb = new(); + } + + public bool HasWrapper(Type type) => _genTool.group.declaredTypes.Contains(type); + public bool HasWrapperDelegate(Type type) => _genTool.group.declaredDelegateTypes.Contains(type); + + public ParameterTypeName GetTypeName(ParameterInfo p) + { + ParameterTypeName result = new(); + result.typeName = GetTypeName(p.ParameterType); + result.parameter = p; + if (p.IsOut) + + result.refMode = RefMode.Out; + else if (p.IsIn) + result.refMode = RefMode.In; + else if (p.ParameterType.IsByRef) + result.refMode = RefMode.Ref; + else + result.refMode = RefMode.None; + return result; + } + public TypeName GetTypeName(Type t) + { + TypeName result = new(); + if (t.IsByRef) + t = t.GetElementType(); + + if (t == EditorUtils.typeof_Void) + { + result.name = "void"; + result.mode = TypeNameMode.Void; + } + else if (t.IsGenericParameter) + { + result.name = t.Name; + result.mode = TypeNameMode.Generic; + } + else if (t.IsRealPublic()) + { + result.name = t.GetTypeDisplayName(false); + result.mode = TypeNameMode.Public; + } + else if (HasWrapper(t)) + { + result.name = t.GetTypeDisplayName(true); + result.mode = TypeNameMode.Wrap; + } + else if (HasWrapperDelegate(t)) + { + result.name = t.DeclaringType != type ? $"{t.DeclaringType.GetTypeDisplayName(true)}.{t.Name}" : t.Name; + result.mode = TypeNameMode.WrapDelegate; + } + else if (t.IsArray) + { + result.name = "Array"; + result.mode = TypeNameMode.Array; + } + else if (t.Is(typeof(IList))) + { + result.name = "System.Collections.IList"; + result.mode = TypeNameMode.List; + } + else if (t.Is(typeof(IDictionary))) + { + result.name = "System.Collections.IDictionary"; + result.mode = TypeNameMode.Dictionary; + } + else if (t.Is()) + { + result.name = "Delegate"; + result.mode = TypeNameMode.Delegate; + } + else + { + result.name = "object"; + result.mode = TypeNameMode.Object; + } + + return result; + } + + private Type TestSuperType(Type t) + { + if (t == null) + return null; + if (t == EditorUtils.typeof_Object || t == EditorUtils.typeof_UnityObject) + return null; + if (t.IsRealPublic()) + return t; + if (HasWrapper(t)) + return t; + return t.BaseType; + } + + public Type GetSuperType(Type t) => t.IsRealPublic() ? t : TestSuperType(t.BaseType); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected void line(string text = "") => this.sb?.AppendIndentLine(text, indent); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected void line_begin(string text) => this.sb?.AppendIndent(text, indent); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected void line_end(string text = "") => this.sb?.AppendLine(text); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected void append(string text) => this.sb?.Append(text); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected void comment(string text) => this.sb?.AppendIndentComment(text, indent); + + public void Save() + { + var path = Path.Combine(collection.isCSharpAssembly ? CSharpGeneratePath : SelfGeneratePath, fileName); + EditorUtils.WriteToFile(path, sb.ToString()); + } + + public abstract void Execute(); + } + + public abstract GenInfoBase[] genInfoList { get; } + public MemberCollectionGroup group = new(); + + + public abstract GenJobBase CreateJob(MemberCollection collection); + public void Execute() + { + group.AddMember(genInfoList); + + List resultList = new(); + foreach (var collection in group.list) + resultList.Add(CreateJob(collection)); + + var handleList = resultList.Select(x => Task.Run(x.Execute)); + foreach (var handle in handleList) + { + handle.Wait(); + } + } + } + + } +} \ No newline at end of file diff --git a/Assets/URS/Utils/Editor/ReflectionHelper/ReflectionTool.cs.meta b/Assets/URS/Utils/Editor/ReflectionHelper/ReflectionTool.cs.meta new file mode 100644 index 0000000..416094b --- /dev/null +++ b/Assets/URS/Utils/Editor/ReflectionHelper/ReflectionTool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3f5c55a16a7ae364992e29f5cc56a6b3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/SharedObjectPool.cs b/Assets/URS/Utils/Editor/SharedObjectPool.cs new file mode 100644 index 0000000..069e8a8 --- /dev/null +++ b/Assets/URS/Utils/Editor/SharedObjectPool.cs @@ -0,0 +1,17 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Pool; + +namespace NinjaBeats +{ + + public class SharedObjectPool where T : class, new() + { + private static ObjectPool _Shared = new ObjectPool(() => new T()); + + public static T Get() => _Shared.Get(); + public static PooledObject Get(out T o) => _Shared.Get(out o); + public static void Release(T o) => _Shared.Release(o); + } +} \ No newline at end of file diff --git a/Assets/URS/Utils/Editor/SharedObjectPool.cs.meta b/Assets/URS/Utils/Editor/SharedObjectPool.cs.meta new file mode 100644 index 0000000..a025946 --- /dev/null +++ b/Assets/URS/Utils/Editor/SharedObjectPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: de6b2a5209c0a824e8839a573be2266a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/UnityMacro.cs b/Assets/URS/Utils/Editor/UnityMacro.cs new file mode 100644 index 0000000..a9d6ce7 --- /dev/null +++ b/Assets/URS/Utils/Editor/UnityMacro.cs @@ -0,0 +1,57 @@ + +using System.Linq; +using System.Reflection; +using UnityEngine; +using NinjaBeats; + +public partial class UnityMacro +{ + private static UnityMacro s_Instance = null; + + public static UnityMacro Instance + { + get + { + if (s_Instance == null) + { + s_Instance = new(); + var type = s_Instance.GetType(); + var fields = type.GetFields((BindingFlags)(-1)); + var injectFields = fields.Where(x => x.Name.StartsWith("inject_")); + foreach (var injectField in injectFields) + { + var fieldName = injectField.Name.Substring("inject_".Length); + var field = fields.Find(x => x.Name == fieldName); + if (field == null) + continue; + + if (field.FieldType != injectField.FieldType) + { + Debug.LogError( + $"UnityMacro Inject [{field.Name}] error, injectFieldType:{injectField.FieldType} fieldType:{field.FieldType}"); + continue; + } + + var value = injectField.GetValue(s_Instance); + field.SetValue(s_Instance, value); + +#if UNITY_EDITOR + Debug.LogWarning($"UnityMacro Inject [{field.Name}], value:{value}"); +#endif + } + } + + return s_Instance; + } + } + + public string BUILD_CHANNEL = ""; + public string SERVER_URL = "http://ninja.happyelements.net:8020"; + public string DEFAULT_LANGUAGE = ""; + public bool ENABLE_CONSOLE = true; + public int MAINTENANCE_VERSION_COUNT= 4; + public bool ENABLE_HOTUPDATE = true; + public bool ENABLE_DEVELOPMENT_BUILD = false; + public bool ENABLE_HESDK = true; + +} \ No newline at end of file diff --git a/Assets/URS/Utils/Editor/UnityMacro.cs.meta b/Assets/URS/Utils/Editor/UnityMacro.cs.meta new file mode 100644 index 0000000..e9f96f4 --- /dev/null +++ b/Assets/URS/Utils/Editor/UnityMacro.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 915b7ff512e7a4445af6b660a990b69e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/Utils.Collection.cs b/Assets/URS/Utils/Editor/Utils.Collection.cs new file mode 100644 index 0000000..53b39d4 --- /dev/null +++ b/Assets/URS/Utils/Editor/Utils.Collection.cs @@ -0,0 +1,760 @@ +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using UnityEngine; +using UnityEngine.Pool; + +namespace NinjaBeats +{ + public static partial class Utils + { + class ListDummy + { + public T[] _items; + public int _size; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void EnsureCapacity(this List self, int size) + { + if (self.Capacity < size) + self.Capacity = size > 1024 ? (size + 256) : Mathf.NextPowerOfTwo(size + 1); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Span AddBlock(this List self, int blockSize) + { + if (self == null) + return Span.Empty; + self.EnsureCapacity(self.Count + blockSize); + var dummy = Unsafe.As>(self); + var old = dummy._size; + dummy._size += blockSize; + return dummy._items.AsSpan(old, blockSize); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Span AsSpan(this List self) + { + if (self == null) + return Span.Empty; + var dummy = Unsafe.As>(self); + return dummy._items.AsSpan(0, dummy._size); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int FindIndex(this IList self, Predicate func) + { + for (int i = 0; i < self.Count; ++i) + { + var value = self[i]; + if (func(value)) + return i; + } + + return -1; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T Find(this IList self, Predicate func) + { + for (int i = 0; i < self.Count; ++i) + { + var value = self[i]; + if (func(value)) + return value; + } + + return default; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool Empty(this IList self) => self.Count == 0; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool NotEmpty(this IList self) => self.Count > 0; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddTimes(this IList self, T item, int count) + { + if (count <= 0) + return; + for (int i = 0; i < count; ++i) + self.Add(item); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddTimes(this List self, T item, int count) + { + if (count <= 0) + return; + self.AddBlock(count).Fill(item); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddRange(this IList self, IEnumerable list) + { + if (self == null || list == null) + return; + foreach (var v in list) + self.Add(v); + } + + // foreach 接口会 GC Alloc + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddRange(this ISet self, IList items) + { + if (self == null || items == null) + return; + for (int i = 0; i < items.Count; ++ i) + self.Add(items[i]); + } + // foreach 接口会 GC Alloc + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddRange(this ISet self, HashSet items) + { + if (self == null || items == null) + return; + foreach (var item in items) + self.Add(item); + } + // foreach 接口会 GC Alloc + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddRangeNonAlloc(this IList self, HashSet items) + { + if (self == null || items == null) + return; + foreach (var item in items) + self.Add(item); + } + // foreach 接口会 GC Alloc + public static void AddValues(this IList self, Dictionary dict) + { + if (self == null || dict == null) + return; + foreach (var pair in dict) + self.Add(pair.Value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddUnique(this IList self, T item, Func equalFunc) + { + if (self.FindIndex(x => equalFunc.Invoke(item, x)) != -1) + return; + self.Add(item); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddUnique(this IList self, T item) where T : IEquatable + { + if (self.FindIndex(x => x.Equals(item)) != -1) + return; + self.Add(item); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool Has(this IList self, Predicate func) => self.FindIndex(func) != -1; + + // [MethodImpl(MethodImplOptions.AggressiveInlining)] + // public static void AddUnique(this IList self, Vector2 item) => + // self.AddUnique(item, (x, y) => x == y); + + public delegate int RandomRangeDelegate(int min, int max); + + /// + /// 从[min,max]中选择count个数字 + /// + /// + /// + /// + /// + /// + /// + /// + public static T RandomSelect(int min, int max, int count, bool allowDuplicate, T result, RandomRangeDelegate randomInclusiveMax) where T : IList + { + result.Clear(); + if (allowDuplicate) + { + for (int i = 0; i < count; ++i) + result.Add(randomInclusiveMax(min, max)); + } + else + { + if (max < min) + (min, max) = (max, min); + + int total = max - min + 1; + if (count > total) + throw new Exception($"not enough number:{count} in [{min}, {max}]"); + + if (count >= total / 2) + { + var temp = new List(); + { + for (int i = min; i <= max; ++i) + temp.Add(i); + temp.RandomSelect(count, allowDuplicate, result, randomInclusiveMax); + } + } + else + { + var temp = new HashSet(); + { + for (int i = 0; i < count; ++i) + { + while (true) + { + var randomValue = randomInclusiveMax(min, max); + if (!temp.Contains(randomValue)) + { + temp.Add(randomValue); + result.Add(randomValue); + break; + } + } + } + } + } + } + return result; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int RandomIdx(this IList self, RandomRangeDelegate randomInclusiveMax) => self.Count <= 0 ? -1 : randomInclusiveMax(0, self.Count); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T Random(this IList self, RandomRangeDelegate randomInclusiveMax) => self[self.RandomIdx(randomInclusiveMax)]; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IdxValid(this IList self, int idx) => idx >= 0 && idx < self.Count; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IndexValid(this IList self, int idx) => self.IdxValid(idx); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ThrowIfIdxInvalid(this IList self, int idx) + { + if (!self.IdxValid(idx)) + throw new Exception($"index:{idx} of list:{self.Count} is out of range"); + } + public static TList RandomSelect(this IList self, int count, bool allowDuplicate, TList result, RandomRangeDelegate randomInclusiveMax) where TList : IList + { + result.Clear(); + int size = self.Count; + if (count > 0 && size > 0) + { + //Span idxArr = stackalloc int[count]; + if (allowDuplicate) + { + for (int i = 0; i < count; ++i) + { + var randomIdx = self.RandomIdx(randomInclusiveMax); + if (self.IdxValid(randomIdx)) + { + result.Add(self[randomIdx]); + } + else + { + throw new Exception($"{nameof(RandomSelect)} not enough valid item, size:{size}, count:{count}"); + } + } + } + else + { + if (count > size) + throw new Exception($"{nameof(RandomSelect)} out of range, size:{size}, count:{count}"); + + var temp = new List(); + { + foreach (var v in self) + temp.Add(v); + + for (int i = 0; i < count; ++i) + { + var randomIdx = temp.RandomIdx(randomInclusiveMax); + if (temp.IdxValid(randomIdx)) + { + result.Add(temp[randomIdx]); + temp.RemoveAt(randomIdx); + } + else + { + throw new Exception($"{nameof(RandomSelect)} not enough valid item, size:{size}, count:{count}"); + } + } + } + } + } + return result; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static List RandomSelect(this IList self, int count, bool allowDuplicate, RandomRangeDelegate randomInclusiveMax) => self.RandomSelect(count, allowDuplicate, new List(), randomInclusiveMax); + + public static int BinaryLowerBound(this IList self, int index, int count, TKey item, Func comparer) + { + int end = index + count; + int first = index; + int mid, count2; + + while (0 < count) + { + count2 = count / 2; + mid = first + count2; + if (comparer(self[mid], item) < 0) + { + first = mid + 1; + count = count - count2 - 1; + } + else + { + count = count2; + } + } + if (first >= end || first >= self.Count) + return -1; + return first; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BinaryLowerBound(this IList self, int index, TKey item, Func comparer) => self.BinaryLowerBound(index, self.Count - index, item, comparer); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BinaryLowerBound(this IList self, TKey item, Func comparer) => self.BinaryLowerBound(0, self.Count, item, comparer); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BinaryLowerBound(this IList self, int index, int count, T item, IComparer comparer = null) => self.BinaryLowerBound(index, count, item, comparer.Compare); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BinaryLowerBound(this IList self, int index, T item, IComparer comparer = null) => self.BinaryLowerBound(index, self.Count - index, item, comparer.Compare); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BinaryLowerBound(this IList self, T item, IComparer comparer = null) => self.BinaryLowerBound(0, self.Count, item, comparer.Compare); + public static int BinaryUpperBound(this IList self, int index, int count, TKey item, Func comparer) + { + int end = index + count; + int first = index; + int mid, count2; + + while (0 < count) + { + count2 = count / 2; + mid = first + count2; + if (comparer(self[mid], item) <= 0) + { + first = mid + 1; + count = count - count2 - 1; + } + else + { + count = count2; + } + } + if (first >= end || first >= self.Count) + return -1; + return first; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BinaryUpperBound(this IList self, int index, TKey item, Func comparer) => self.BinaryUpperBound(index, self.Count - index, item, comparer); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BinaryUpperBound(this IList self, TKey item, Func comparer) => self.BinaryUpperBound(0, self.Count, item, comparer); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BinaryUpperBound(this IList self, int index, int count, T item, IComparer comparer = null) => self.BinaryUpperBound(index, count, item, (comparer ?? Comparer.Default).Compare); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BinaryUpperBound(this IList self, int index, T item, IComparer comparer = null) => self.BinaryUpperBound(index, self.Count - index, item, (comparer ?? Comparer.Default).Compare); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int BinaryUpperBound(this IList self, T item, IComparer comparer = null) => self.BinaryUpperBound(0, self.Count, item, (comparer ?? Comparer.Default).Compare); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void InsertAscending(this IList self, TKey key, TValue item, Func comparer) + { + var it = self.BinaryLowerBound(0, self.Count, key, comparer); + if (!self.IdxValid(it)) + self.Add(item); + else + self.Insert(it, item); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void InsertAscending(this IList self, T item, IComparer comparer = null) => self.InsertAscending(item, item, (comparer ?? Comparer.Default).Compare); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void InsertDescending(this IList self, TKey key, TValue item, Func comparer) + { + var it = self.BinaryLowerBound(0, self.Count, key, (v, k) => -1 * comparer(v, k)); + if (!self.IdxValid(it)) + self.Add(item); + else + self.Insert(it, item); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void InsertDescending(this IList self, T item, IComparer comparer = null) => self.InsertDescending(item, item, (comparer ?? Comparer.Default).Compare); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe bool IsEquals(byte[] buffer1, byte* buffer2) + { + for (int i = 0; i < buffer1.Length; ++i) + { + if (buffer1[i] != buffer2[i]) + return false; + } + + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe bool IsEquals(byte* buffer1, byte* buffer2, int length) + { + for (int i = 0; i < length; ++i) + { + if (buffer1[i] != buffer2[i]) + return false; + } + + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe bool IsEquals(byte[] buffer1, int offset1, byte* buffer2, int length) + { + fixed (byte* ptr1 = buffer1) + return IsEquals(ptr1 + offset1, buffer2, length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe bool IsEquals(byte* buffer1, byte[] buffer2, int offset2, int length) + { + fixed (byte* ptr2 = buffer2) + return IsEquals(buffer1, ptr2 + offset2, length); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe bool IsEquals(byte[] buffer1, int offset1, byte[] buffer2, int offset2, int length) + { + fixed (byte* ptr1 = buffer1) + fixed (byte* ptr2 = buffer2) + return IsEquals(ptr1 + offset1, ptr2 + offset2, length); + } + + public struct _ConvertScopeImpl : IDisposable where T : class + { + public IList self; + public List list; + public Action setter; + + public _ConvertScopeImpl(IList self, Func getter, Action setter) + { + this.self = self; + this.list = ListPool.Get(); + this.setter = setter; + if (getter != null && self != null) + { + foreach (var t in self) + this.list.Add(getter(t)); + } + } + + public void Dispose() + { + if (list != null) + { + if (setter != null && self != null && self.Count == list.Count) + { + for (int i = 0; i < list.Count; ++i) + setter(self[i], list[i]); + } + ListPool.Release(list); + } + } + } + + public static _ConvertScopeImpl ConvertScope(this IList self, out List list, Func getter, Action setter) where T : class + { + _ConvertScopeImpl r = new(self, getter, setter); + list = r.list; + return r; + } + + public static List ConvertToList(this IList self, Func func, List r = null) + { + if (self == null) + return null; + + r ??= new(); + foreach (var v in self) + r.Add(func(v)); + return r; + } + + public static List ConvertToList(this IList self, Func func) + { + if (self == null) + return null; + + List r = new(); + foreach (var v in self) + r.Add(func(v)); + return r; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T[] ConvertArray(Array fromArray) + { + return (T[])ConvertArray(fromArray, typeof(T[])); + } + + public static Array ConvertArray(Array fromArray, Type toType) + { + if (fromArray == null) + return null; + var ret = Array.CreateInstance(toType.GetElementType(), fromArray.Length); + for (int i = 0; i < fromArray.Length; ++i) + ret.SetValue(fromArray.GetValue(i), i); + return ret; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static TOutput[] ConvertArray(TInput[] fromArray, Converter converter) + { + if (fromArray == null) + return null; + return Array.ConvertAll(fromArray, converter); + } + + public static bool IsEquals(this ICollection a, ICollection b) + { + if ((a == null) != (b == null)) + return false; + if (a == null) + return true; + if (a.Count != b.Count) + return false; + foreach (var v in a) + { + if (!b.Contains(v)) + return false; + } + + return true; + } + + public static bool IsEquals(this IList a, IList b, Func f) + { + if ((a == null) != (b == null)) + return false; + if (a == null) + return true; + int count = a.Count; + if (count != b.Count) + return false; + for (int i = 0; i < count; ++i) + { + if (!f(a[i], b[i])) + return false; + } + + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int IndexOf(this T[] self, Predicate match) + { + for (int i = 0; i < self.Length; ++i) + { + if (match(self[i])) + return i; + } + + return -1; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AddIfValid(this IList self, T value) where T : class + { + if (value != null) + self.Add(value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool AddIfValid(this IProducerConsumerCollection self, T value) where T : class + { + if (value != null) + return self.TryAdd(value); + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool PopFirst(this IList self, out T first) + { + if (self.Count == 0) + { + first = default; + return false; + } + + first = self[0]; + self.RemoveAt(0); + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool PopLast(this IList self, out T last) + { + if (self.Count == 0) + { + last = default; + return false; + } + + last = self[self.Count - 1]; + self.RemoveAt(self.Count - 1); + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static V SafeGetValue(this Dictionary self, K key) + { + V value = default(V); + if (self.TryGetValue(key, out value)) + return value; + return value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static V GetOrAdd(this Dictionary self, K key, Func newFunc) + { + if (self.TryGetValue(key, out var value)) + return value; + value = newFunc(); + self.Add(key, value); + return value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static V GetOrAdd(this IDictionary self, K key) where V : new() + { + if (self.TryGetValue(key, out var value)) + return value; + value = new V(); + self.Add(key, value); + return value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T GetOrAdd(this IList self, Predicate match, Func func) + { + var index = self.FindIndex(match); + if (index == -1) + { + var value = func(); + self.Add(value); + return value; + } + + return self[index]; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void RemoveIf(this List self, Predicate match) + { + var idx = self.FindIndex(match); + if (idx != -1) + self.RemoveAt(idx); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T IdxOrDefault(this IList self, int idx) + { + if (idx >= 0 && idx < self.Count) + return self[idx]; + return default; + } + + public static bool IsSimilar(IDictionary a, IDictionary b, Func func) + { + if (object.ReferenceEquals(a, b)) + return true; + if (a == null || b == null) + return false; + if (a.Count != b.Count) + return false; + + foreach (var pair in a) + { + if (!b.TryGetValue(pair.Key, out var vb)) + return false; + + if (!func(pair.Value, vb)) + return false; + } + + return true; + } + + public static bool IsSimilar(IList a, IList b, Func func) + { + if (object.ReferenceEquals(a, b)) + return true; + if (a == null || b == null) + return false; + if (a.Count != b.Count) + return false; + + for (int ia = 0; ia < a.Count; ++ ia) + { + var va = a[ia]; + bool exist = false; + + for (int ib = 0; ib < b.Count; ++ ib) + { + var vb = b[ib]; + if (func(va, vb)) + { + exist = true; + break; + } + } + + if (!exist) + return false; + } + + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T[] NewArray(int size) where T : new() + { + var arr = new T[size]; + for (int i = 0; i < size; ++i) + arr[i] = new(); + return arr; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WaitTask(this IList self) + { + for (int i = 0; i < self.Count; ++i) + self[i].Wait(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WaitTask(this IList> self) + { + for (int i = 0; i < self.Count; ++i) + self[i].Wait(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WaitTask(this IEnumerable self) + { + foreach (var item in self) + item.Wait(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WaitTask(this IEnumerable> self) + { + foreach (var item in self) + item.Wait(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Update(this IDictionary self, K k, V v, bool enable) + { + if (enable) + self.TryAdd(k, v); + else + self.Remove(k); + } + } +} \ No newline at end of file diff --git a/Assets/URS/Utils/Editor/Utils.Collection.cs.meta b/Assets/URS/Utils/Editor/Utils.Collection.cs.meta new file mode 100644 index 0000000..e6f810c --- /dev/null +++ b/Assets/URS/Utils/Editor/Utils.Collection.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4e512ede0b1a75b4aa2998aeb6e80662 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/Utils.Misc.cs b/Assets/URS/Utils/Editor/Utils.Misc.cs new file mode 100644 index 0000000..b278f0b --- /dev/null +++ b/Assets/URS/Utils/Editor/Utils.Misc.cs @@ -0,0 +1,227 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using Unity.Collections; +using Unity.Collections.LowLevel.Unsafe; +using Unity.IO.LowLevel.Unsafe; +using UnityEngine.Pool; + +namespace NinjaBeats +{ + + public unsafe struct UnsafeFileBuffer : IDisposable + { + public byte* buffer; + public long length; + + public IntPtr ptr => new(buffer); + public int ptrCount => (int)length; + + public static readonly UnsafeFileBuffer Empty = new(); + + public bool isValid => buffer != null && length > 0; + public void Dispose() + { + if (buffer != null) + { + UnsafeUtility.Free(buffer, Allocator.Temp); + buffer = null; + } + } + } + + + public static partial class Utils + { + public static UnityEngine.Pool.ObjectPool sStringBuilderPool = + new UnityEngine.Pool.ObjectPool( + () => new StringBuilder(), + null, + x => x.Clear() + ); + + public static int Compare(string a, string b) + { + if (a == null) + { + if (b == null) + return 0; + else + return -1; + } + + if (b == null) + return 1; + + for (int i = 0; i < a.Length && i < b.Length; ++i) + { + if (a[i] < b[i]) + return -1; + else if (a[i] > b[i]) + return 1; + } + + if (a.Length < b.Length) + return -1; + else if (a.Length > b.Length) + return 1; + return 0; + } + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T GetOrAddComponent(this Component component) where T : Component + { + if (component.TryGetComponent(out var r)) + return r; + return component.gameObject.AddComponent(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T GetOrAddComponent(this GameObject gameObject) where T : Component + { + if (gameObject.TryGetComponent(out var r)) + return r; + return gameObject.AddComponent(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void EnableKeyword(this Material self, string name, bool value) + { + if (value) + self.EnableKeyword(name); + else + self.DisableKeyword(name); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int GetKeyword(this Material self, string name) => self.IsKeywordEnabled(name) ? 1 : 0; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void SetKeyword(this Material self, string name, int value) => + self.EnableKeyword(name, value != 0); + + public static bool IsChildOf(this Transform self, Transform parent) + { + if (self == null || parent == null) + return false; + + if (self == parent) + return true; + + return IsChildOf(self.parent, parent); + } + + public static string FullPathInHierarchy(this Transform self) + { + using (sStringBuilderPool.Get(out var sb)) + { + for (Transform it = self; it != null; it = it.parent) + { + if (it == self) + { + sb.Append(it.name); + } + else + { + sb.Insert(0, '/'); + sb.Insert(0, it.name); + } + } + + return sb.ToString(); + } + } + + public static GameObject[] GetDontDestroyOnLoadObjects() + { + if (!Application.isPlaying) + return new GameObject[0]; + GameObject temp = null; + try + { + temp = new GameObject(); + UnityEngine.Object.DontDestroyOnLoad(temp); + UnityEngine.SceneManagement.Scene dontDestroyOnLoad = temp.scene; + UnityEngine.Object.DestroyImmediate(temp); + temp = null; + + if (dontDestroyOnLoad != null) + return dontDestroyOnLoad.GetRootGameObjects(); + else + return new GameObject[0]; + } + finally + { + if (temp != null) + UnityEngine.Object.DestroyImmediate(temp); + } + } + + private static int s_MaxFileMB = 10; + + public static bool FileExists(string path) => GetFileInfo(path, out _); + public unsafe static bool GetFileInfo(string path, out long fileSize) + { + fileSize = 0; + if (string.IsNullOrEmpty(path)) + return false; + + FileInfoResult info = new(); + var readHandle = AsyncReadManager.GetFileInfo(path, &info); + readHandle.JobHandle.Complete(); + readHandle.Dispose(); + + if (info.FileState == FileState.Exists) + { + fileSize = info.FileSize; + return true; + } + return false; + } + + public unsafe static UnsafeFileBuffer ReadFileUnsafeBuffer(string path) + { + if (!GetFileInfo(path, out var byteCount)) + return UnsafeFileBuffer.Empty; + + if (byteCount > s_MaxFileMB * 1024L * 1024L || byteCount > int.MaxValue) + { + Debug.LogError($"超过{s_MaxFileMB}MB"); + return UnsafeFileBuffer.Empty; + } + + UnsafeFileBuffer self = new(); + self.length = byteCount; + self.buffer = (byte*)UnsafeUtility.Malloc(byteCount, 16, Allocator.Temp); + + ReadCommand cmd; + cmd.Offset = 0; + cmd.Size = self.length; + cmd.Buffer = self.buffer; + + var fileHandle = AsyncReadManager.OpenFileAsync(path); + + ReadCommandArray readCmdArray; + readCmdArray.ReadCommands = &cmd; + readCmdArray.CommandCount = 1; + + var readHandle = AsyncReadManager.Read(fileHandle, readCmdArray); + + var closeJob = fileHandle.Close(readHandle.JobHandle); + closeJob.Complete(); + + readHandle.Dispose(); + + return self; + } + + } +} \ No newline at end of file diff --git a/Assets/URS/Utils/Editor/Utils.Misc.cs.meta b/Assets/URS/Utils/Editor/Utils.Misc.cs.meta new file mode 100644 index 0000000..b069066 --- /dev/null +++ b/Assets/URS/Utils/Editor/Utils.Misc.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a758e2119eebbf744b929588aba8b45f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/Utils.Reflection.cs b/Assets/URS/Utils/Editor/Utils.Reflection.cs new file mode 100644 index 0000000..4f8c0f6 --- /dev/null +++ b/Assets/URS/Utils/Editor/Utils.Reflection.cs @@ -0,0 +1,767 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using System; +using System.Collections.Concurrent; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace NinjaBeats +{ + + public static partial class Utils + { + + /// + /// return Attribute.IsDefined(m, typeof(T)); + /// + /// + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool HasAttribute(this MemberInfo m) where T : Attribute + { + return Attribute.IsDefined(m, typeof(T)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T GetValue(this FieldInfo self, object value = null) + { + if (self == null) + return default; + return (T)self.GetValue(value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T GetValue(this PropertyInfo self, object value = null) + { + if (self == null) + return default; + return (T)self.GetValue(value); + } + + static ConcurrentDictionary s_RealPublicMap = new (); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool IsRealPublicImpl(this Type self) + { + if (!s_RealPublicMap.TryGetValue(self, out var value)) + { + value = true; + var it = self; + while (it.IsNested) + { + if (!it.IsNestedPublic) + { + value = false; + break; + } + + it = it.DeclaringType; + } + + if (value && !it.IsPublic && !it.IsGenericParameter) + value = false; + + if (value && self.IsGenericType) + { + foreach (var gt in self.GetGenericArguments()) + { + if (!gt.IsRealPublicImpl()) + { + value = false; + break; + } + } + } + + if (value && self.HasElementType) + { + if (!self.GetElementType().IsRealPublicImpl()) + value = false; + } + + s_RealPublicMap.TryAdd(self, value); + } + return value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsGetRealPublic(this PropertyInfo self) + { + if (self.CanRead && !self.GetMethod.IsPublic) + return false; + return self.DeclaringType.IsRealPublic(); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsSetRealPublic(this PropertyInfo self) + { + if (self.CanWrite && !self.SetMethod.IsPublic) + return false; + return self.DeclaringType.IsRealPublic(); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsRealPublic(this T self) where T : MemberInfo => MemberInfoTraits.IsRealPublic(self); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsRealStatic(this T self) where T : MemberInfo => MemberInfoTraits.IsRealStatic(self); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsRealCanRead(this T self) where T : MemberInfo => MemberInfoTraits.IsRealCanRead(self); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsRealCanWrite(this T self) where T : MemberInfo => MemberInfoTraits.IsRealCanWrite(self); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Type GetRealMemberType(this T self) where T : MemberInfo => MemberInfoTraits.GetRealMemberType(self); + + private static bool s_MemberInfoTraitsInited = false; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void MemberInfoTraitsInit() + { + if (s_MemberInfoTraitsInited) + return; + + MemberInfoTraitsInitImpl(); + } + +#if UNITY_EDITOR + [UnityEditor.InitializeOnLoadMethod] +#endif + private static void MemberInfoTraitsInitImpl() + { + s_MemberInfoTraitsInited = true; + + MemberInfoTraits.IsRealPublic = x => x.IsPublic && x.DeclaringType.IsRealPublic(); + MemberInfoTraits.IsRealPublic = x => + { + if (x.CanRead && !x.GetMethod.IsPublic) + return false; + if (x.CanWrite && !x.SetMethod.IsPublic) + return false; + return x.DeclaringType.IsRealPublic(); + }; + MemberInfoTraits.IsRealPublic = x => x.IsPublic && x.DeclaringType.IsRealPublic(); + MemberInfoTraits.IsRealPublic = x => x.IsPublic && x.DeclaringType.IsRealPublic(); + MemberInfoTraits.IsRealPublic = x => + { + if (x.AddMethod?.IsPublic == false) + return false; + if (x.RemoveMethod?.IsPublic == false) + return false; + if (x.RaiseMethod?.IsPublic == false) + return false; + return x.DeclaringType.IsRealPublic(); + }; + MemberInfoTraits.IsRealPublic = IsRealPublicImpl; + MemberInfoTraits.IsRealPublic = x => x switch + { + FieldInfo fi => fi.IsRealPublic(), + PropertyInfo pi => pi.IsRealPublic(), + MethodInfo mi => mi.IsRealPublic(), + ConstructorInfo ci => ci.IsRealPublic(), + EventInfo ei => ei.IsRealPublic(), + Type t => t.IsRealPublic(), + _ => false + }; + + MemberInfoTraits.IsRealStatic = x => x.IsStatic; + MemberInfoTraits.IsRealStatic = x => + { + if (x.CanRead && !x.GetMethod.IsStatic) + return false; + if (x.CanWrite && !x.SetMethod.IsStatic) + return false; + return true; + }; + MemberInfoTraits.IsRealStatic = x => x.IsStatic; + MemberInfoTraits.IsRealStatic = x => x.IsStatic; + MemberInfoTraits.IsRealStatic = x => + { + if (x.AddMethod?.IsStatic == false) + return false; + if (x.RemoveMethod?.IsStatic == false) + return false; + if (x.RaiseMethod?.IsStatic == false) + return false; + return true; + }; + MemberInfoTraits.IsRealStatic = x => x.IsAbstract && x.IsSealed; + MemberInfoTraits.IsRealStatic = x => x switch + { + FieldInfo fi => fi.IsRealStatic(), + PropertyInfo pi => pi.IsRealStatic(), + MethodInfo mi => mi.IsRealStatic(), + ConstructorInfo ci => ci.IsRealStatic(), + EventInfo ei => ei.IsRealStatic(), + Type t => t.IsRealStatic(), + _ => false + }; + + MemberInfoTraits.GetRealMemberType = x => x.FieldType; + MemberInfoTraits.GetRealMemberType = x => x.PropertyType; + MemberInfoTraits.GetRealMemberType = x => x.ReturnType; + MemberInfoTraits.GetRealMemberType = x => x.DeclaringType; + MemberInfoTraits.GetRealMemberType = x => x.EventHandlerType; + MemberInfoTraits.GetRealMemberType = x => x; + MemberInfoTraits.GetRealMemberType = x => x switch + { + FieldInfo fi => fi.GetRealMemberType(), + PropertyInfo pi => pi.GetRealMemberType(), + MethodInfo mi => mi.GetRealMemberType(), + ConstructorInfo ci => ci.GetRealMemberType(), + EventInfo ei => ei.GetRealMemberType(), + Type t => t.GetRealMemberType(), + _ => null + }; + + MemberInfoTraits.IsRealCanRead = x => true; + MemberInfoTraits.IsRealCanRead = x => x.CanRead; + MemberInfoTraits.IsRealCanRead = x => false; + MemberInfoTraits.IsRealCanRead = x => false; + MemberInfoTraits.IsRealCanRead = x => false; + MemberInfoTraits.IsRealCanRead = x => false; + MemberInfoTraits.IsRealCanRead = x => x switch + { + FieldInfo fi => true, + PropertyInfo pi => pi.CanRead, + _ => false + }; + + MemberInfoTraits.IsRealCanWrite = x => true; + MemberInfoTraits.IsRealCanWrite = x => x.CanWrite; + MemberInfoTraits.IsRealCanWrite = x => false; + MemberInfoTraits.IsRealCanWrite = x => false; + MemberInfoTraits.IsRealCanWrite = x => false; + MemberInfoTraits.IsRealCanWrite = x => false; + MemberInfoTraits.IsRealCanWrite = x => x switch + { + FieldInfo fi => true, + PropertyInfo pi => pi.CanWrite, + _ => false + }; + + } + public class MemberInfoTraits where T : MemberInfo + { + private static Func s_IsRealPublic; + private static Func s_IsRealStatic; + private static Func s_IsRealCanRead; + private static Func s_IsRealCanWrite; + private static Func s_GetRealMemberType; + private static Type s_Type = typeof(T); + + public static Func IsRealPublic + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + MemberInfoTraitsInit(); + return s_IsRealPublic; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => s_IsRealPublic = value; + } + public static Func IsRealStatic + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + MemberInfoTraitsInit(); + return s_IsRealStatic; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => s_IsRealStatic = value; + } + public static Func IsRealCanRead + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + MemberInfoTraitsInit(); + return s_IsRealCanRead; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => s_IsRealCanRead = value; + } + public static Func IsRealCanWrite + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + MemberInfoTraitsInit(); + return s_IsRealCanWrite; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => s_IsRealCanWrite = value; + } + public static Func GetRealMemberType + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + MemberInfoTraitsInit(); + return s_GetRealMemberType; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + set => s_GetRealMemberType = value; + } + } + + + static Dictionary s_ValueTypeMap = new Dictionary(); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsValueTypeFast(this Type self) + { + if (!s_ValueTypeMap.TryGetValue(self, out var value)) + { + value = self.IsValueType; + s_ValueTypeMap.Add(self, value); + } + return value; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsNullable(this Type type) + { + return type.IsValueType && type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsOneRankArray(this Type type) + { + return type.IsArray && type.GetArrayRank() == 1; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool Is(this Type type) => type.Is(typeof(T)); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool Is(this Type type , Type baseType) + { + if (type == null) + return false; + + return baseType.IsAssignableFrom(type); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static object CreateInstance(this Type type) + { + return type != null ? Activator.CreateInstance(type) : null; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static object CreateInstance() + { + return CreateInstance(typeof(T)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static T Cast(this Delegate self) where T : Delegate => (T)self.Cast(typeof(T)); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Delegate Cast(this Delegate self, Type type) => self != null && type != null ? Delegate.CreateDelegate(type, self.Target, self.Method) : null; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static object GetDefaultValue(FieldInfo field) + { + return field.GetValue(CreateInstance(field.DeclaringType)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsArrayOrGenericList(this Type type) + { + return type.IsArray || type.IsGenericList(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsGenericList(this Type type) + { + return type.IsGenericType && typeof(IList).IsAssignableFrom(type); + } + + public static bool GetArrayOrListElementType(this Type type, out Type elementType) + { + elementType = null; + if (type.IsArray) + { + elementType = type.GetElementType(); + return true; + } + + if (type.IsGenericType && typeof(IList).IsAssignableFrom(type)) + { + elementType = type.GetGenericArguments().IdxOrDefault(0); + return true; + } + + return false; + } + + + public static bool IsGenericDictionary(this Type type) + { + if (typeof(IDictionary).IsAssignableFrom(type) && type.IsGenericType) + { + var types = type.GetGenericArguments(); + if (types.Length == 2) + { + return true; + } + } + + return false; + } + + public static bool GetDictionaryElementType(this Type type, out Type keyType, out Type valueType) + { + keyType = null; + valueType = null; + if (typeof(IDictionary).IsAssignableFrom(type) && type.IsGenericType) + { + var types = type.GetGenericArguments(); + if (types.Length == 2) + { + keyType = types[0]; + valueType = types[1]; + return true; + } + } + + return false; + } + + /// + /// 判断指定的类型 是否是指定泛型类型的子类型,或实现了指定泛型接口。 + /// + /// 需要测试的类型。 + /// 泛型接口类型,传入 typeof(IXxx<>) + /// 如果是泛型接口的子类型,则返回 true,否则返回 false。 + public static bool HasImplementedRawGeneric(this Type type, Type generic) + { + if (type == null) throw new ArgumentNullException(nameof(type)); + if (generic == null) throw new ArgumentNullException(nameof(generic)); + + // 测试接口。 + var isTheRawGenericType = type.GetInterfaces().Any(IsTheRawGenericType); + if (isTheRawGenericType) return true; + + // 测试类型。 + while (type != null && type != typeof(object)) + { + isTheRawGenericType = IsTheRawGenericType(type); + if (isTheRawGenericType) return true; + type = type.BaseType; + } + + // 没有找到任何匹配的接口或类型。 + return false; + + // 测试某个类型是否是指定的原始接口。 + bool IsTheRawGenericType(Type test) + => generic == (test.IsGenericType ? test.GetGenericTypeDefinition() : test); + } + + public static FieldInfo GetFieldInfo(this Type self, string name) + { + var r = self.GetField(name, (BindingFlags)(-1)); + if (r != null) + return r; + if (self.BaseType != null) + return self.BaseType.GetFieldInfo(name); + return null; + } + + public static PropertyInfo GetPropertyInfo(this Type self, string name) + { + var r = self.GetProperty(name, (BindingFlags)(-1)); + if (r != null) + return r; + if (self.BaseType != null) + return self.BaseType.GetPropertyInfo(name); + return null; + } + + + public static MethodInfo GetAnyMethodInfo(this Type self, string name) + { + foreach (var method in self.GetMethods((BindingFlags)(-1))) + { + if (method.Name != name) + continue; + return method; + } + + if (self.BaseType != null) + return self.BaseType.GetAnyMethodInfo(name); + return null; + } + + public static MethodInfo GetMethodInfoByParameterTypeNames(this Type self, string name, params string[] parameterTypes) + { + int paramCount = parameterTypes?.Length ?? 0; + foreach (var method in self.GetMethods((BindingFlags)(-1))) + { + if (method.Name != name) + continue; + var parameters = method.GetParameters(); + if (parameters.Length != paramCount) + continue; + + if (parameters.IsEquals(parameterTypes, (x, y) => x.ParameterType.FullName == y)) + return method; + } + + return self.BaseType?.GetMethodInfoByParameterTypeNames(name, parameterTypes); + } + + public static MethodInfo GetMethodInfoByParameterTypes(this Type self, string name, params Type[] parameterTypes) + { + int paramCount = parameterTypes?.Length ?? 0; + foreach (var method in self.GetMethods((BindingFlags)(-1))) + { + if (method.Name != name) + continue; + var parameters = method.GetParameters(); + if (parameters.Length != paramCount) + continue; + + if (parameters.IsEquals(parameterTypes, (x, y) => (x.ParameterType.IsByRef ? x.ParameterType.GetElementType() : x.ParameterType) == y)) + return method; + } + + return self.BaseType?.GetMethodInfoByParameterTypes(name, parameterTypes); + } + + public static ConstructorInfo GetConstructorInfoByParameterTypes(this Type self, params Type[] parameterTypes) + { + int paramCount = parameterTypes?.Length ?? 0; + foreach (var constructor in self.GetConstructors((BindingFlags)(-1))) + { + var parameters = constructor.GetParameters(); + if (parameters.Length != paramCount) + continue; + + if (parameters.IsEquals(parameterTypes, (x, y) => (x.ParameterType.IsByRef ? x.ParameterType.GetElementType() : x.ParameterType) == y)) + return constructor; + } + + return null; + } + + public static MethodInfo GetMethodInfo(this Type self, string name, int paramCount) + { + foreach (var method in self.GetMethods((BindingFlags)(-1))) + { + if (method.Name != name) + continue; + var parameters = method.GetParameters(); + if (parameters.Length == paramCount) + return method; + } + + if (self.BaseType != null) + return self.BaseType.GetMethodInfo(name, paramCount); + return null; + } + + public static MethodInfo GetMethodInfo(this Type self, string name) + { + foreach (var method in self.GetMethods((BindingFlags)(-1))) + { + if (method.Name != name) + continue; + var parameters = method.GetParameters(); + if (parameters.Length == 1 && parameters[0].ParameterType == typeof(T)) + return method; + } + + if (self.BaseType != null) + return self.BaseType.GetMethodInfo(name); + return null; + } + + public static MethodInfo GetMethodInfo(this Type self, string name) + { + foreach (var method in self.GetMethods((BindingFlags)(-1))) + { + if (method.Name != name) + continue; + var parameters = method.GetParameters(); + if (parameters.Length == 2 && parameters[0].ParameterType == typeof(T1) && + parameters[1].ParameterType == typeof(T2)) + return method; + } + + if (self.BaseType != null) + return self.BaseType.GetMethodInfo(name); + return null; + } + + public static MethodInfo GetMethodInfo(this Type self, string name) + { + foreach (var method in self.GetMethods((BindingFlags)(-1))) + { + if (method.Name != name) + continue; + var parameters = method.GetParameters(); + if (parameters.Length == 3 && parameters[0].ParameterType == typeof(T1) && + parameters[1].ParameterType == typeof(T2) && parameters[2].ParameterType == typeof(T3)) + return method; + } + + if (self.BaseType != null) + return self.BaseType.GetMethodInfo(name); + return null; + } + + public static MethodInfo GetMethodInfo(this Type self, string name) + { + foreach (var method in self.GetMethods((BindingFlags)(-1))) + { + if (method.Name != name) + continue; + var parameters = method.GetParameters(); + if (parameters.Length == 4 && parameters[0].ParameterType == typeof(T1) && + parameters[1].ParameterType == typeof(T2) && parameters[2].ParameterType == typeof(T3) && + parameters[3].ParameterType == typeof(T4)) + return method; + } + + if (self.BaseType != null) + return self.BaseType.GetMethodInfo(name); + return null; + } + + public static MethodInfo GetMethodInfo(this Type self, string name) + { + foreach (var method in self.GetMethods((BindingFlags)(-1))) + { + if (method.Name != name) + continue; + var parameters = method.GetParameters(); + if (parameters.Length == 5 && parameters[0].ParameterType == typeof(T1) && + parameters[1].ParameterType == typeof(T2) && parameters[2].ParameterType == typeof(T3) && + parameters[3].ParameterType == typeof(T4) && parameters[4].ParameterType == typeof(T5)) + return method; + } + + if (self.BaseType != null) + return self.BaseType.GetMethodInfo(name); + return null; + } + + public static MethodInfo GetMethodInfo(this Type self, string name) + { + foreach (var method in self.GetMethods((BindingFlags)(-1))) + { + if (method.Name != name) + continue; + var parameters = method.GetParameters(); + if (parameters.Length == 6 && parameters[0].ParameterType == typeof(T1) && + parameters[1].ParameterType == typeof(T2) && parameters[2].ParameterType == typeof(T3) && + parameters[3].ParameterType == typeof(T4) && parameters[4].ParameterType == typeof(T5) && + parameters[5].ParameterType == typeof(T6)) + return method; + } + + if (self.BaseType != null) + return self.BaseType.GetMethodInfo(name); + return null; + } + + + static object[] _sParam0Array = new object[0]; + static FixedArrayPool _sParam1ArrayPool = new FixedArrayPool(1); + static FixedArrayPool _sParam2ArrayPool = new FixedArrayPool(2); + static FixedArrayPool _sParam3ArrayPool = new FixedArrayPool(3); + static FixedArrayPool _sParam4ArrayPool = new FixedArrayPool(4); + + public static void Invoke(this MethodInfo self, object obj) + { + self.Invoke(obj, _sParam0Array); + } + + public static void Invoke(this MethodInfo self, object obj, object t1) + { + var ps = _sParam1ArrayPool.Rent(); + ps[0] = t1; + self.Invoke(obj, ps); + _sParam1ArrayPool.Return(ps); + } + + public static void Invoke(this MethodInfo self, object obj, object t1, object t2) + { + var ps = _sParam2ArrayPool.Rent(); + ps[0] = t1; + ps[1] = t2; + self.Invoke(obj, ps); + _sParam2ArrayPool.Return(ps); + } + + public static void Invoke(this MethodInfo self, object obj, object t1, object t2, object t3) + { + var ps = _sParam3ArrayPool.Rent(); + ps[0] = t1; + ps[1] = t2; + ps[2] = t3; + self.Invoke(obj, ps); + _sParam3ArrayPool.Return(ps); + } + + public static void Invoke(this MethodInfo self, object obj, object t1, object t2, object t3, object t4) + { + var ps = _sParam4ArrayPool.Rent(); + ps[0] = t1; + ps[1] = t2; + ps[2] = t3; + ps[3] = t4; + self.Invoke(obj, ps); + _sParam4ArrayPool.Return(ps); + } + + public static R Invoke(this MethodInfo self, object obj) + { + return (R)self.Invoke(obj, _sParam0Array); + } + + public static R Invoke(this MethodInfo self, object obj, object t1) + { + var ps = _sParam1ArrayPool.Rent(); + ps[0] = t1; + var r = self.Invoke(obj, ps); + _sParam1ArrayPool.Return(ps); + return (R)r; + } + + public static R Invoke(this MethodInfo self, object obj, object t1, object t2) + { + var ps = _sParam2ArrayPool.Rent(); + ps[0] = t1; + ps[1] = t2; + var r = self.Invoke(obj, ps); + _sParam2ArrayPool.Return(ps); + return (R)r; + } + + public static R Invoke(this MethodInfo self, object obj, object t1, object t2, object t3) + { + var ps = _sParam3ArrayPool.Rent(); + ps[0] = t1; + ps[1] = t2; + ps[2] = t3; + var r = self.Invoke(obj, ps); + _sParam3ArrayPool.Return(ps); + return (R)r; + } + + public static R Invoke(this MethodInfo self, object obj, object t1, object t2, object t3, object t4) + { + var ps = _sParam4ArrayPool.Rent(); + ps[0] = t1; + ps[1] = t2; + ps[2] = t3; + ps[3] = t4; + var r = self.Invoke(obj, ps); + _sParam4ArrayPool.Return(ps); + return (R)r; + } + } +} \ No newline at end of file diff --git a/Assets/URS/Utils/Editor/Utils.Reflection.cs.meta b/Assets/URS/Utils/Editor/Utils.Reflection.cs.meta new file mode 100644 index 0000000..16e85d5 --- /dev/null +++ b/Assets/URS/Utils/Editor/Utils.Reflection.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 826faa22159e17d409e70efadf7c3e4d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/Editor/Utils.String.cs b/Assets/URS/Utils/Editor/Utils.String.cs new file mode 100644 index 0000000..11d9829 --- /dev/null +++ b/Assets/URS/Utils/Editor/Utils.String.cs @@ -0,0 +1,158 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; + +namespace NinjaBeats +{ + + public static partial class Utils + { + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AppendRepeat(this StringBuilder self, string value, int count) + { + for (int i = 0; i < count; ++i) + self.Append(value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AppendRepeat(this StringBuilder self, char value, int count) + { + for (int i = 0; i < count; ++i) + self.Append(value); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void AppendSlash(this StringBuilder self) + { + int len = self.Length; + if (len > 0) + { + var last = self[len - 1]; + if (last == '\\' || last == '/') + return; + } + + self.Append('/'); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe void ReplaceCharNoGC(this string str, char oldChar, char newChar) + { + if (string.IsNullOrEmpty(str)) + return; + + fixed (char* ptr = str) + { + int len = str.Length; + for (int i = 0; i < len; ++i) + { + if (ptr[i] == oldChar) + ptr[i] = newChar; + } + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string Replace(this string body, string oldStr, string newStr, int startIndex) + { + return body.Remove(startIndex, oldStr.Length).Insert(startIndex, newStr); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static string Between(this string self, char left, char right) + { + int leftIdx = self.IndexOf(left); + if (leftIdx == -1) + return default; + + int rightIdx = self.LastIndexOf(right); + return self.Substring(leftIdx + 1, rightIdx - leftIdx - 1); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static unsafe string Inverse(this string text) + { + if (!string.IsNullOrEmpty(text)) + { + var len = text.Length; + var halfLen = len / 2; + fixed (char* p = text) + { + for (int i = 0; i < halfLen; ++i) + { + var j = len - i - 1; + var t = p[i]; + p[i] = p[j]; + p[j] = t; + } + } + } + + return text; + } + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool ToInt32(this string self, out int result) + { + result = 0; + try + { + if (int.TryParse(self, out result)) + return true; + return false; + } + catch + { + result = 0; + return false; + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int ToInt32(this string self) => self.ToInt32(out var result) ? result : 0; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool ToFloat(this string self, out float result) + { + result = 0; + try + { + if (float.TryParse(self, out result)) + return true; + return false; + } + catch + { + result = 0; + return false; + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float ToFloat(this string self) => self.ToFloat(out var result) ? result : 0; + + private const int cLower2Upper = (int)'A' - (int)'a'; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsSpace(this char self) => self == '\r' || self == '\n' || self == '\t' || self == ' '; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsLowerLetter(this char self) => self >= 'a' && self <= 'z'; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsUpperLetter(this char self) => self >= 'A' && self <= 'Z'; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsLetter(this char self) => self.IsLowerLetter() || self.IsUpperLetter(); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsNumber(this char self) => self >= '0' && self <= '9'; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsToken(this char self) => self.IsLetter() || self.IsNumber() || self == '_'; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static char ToUpper(this char self) => self.IsLowerLetter() ? (char)((int)self + cLower2Upper) : self; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static char ToLower(this char self) => self.IsUpperLetter() ? (char)((int)self - cLower2Upper) : self; + + } +} \ No newline at end of file diff --git a/Assets/URS/Utils/Editor/Utils.String.cs.meta b/Assets/URS/Utils/Editor/Utils.String.cs.meta new file mode 100644 index 0000000..8a77a58 --- /dev/null +++ b/Assets/URS/Utils/Editor/Utils.String.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b5aa4cc130d2abf4899a30fa2023ece4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/Utils/urs.utils.editor.asmdef b/Assets/URS/Utils/urs.utils.editor.asmdef new file mode 100644 index 0000000..8ac0163 --- /dev/null +++ b/Assets/URS/Utils/urs.utils.editor.asmdef @@ -0,0 +1,14 @@ +{ + "name": "urs.utils.editor", + "rootNamespace": "", + "references": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": true, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} \ No newline at end of file diff --git a/Assets/URS/Utils/urs.utils.editor.asmdef.meta b/Assets/URS/Utils/urs.utils.editor.asmdef.meta new file mode 100644 index 0000000..5ec7428 --- /dev/null +++ b/Assets/URS/Utils/urs.utils.editor.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 81c4d37d6b16ed2428ad2691b45fb45a +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/Build.FromCommandLine.cs b/Assets/URS/YooAsset/Editor/Build.FromCommandLine.cs deleted file mode 100644 index 4aad591..0000000 --- a/Assets/URS/YooAsset/Editor/Build.FromCommandLine.cs +++ /dev/null @@ -1,238 +0,0 @@ - -using UnityEditor; -using System; -using System.IO; -using UnityEngine; -using TagInfo = System.Collections.Generic.Dictionary; -using Context = System.Collections.Generic.Dictionary; -using Debug = UnityEngine.Debug; - -public enum Enum_Build_CommandLine_Arg -{ - IL2CPP, - ENABLE_HE_SDK, - ONLY_EXPORT_PROJECT, - CHANNEL, - VERSION, - BUILD_NUMBER, - APP_IDENTIFIER, -} - -namespace URS -{ - public static partial class Build - { - public class BuildTaskAwaitable : System.Runtime.CompilerServices.INotifyCompletion - { - protected Action Continuation; - public object Result { get; protected set; } - public bool IsCompleted { get; protected set; } - - public void OnCompleted(Action continuation) - { - if (IsCompleted) - { - continuation?.Invoke(); - } - else - { - if (continuation != null) - Continuation += continuation; - } - } - - public void SetDone() - { - if (IsCompleted) - return; - Result = null; - IsCompleted = true; - Continuation?.Invoke(); - } - - public object GetResult() => Result; - - public BuildTaskAwaitable GetAwaiter() => this; - } - - private static BuildTaskAwaitable WaitBuildTask() - { - BuildTaskAwaitable r = new(); - EditorApplication.CallbackFunction func = null; - func = () => - { - if (hasTask) - { - if (_buildTaskWorkSpaces[0].hasException) - EditorApplication.Exit(1); - return; - } - - EditorApplication.update -= func; - r.SetDone(); - }; - EditorApplication.update += func; - return r; - } - - private static bool GetArg(Enum_Build_CommandLine_Arg type, out string arg) - { - arg = EditorUtils.CommandLineGetArgValue(type.ToString()); - if (string.IsNullOrWhiteSpace(arg)) - { - Debug.LogError($"{type.ToString()} is invalid"); - EditorApplication.Exit(1); - return false; - } - return true; - } - - private static bool GetArgInt(Enum_Build_CommandLine_Arg type, out int arg) - { - arg = EditorUtils.CommandLineGetArgValueInt(type.ToString()); - if (arg == 0) - { - Debug.LogError($"{type.ToString()} is invalid"); - EditorApplication.Exit(1); - return false; - } - return true; - } - - // 收集Shader变体 - public static async void ExportShaderFromCommandLine() - { - ExportShaderVariantCollection(); - - await WaitBuildTask(); - - EditorApplication.Exit(0); - } - - private static string GenerateVersion(string channel, string ver) - { - if (!System.Version.TryParse(ver, out var version)) - return ver; - - var build = version.Build; - - var stored_version_path = Path.Combine(Application.dataPath, $"../BuildInfo/{channel}/stored_version.txt"); - if (build == 0) - { - var str = EditorUtils.ReadAllText(stored_version_path); - if (!string.IsNullOrWhiteSpace(str) && System.Version.TryParse(str, out var stored_version)) - { - if (version.Major == stored_version.Major && version.Minor == stored_version.Minor) - { - build = stored_version.Build + 1; - } - } - } - - var r = $"{version.Major}.{version.Minor}.{build}"; - EditorUtils.WriteAllText(stored_version_path, r); - return r; - } - - private static bool PrepareBuildEnvironment() - { - if (!GetArg(Enum_Build_CommandLine_Arg.APP_IDENTIFIER, out var APP_IDENTIFIER)) - return false; - if (!GetArg(Enum_Build_CommandLine_Arg.CHANNEL, out var CHANNEL)) - return false; - if (!GetArg(Enum_Build_CommandLine_Arg.VERSION, out var VERSION)) - return false; - if (!GetArgInt(Enum_Build_CommandLine_Arg.BUILD_NUMBER, out var BUILD_NUMBER)) - return false; - - VERSION = GenerateVersion(CHANNEL, VERSION); - - // [包]的版本号 - PlayerSettings.bundleVersion = VERSION; - // [包]的构建号 - PlayerSettings.Android.bundleVersionCode = BUILD_NUMBER; -#if UNITY_EDITOR_OSX || UNITY_IOS - // [包]的构建号 - PlayerSettings.iOS.buildNumber = BUILD_NUMBER.ToString(); -#endif - - // [资源]APP标识 - URSEditorUserSettings.instance.AppId = APP_IDENTIFIER; - // [资源]渠道 - URSEditorUserSettings.instance.BuildChannel = CHANNEL; - // [资源]的版本号 - URSEditorUserSettings.instance.BuildVersionCode = $"{VERSION}-{BUILD_NUMBER}"; - // [资源]的版本号(进[包]的) - URSEditorUserSettings.instance.CopyToStreamTargetVersion = $"{VERSION}-{BUILD_NUMBER}"; - - return true; - } - - // 生成资源补丁包 - public static async void BuildResourcePatch() - { - EditorUtils.CommandLineListenError(); - // if (!PrepareBuildEnvironment()) - // return; - // - // BuildChannelRouter(); - // - // await WaitBuildTask(); - - EditorUtils.CommandLineSaveError(); - EditorApplication.Exit(0); - } - - // 只打资源不打包 - public static async void BuildResourceFromCommandLine() - { - EditorUtils.CommandLineListenError(); - if (!PrepareBuildEnvironment()) - return; - - BuildBundleAndRaw(); - - await WaitBuildTask(); - - EditorUtils.CommandLineSaveError(); - EditorApplication.Exit(0); - } - - public static async void ClearBundleCacheFromCommandLine() - { - EditorUtils.CommandLineListenError(); - if (!PrepareBuildEnvironment()) - return; - - ClearBundleCache(); - - await WaitBuildTask(); - - EditorUtils.CommandLineSaveError(); - EditorApplication.Exit(0); - } - - // 打资源且打包 - public static async void BuildFromCommandLine() - { - EditorUtils.CommandLineListenError(); - if (!PrepareBuildEnvironment()) - return; - - bool IL2CPP = EditorUtils.CommandLineHasArg(nameof(Enum_Build_CommandLine_Arg.IL2CPP)); - bool ONLY_EXPORT_PROJECT = EditorUtils.CommandLineHasArg(nameof(Enum_Build_CommandLine_Arg.ENABLE_HE_SDK)) || EditorUtils.CommandLineHasArg(nameof(Enum_Build_CommandLine_Arg.ONLY_EXPORT_PROJECT)); - - if (IL2CPP) - BuildResourceAndPlayer_Standard(); - else - BuildResourceAndPlayer_Fast(); - - await WaitBuildTask(); - - EditorUtils.CommandLineSaveError(); - EditorApplication.Exit(0); - } - - } -} - diff --git a/Assets/URS/YooAsset/Editor/Build.FromCommandLine.cs.meta b/Assets/URS/YooAsset/Editor/Build.FromCommandLine.cs.meta deleted file mode 100644 index 577507d..0000000 --- a/Assets/URS/YooAsset/Editor/Build.FromCommandLine.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6b8b963effca200408cc14454d4ddf0d -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/Build.cs b/Assets/URS/YooAsset/Editor/Build.cs index 5ee364e..f863dd6 100644 --- a/Assets/URS/YooAsset/Editor/Build.cs +++ b/Assets/URS/YooAsset/Editor/Build.cs @@ -22,11 +22,9 @@ using YooAsset; using UnityEditor.Build.Content; using BuildCompression = UnityEngine.BuildCompression; -using UnityEditor.Search; using Context = System.Collections.Generic.Dictionary; using Debug = UnityEngine.Debug; using URS.Editor; -using MHLab.Patch.Core.IO; namespace URS { @@ -44,7 +42,7 @@ public static void BuildUpdate() { if (_buildTaskWorkSpaces.Count > 0) { - for (int i = _buildTaskWorkSpaces.Count-1; i >=0; i--) + for (int i = _buildTaskWorkSpaces.Count - 1; i >= 0; i--) { var ws = _buildTaskWorkSpaces[i]; ws.Update(); @@ -65,134 +63,181 @@ public static void AddBuildTaskWorkSpace(BuildTaskWorkSpace ws) static void SetScriptingImplementation(ScriptingImplementation type) { PlayerSettings.SetScriptingBackend(EditorUserBuildSettings.selectedBuildTargetGroup, type); + if (type == ScriptingImplementation.IL2CPP) + { + PlayerSettings.Android.targetArchitectures = AndroidArchitecture.ARMv7 | AndroidArchitecture.ARM64; + } } - [MenuItem("URS/Build(Resource And Player)-(Mono)")] - public static void BuildResourceAndPlayer_Fast() + public static bool BuildResourceAndPlayer_Fast_Config() { + SetScriptingImplementation(ScriptingImplementation.Mono2x); - BuildResourceAndPlayer(); + return true; } - - [MenuItem("URS/Build(Resource And Player)-(IL2CPP)")] - public static void BuildResourceAndPlayer_Standard() + // [MenuItem("URS/Build(Resource And Player)-(Mono)")] + public static void BuildResourceAndPlayer_Fast( + string buildingResourceVersionCode, + string buildInResourceVersionCode, + string channel + + ) + { + var configSuccess = BuildResourceAndPlayer_Fast_Config(); + if (configSuccess) + { + BuildResourceAndPlayer( + buildingResourceVersionCode, + buildInResourceVersionCode, + channel + ); + } + } + public static bool BuildResourceAndPlayer_Standard_Config() { + SetScriptingImplementation(ScriptingImplementation.IL2CPP); - BuildResourceAndPlayer(); + return true; } - - - - public static void BuildResourceAndPlayer() + + public static void BuildResourceAndPlayer_Standard( + string buildingResourceVersionCode, + string buildInResourceVersionCode, + string channel) { - var versionDirectory = GetVersionDirectory(); - var context = new Context(); - context[BuildTask.CONTEXT_VERSION_DIRECTORY] = versionDirectory; - context[BuildTask.CONTEXT_COPY_STREAM_TARGET_VERSION] = URSEditorUserSettings.instance.BuildVersionCode; - var buildWS = new BuildTaskWorkSpace(); - buildWS.Init(context); - // buildWS.EnqueueTask(new BuildTaskDiableDatabaseAutoSave()); - buildWS.EnqueueTask(new BuildTaskClearTargetVersion()); - RegisterBuildBundleTask(buildWS); - buildWS.EnqueueTask(new BuildTaskBuildRaw()); - buildWS.EnqueueTask(new BuildTaskGenerateVersion()); - buildWS.EnqueueTask(new BuildTaskCopyLatestResourceToStreamAsset()); - buildWS.EnqueueTask(new BuilTaskAppId()); - // buildWS.EnqueueTask(new BuilTaskRecoverAssetDatabaseAutoSave()); - buildWS.EnqueueTask(new BuildTaskBuildPlayer()); - AddBuildTaskWorkSpace(buildWS); + var configSuccess = BuildResourceAndPlayer_Standard_Config(); + if (configSuccess) + { + BuildResourceAndPlayer( + buildingResourceVersionCode, + buildInResourceVersionCode, + channel + ); + } } - [MenuItem("URS/BuildPlayer")] - public static void BuildPlayer() + public static bool ExportAndroidProject_Mono_Config() { - var versionDirectory = GetVersionDirectory(); - var context = new Context(); - var buildWS = new BuildTaskWorkSpace(); - buildWS.Init(context); - buildWS.EnqueueTask(new BuildTaskBuildPlayer()); - AddBuildTaskWorkSpace(buildWS); + + SetScriptingImplementation(ScriptingImplementation.Mono2x); + return true; } - [MenuItem("URS/BuildBundleAndRaw.ThenCopyToStream")] - public static void BuildResource() + public static void ExportAndroidProject_Mono( + string buildingResourceVersionCode, + string buildInResourceVersionCode, + string channel) { - var versionDirectory = GetVersionDirectory(); - var context = new Context(); - context[BuildTask.CONTEXT_VERSION_DIRECTORY] = versionDirectory; - context[BuildTask.CONTEXT_COPY_STREAM_TARGET_VERSION] = URSEditorUserSettings.instance.BuildVersionCode; - var buildWS = new BuildTaskWorkSpace(); - buildWS.Init(context); - // buildWS.EnqueueTask(new BuildTaskDiableDatabaseAutoSave()); - buildWS.EnqueueTask(new BuildTaskClearTargetVersion()); - RegisterBuildBundleTask(buildWS); - buildWS.EnqueueTask(new BuildTaskBuildRaw()); - buildWS.EnqueueTask(new BuildTaskGenerateVersion()); - buildWS.EnqueueTask(new BuildTaskCopyLatestResourceToStreamAsset()); - buildWS.EnqueueTask(new BuilTaskAppId()); - // buildWS.EnqueueTask(new BuilTaskRecoverAssetDatabaseAutoSave()); - AddBuildTaskWorkSpace(buildWS); + var configSuccess = ExportAndroidProject_Mono_Config(); + if (configSuccess) + { + BuildResourceAndPlayer( + buildingResourceVersionCode, + buildInResourceVersionCode, + channel + ); + } } - [MenuItem("URS/BuildBundleAndRaw")] - public static void BuildBundleAndRaw() + public static bool ExportAndroidProject_IL2CPP_Config() { - var versionDirectory = GetVersionDirectory(); - var context = new Context(); - context[BuildTask.CONTEXT_VERSION_DIRECTORY] = versionDirectory; - context[BuildTask.CONTEXT_COPY_STREAM_TARGET_VERSION] = URSEditorUserSettings.instance.BuildVersionCode; - var buildWS = new BuildTaskWorkSpace(); - buildWS.Init(context); - // buildWS.EnqueueTask(new BuildTaskDiableDatabaseAutoSave()); - buildWS.EnqueueTask(new BuildTaskClearTargetVersion()); - RegisterBuildBundleTask(buildWS); - buildWS.EnqueueTask(new BuildTaskBuildRaw()); - buildWS.EnqueueTask(new BuildTaskGenerateVersion()); - buildWS.EnqueueTask(new BuilTaskAppId()); - AddBuildTaskWorkSpace(buildWS); + + SetScriptingImplementation(ScriptingImplementation.IL2CPP); + return true; } - [MenuItem("URS/BuildBundle")] - public static void OnlyBuildBundle() + public static void ExportAndroidProject_IL2CPP( + string buildingResourceVersionCode, + string buildInResourceVersionCode, + string channel) { - var versionDirectory = GetVersionDirectory(); - var context = new Context(); - context[BuildTask.CONTEXT_VERSION_DIRECTORY] = versionDirectory; - var buildWS = new BuildTaskWorkSpace(); - buildWS.Init(context); - buildWS.EnqueueTask(new BuildTaskDiableDatabaseAutoSave()); - buildWS.EnqueueTask(new BuildTaskClearTargetVersion()); - //buildWS.EnqueueTask(new BuildTaskComplierLua()); - RegisterBuildBundleTask(buildWS); - buildWS.EnqueueTask(new BuildTaskGenerateVersion()); - buildWS.EnqueueTask(new BuilTaskAppId()); - // buildWS.EnqueueTask(new BuildTaskCopyLatestResourceToStreamAsset()); - buildWS.EnqueueTask(new BuilTaskRecoverAssetDatabaseAutoSave()); - AddBuildTaskWorkSpace(buildWS); + var configSuccess = ExportAndroidProject_IL2CPP_Config(); + if (configSuccess) + { + BuildResourceAndPlayer( + buildingResourceVersionCode, + buildInResourceVersionCode, + channel + ); + } } - [MenuItem("URS/BuildRaw")] - public static void BuildRawResourceCommand() + public static void HybridBuild( + string buildingResourceVersionCode, + string buildInResourceVersionCode, + string channel, + bool buildResourceVersion, + bool buildRaw, + bool copyBuildInRes, + bool buildPlayer, + bool debug) { - var versionDirectory = GetVersionDirectory(); + var versionDirectory = GetVersionDirectory(channel, buildingResourceVersionCode); var context = new Context(); + context[BuildTask.CONTEXT_VERSION_ROOT_DIRECTORY] = GetVersionRoot(channel); ; context[BuildTask.CONTEXT_VERSION_DIRECTORY] = versionDirectory; - context[BuildTask.CONTEXT_COPY_STREAM_TARGET_VERSION] = URSEditorUserSettings.instance.BuildVersionCode; + context[BuildTask.CONTEXT_COPY_STREAM_TARGET_VERSION] = buildInResourceVersionCode; + context[BuildTask.CONTEXT_BUILDING_VERSION] = buildingResourceVersionCode; + context[BuildTask.CONTEXT_CHANNEL] = channel; + context[BuildTask.CONTEXT_DEBUG] = debug; var buildWS = new BuildTaskWorkSpace(); buildWS.Init(context); - buildWS.EnqueueTask(new BuildTaskClearTargetVersion()); - buildWS.EnqueueTask(new BuildTaskBuildRaw()); - buildWS.EnqueueTask(new BuildTaskGenerateVersion()); - buildWS.EnqueueTask(new BuilTaskAppId()); + if (buildResourceVersion) + { + buildWS.EnqueueTask(new BuildTaskClearTargetVersion()); + RegisterBuildBundleTask(buildWS); + if (buildRaw) + { + buildWS.EnqueueTask(new BuildTaskBuildRaw()); + } + buildWS.EnqueueTask(new BuildTaskGenerateVersion()); + } + + if (copyBuildInRes) + { + buildWS.EnqueueTask(new BuildTaskCopyLatestResourceToStreamAsset(buildPlayer)); + } + buildWS.EnqueueTask(new BuildTaskChannelId()); + if (buildPlayer) + { + buildWS.EnqueueTask(new BuildTaskBuildPlayer()); + } + // buildWS.EnqueueTask(new BuilTaskRecoverAssetDatabaseAutoSave()); + AddBuildTaskWorkSpace(buildWS); } - [MenuItem("URS/CopySettingVersionToStreamAsset")] - public static void CopyResourceToStreamAsset() + + public static void BuildPlayerWithBuildInResource( + string buildInResourceVersionCode, + string channel) { + // var versionDirectory = GetVersionDirectory(channel, buildingResourceVersionCode); var context = new Context(); - context[BuildTask.CONTEXT_VERSION_DIRECTORY] = GetVersionDirectory(); ; - context[BuildTask.CONTEXT_COPY_STREAM_TARGET_VERSION] = GetSettingCopyToStreamTargetVersion(); + context[BuildTask.CONTEXT_VERSION_ROOT_DIRECTORY] = GetVersionRoot(channel); ; + context[BuildTask.CONTEXT_COPY_STREAM_TARGET_VERSION] = buildInResourceVersionCode; + context[BuildTask.CONTEXT_CHANNEL] = channel; var buildWS = new BuildTaskWorkSpace(); buildWS.Init(context); - buildWS.EnqueueTask(new BuildTaskCopyLatestResourceToStreamAsset()); - buildWS.EnqueueTask(new BuilTaskAppId()); + buildWS.EnqueueTask(new BuildTaskCopyLatestResourceToStreamAsset(true)); + buildWS.EnqueueTask(new BuildTaskChannelId()); + // buildWS.EnqueueTask(new BuilTaskRecoverAssetDatabaseAutoSave()); + buildWS.EnqueueTask(new BuildTaskBuildPlayer()); AddBuildTaskWorkSpace(buildWS); } + //[MenuItem("URS/BuildPlayer")] + public static void BuildResourceAndPlayer( + string buildingResourceVersionCode, + string buildInResourceVersionCode, + string channel) + { + HybridBuild( + buildingResourceVersionCode, + buildInResourceVersionCode, + channel, + true, + true, + true, + true, + false); + } + + + [MenuItem("URS/UpdateCollection")] public static void UpdateCollection() { @@ -202,17 +247,7 @@ public static void UpdateCollection() buildWS.EnqueueTask(new BuildTaskUpdateCollection()); AddBuildTaskWorkSpace(buildWS); } - [MenuItem("URS/ClearTargetVersion")] - public static void ClearTargetVersion() - { - var versionDirectory = GetVersionDirectory(); - var context = new Context(); - context[BuildTask.CONTEXT_VERSION_DIRECTORY] = versionDirectory; - var buildWS = new BuildTaskWorkSpace(); - buildWS.Init(context); - buildWS.EnqueueTask(new BuildTaskClearTargetVersion()); - AddBuildTaskWorkSpace(buildWS); - } + [MenuItem("URS/ShowAssetBundleBrowser")] public static void ShowAssetBundleBrowser() { @@ -237,86 +272,149 @@ public static void ExportShaderVariantCollection() AddBuildTaskWorkSpace(buildWS); } - [MenuItem("URS/CleanMaterialPropertys")] - public static void CleanMaterialPropertys() + public static void ValidateAsset(bool validateMaterial, bool validateModel,bool validateParticleSystem,bool validateAnimation) { var context = new Context(); var buildWS = new BuildTaskWorkSpace(); buildWS.Init(context); buildWS.EnqueueTask(new BuildTaskUpdateCollection()); buildWS.EnqueueTask(new BuildTaskCollectAsset()); - buildWS.EnqueueTask(new BuildTaskMaterialCleaner()); + if (validateMaterial) + { + buildWS.EnqueueTask(new BuildTaskValidateMaterial()); + } + if (validateModel) { + buildWS.EnqueueTask(new BuildTaskValidateModel()); + } + if (validateParticleSystem) + { + buildWS.EnqueueTask(new BuildTaskValidateParticleSystem()); + } + if (validateAnimation) + { + buildWS.EnqueueTask(new BuildTaskValidateAnimation()); + } + AddBuildTaskWorkSpace(buildWS); } + [MenuItem("URS/ClearBundleCache")] public static void ClearBundleCache() { BuildCache.PurgeCache(false); } - - - [MenuItem("URS/BuildChannelRouterAndPatch")] - public static void BuildChannelRouter() + + public static void BuildAutoChannelVersionsAndUploadCDN( + string channel, + string channelTargetVersion = "", + int versionKeepCount=4, + bool uploadCDN=false, + bool debug = false) { var context = new Context(); + context[BuildTask.CONTEXT_VERSION_ROOT_DIRECTORY] = GetVersionRoot(channel); ; + context[BuildTask.CONTEXT_CHANNEL] = channel; + context[BuildTask.CONTEXT_CHANNEL_TARGET_VERSION] = channelTargetVersion; + context[BuildTask.CONTEXT_VERSION_KEEP_COUNT] = versionKeepCount; + context[BuildTask.CONTEXT_DEBUG] = debug; var buildWS = new BuildTaskWorkSpace(); buildWS.Init(context); - buildWS.EnqueueTask(new BuildTaskChannelRouter()); - buildWS.EnqueueTask(new BuildTaskBuildPatch()); + buildWS.EnqueueTask(new BuildChannelVersions()); + buildWS.EnqueueTask(new BuildTaskAutoAppVersionRouter()); + if (uploadCDN) + { + buildWS.EnqueueTask(GenUploadCdnBuildTask(channel)); + } + AddBuildTaskWorkSpace(buildWS); } + + [MenuItem("URS/BuildAppId")] - public static void BuildAppId() + public static void BuildChannelId( + string buildingResourceVersionCode, + string buildInResourceVersionCode, + string channel) { + var versionDirectory = GetVersionDirectory(channel, buildingResourceVersionCode); var context = new Context(); + context[BuildTask.CONTEXT_VERSION_ROOT_DIRECTORY] = GetVersionRoot(channel); ; + context[BuildTask.CONTEXT_VERSION_DIRECTORY] = versionDirectory; + context[BuildTask.CONTEXT_COPY_STREAM_TARGET_VERSION] = buildInResourceVersionCode; + context[BuildTask.CONTEXT_CHANNEL] = channel; var buildWS = new BuildTaskWorkSpace(); buildWS.Init(context); - buildWS.EnqueueTask(new BuilTaskAppId()); + buildWS.EnqueueTask(new BuildTaskChannelId()); AddBuildTaskWorkSpace(buildWS); } - public static void RegisterBuildBundleTask(BuildTaskWorkSpace workSpace,bool combineShareBundle= true) + + public static void RegisterBuildBundleTask(BuildTaskWorkSpace workSpace, bool combineShareBundle = true) { workSpace.EnqueueTask(new BuildTaskUpdateCollection()); workSpace.EnqueueTask(new BuildTaskBeforeShaderComplier()); workSpace.EnqueueTask(new BuildTaskCollectAsset()); workSpace.EnqueueTask(new BuildTaskGenerateBundleLayout()); workSpace.EnqueueTask(new BuildTaskBuidBundle()); - if (combineShareBundle) + if (combineShareBundle) { workSpace.EnqueueTask(new BuildTaskRegenerateAssetBundleName()); workSpace.EnqueueTask(new BuildTaskGenerateBundleLayout()); + workSpace.EnqueueTask(new BuildTaskOptimizeShareAssetBundleName()); workSpace.EnqueueTask(new BuildTaskReBuildAssetBundle()); } workSpace.EnqueueTask(new BuildTaskCopyAsssetBundle()); workSpace.EnqueueTask(new BuildTaskAfterShaderComplier()); } - public static string GetVersionDirectory() + private static string GetVersionDirectory( string channel,string buildingResourceVersionCode) { - var setting= URSEditorUserSettings.instance; - return $"{GetVersionRoot()}/{setting.BuildVersionCode}"; + // var setting = URSEditorUserSettings.instance; + return $"{GetVersionRoot(channel)}/{buildingResourceVersionCode}"; } - public static string GetVersionRoot() + private static string GetVersionRoot(string channel) { - var setting = URSEditorUserSettings.instance; - return $"{GetChannelRoot()}/{setting.BuildChannel}/{URS.PlatformMappingService.GetPlatformPathSubFolder()}"; + // var setting = URSEditorUserSettings.instance; + return $"{GetChannelRoot()}/{channel}/{URS.PlatformMappingService.GetPlatformPathSubFolder()}"; } public static string GetChannelRoot() { return $"URS/channels"; } - public static string GetSettingCopyToStreamTargetVersion() { - var setting = URSEditorUserSettings.instance; - return setting.CopyToStreamTargetVersion; + + public static string GetBuildInResourceTempFolder() + { + return $"URS/temp_buildin_resource"; } public static string GetTempBundleOutDirectoryPath() { return $"URS/temp_bundle_out/{URS.PlatformMappingService.GetPlatformPathSubFolder()}"; } + + public static string GetVersionHistoryFolder(string channel) + { + return $"URS/version_history/{channel}/{URS.PlatformMappingService.GetPlatformPathSubFolder()}"; + } + + public static string GetShareAssetBundleNameConfigFilePath() + { + return $"URS/ShareAssetBundleName.json"; + } + public static void ExportDefaultURSRuntimeSetting(string SaveDiretoryPath) + { + var defaultSetting = new URSRuntimeSetting(); + var content= UnityEngine.JsonUtility.ToJson(defaultSetting,true); + var savePath = $"{SaveDiretoryPath}/{URSRuntimeSetting.SAVE_RESOUCE_PATH}"; + if (File.Exists(savePath)) { + File.Delete(savePath); + } + File.WriteAllText(savePath, content ); + UnityEditor.AssetDatabase.Refresh(); + UnityEditor.AssetDatabase.SaveAssets(); + } } } diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuidTaskBuildPatch.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuidTaskBuildPatch.cs index ef86bb1..2a87f8b 100644 --- a/Assets/URS/YooAsset/Editor/BuildTask/BuidTaskBuildPatch.cs +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuidTaskBuildPatch.cs @@ -6,13 +6,18 @@ using URS; using URS.Editor; -public class BuildTaskBuildPatch : BuildTask +public class BuildChannelVersions : BuildTask { public override void BeginTask() { base.BeginTask(); - VersionBuilder.BuildChannleVersionPatches(Build.GetChannelRoot()); + var versionRootDirectory = (string)_context[CONTEXT_VERSION_ROOT_DIRECTORY]; + var channelTargetVersion= (string)_context[CONTEXT_CHANNEL_TARGET_VERSION]; + var versionKeepCount = (int)_context[CONTEXT_VERSION_KEEP_COUNT]; + var channel= (string)_context[CONTEXT_CHANNEL]; + var debug= (bool)_context[CONTEXT_DEBUG]; + VersionBuilder.BuildChannelVersions(channel,versionRootDirectory, versionKeepCount, channelTargetVersion, debug); this.FinishTask(); } diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTask.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTask.cs index b2d8adc..bf122b2 100644 --- a/Assets/URS/YooAsset/Editor/BuildTask/BuildTask.cs +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTask.cs @@ -7,16 +7,27 @@ public class BuildTask { public const string CONTEXT_VERSION_DIRECTORY = "version_directory"; + public const string CONTEXT_VERSION_ROOT_DIRECTORY = "version_root_directory"; // public const string CONTEXT_RAW_FILES = "raw_files"; public const string CONTEXT_ASSET_DATABASE_AUTO_SAVE = "asset_database_auto_save"; public const string CONTEXT_ASSET_INFO = "asset_info"; public const string CONTEXT_BUNDLE_INFO = "bundle_info"; public const string CONTEXT_BUNDLE_RESULT = "bundle_result"; + public const string CONTEXT_BUNDLE_LAYOUT = "bundle_layout"; public const string CONTEXT_GLOBAL_BUNDLE_EXTRA_ASSET = "global_bundle_extra_asset"; public const string CONTEXT_SPRITE_CHECHER = "sprite_in_atlas_checker"; public const string CONTEXT_FILE_ADDITION_INFO = "addition_file_info"; public const string CONTEXT_COPY_STREAM_TARGET_VERSION = "copy_stream_target_version"; + public const string CONTEXT_BUILDING_VERSION = "building_version"; + + public const string CONTEXT_CHANNEL = "channel"; + public const string CONTEXT_CHANNEL_TARGET_VERSION = "channel_target_version"; + public const string CONTEXT_VERSION_KEEP_COUNT = "version_keep_count"; + public const string CONTEXT_VERSION_HISTORY = "version_history"; + public const string CONTEXT_VERSION_BUNDLE_HASH = "version_hash"; + public const string CONTEXT_DEBUG = "debug"; + //public const string TEMP_VERSION_DIRECTORY = "temp_version_directory"; @@ -30,15 +41,15 @@ public void SetContext(Context context) { _context = context; } - public T GetData(string key) where T : class { + public T GetData(string key) { if (_context.ContainsKey(key)) { var ob = (_context[key]); - return ob as T; + return (T)ob ; } return default(T); } - + public T GetOrAddData(string key) where T : class, new() { if (_context.ContainsKey(key)) diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskAppId.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskAppId.cs index 4718ca2..e8745d6 100644 --- a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskAppId.cs +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskAppId.cs @@ -4,20 +4,19 @@ using System.IO; using System; -public class BuilTaskAppId : BuildTask +public class BuildTaskChannelId : BuildTask { public override void BeginTask() { base.BeginTask(); - var streamSandboxFolderName = YooAsset.AssetPathHelper.GetStreamingSandboxDirectory(); - - var appFilePath = $"{YooAsset.AssetPathHelper.GetStreamingSandboxDirectory()}/{URSRuntimeSetting.instance.AppIdFileName}" ; - Directory.CreateDirectory(System.IO.Path.GetDirectoryName(appFilePath)); - if (File.Exists(appFilePath)) + var channelFilePath = $"{YooAsset.AssetPathHelper.GetBuildInChannelFilePath()}" ; + Directory.CreateDirectory(System.IO.Path.GetDirectoryName(channelFilePath)); + if (File.Exists(channelFilePath)) { - File.Delete(appFilePath); + File.Delete(channelFilePath); } - File.WriteAllText(appFilePath, URSEditorUserSettings.instance.AppId); + var channel = GetData(CONTEXT_CHANNEL); + File.WriteAllText(channelFilePath, channel); UnityEditor.AssetDatabase.Refresh(); UnityEditor.AssetDatabase.SaveAssets(); this.FinishTask(); diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskBuidBundle.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskBuidBundle.cs index 92b03fd..2d93845 100644 --- a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskBuidBundle.cs +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskBuidBundle.cs @@ -34,7 +34,7 @@ public URSBundleBuildParameters(BuildTarget target, BuildTargetGroup group, stri DisableVisibleSubAssetRepresentations = false; - BundleCompression = BuildCompression.LZ4Runtime; + BundleCompression = BuildCompression.LZ4; ContentBuildFlags = ContentBuildFlags.None; @@ -111,12 +111,26 @@ public class AssetInfo // public string resourceGroup; public bool isMain = false; public int refrenceCount = 0; + + public List shareReferencedMainAssets = null; public List mainAssetDependencys = null; public HashSet assetBundleNames = null; public string shareCombineAssetBundleName = null; + + public string optimizedShareAssetBundleName = null; + private bool forceNoBundleName = false; + + public void AddShareReferencedMainAssets(string path) + { + + if (shareReferencedMainAssets == null) { + shareReferencedMainAssets= new List(); + } + shareReferencedMainAssets.Add(path); + } public bool HasAssetBundleName() { if (forceNoBundleName) @@ -159,6 +173,10 @@ public string GetAssetBundleName() } else { + if (!string.IsNullOrEmpty(optimizedShareAssetBundleName)) + { + return optimizedShareAssetBundleName; + } if (!string.IsNullOrEmpty(shareCombineAssetBundleName)) { return shareCombineAssetBundleName; @@ -264,6 +282,8 @@ public ReturnCode BuildBundleResource() buildTasks.Add(extractData); var generation = new BuildLayoutGenerationTask(); buildTasks.Add(generation); + var checkHash = new BuidTaskCheckBundleHash(); + buildTasks.Add(checkHash); var targetGroup = BuildPipeline.GetBuildTargetGroup(UnityEditor.EditorUserBuildSettings.activeBuildTarget); var target = UnityEditor.EditorUserBuildSettings.activeBuildTarget; var outFolder = Build.GetTempBundleOutDirectoryPath(); @@ -298,7 +318,8 @@ public ReturnCode BuildBundleResource() } File.WriteAllText(manifestFileName, manifest.ToString()); SetData(CONTEXT_BUNDLE_RESULT, results); - + SetData(CONTEXT_BUNDLE_LAYOUT, generation.LayoutLookupTables); + SetData(CONTEXT_VERSION_BUNDLE_HASH, checkHash.BundleHash); return ReturnCode.Success; } diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskBuildPlayer.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskBuildPlayer.cs index 73efa56..472e949 100644 --- a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskBuildPlayer.cs +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskBuildPlayer.cs @@ -14,6 +14,7 @@ using UnityEditor.Callbacks; using UnityEditor.SceneManagement; using Debug = UnityEngine.Debug; +using NinjaBeats; public class BuildTaskBuildPlayer : BuildTask { @@ -65,6 +66,7 @@ private static void BuildPlayer(bool debug) return; BuildOptions options = BuildOptions.None; + options |= BuildOptions.CompressWithLz4; if (EditorUserBuildSettings.development) { debug = true; @@ -126,9 +128,13 @@ private static bool CleanupTempData(BuildTarget target) { try { - var iosProjectPath = Path.Combine(Application.dataPath, "../Build/iOSProject"); - if (Directory.Exists(iosProjectPath)) - Directory.Delete(iosProjectPath, true); + var path = Path.Combine(Application.dataPath, "../Build/iOSProject/Data/Raw/"); + if (Directory.Exists(path)) + Directory.Delete(path, true); + + path = Path.Combine(Application.dataPath, "../Build/iOSProject/ExportIpa/"); + if (Directory.Exists(path)) + Directory.Delete(path, true); } catch (Exception e) { @@ -148,12 +154,12 @@ public static void OnPostprocessBuild(BuildTarget buildTarget, string pathToBuil { if (buildTarget == BuildTarget.iOS) { - var CHANNEL = EditorUtils.CommandLineGetArgValue(nameof(Enum_Build_CommandLine_Arg.CHANNEL)); - if (string.IsNullOrEmpty(CHANNEL)) - CHANNEL = "dev_ios"; + var HESDK_CHANNEL = EditorUtils.CommandLineGetArgValue(nameof(CommandLine.Enum_Build_CommandLine_Arg.HESDK_CHANNEL)); + if (string.IsNullOrEmpty(HESDK_CHANNEL)) + HESDK_CHANNEL = "dev_ios"; var productName = PlayerSettings.productName; - var APP_IDENTIFIER = EditorUtils.CommandLineGetArgValue(nameof(Enum_Build_CommandLine_Arg.APP_IDENTIFIER)); + var APP_IDENTIFIER = EditorUtils.CommandLineGetArgValue(nameof(CommandLine.Enum_Build_CommandLine_Arg.APP_IDENTIFIER)); if (!string.IsNullOrEmpty(APP_IDENTIFIER) && APP_IDENTIFIER.IndexOf('.') != -1) productName = APP_IDENTIFIER.Substring(APP_IDENTIFIER.LastIndexOf('.') + 1); @@ -170,7 +176,7 @@ public static void OnPostprocessBuild(BuildTarget buildTarget, string pathToBuil var MMNViOSCoreHapticsInterfacePath = Path.Combine(pathToBuiltProject, "Libraries/Packages/NiceVibrations/Common/Plugins/iOS/Swift/MMNViOSCoreHapticsInterface.mm"); var MMNViOSCoreHapticsInterface = File.ReadAllText(MMNViOSCoreHapticsInterfacePath); MMNViOSCoreHapticsInterface = MMNViOSCoreHapticsInterface.Replace("\"UnityFramework/UnityFramework-Swift.h\"", - $"<{productName}_UnityFramework_{CHANNEL}/{productName}_UnityFramework_{CHANNEL}-Swift.h>"); + $"<{productName}_UnityFramework_{HESDK_CHANNEL}/{productName}_UnityFramework_{HESDK_CHANNEL}-Swift.h>"); File.WriteAllText(MMNViOSCoreHapticsInterfacePath, MMNViOSCoreHapticsInterface); #endif } @@ -180,7 +186,7 @@ private static bool BuildFinalTarget(BuildTarget target, string finalTargetName) { if (EditorUserBuildSettings.exportAsGoogleAndroidProject && target == BuildTarget.Android) { - if (EditorUtils.CommandLineHasArg(nameof(Enum_Build_CommandLine_Arg.ONLY_EXPORT_PROJECT))) + if (EditorUtils.CommandLineHasArg(nameof(CommandLine.Enum_Build_CommandLine_Arg.ONLY_EXPORT_PROJECT))) return true; #if UNITY_EDITOR_WIN || UNITY_EDITOR_OSX @@ -255,8 +261,17 @@ private static bool BuildFinalTarget(BuildTarget target, string finalTargetName) private static void GetBuildTargetName(BuildTarget target, out string middleTargetName, out string finalTargetName) { - var productName = PlayerSettings.productName + "-v" + PlayerSettings.bundleVersion ; - finalTargetName = string.Format("/{0}-{1}", productName, GetTimeForNow()); + var ENABLE_HESDK = false; // ~~! + if (!ENABLE_HESDK) + { + finalTargetName = "/dev-release"; + } + else + { + var productName = PlayerSettings.productName + "-v" + PlayerSettings.bundleVersion ; + finalTargetName = string.Format("/{0}-{1}", productName, GetTimeForNow()); + } + switch (target) { case BuildTarget.Android: diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskChannelRouter.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskChannelRouter.cs index b7ba596..e7a568d 100644 --- a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskChannelRouter.cs +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskChannelRouter.cs @@ -5,20 +5,18 @@ using System.IO; using System; using URS; +using URS.Editor; -public class BuildTaskChannelRouter : BuildTask +public class BuildTaskAutoAppVersionRouter : BuildTask { public override void BeginTask() { base.BeginTask(); - var routerFilePath = $"{Build.GetChannelRoot()}/{URSRuntimeSetting.instance.RemoteAppToChannelRouterFileName}"; - Directory.CreateDirectory(System.IO.Path.GetDirectoryName(routerFilePath)); - if (File.Exists(routerFilePath)) - { - File.Delete(routerFilePath); - } - File.WriteAllText(routerFilePath, JsonUtility.ToJson(URSEditorUserSettings.instance.AppToChannelRouter,true)); + var versionRootDirectory = (string)_context[CONTEXT_VERSION_ROOT_DIRECTORY]; + var channelTargetVersion = (string)_context[CONTEXT_CHANNEL_TARGET_VERSION]; + VersionBuilder.BuildAutoAppVersionRouter(versionRootDirectory, channelTargetVersion); + this.FinishTask(); } diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskClearTargetVersion.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskClearTargetVersion.cs index 3beab7c..4e75c8a 100644 --- a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskClearTargetVersion.cs +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskClearTargetVersion.cs @@ -17,8 +17,8 @@ public override void BeginTask() Directory.Delete(path, true); } - var versionRoot= Build.GetVersionRoot(); - + var versionRoot= (string)_context[CONTEXT_VERSION_ROOT_DIRECTORY]; ; + var buildingVersion = GetData(CONTEXT_BUILDING_VERSION); if (Directory.Exists(versionRoot)) { var di = new DirectoryInfo(versionRoot); @@ -27,7 +27,7 @@ public override void BeginTask() var name = subDirectory.Name; var names = name.Split("---"); var versionCode = names[0]; - if (versionCode == URSEditorUserSettings.instance.BuildVersionCode) + if (versionCode == buildingVersion) { Directory.Delete(subDirectory.FullName, true); } diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskCollectAsset.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskCollectAsset.cs index faae70c..4fe87dc 100644 --- a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskCollectAsset.cs +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskCollectAsset.cs @@ -29,7 +29,7 @@ public class BuildTaskCollectAsset : BuildTask public override void BeginTask() { base.BeginTask(); - var shadervaraintCollectionPath = "Assets/GameResources/ShaderVarians/ShaderVariantCollection.shadervariants"; + var shadervaraintCollectionPath = URS.URSShaderVariantConstant.SHADER_VARIANT_SAVE_PATH; CollectAssets(true, shadervaraintCollectionPath); this.FinishTask(); } @@ -39,7 +39,7 @@ public void CollectAssets(bool combineShareShader = true, string shadervaraintCo #if SPRITE_STRIP BuildTaskStripSpriteInAtlas.Checker checker = GetOrAddData(CONTEXT_SPRITE_CHECHER); #endif - EditorUtility.DisplayProgressBar("CollectAssets", "Դ", 0); + EditorUtility.DisplayProgressBar("CollectAssets", "整理资源", 0); var dependencyCache = new Dictionary>(); System.Func> getDependencys = (string assetPath) => { @@ -85,7 +85,7 @@ public void CollectAssets(bool combineShareShader = true, string shadervaraintCo { var first = assets[item.AssetPath]; var second = collection; - Debug.LogErrorFormat("2ظռԴ Դ· {0}һֻӦõһ", item.AssetPath); + Debug.LogErrorFormat("存在2个组重复收集的资源 资源路径 {0},这种情况一下只会应用第一组的配置", item.AssetPath); } else { @@ -128,6 +128,7 @@ public void CollectAssets(bool combineShareShader = true, string shadervaraintCo if (shareShaderAssets.ContainsKey(referenceAsset)) { var shaderAsset = shareShaderAssets[referenceAsset]; + shaderAsset.refrenceCount++; shaderAsset.customTag.UnionWith(mainAssetTag); } else @@ -163,6 +164,39 @@ public void CollectAssets(bool combineShareShader = true, string shadervaraintCo }; shareShaderAssets[shadervaraintCollectionPath]= shaderVaraintCollectionAssetInfo; + var warmShadeerJsonFilePath = URSShaderVariantConstant.WARM_SHADER_JSON_FILE; + if (File.Exists(warmShadeerJsonFilePath)) + { + var warmShaderVariantJsonInfo = new AssetInfo() + { + assetPath = warmShadeerJsonFilePath, + assetBundleNames = new HashSet(new string[] { "share_shader.bundle" }), + customTag = shaderVaraintCollectionTag, + isMain = true, + refrenceCount = 1, + mainAssetDependencys = getDependencys(warmShadeerJsonFilePath) + }; + shareShaderAssets[warmShadeerJsonFilePath] = warmShaderVariantJsonInfo; + + var warmShaderVariants = UnityEngine.JsonUtility.FromJson(File.ReadAllText(URSShaderVariantConstant.WARM_SHADER_JSON_FILE)); + var warmShaderVariantPaths = warmShaderVariants.paths; + if (warmShaderVariantPaths != null) + { + foreach (var warmShaderVariantPath in warmShaderVariantPaths) + { + var warmShaderVariantInfo = new AssetInfo() + { + assetPath = warmShaderVariantPath, + assetBundleNames = new HashSet(new string[] { "share_shader.bundle" }), + customTag = shaderVaraintCollectionTag, + isMain = true, + refrenceCount = 1, + mainAssetDependencys = getDependencys(warmShaderVariantPath) + }; + shareShaderAssets[warmShaderVariantPath] = warmShaderVariantInfo; + } + } + } foreach (var item in shareShaderAssets) { assets[item.Key] = item.Value; @@ -187,6 +221,7 @@ public void CollectAssets(bool combineShareShader = true, string shadervaraintCo isMain = false, refrenceCount = 1, }; + dpInfo.AddShareReferencedMainAssets(assetInfo.assetPath); dependencyAssets[dp] = dpInfo; } else @@ -195,6 +230,7 @@ public void CollectAssets(bool combineShareShader = true, string shadervaraintCo dpInfo.assetBundleNames.UnionWith(assetInfo.assetBundleNames); dpInfo.customTag.UnionWith(assetInfo.customTag); dpInfo.refrenceCount = dpInfo.refrenceCount + 1; + dpInfo.AddShareReferencedMainAssets(assetInfo.assetPath); } } } @@ -208,6 +244,10 @@ public void CollectAssets(bool combineShareShader = true, string shadervaraintCo { bool remove = false; var extension= Path.GetExtension(path); + if (path.Contains("/Resources/")) + { + Debug.LogWarning("出现AB 引用Resource的情况,建议ab的引用都不要放到Resource文件夹 :::"+ path); + } if (extension==".cs") { remove = true; @@ -279,7 +319,7 @@ public static string ExtractAssetBundleName(LibraryItem item, LibraryCollection assetBundleName = $"{GetParentDiretoryName(item)}_{selfName}.bundle"; break; } - /// ԷְҪ󣬿չ + /// 如果对分包有特殊的要求,可以在这里扩展 } } } diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskCopyAsssetBundle.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskCopyAsssetBundle.cs index 9ded448..bc81d24 100644 --- a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskCopyAsssetBundle.cs +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskCopyAsssetBundle.cs @@ -22,6 +22,7 @@ using UnityEditor.Search; using Context = System.Collections.Generic.Dictionary; using MHLab.Patch.Core.Utilities; +using URS.Editor; public class BuildTaskCopyAsssetBundle : BuildTask { @@ -34,8 +35,64 @@ public override void BeginTask() var results = GetData(CONTEXT_BUNDLE_RESULT); GenerateBundleManifest(outFolder, results, bundleInfo, assets, out var bundleManifest); CopyBundleFilesToVersionFolder(outFolder, bundleManifest); + var debug = GetData(CONTEXT_DEBUG); + var bundleLayout = GetData(CONTEXT_BUNDLE_LAYOUT); + var bundleHash = GetData(CONTEXT_VERSION_BUNDLE_HASH); + if (debug) + { + GenerateVersionHistory(outFolder,assets, bundleInfo, results, bundleLayout, bundleHash); + } this.FinishTask(); } + + public void GenerateVersionHistory(string bundleOutDirectory, Dictionary assetInfos, Dictionary bundleInfos, IBundleBuildResults bundleDetail, LayoutLookupTables bundleLayout,BundleHash bundleHash) + { + var versionHistory = GetOrAddData(CONTEXT_VERSION_HISTORY); + versionHistory.AssetVersion = new AssetVersionHistory(); + versionHistory.AssetBundleVersion= new AssetBundleVersionHistory(); + versionHistory.BundleLayout = bundleLayout; + versionHistory.BundleHash= bundleHash; + + var buidLogFilePath = $"{bundleOutDirectory}/buildlogtep.json"; + if (File.Exists(buidLogFilePath)) + { + versionHistory.BundleBuildLog= File.ReadAllText(buidLogFilePath) ; + } + List items= new List(); + foreach (var kv in assetInfos) + { + var assetInfo = kv.Value; + var assetVersionItem = new AssetVersionItem() + { + AssetPath = assetInfo.assetPath, + AssetFileHash = Hashing.GetFileXXhash(assetInfo.assetPath), + HasAssetBundleName = assetInfo.HasAssetBundleName(), + }; + if (assetInfo.HasAssetBundleName()) + { + assetVersionItem.AssetBundleName= assetInfo.GetAssetBundleName(); + } + items.Add(assetVersionItem); + } + versionHistory.AssetVersion.Assets= items.ToArray(); + + + List abItems = new List(); + foreach (var kv in bundleInfos) + { + var bundleInfo = kv.Value; + var bundleName = bundleInfo.bundleName; + var detail = bundleDetail.BundleInfos[bundleName]; + var assetBundleVersionItem = new AssetBundleVersionItem() + { + BundleName = bundleInfo.bundleName, + AssetPaths = bundleInfo.paths.ToArray(), + }; + abItems.Add(assetBundleVersionItem); + } + versionHistory.AssetBundleVersion.AssetBundles = abItems.ToArray(); + + } public void CopyBundleFilesToVersionFolder(string srcBundleFolder, BundleManifest bundleManifest) { EditorUtility.DisplayProgressBar("CopyBundleFilesToVersionFolder", "ͬµļ", 0); @@ -60,7 +117,7 @@ public void CopyBundleFilesToVersionFolder(string srcBundleFolder, BundleManifes additionFileInfos = new Dictionary(); SetData(CONTEXT_FILE_ADDITION_INFO, additionFileInfos); } - var rPath = URSRuntimeSetting.instance.BundleManifestFileName; + var rPath = URSRuntimeSetting.instance.BundleManifestFileRelativePath; if (additionFileInfos.ContainsKey(rPath)) { Debug.LogWarning("already exist path " + rPath); @@ -72,7 +129,7 @@ public void CopyBundleFilesToVersionFolder(string srcBundleFolder, BundleManifes IsEncrypted = false, IsUnityBundle = false }; - BundleManifest.Serialize($"{versionDirectory}/{URSRuntimeSetting.instance.BundleManifestFileName}", bundleManifest, true); + BundleManifest.Serialize($"{versionDirectory}/{URSRuntimeSetting.instance.BundleManifestFileRelativePath}", bundleManifest, true); EditorUtility.ClearProgressBar(); } diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskCopyLatestResourceToStreamAsset.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskCopyLatestResourceToStreamAsset.cs index ffcfffb..f500c80 100644 --- a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskCopyLatestResourceToStreamAsset.cs +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskCopyLatestResourceToStreamAsset.cs @@ -1,41 +1,59 @@ -using System.Collections; using System.Collections.Generic; -using UnityEngine; -using UnityEditor; -using Bewildered.SmartLibrary; using System.IO; -using System; -using UnityEditor.Build.Pipeline; -using UnityEditor.Build.Pipeline.Injector; -using UnityEditor.Build.Pipeline.Interfaces; -using UnityEditor.Build.Pipeline.Tasks; -using UnityEditor.Build.Pipeline.Utilities; -using UnityEngine.SceneManagement; -using UnityEditor.SceneManagement; -using TagInfo = System.Collections.Generic.Dictionary; using URS; -using YooAsset.Utility; -using System.Linq; -using YooAsset; -using UnityEditor.Build.Content; -using BuildCompression = UnityEngine.BuildCompression; -using UnityEditor.Search; -using Context = System.Collections.Generic.Dictionary; -using MHLab.Patch.Core.IO; -using MHLab.Patch.Core.Utilities; +using UnityEditor.Build; + +public class StreamingAssetsVersionHook : BuildPlayerProcessor +{ + public static bool Enable = false; + public static string TargetVersion = null; + public override void PrepareForBuild(BuildPlayerContext buildPlayerContext) + { + if (!string.IsNullOrEmpty(TargetVersion)&& Enable) + { + var tempFolder = Build.GetBuildInResourceTempFolder(); + buildPlayerContext.AddAdditionalPathToStreamingAssets(tempFolder, YooAsset.AssetPathHelper.GetURSBuildInResourceFolderName()); + } + } +} public class BuildTaskCopyLatestResourceToStreamAsset : BuildTask { + + public bool _useLazyHook = false; + + public BuildTaskCopyLatestResourceToStreamAsset(bool useLazyHook) + { + _useLazyHook = useLazyHook; + } + public override void BeginTask() { base.BeginTask(); - CopyLatestResourceToStreamAsset(); + var targetVersion = GetData(CONTEXT_COPY_STREAM_TARGET_VERSION); + StreamingAssetsVersionHook.TargetVersion = targetVersion; + StreamingAssetsVersionHook.Enable = _useLazyHook; + var streamTarget = YooAsset.AssetPathHelper.GetURSBuildInResourceFolder(); + if (Directory.Exists(streamTarget)) + { + Directory.Delete(streamTarget,true); + } + var versionRootDirectory = (string)_context[CONTEXT_VERSION_ROOT_DIRECTORY]; + // unity汾֧ buildPlayerContext.AddAdditionalPathToStreamingAssets л CopyLatestResourceToStreamAsset + if (!string.IsNullOrEmpty(targetVersion) && _useLazyHook) + { + var tempFolder = Build.GetBuildInResourceTempFolder(); + BuildTaskCopyLatestResourceToStreamAsset.CopyLatestResourceToStreamAsset(versionRootDirectory,targetVersion, tempFolder, false); + } + else + { + CopyLatestResourceToStreamAsset(versionRootDirectory,targetVersion, YooAsset.AssetPathHelper.GetURSBuildInResourceFolder(), true); + } this.FinishTask(); } - public void CopyLatestResourceToStreamAsset() + public static void CopyLatestResourceToStreamAsset(string versionRootDirectory,string targetVersion, string targetFolder,bool freshAssetDataBase) { - var targetVersionCode = GetData(CONTEXT_COPY_STREAM_TARGET_VERSION); - var versionRootDirectory = Build.GetVersionRoot(); + var targetVersionCode = targetVersion; var di = new DirectoryInfo(versionRootDirectory); foreach (DirectoryInfo subDirectory in di.GetDirectories()) { @@ -54,25 +72,27 @@ public void CopyLatestResourceToStreamAsset() var fm = FileManifest.Deserialize(json); List fileMetas = new List(); fm.GetFileMetaByTag(new string[] { URSRuntimeSetting.instance.BuildinTag }, ref fileMetas); - var streamSandboxFolderName = YooAsset.AssetPathHelper.GetStreamingSandboxDirectory(); - if (Directory.Exists(streamSandboxFolderName)) + if (Directory.Exists((string)targetFolder)) { - Directory.Delete(streamSandboxFolderName, true); + Directory.Delete((string)targetFolder, true); } for (int i = 0; i < fileMetas.Count; i++) { string rlPath = fileMetas[i].RelativePath; string srcPath = $"{versionDirectory}/{rlPath}"; - string dstPath = $"{streamSandboxFolderName}/{rlPath}"; + string dstPath = $"{targetFolder}/{rlPath}"; var dstDirectoryName = Path.GetDirectoryName(dstPath); Directory.CreateDirectory(dstDirectoryName); File.Copy(srcPath, dstPath); } - FileManifest fileManifest = new FileManifest(fileMetas.ToArray()); - string buildinFileManifestPath = $"{streamSandboxFolderName}/{URSRuntimeSetting.instance.FileManifestFileName}"; + FileManifest fileManifest = new FileManifest(fileMetas.ToArray(), versionCode); + string buildinFileManifestPath = $"{targetFolder}/{URSRuntimeSetting.instance.FileManifestFileName}"; FileManifest.Serialize(buildinFileManifestPath, fileManifest, true); - UnityEditor.AssetDatabase.Refresh(); - UnityEditor.AssetDatabase.SaveAssets(); + if (freshAssetDataBase) + { + UnityEditor.AssetDatabase.Refresh(); + UnityEditor.AssetDatabase.SaveAssets(); + } } break; } diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskExportShaderVariantCollection.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskExportShaderVariantCollection.cs index eef7fb3..525cbfd 100644 --- a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskExportShaderVariantCollection.cs +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskExportShaderVariantCollection.cs @@ -6,54 +6,66 @@ using System; using UnityEditor.SceneManagement; using System.Reflection; -using System.Diagnostics; -using System.Text; using Debug = UnityEngine.Debug; +using System.Linq; +using Soco.ShaderVariantsCollection; +using URS; +//using UnityEngine.Rendering.Universal; +using UnityEngine.Rendering; +public class URSMaterials : IMaterialCollector +{ + public List Materials { get; set; } = new List(); + public override void AddMaterialBuildDependency(IList buildDependencyList) { + if (Materials.Count > 0) + { + foreach (var material in Materials) + { + buildDependencyList.Add(material); + } + } + } +} public class BuildTaskExportShaderVariantCollection : BuildTask { - public const string SHADER_VARIANT_COLLECT_SAVE_PATH = "Assets/GameResources/ShaderVarians/ShaderVariantCollection.shadervariants"; - private HashSet _allGlobalKeywords = new(); - private int _keywordIndex = 0; - private List> _enabledGlobalKeywordsList = new(); + //public const string SHADER_VARIANT_COLLECT_SAVE_PATH = "Assets/GameResources/ShaderVarians/ShaderVariantCollection.shadervariants"; + + // private HashSet _allGlobalKeywords = new(); + // private int _keywordIndex = 0; + // private List> _enabledGlobalKeywordsList = new(); private List _materialList = new(); + private double? _beginTime = null; + public override void BeginTask() { base.BeginTask(); _materialList.Clear(); - Prepare(); + //ProcessMaterials(); + collect(); + this.FinishTask(); } public override void FinishTask() { _materialList.Clear(); + _beginTime = null; base.FinishTask(); } - - public void Prepare() + + public void collect() { var assetInfos = this.GetData>(CONTEXT_ASSET_INFO); - var allMaterial = new HashSet(); - foreach (var assetPath in assetInfos.Keys) - { - if (Path.GetExtension(assetPath) == ".mat") - { - if (!allMaterial.Contains(assetPath)) - { - allMaterial.Add(assetPath); - } - } - } _materialList = new List(); var shaderDict = new Dictionary>(); - foreach (var key in allMaterial) + var allMaterial = new HashSet(); + + Action collectAction = (Material material) => { - var material = AssetDatabase.LoadAssetAtPath(key); - if (material != null) + if (material) { if (material.shader != null) { @@ -68,32 +80,409 @@ public void Prepare() } if (!_materialList.Contains(material)) { + // Debug.LogError("add material name " + material.name + " shader keyword count" + material.shaderKeywords.Count() + " instance id" + material.GetInstanceID()); _materialList.Add(material); } + else + { + // Debug.LogError("reject material name " + material.name + " shader keyword count" + material.shaderKeywords.Count() + " instance id" + material.GetInstanceID()); + } + } + }; + foreach (var assetPath in assetInfos.Keys) + { + var extension = Path.GetExtension(assetPath); + if (extension == ".mat") + { + var material = AssetDatabase.LoadAssetAtPath(assetPath); + collectAction(material); + } + /* + else if (extension == ".prefab") + { + var gm = AssetDatabase.LoadAssetAtPath(assetPath); + var mvs = gm.GetComponentsInChildren(true); + foreach (var mv in mvs) + { + if (mv is UIMaterialBlock uIMaterialBlock) + { + var material = mv.GetModifiedMaterial(uIMaterialBlock.material); + if (!material) + Debug.LogWarning(assetPath + "material variant is null name :" + mv.gameObject.name); + else + { + collectAction(material); + } + } + else + { + var graphic = mv.gameObject.GetComponent(); + if (graphic is TMPro.TextMeshProUGUI tmp) + { + var material = mv.GetModifiedMaterial(tmp.fontMaterial); + + if (!material) + Debug.LogWarning(assetPath + "material variant is null name :" + mv.gameObject.name); + else + { + collectAction(material); + } + } + else if (graphic) + { + var material = mv.GetModifiedMaterial(graphic.material); + if (!material) + Debug.LogWarning(assetPath + "material variant is null name :" + mv.gameObject.name); + else + { + collectAction(material); + } + } + } + } + } + */ + } + URSMaterials uRSMaterials = new URSMaterials(); + uRSMaterials.Materials = _materialList; + ShaderVariantCollectionMaterialVariantConverter converter = new ShaderVariantCollectionMaterialVariantConverter(); + converter.CollectMaterial(new List() { uRSMaterials }); + converter.CollectVariant(); + ShaderVariantCollection shaderVariantCollection = new ShaderVariantCollection(); + converter.WriteToShaderVariantCollectionFile(shaderVariantCollection); + + ShaderVariantCollectionMapper shaderVariantCollectionMapper = new ShaderVariantCollectionMapper(shaderVariantCollection); + shaderVariantCollectionMapper.Init(shaderVariantCollection); + + var shaders = shaderVariantCollectionMapper.shaders; + foreach (var shader in shaders) + { + + var multiKeywords = GetMultiKeyWordGroups(converter, shader); + if (multiKeywords.Count > 0) { + VariantKeywordCombination vkc = new VariantKeywordCombination(); + vkc.mShader = shader; + vkc.mKeywordDeclareGroups = multiKeywords; + vkc.Execute(shaderVariantCollectionMapper); } + //VariantKeywordCombinationEditor.TryParseShader(vkc.mShader,vkc.mKeywordDeclareGroups); } - ProcessMaterials(); - var sb = new System.Text.StringBuilder(); - foreach (var kvp in shaderDict) + shaderVariantCollectionMapper.Refresh(); + var mapper = shaderVariantCollectionMapper.GetMapper(); + + + // StripperShaderVariants stripperShaderVariants = new StripperShaderVariants(); + // List variants = new List(); + #region stripper fog shader variant; + ShaderVariantCollection blackShaderCollection = new ShaderVariantCollection(); + ShaderVariantCollectionMapper blackShaderVariantCollectionMapper = new ShaderVariantCollectionMapper(blackShaderCollection); + + + + foreach (var kv in mapper) { - sb.AppendLine(kvp.Key + " " + kvp.Value.Count + " times"); + var shader = kv.Key; + var shaderVariants = kv.Value; - if (kvp.Value.Count <= 5) + Dictionary shaderPassFogInfo = new Dictionary (); + //bool hasFog = false; + foreach (var sv in shaderVariants) { - Debug.LogWarning("Shader: " + kvp.Key.name, kvp.Key); + if (!shaderPassFogInfo.ContainsKey(sv.passType)) + { + var sfi = new ShaderPassFogInfo() + { + passType = sv.passType, + }; + sfi.shaderVariants.Add(sv); + shaderPassFogInfo.Add(sv.passType, sfi); + } + else + { + var sfi = shaderPassFogInfo[sv.passType]; + sfi.shaderVariants.Add (sv); + } + } + foreach (var sfi in shaderPassFogInfo) + { + bool hasFog = false; + foreach (var sv in sfi.Value.shaderVariants) + { + if (sv.keywords.Contains("FOG_LINEAR")) { + hasFog = true; + break; + } + } + if (hasFog) + { + foreach (var sv in sfi.Value.shaderVariants) + { + if (!sv.keywords.Contains("FOG_LINEAR")) + { + blackShaderCollection.Add(sv.Deserialize()); + } + } + + } + + } + + } +#endregion + blackShaderVariantCollectionMapper.Refresh(); - foreach (var m in kvp.Value) + var blackMapper = blackShaderVariantCollectionMapper.GetMapper(); + foreach (var kv in blackMapper) + { + var variants = kv.Value; + foreach (var variant in variants) + { + shaderVariantCollectionMapper.RemoveVariant(variant.Deserialize()); + } + } + + HashSet warmpShaders = new HashSet(); + warmpShaders.Add(Shader.Find("HE/ToonLit")); // ÓÅÏÈ + warmpShaders.Add(Shader.Find("HE/SceneLit")); + warmpShaders.Add(Shader.Find("HE/Glass")); + + foreach (var item in mapper) + { + var shader = item.Key; + var variants = item.Value; + var assetPath = AssetDatabase.GetAssetPath(shader); + if (assetPath.StartsWith("Assets/") || assetPath.StartsWith("Packages/")) + { + if (assetInfos.ContainsKey(assetPath)) + { + var assetInfo = assetInfos[assetPath]; + var referenceCount = assetInfo.refrenceCount; + // Debug.LogError($"shader name {shader.name} reference count {referenceCount}"); + if (referenceCount > 5) + { + warmpShaders.Add(shader); + } + } + else { - Debug.Log(AssetDatabase.GetAssetPath(m), m); + Debug.LogError("can not find shader asset path {assetPath}"); } } } - Debug.Log(sb.ToString()); + + List allWarmShaderVariant = new List(); + int maxCount = URSShaderVariantConstant.WARM_ONE_SHADER_VARIANT_COUNT; + ShaderVariantCollection currentShaderVariant = new ShaderVariantCollection(); + List ShaderVariantCollections = new List(); + ShaderVariantCollections.Add(currentShaderVariant); + foreach (var warmShader in warmpShaders) + { + if (mapper.ContainsKey(warmShader)) + { + var variants = mapper[warmShader]; + allWarmShaderVariant.AddRange(variants); + } + } + while (allWarmShaderVariant.Count > 0) + { + var lastIndex = allWarmShaderVariant.Count - 1; + var last = allWarmShaderVariant[lastIndex]; + allWarmShaderVariant.RemoveAt(lastIndex); + if (currentShaderVariant.variantCount < maxCount) + { + currentShaderVariant.Add(last.Deserialize()); + } + else + { + currentShaderVariant = new ShaderVariantCollection(); + ShaderVariantCollections.Add(currentShaderVariant); + currentShaderVariant.Add(last.Deserialize()); + } + } + WarmShaderVariants warmShaderVariants = new WarmShaderVariants(); + List paths = new List(); + for (int i = 0; i < ShaderVariantCollections.Count; i++) + { + var svs = ShaderVariantCollections[i]; + var path = string.Format(URS.URSShaderVariantConstant.WARM_SHADER_FILE_FORMAT, i); + paths.Add(path); + AssetDatabase.CreateAsset(svs, path); + } + warmShaderVariants.paths = paths.ToArray(); + + var warmJsonPath = URSShaderVariantConstant.WARM_SHADER_JSON_FILE; + if (File.Exists(warmJsonPath)) + { + File.Delete(warmJsonPath); + } + var jsonContent = UnityEngine.JsonUtility.ToJson(warmShaderVariants, true); + System.IO.File.WriteAllText(warmJsonPath, jsonContent); + + + + ShaderVariantCollection buildInShaderVariantCollection = new ShaderVariantCollection(); + ShaderVariantCollectionMapper buildInShaderVariantCollectionMapper = new ShaderVariantCollectionMapper(buildInShaderVariantCollection); + + // buildin Shader 穷举 ,这里的代码,可以监听 build player的时候,shader的编译,那样可以完全捕获所有的build in shader variant,我这里只选择了自己项目重要的 + var buildInShaders = new List(); + /* + PostProcessData.ReloadDefaultPostProcessData(); + PostProcessData ppd = PostProcessData.GetDefaultPostProcessData(); + + + + // buildInShaders.Add(ppd.shaders.stopNanPS); + // buildInShaders.Add(ppd.shaders.subpixelMorphologicalAntialiasingPS); + // buildInShaders.Add(ppd.shaders.gaussianDepthOfFieldPS); + // buildInShaders.Add(ppd.shaders.bokehDepthOfFieldPS); + // buildInShaders.Add(ppd.shaders.cameraMotionBlurPS); + // buildInShaders.Add(ppd.shaders.paniniProjectionPS); + buildInShaders.Add(ppd.shaders.lutBuilderLdrPS); + buildInShaders.Add(ppd.shaders.lutBuilderHdrPS); + buildInShaders.Add(ppd.shaders.bloomPS); + // buildInShaders.Add(ppd.shaders.LensFlareDataDrivenPS); + buildInShaders.Add(ppd.shaders.scalingSetupPS); + // buildInShaders.Add(ppd.shaders.easuPS); + buildInShaders.Add(ppd.shaders.uberPostPS); + buildInShaders.Add(ppd.shaders.finalPostPassPS); + + //buildInShaders.AddRange(ppd.xPostProcessShaders); + //buildInShaders.Add(ppd.screenFadeShader); + */ + buildInShaders.Add(Shader.Find("HighlightPlus/Geometry/Mask")); + buildInShaders.Add(Shader.Find("HighlightPlus/Geometry/SeeThrough")); + buildInShaders.Add(Shader.Find("UI/Default")); + buildInShaders.Add(Shader.Find("Hidden/BOXOPHOBIC/Atmospherics/Height Fog Global")); + buildInShaders.Add(Shader.Find("Custom/RenderFeature/UIBlur")); + + foreach (var shader in buildInShaders) + { + //Debug.LogError("shader.name" + shader.name); + buildInShaderVariantCollectionMapper.AddShader(shader); + VariantKeywordCombination vkc = new VariantKeywordCombination(); + vkc.mShader = shader; + vkc.mKeywordDeclareGroups = new List(); + VariantKeywordCombinationEditor.TryParseShader(vkc.mShader, vkc.mKeywordDeclareGroups); + vkc.Execute(buildInShaderVariantCollectionMapper); + } + // URSshaderVariantCollection ursShaderVariant = new URSshaderVariantCollection(); + // List uRSshaderVariants= new List(); + + var buildInMapper = buildInShaderVariantCollectionMapper.GetMapper(); + + allWarmShaderVariant.Clear(); + currentShaderVariant = new ShaderVariantCollection(); + ShaderVariantCollections.Clear(); + ShaderVariantCollections.Add(currentShaderVariant); + foreach (var warmShader in buildInShaders) + { + if (buildInMapper.ContainsKey(warmShader)) + { + var variants = buildInMapper[warmShader]; + allWarmShaderVariant.AddRange(variants); + } + } + while (allWarmShaderVariant.Count > 0) + { + var lastIndex = allWarmShaderVariant.Count - 1; + var last = allWarmShaderVariant[lastIndex]; + allWarmShaderVariant.RemoveAt(lastIndex); + if (currentShaderVariant.variantCount < maxCount) + { + currentShaderVariant.Add(last.Deserialize()); + } + else + { + currentShaderVariant = new ShaderVariantCollection(); + ShaderVariantCollections.Add(currentShaderVariant); + currentShaderVariant.Add(last.Deserialize()); + } + } + for (int i = 0; i < ShaderVariantCollections.Count; i++) + { + var svs = ShaderVariantCollections[i]; + var path = string.Format(URS.URSShaderVariantConstant.BUILD_IN_WARM_SHADER_SAVE_PATH_FORMAT, i); + paths.Add(path); + Directory.CreateDirectory(Path.GetDirectoryName(path)); + AssetDatabase.CreateAsset(svs, path); + } + + + + AssetDatabase.CreateAsset(shaderVariantCollection, URS.URSShaderVariantConstant.SHADER_VARIANT_SAVE_PATH); + AssetDatabase.CreateAsset(blackShaderCollection, URS.URSShaderVariantConstant.BLACK_SHADER_VARIANT_STRIPPER_SAVE_PATH); + AssetDatabase.Refresh(); + + } + + private static List GlobalProjectPerhapsMultiKeywords = new List(); + + private class ShaderPassFogInfo{ + + public PassType passType; + public List shaderVariants= new List(); + + + } + static BuildTaskExportShaderVariantCollection() + { + // ÕâÀïÊǼÓËÙ½âÎö¹ý³Ì£¬Ö±½ÓÇî¾ÙÁË ÏîÄ¿ÖÐµÄ ¾²Ì¬¹Ø¼ü×Ö£¨mutil_compiler£©,²»Í¬ÏîÄ¿×Ô¼º¶¨ÖÆ + AddGlobalProjectPerhapsMultiKeywords("_", "_SCREEN_SPACE_OCCLUSION"); + AddGlobalProjectPerhapsMultiKeywords("_", "LIGHTMAP_ON"); + AddGlobalProjectPerhapsMultiKeywords("_", "FOG_LINEAR"); + AddGlobalProjectPerhapsMultiKeywords("_", "_CASTING_PUNCTUAL_LIGHT_SHADOW"); + AddGlobalProjectPerhapsMultiKeywords("_", "UNITY_UI_CLIP_RECT"); + AddGlobalProjectPerhapsMultiKeywords("_", "UNITY_UI_ALPHACLIP"); + } + private static void AddGlobalProjectPerhapsMultiKeywords( params string[] keyword) + { + KeywordDeclareGroup kdg= new KeywordDeclareGroup(); + kdg.keywords = new List(); + kdg.keywords.AddRange(keyword); + GlobalProjectPerhapsMultiKeywords.Add(kdg); } + + + private List GetMultiKeyWordGroups(ShaderVariantCollectionMaterialVariantConverter converter,Shader shader) + { + List < KeywordDeclareGroup > kgp= new List(); + foreach (KeywordDeclareGroup item in GlobalProjectPerhapsMultiKeywords) + { + var keywords = item.keywords; + bool isOk = false; + for (int i = 0; i < keywords.Count; i++) + { + var keyword = keywords[i]; + if (keyword == "_") continue; + if (!converter.IsKeywordBelongToShader(shader, keyword)) + { + break; + } + if (i == keywords.Count - 1) { + + isOk = true; + } + } + if (isOk) + { + kgp.Add(item); + } + } + if (kgp.Count == 0) + { + kgp.Add(new KeywordDeclareGroup() + { + keywords = new List() + }); ; + } + return kgp; + } + private void ProcessMaterials() { EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects); + collect(); InvokeInternalStaticMethod(typeof(ShaderUtil), "ClearCurrentShaderVariantCollection"); Debug.Log(InvokeInternalStaticMethod(typeof(ShaderUtil), "GetCurrentShaderVariantCollectionShaderCount")); @@ -120,12 +509,10 @@ private void ProcessMaterials() Selection.activeGameObject = camera.gameObject; EditorApplication.ExecuteMenuItem("GameObject/Align View to Selected"); - int xMax = (int)(width - 1); int x = 0; int y = 0; - for (int i = 0; i < _materialList.Count; i++) { var material = _materialList[i]; @@ -145,32 +532,16 @@ private void ProcessMaterials() x++; } } - - _enabledGlobalKeywordsList.Add(new HashSet()); - _enabledGlobalKeywordsList.Add(new HashSet() - { - "FOG_LINEAR" - }); - - foreach (var keywords in _enabledGlobalKeywordsList) - { - foreach (var keyword in keywords) - { - if (!string.IsNullOrWhiteSpace(keyword)) - _allGlobalKeywords.Add(keyword); - } - } - - _keywordIndex = 0; - - // Debug.LogError("开始收集计时"+ EditorApplication.timeSinceStartup+" frameCount "+ sFrameCount); + camera.Render(); + _beginTime = EditorApplication.timeSinceStartup; + Debug.Log("begin render shader scene "+ EditorApplication.timeSinceStartup); } private static void CreateSphere(Material material, Vector3 position, int x, int y, int index) { var go = GameObject.CreatePrimitive(PrimitiveType.Sphere); go.GetComponent().material = material; go.transform.position = position; - go.name = string.Format("Sphere_{0}|{1}_{2}|{3}", index, x, y, material.name); + go.name = string.Format("Sphere_{0}|{1}_{2}|{3}|{4}", index, x, y, material.name, material.shader.name); } private static object InvokeInternalStaticMethod(System.Type type, string method, params object[] parameters) @@ -189,41 +560,14 @@ public override void OnTaskUpdate() { base.OnTaskUpdate(); - if (_keywordIndex < _enabledGlobalKeywordsList.Count) - { - var camera = Camera.main; - if (camera != null) - { - var keywords = _enabledGlobalKeywordsList[_keywordIndex]; - - foreach (var v in _allGlobalKeywords) - { - foreach (var mat in _materialList) - { - mat.DisableKeyword(v); - } - } - - foreach (var v in keywords) - { - foreach (var mat in _materialList) - { - mat.EnableKeyword(v); - } - } - - camera.Render(); - } - - _keywordIndex++; - } - else - { + if (_beginTime.HasValue && (EditorApplication.timeSinceStartup - _beginTime.Value) > 2) { + _beginTime = null; Debug.Log(InvokeInternalStaticMethod(typeof(ShaderUtil), "GetCurrentShaderVariantCollectionVariantCount")); - InvokeInternalStaticMethod(typeof(ShaderUtil), "SaveCurrentShaderVariantCollection", SHADER_VARIANT_COLLECT_SAVE_PATH); + InvokeInternalStaticMethod(typeof(ShaderUtil), "SaveCurrentShaderVariantCollection",URSShaderVariantConstant.SHADER_VARIANT_SAVE_PATH); Debug.Log(InvokeInternalStaticMethod(typeof(ShaderUtil), "GetCurrentShaderVariantCollectionShaderCount")); - Debug.Log("结束收集"); + Debug.Log("end render shader scene " + EditorApplication.timeSinceStartup); this.FinishTask(); } + } } diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskGenerateVersion.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskGenerateVersion.cs index 42d9444..2383cc1 100644 --- a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskGenerateVersion.cs +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskGenerateVersion.cs @@ -40,8 +40,11 @@ public void GenerateVersionFileManifest() { var versionDirectory = (string)this._context[CONTEXT_VERSION_DIRECTORY]; var additionFileInfos = GetData>(CONTEXT_FILE_ADDITION_INFO); - var setting = URSEditorUserSettings.instance; - VersionBuilder.BuildVersion(versionDirectory,new FileSystem(), setting.BuildVersionCode, additionFileInfos,out string newVersionDirctoryName); + var buildingVersion = GetData(CONTEXT_BUILDING_VERSION); + var versionHistory = GetData(CONTEXT_VERSION_HISTORY); + var debug= GetData(CONTEXT_DEBUG); + var channel= GetData(CONTEXT_CHANNEL); + VersionBuilder.BuildVersion(channel,versionDirectory,new FileSystem(), buildingVersion, additionFileInfos, versionHistory,out string newVersionDirctoryName, debug); SetData(CONTEXT_VERSION_DIRECTORY, newVersionDirctoryName); } /* diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskOptimizeShareAssetBundleName.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskOptimizeShareAssetBundleName.cs new file mode 100644 index 0000000..8d8728c --- /dev/null +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskOptimizeShareAssetBundleName.cs @@ -0,0 +1,222 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +using Bewildered.SmartLibrary; +using System.IO; +using System; +using UnityEditor.Build.Pipeline; +using UnityEditor.Build.Pipeline.Injector; +using UnityEditor.Build.Pipeline.Interfaces; +using UnityEditor.Build.Pipeline.Tasks; +using UnityEditor.Build.Pipeline.Utilities; +using UnityEngine.SceneManagement; +using UnityEditor.SceneManagement; +using TagInfo = System.Collections.Generic.Dictionary; +using URS; +using YooAsset.Utility; +using System.Linq; +using YooAsset; +using UnityEditor.Build.Content; +using BuildCompression = UnityEngine.BuildCompression; +using Context = System.Collections.Generic.Dictionary; + +[Serializable] +public class ShareAssetBundleName +{ + [SerializeField] + public ShareAssetBundleNameItem[] AssetBundleNameItems; + + [NonSerialized] + public Dictionary AssetPathToBundleName; + + public void Init() + { + AssetPathToBundleName = new Dictionary(); + foreach (var item in AssetBundleNameItems) + { + AssetPathToBundleName[item.AssetPath] = item.AssetBundleName; + } + } +} + +[Serializable] +public class ShareAssetBundleNameItem +{ + [SerializeField] + public string AssetPath; + + [SerializeField] + public string AssetBundleName; + +} +public class BuildTaskOptimizeShareAssetBundleName : BuildTask +{ + private Dictionary _assetPathToBundleName = null; + private int _nextBundleNameIndex = 1; + + public override void BeginTask() + { + base.BeginTask(); + OptimizShareAssetBundleName(); + this.FinishTask(); + } + public void LoadConfig() + { + var filePath = Build.GetShareAssetBundleNameConfigFilePath(); + + ShareAssetBundleName sabn = null; + if (File.Exists(filePath)) + { + sabn = UnityEngine.JsonUtility.FromJson(File.ReadAllText(filePath)); + sabn.Init(); + } + if (sabn != null) + { + _assetPathToBundleName = sabn.AssetPathToBundleName; + var currentMaxIndex = 0; + foreach (var item in _assetPathToBundleName) + { + var bundleName = item.Value; + bundleName = Path.GetFileNameWithoutExtension(bundleName); + var split = bundleName.Split("-"); + var index = int.Parse(split[2]); + if (index > currentMaxIndex) + { + currentMaxIndex = index; + } + } + _nextBundleNameIndex = currentMaxIndex + 1; + } + else + { + _assetPathToBundleName = new Dictionary(); + _nextBundleNameIndex = 1; + } + } + + public string GetAssetBundleName(string assetPath, List orignBundleAssetPaths) + { + if (_assetPathToBundleName.ContainsKey(assetPath)) + { + return _assetPathToBundleName[assetPath]; + } + if (orignBundleAssetPaths.Count > 0) + { + foreach (var path in orignBundleAssetPaths) + { + if (assetPath == path) + { + continue; + } + else + { + if (_assetPathToBundleName.ContainsKey(path)) + { + var sameBundleName = _assetPathToBundleName[path]; + _assetPathToBundleName[assetPath] = sameBundleName; + return sameBundleName; + } + } + } + } + var newBundleName = $"share-static-{_nextBundleNameIndex++}.bundle"; + _assetPathToBundleName[assetPath] = newBundleName; + return newBundleName; + } + public void SaveConfig(Dictionary orignAssets) + { + List deletes= new List(); + foreach (var item in _assetPathToBundleName) + { + if (!orignAssets.ContainsKey(item.Key)) { + deletes.Add(item.Key); + } + } + foreach (var item in deletes) + { + _assetPathToBundleName.Remove(item); + } + List< ShareAssetBundleNameItem > abNameItems= new List(); + foreach (var item in _assetPathToBundleName) + { + ShareAssetBundleNameItem abNameItem = new ShareAssetBundleNameItem(); + abNameItem.AssetPath = item.Key; + abNameItem.AssetBundleName= item.Value; + abNameItems.Add(abNameItem); + } + ShareAssetBundleName config= new ShareAssetBundleName (); + config.AssetBundleNameItems = abNameItems.ToArray(); + + var filePath = Build.GetShareAssetBundleNameConfigFilePath(); + if (File.Exists(filePath)) + { + File.Delete(filePath); + } + File.WriteAllText(filePath,UnityEngine.JsonUtility.ToJson(config,true)); + } + public void OptimizShareAssetBundleName() + { + EditorUtility.DisplayProgressBar("BuildTaskOptimizeShareAssetBundleName", "Ż", 0); + + LoadConfig(); + var bundleInfo = GetData>(CONTEXT_BUNDLE_INFO); + var newBundleInfos = new Dictionary(); + var orignShareAssetToBundleName = new Dictionary(); + foreach (var item in bundleInfo) + { + var bundleAssetPaths = item.Value.paths; + if (item.Value.isShareBundle) + { + foreach (var assetPath in bundleAssetPaths) + { + if (!orignShareAssetToBundleName.ContainsKey(assetPath)) + { + orignShareAssetToBundleName[assetPath] = item.Value.bundleName; + } + else + { + throw new Exception($"bundle name conflict ,first {orignShareAssetToBundleName[assetPath]},second {item.Value.bundleName} "); + } + } + } + else + { + newBundleInfos.Add(item.Key, item.Value); + } + } + + var newShareBundle= new Dictionary(); + foreach (var item in orignShareAssetToBundleName) + { + var assetPath = item.Key; + var orignBundleAssetPaths = bundleInfo[item.Value].paths; + var newBundleName = GetAssetBundleName(assetPath,orignBundleAssetPaths); + newShareBundle[assetPath] = newBundleName; + } + foreach (var item in newShareBundle) + { + var assetPath = item.Key; + var newBundleName = item.Value; + if (!newBundleInfos.ContainsKey(newBundleName)) + { + List paths = new List(); + paths.Add(assetPath); + BundleInfo newBundleInfo = new BundleInfo(newBundleName, paths, true); + newBundleInfos.Add(newBundleName, newBundleInfo); + } + else + { + BundleInfo newBundleInfo = newBundleInfos[newBundleName]; + var paths = newBundleInfo.paths; + if (!paths.Contains(assetPath)) { + paths.Add(assetPath); + } + } + } + SetData(CONTEXT_BUNDLE_INFO, newBundleInfos); + SaveConfig(orignShareAssetToBundleName); + EditorUtility.ClearProgressBar(); + } + +} diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskOptimizeShareAssetBundleName.cs.meta b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskOptimizeShareAssetBundleName.cs.meta new file mode 100644 index 0000000..de455a0 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskOptimizeShareAssetBundleName.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3ee9abcf76ba1ba448428ede21d46735 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskReBuildAssetBundle.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskReBuildAssetBundle.cs index e945b18..aabc5b5 100644 --- a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskReBuildAssetBundle.cs +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskReBuildAssetBundle.cs @@ -82,6 +82,8 @@ public ReturnCode BuildBundleResource() buildTasks.Add(extractData); var generation = new BuildLayoutGenerationTask(); buildTasks.Add(generation); + var checkHash = new BuidTaskCheckBundleHash(); + buildTasks.Add(checkHash); var targetGroup = BuildPipeline.GetBuildTargetGroup(UnityEditor.EditorUserBuildSettings.activeBuildTarget); var target = UnityEditor.EditorUserBuildSettings.activeBuildTarget; var outFolder = Build.GetTempBundleOutDirectoryPath(); @@ -116,6 +118,8 @@ public ReturnCode BuildBundleResource() } File.WriteAllText(manifestFileName, manifest.ToString()); SetData(CONTEXT_BUNDLE_RESULT, results); + SetData(CONTEXT_BUNDLE_LAYOUT, generation.LayoutLookupTables); + SetData(CONTEXT_VERSION_BUNDLE_HASH, checkHash.BundleHash); return ReturnCode.Success; } } diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskRegenerateAssetBundleName.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskRegenerateAssetBundleName.cs index dad027f..956b70d 100644 --- a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskRegenerateAssetBundleName.cs +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskRegenerateAssetBundleName.cs @@ -27,9 +27,15 @@ public class BuildTaskRegenerateAssetBundleName : BuildTask { public const long MAX_COMBINE_SHARE_AB_ITEM_SIZE = 500*1024 * 8; // 500K ļСܺϲ public const long MAX_COMBINE_SHARE_AB_SIZE = 1024 * 1024 * 8; // 1M պϲĿС - public const long MAX_COMBINE_SHARE_NO_NAME = 10 * 1024 * 8; // 10K ûа - public const int MAX_COMBINE_SHARE_NO_NAME_REFERENCE_COUNT = 5; // ûаü - public const int MIN_COMBINE_SHARE_MIN_REFERENCE_COUNT = 7;//Сü + + public const long MIN_NO_NAME_COMBINE_SIZE= 32 * 1024 * 8; // 32K պϲĿС + + + // public const long MAX_COMBINE_SHARE_NO_NAME = 60 * 1024 * 8; // 60K ûа + // public const int MAX_COMBINE_SHARE_NO_NAME_REFERENCE_COUNT = 7; // ûаü + + // public const int MIN_COMBINE_AB_SIZE_2 = 100 * 1024 * 8;// 100K ûа + public const int MAX_COMBINE_SHARE_MIN_REFERENCE_COUNT = 3;//ü public override void BeginTask() { base.BeginTask(); @@ -107,7 +113,7 @@ public void RegenerateAssetBundleName() foreach (var abInfo in abInfos) { var bundleName = abInfo.name; - if (abInfo.size < MAX_COMBINE_SHARE_NO_NAME && abInfo.refrenceCount < MAX_COMBINE_SHARE_NO_NAME_REFERENCE_COUNT) + if (abInfo.size * abInfo.refrenceCount < MIN_NO_NAME_COMBINE_SIZE) { allShareRemoveByNoName++; var bundleInfo = bundleInfos[bundleName]; @@ -120,12 +126,15 @@ public void RegenerateAssetBundleName() allCombines.Remove(bundleName); continue; } - - if (abInfo.refrenceCount < MIN_COMBINE_SHARE_MIN_REFERENCE_COUNT) + else { - allShareRmoveByRefrenceCountTooFew++; - allCombines.Remove(bundleName); - continue; + if ( abInfo.refrenceCount < MAX_COMBINE_SHARE_MIN_REFERENCE_COUNT) + { + allShareRmoveByRefrenceCountTooFew++; + allCombines.Remove(bundleName); + continue; + } + } } diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskUpdateCollection.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskUpdateCollection.cs index 860d45b..ded1394 100644 --- a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskUpdateCollection.cs +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskUpdateCollection.cs @@ -19,7 +19,7 @@ public override void BeginTask() base.BeginTask(); // SearchService.Refresh(); LibraryDatabase.RootCollection.RemoveInvailidItem(); - EditorUtility.DisplayProgressBar("UpdateCollections", "ʼռԴ", 0); + EditorUtility.DisplayProgressBar("UpdateCollections", "开始收集打包资源", 0); _tasks = new List(); var root = SessionData.instance; if (root != null) diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateAnimation.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateAnimation.cs new file mode 100644 index 0000000..c2d4655 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateAnimation.cs @@ -0,0 +1,132 @@ +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +using System.Reflection; +using System.IO; +using System; + +public class BuildTaskValidateAnimation : BuildTask +{ + + public override void BeginTask() + { + base.BeginTask(); + EditorUtility.DisplayProgressBar("CheckAnimation", "鶯Դ", 0); + var assetInfos = this.GetData>(CONTEXT_ASSET_INFO); + var propertyCheck = GetPropertyIsAnimatable(); + foreach (var assetPath in assetInfos.Keys) + { + if (Path.GetExtension(assetPath) == ".prefab") + { + var gm = AssetDatabase.LoadAssetAtPath(assetPath); + Check(gm, assetPath, propertyCheck); + } + } + EditorUtility.ClearProgressBar(); + this.FinishTask(); + } + + + static void Check(GameObject gm, string path,MethodInfo propertyCheck ) + { + var animators = gm.GetComponentsInChildren(); + if (animators != null) + { + foreach (var animator in animators) + { + + var runtime = animator.runtimeAnimatorController; + var animatorGameObject = animator.gameObject; + + if (runtime!=null&&runtime.animationClips != null && runtime.animationClips.Length > 0) + { + foreach (var clip in runtime.animationClips) + { + List binds = new List(); + var bindsCurve = AnimationUtility.GetCurveBindings(clip); + var bindsObjectReference = AnimationUtility.GetObjectReferenceCurveBindings(clip); + binds.AddRange(bindsCurve); + binds.AddRange(bindsObjectReference); + + foreach (var bind in binds) + { + Transform child = animatorGameObject.transform.Find(bind.path); + + if (child == null) + { + Debug.LogError($"ERROR:GameObjectPath {path},animatorPath {GetRelativePath(gm, animatorGameObject)} clipName {clip.name} ,Can not find bindPath {bind.path} ,bindType {bind.type.FullName}, bind.propertyName {bind.propertyName}"); + continue; + } + UnityEngine.Object target = null; + if (bind.type == typeof(GameObject)) + { + target = child.gameObject; + } + else + { + target = child.GetComponent(bind.type); + if (target == null) + { + Debug.LogError($"ERROR:GameObjectPath {path},animatorPath {GetRelativePath(gm, animatorGameObject)} clipName {clip.name} ,Can not find bindType {bind.type.FullName} bindPath {bind.path}, bind.propertyName {bind.propertyName}"); + continue; + } + } + if (bind.type == typeof(Animator)) + { + if (bind.propertyName.StartsWith("RootQ.") || bind.propertyName.StartsWith("RootT.")) + { + continue; + } + } + // else if (bind.type == typeof(Transform)) + // { + // if (bind.propertyName.StartsWith("m_LocalRotation.") || bind.propertyName.StartsWith("m_LocalScale.") || bind.propertyName.StartsWith("m_LocalPosition.")) + // { + // continue; + // } + // } + var result= propertyCheck.Invoke(null, new object[] { target, bind.propertyName,null}); + var PropertyIsAnimatable =(bool) result; + if (!PropertyIsAnimatable) + { + Debug.LogError($"ERROR:GameObjectPath {path},animatorPath {GetRelativePath(gm, animatorGameObject)} clipName {clip.name} ,Can not find bind.propertyName {bind.propertyName} bindType {bind.type.FullName} bindPath {bind.path}"); + continue; + } + } + } + } + } + } + } + + static string GetRelativePath(GameObject root, GameObject children) + { + List path = new List(); + path.Add(children.name); + while (children != root) + { + var parent = children.transform.parent.gameObject; + path.Add(parent.name); + children = parent; + } + path.Reverse(); + return string.Join("/", path); + + } + + static MethodInfo GetPropertyIsAnimatable() { + + Assembly asm = Assembly.GetAssembly(typeof(UnityEditorInternal.AssetStore)); + Type type = asm.GetType("UnityEditorInternal.AnimationWindowUtility"); + + if (type == null) + { + return null; + } + + MethodInfo propertyIsAnimatable = type.GetMethod("PropertyIsAnimatable", BindingFlags.Static | BindingFlags.Public); + return propertyIsAnimatable; + } + +} + diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateAnimation.cs.meta b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateAnimation.cs.meta new file mode 100644 index 0000000..aab3af3 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateAnimation.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 73387045c55a0f74bb17c9ca6a61c083 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskMaterialCleaner.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateMaterial.cs similarity index 87% rename from Assets/URS/YooAsset/Editor/BuildTask/BuildTaskMaterialCleaner.cs rename to Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateMaterial.cs index a7e94c3..5007e98 100644 --- a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskMaterialCleaner.cs +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateMaterial.cs @@ -1,16 +1,9 @@ -using System.Collections; using System.Collections.Generic; using UnityEngine; -using System.Text.RegularExpressions; using UnityEditor; -using UnityEngine.Rendering; using System.Reflection; using System.IO; -using System.Collections; -using System.Collections.Generic; -using UnityEngine; -using UnityEditor; -public class BuildTaskMaterialCleaner : BuildTask +public class BuildTaskValidateMaterial : BuildTask { public override void BeginTask() @@ -18,7 +11,7 @@ public override void BeginTask() base.BeginTask(); var assetInfos = this.GetData>(CONTEXT_ASSET_INFO); - EditorApplication.ExecuteMenuItem("Window/Inspector"); + EditorApplication.ExecuteMenuItem("Window/General/Inspector"); foreach (var assetPath in assetInfos.Keys) { if (Path.GetExtension(assetPath) == ".mat") @@ -35,7 +28,7 @@ public override void BeginTask() AssetDatabase.SaveAssets(); this.FinishTask(); } - //ȡshaderеĺ + //获取shader中所有的宏 public static bool GetShaderKeywords(Shader target, out string[] global, out string[] local) { try @@ -67,13 +60,13 @@ static void ClearnMaterial(Material m,string path) { keywords.Add(l); } - //keywords + //重置keywords List resetKeywords = new List(m.shaderKeywords); foreach (var item in m.shaderKeywords) { if (!keywords.Contains(item)) { - //Debug.LogError("Ƿؼ "+ item+" path "+path); + //Debug.LogError("非法关键字 :"+ item+" path "+path); resetKeywords.Remove(item); } @@ -82,6 +75,13 @@ static void ClearnMaterial(Material m,string path) } */ HashSet property = new HashSet(); + if (!m) { + Debug.LogError("材质球为空 :path " + path); + } + if (!m.shader) + { + Debug.LogError("材质球shader为空 :path " + path); + } int count = m.shader.GetPropertyCount(); for (int i = 0; i < count; i++) { @@ -94,12 +94,12 @@ static void ClearnMaterial(Material m,string path) SerializedProperty TexEnvs = SavedProperties.FindPropertyRelative("m_TexEnvs"); SerializedProperty Floats = SavedProperties.FindPropertyRelative("m_Floats"); SerializedProperty Colors = SavedProperties.FindPropertyRelative("m_Colors"); - //Աɾ + //对比属性删除残留的属性 // for (int i = disabledShaderPasses.arraySize - 1; i >= 0; i--) // { // if (!property.Contains(disabledShaderPasses.GetArrayElementAtIndex(i).displayName)) // { - // //Debug.LogError("Ƿͨ " + disabledShaderPasses.GetArrayElementAtIndex(i).displayName + " path " + path); + // //Debug.LogError("非法通道 :" + disabledShaderPasses.GetArrayElementAtIndex(i).displayName + " path " + path); // disabledShaderPasses.DeleteArrayElementAtIndex(i); // } // } @@ -108,7 +108,7 @@ static void ClearnMaterial(Material m,string path) { if (!property.Contains(TexEnvs.GetArrayElementAtIndex(i).displayName)) { - // Debug.LogError("ǷTexEnvs " + TexEnvs.GetArrayElementAtIndex(i).displayName + " path " + path); + // Debug.LogError("非法TexEnvs :" + TexEnvs.GetArrayElementAtIndex(i).displayName + " path " + path); TexEnvs.DeleteArrayElementAtIndex(i); if (!dirty) { dirty = true; @@ -119,7 +119,7 @@ static void ClearnMaterial(Material m,string path) { if (!property.Contains(Floats.GetArrayElementAtIndex(i).displayName)) { - // Debug.LogError("ǷFloats " + Floats.GetArrayElementAtIndex(i).displayName + " path " + path); + // Debug.LogError("非法Floats :" + Floats.GetArrayElementAtIndex(i).displayName + " path " + path); Floats.DeleteArrayElementAtIndex(i); if (!dirty) { @@ -131,7 +131,7 @@ static void ClearnMaterial(Material m,string path) { if (!property.Contains(Colors.GetArrayElementAtIndex(i).displayName)) { - //Debug.LogError("ǷColors " + Colors.GetArrayElementAtIndex(i).displayName + " path " + path); + //Debug.LogError("非法Colors :" + Colors.GetArrayElementAtIndex(i).displayName + " path " + path); Colors.DeleteArrayElementAtIndex(i); if (!dirty) { diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskMaterialCleaner.cs.meta b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateMaterial.cs.meta similarity index 100% rename from Assets/URS/YooAsset/Editor/BuildTask/BuildTaskMaterialCleaner.cs.meta rename to Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateMaterial.cs.meta diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateModel.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateModel.cs new file mode 100644 index 0000000..d827159 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateModel.cs @@ -0,0 +1,32 @@ +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +using System.IO; + +public class BuildTaskValidateModel : BuildTask +{ + + public override void BeginTask() + { + base.BeginTask(); + var assetInfos = this.GetData>(CONTEXT_ASSET_INFO); + + foreach (var assetPath in assetInfos.Keys) + { + if (Path.GetExtension(assetPath) == ".fbx") + { + var m = ModelImporter.GetAtPath(assetPath) as ModelImporter; + bool isReadable = assetPath.Contains("/VFX/"); + if (m.isReadable!= isReadable) + { + Debug.LogWarning($"纠正{assetPath} mesh isReadable 为 {isReadable}"); + m.isReadable = isReadable; + } + } + } + AssetDatabase.Refresh(); + AssetDatabase.SaveAssets(); + this.FinishTask(); + } + +} diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateModel.cs.meta b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateModel.cs.meta new file mode 100644 index 0000000..83e65d9 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 21414d81e12e116419cc34bb871157f8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateParticleSystem.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateParticleSystem.cs new file mode 100644 index 0000000..58bfb83 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateParticleSystem.cs @@ -0,0 +1,74 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using System.IO; +using UnityEditor; +using UnityEditor.SceneManagement; +using System.Linq; + +public class BuildTaskValidateParticleSystem : BuildTask +{ + + public override void BeginTask() + { + base.BeginTask(); + var assetInfos = this.GetData>(CONTEXT_ASSET_INFO); + + foreach (var assetPath in assetInfos.Keys) + { + if (Path.GetExtension(assetPath) == ".prefab") + { + if (assetPath.Contains("/VFX/")) + { + var gm = AssetDatabase.LoadAssetAtPath(assetPath); + var particleSystems= gm.GetComponentsInChildren(true); + foreach (var particleSystem in particleSystems) + { + var change = false; + var main = particleSystem.main; + bool renderMesh = false; + var render= particleSystem.GetComponent(); + renderMesh = render.renderMode == ParticleSystemRenderMode.Mesh; + if (main.prewarm) + { + // main.prewarm = false; + // change= true; + Debug.LogWarning($"需要人工确认 {assetPath}下的 {particleSystem.gameObject.name} prewarm 是否要打开"); + } + + // int maxParticleCount = 30; + // if (renderMesh&& render.enabled) + // { + // maxParticleCount = 5; + // } + int unityDeault = 1000; + int myDefault = 100; + if (main.maxParticles == unityDeault) + { + main.maxParticles= myDefault; + change = true; + Debug.LogWarning($"修正{assetPath} 下的 {particleSystem.gameObject.name} 最大粒子数为{myDefault}"); + } + if (renderMesh && render.mesh) + { + var current = render.mesh.triangles.Count(); + var targetCount = 500; + if (current > targetCount) + { + Debug.LogError($"需要手工修正 {assetPath} 下的 {particleSystem.gameObject.name} 引用的mesh面数过多 {current},高于建议的 {targetCount}"); + } + } + if (change) + { + EditorUtility.SetDirty(gm); + } + } + } + } + } + AssetDatabase.Refresh(); + AssetDatabase.SaveAssets(); + this.FinishTask(); + } + +} diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateParticleSystem.cs.meta b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateParticleSystem.cs.meta new file mode 100644 index 0000000..0c2aece --- /dev/null +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskValidateParticleSystem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 42b77ed89482bf54eb2dd5985e4be2d7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskWorkSpace.cs b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskWorkSpace.cs index 7c8ad37..098c999 100644 --- a/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskWorkSpace.cs +++ b/Assets/URS/YooAsset/Editor/BuildTask/BuildTaskWorkSpace.cs @@ -46,6 +46,17 @@ public void DoNextTask() } } } + + public void StartAndWaitComplete() + { + this.DoNextTask(); + + while (this.HasAnyWork() && !this.hasException) + { + this.Update(); + } + } + public void Update() { if (_buildException != null) diff --git a/Assets/URS/YooAsset/Editor/BuildTask/SBPTask/BuidTaskCheckBundleHash.cs b/Assets/URS/YooAsset/Editor/BuildTask/SBPTask/BuidTaskCheckBundleHash.cs new file mode 100644 index 0000000..b5170e4 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/BuildTask/SBPTask/BuidTaskCheckBundleHash.cs @@ -0,0 +1,182 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor.Build.Content; +using UnityEditor.Build.Pipeline; +using UnityEditor.Build.Pipeline.Injector; +using UnityEditor.Build.Pipeline.Interfaces; +using UnityEditor; +using UnityEngine; +using UnityEditor.Build.Pipeline.Utilities; + +namespace URS +{ + [Serializable] + public class BundleHash { + + [SerializeField] + public BundleHashItem[] bundleHashItems; + + [NonSerialized] + private Dictionary lookUp = null; + + public void Init() + { + lookUp = new Dictionary(); + if (bundleHashItems != null && bundleHashItems.Length > 0) + { + foreach (var item in bundleHashItems) + { + lookUp[item.BundleName] = item; + } + } + } + + public void Compare(BundleHash another, HashSet differentFileHashBundleName) + { + foreach (var item in lookUp) + { + var bundleName = item.Key; + var fileHashIsDifferent = differentFileHashBundleName.Contains(bundleName); + if (another.lookUp.ContainsKey(bundleName)) { + var myBundleHash = item.Value; + var anotherhash = another.lookUp[bundleName]; + if (fileHashIsDifferent) + { + Debug.LogError($">>>>>>>>>>>>>>bundleName{bundleName} file hash is different: {fileHashIsDifferent} my :{myBundleHash.ToString()} another:{anotherhash.ToString()}"); + if (myBundleHash.OrignBundleAssetHash == anotherhash.OrignBundleAssetHash) { + Debug.LogError($"<<<<<<<<<< + /// The BuildTask used to generate the bundle layout. + /// + public class BuidTaskCheckBundleHash : IBuildTask + { + const int k_Version = 1; + + /// + /// The BuidTaskCheckBundleHash version. + /// + public int Version { get { return k_Version; } } + + public BundleHash BundleHash = new BundleHash(); + + [InjectContext(ContextUsage.In)] + IBuildParameters m_Parameters; + + [InjectContext] + IBundleWriteData m_BundleWriteData; + + [InjectContext(ContextUsage.In, true)] + IBuildLogger m_Log; + + [InjectContext] + IBuildResults m_Results; + + [InjectContext(ContextUsage.In)] + IDependencyData m_DependencyData; + + [InjectContext(ContextUsage.In)] + IBundleBuildResults m_BuildBundleResults; + + [InjectContext(ContextUsage.In)] + IWriteData m_WriteData; +#pragma warning restore 649 + + + /// + /// Runs the build task with the injected context. + /// + /// The success or failure ReturnCode + public ReturnCode Run() + { + Dictionary> bundleToObjectIds = new Dictionary>(); + + foreach (var item in m_BundleWriteData.FileToObjects) + { + var fileName = item.Key; + var objectIds = item.Value; + var bundleName = m_BundleWriteData.FileToBundle[fileName]; + + HashSet ids = null; + if (bundleToObjectIds.ContainsKey(bundleName)) + { + ids = bundleToObjectIds[bundleName]; + } + else + { + ids = new HashSet(); + bundleToObjectIds[bundleName] = ids; + } + foreach (var id in objectIds) + { + if (!ids.Contains(id)) + { + ids.Add(id); + } + } + } + List bundleItems = new List(); + foreach (var item in bundleToObjectIds) + { + List hashs = new List(); + var idList = item.Value.ToList(); + var bundleName = item.Key; + idList.Sort((a, b) => { + if (a > b) + return 1; + else + return -1; + }); + foreach (var id in item.Value) + { + if (id.fileType == FileType.MetaAssetType || id.fileType == FileType.SerializedAssetType) + { + var guid = id.guid; + hashs.Add(AssetDatabase.GetAssetDependencyHash(guid)); + } + } + BundleHashItem hashItem = new BundleHashItem(); + hashItem.BundleName = bundleName; + hashItem.OrignBundleAssetHash = HashingMethods.Calculate(hashs).ToHash128().ToString(); + hashItem.ResultBundleCrc = m_BuildBundleResults.BundleInfos[bundleName].Crc; + hashItem.ResultBundleHash = m_BuildBundleResults.BundleInfos[bundleName].Hash.ToString(); + hashItem.ResultBundleContentHash = m_BuildBundleResults.BundleInfos[bundleName].ContentHash.ToString(); + bundleItems.Add(hashItem); + } + BundleHash.bundleHashItems = bundleItems.ToArray(); + return ReturnCode.Success; + } + } +} diff --git a/Assets/URS/YooAsset/Editor/BuildTask/SBPTask/BuidTaskCheckBundleHash.cs.meta b/Assets/URS/YooAsset/Editor/BuildTask/SBPTask/BuidTaskCheckBundleHash.cs.meta new file mode 100644 index 0000000..7c4fcd4 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/BuildTask/SBPTask/BuidTaskCheckBundleHash.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 70d891424d26c094f86ea7fb465cca84 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/BuildTask/SBPTask/BuildLayout.cs b/Assets/URS/YooAsset/Editor/BuildTask/SBPTask/BuildLayout.cs index 74fa444..2874d59 100644 --- a/Assets/URS/YooAsset/Editor/BuildTask/SBPTask/BuildLayout.cs +++ b/Assets/URS/YooAsset/Editor/BuildTask/SBPTask/BuildLayout.cs @@ -86,14 +86,17 @@ public class Bundle /// /// The name of the AssetBundle /// + [SerializeField] public string Name; /// /// The file size of the AssetBundle on disk, in bytes /// + [SerializeField] public ulong FileSize; /// /// The Compression method used for the AssetBundle. /// + [SerializeField] public string Compression; /// @@ -106,8 +109,11 @@ public class Bundle /// List of the Files referenced by the AssetBundle /// [SerializeReference] + [NonSerialized] public List Files = new List(); + [SerializeField] + public string[] files; /// /// A list of the direct dependencies of the AssetBundle /// @@ -118,7 +124,25 @@ public class Bundle /// The full dependency list, flattened into a list /// [SerializeReference] + [NonSerialized] public List ExpandedDependencies; + + + [SerializeField] + public string[] expandedDependencies; + + private bool prepared= false; + public void PrepareSerialize() + { + if(prepared) return; + prepared = true; + + Files.ForEach(f => f.PrepareSerialize()); + ExpandedDependencies.ForEach(f => f.PrepareSerialize()); + + files = Files.Select(file => file.Name).ToArray(); + expandedDependencies= ExpandedDependencies.Select(ed => ed.Name).ToArray(); + } } /// @@ -150,52 +174,96 @@ public class File /// /// The name of the File. /// + [SerializeField] public string Name; /// /// The AssetBundle data that relates to a built file. /// + [NonSerialized] [SerializeReference] public Bundle Bundle; + [SerializeField] + public string BundleName; + /// /// List of the resource files created by the build pipeline that a File references /// [SerializeReference] + [NonSerialized] public List SubFiles = new List(); + + [SerializeField] + public SubFile[] subFiles; /// /// A list of the explicit asset defined in the AssetBundle /// [SerializeReference] + [NonSerialized] public List Assets = new List(); + [SerializeField] + public string[] assets; + /// /// A list of implicit assets built into the AssetBundle, typically through references by Assets that are explicitly defined. /// [SerializeReference] + [NonSerialized] public List OtherAssets = new List(); + [SerializeField] + public DataFromOtherAsset[] otherAssets; /// /// The final filename of the AssetBundle file /// + [SerializeField] public string WriteResultFilename; /// /// Data about the AssetBundleObject /// + [SerializeField] public AssetBundleObjectInfo BundleObjectInfo; /// /// The size of the data that needs to be preloaded for this File. /// + [SerializeField] public int PreloadInfoSize; /// /// The number of Mono scripts referenced by the File /// + [SerializeField] public int MonoScriptCount; /// /// The size of the Mono scripts referenced by the File /// + [SerializeField] public ulong MonoScriptSize; + + + + private bool prepared = false; + public void PrepareSerialize() + { + if (prepared) return; + prepared = true; + + if (Bundle != null) + { + Bundle.PrepareSerialize(); + BundleName = Bundle.Name; + } + + + OtherAssets.ForEach(asset => asset.PrepareSerialize()); + Assets.ForEach((asset) => { asset.PrepareSerialize(); }); + + + otherAssets = OtherAssets.ToArray(); + assets= Assets.Select(ea=>ea.AssetPath).ToArray(); + } } /// @@ -207,43 +275,91 @@ public class ExplicitAsset /// /// The Asset Guid. /// + [SerializeField] public string Guid; /// /// The Asset path on disk /// + /// + [SerializeField] public string AssetPath; /// /// The Addressable address defined in the Addressable Group window for an Asset. /// + [SerializeField] public string AddressableName; /// /// The size of the file on disk. /// + [SerializeField] public ulong SerializedSize; /// /// The size of the streamed Asset. /// + [SerializeField] public ulong StreamedSize; /// /// The file that the Asset was added to /// [SerializeReference] + [NonSerialized] public File File; + + + [SerializeField] + public string file; /// /// List of data from other Assets referenced by an Asset in the File /// [SerializeReference] + [NonSerialized] public List InternalReferencedOtherAssets = new List(); + + [SerializeField] + public DataFromOtherAsset[] internalReferencedOtherAssets; + /// /// List of explicit Assets in the File /// [SerializeReference] + [NonSerialized] public List InternalReferencedExplicitAssets = new List(); + + [SerializeField] + public string[] internalReferencedExplicitAssets; /// /// List of Assets referenced by the File, but not included in the File. /// [SerializeReference] + [NonSerialized] public List ExternallyReferencedAssets = new List(); + + + [SerializeField] + public string[] externallyReferencedAssets; + + private bool prepared = false; + public void PrepareSerialize() + { + if (prepared) { return; } + prepared = true; + + if (File != null) + { + File.PrepareSerialize(); + file = File.Name; + } + + InternalReferencedOtherAssets.ForEach((roa)=>roa.PrepareSerialize()); + internalReferencedOtherAssets= InternalReferencedOtherAssets.ToArray(); + + InternalReferencedExplicitAssets.ForEach((roa) => roa.PrepareSerialize()); + internalReferencedExplicitAssets = InternalReferencedExplicitAssets.Select(ea=>ea.AssetPath).ToArray(); + + + ExternallyReferencedAssets.ForEach((roa) => roa.PrepareSerialize()); + externallyReferencedAssets = ExternallyReferencedAssets.Select(ea => ea.AssetPath).ToArray(); + } } /// @@ -255,30 +371,49 @@ public class DataFromOtherAsset /// /// The Guid of the Asset /// + [SerializeField] public string AssetGuid; /// /// The Asset path on disk - /// + /// /// A list of Assets that reference this data /// [SerializeReference] + [NonSerialized] public List ReferencingAssets = new List(); + [SerializeField] + public string[] referencingAssets; /// /// The number of Objects in the data /// + [SerializeField] public int ObjectCount; /// /// The size of the data on disk /// + [SerializeField] public ulong SerializedSize; /// /// The size of the streamed data /// + [SerializeField] public ulong StreamedSize; + + private bool prepared = false; + public void PrepareSerialize() + { + if (prepared) return; + prepared = true; + + ReferencingAssets.ForEach((ea)=>ea.PrepareSerialize()); + var list = ReferencingAssets.Select(ea=>ea.AssetPath); + referencingAssets= list.ToArray(); + } } /// @@ -297,24 +432,55 @@ public class DataFromOtherAsset /// /// Utility used to quickly reference data built with the build pipeline /// + /// + [Serializable] public class LayoutLookupTables { /// /// The AssetBundle name to the Bundle data map. /// + [NonSerialized] public Dictionary Bundles = new Dictionary(); /// /// File name to File data map. /// + [NonSerialized] public Dictionary Files = new Dictionary(); /// /// Guid to ExplicitAsset data map. /// + /// + [NonSerialized] public Dictionary GuidToExplicitAsset = new Dictionary(); /// /// Group name to Group data map. /// // public Dictionary GroupLookup = new Dictionary(); + + [SerializeField] + public BuildLayout.Bundle[] bundles; + + [SerializeField] + public BuildLayout.File[] files; + + [SerializeField] + public BuildLayout.ExplicitAsset[] explicitAssets; + + public void PrepareSerialize() + { + var bundleList = Bundles.Values.ToList(); + bundleList.ForEach(bundle => { bundle.PrepareSerialize(); }); + bundles = bundleList.ToArray(); + + var fileList = Files.Values.ToList(); + fileList.ForEach(file => { file.PrepareSerialize(); }); + files = fileList.ToArray(); + + var guidToExplicit = GuidToExplicitAsset.Values.ToList(); + guidToExplicit.ForEach(ea => { ea.PrepareSerialize(); }); + explicitAssets = guidToExplicit.ToArray(); + } + } /// /// Helper methods for gathering data about a build layout. diff --git a/Assets/URS/YooAsset/Editor/BuildTask/SBPTask/BuildLayoutGenerationTask.cs b/Assets/URS/YooAsset/Editor/BuildTask/SBPTask/BuildLayoutGenerationTask.cs index 935b1c7..c41b493 100644 --- a/Assets/URS/YooAsset/Editor/BuildTask/SBPTask/BuildLayoutGenerationTask.cs +++ b/Assets/URS/YooAsset/Editor/BuildTask/SBPTask/BuildLayoutGenerationTask.cs @@ -17,7 +17,7 @@ public class BuildLayoutGenerationTask : IBuildTask { const int k_Version = 1; - internal static Action s_LayoutCompleteCallback; + public LayoutLookupTables LayoutLookupTables { get; private set; } /// /// The GenerateLocationListsTask version. @@ -262,16 +262,21 @@ private LayoutLookupTables CreateBuildLayout() /// The success or failure ReturnCode public ReturnCode Run() { - LayoutLookupTables LayoutLookupTables = CreateBuildLayout(); - + LayoutLookupTables lookTable = CreateBuildLayout(); + lookTable.PrepareSerialize(); var path = (m_Parameters as BuildParameters).OutputFolder + "/buildlayout.txt"; Directory.CreateDirectory(Path.GetDirectoryName(path)); - using (FileStream s = File.Open(path, FileMode.Create)) - BuildLayoutPrinter.WriteBundleLayout(s, LayoutLookupTables); + // using (FileStream s = File.Open(path, FileMode.Create)) + // BuildLayoutPrinter.WriteBundleLayout(s, LayoutLookupTables); + if (File.Exists(path)) + { + File.Delete(path); + } + File.WriteAllText(path,UnityEngine.JsonUtility.ToJson(lookTable,true)); UnityEngine.Debug.Log($"Build layout written to {path}"); - s_LayoutCompleteCallback?.Invoke(LayoutLookupTables); + this.LayoutLookupTables = lookTable; return ReturnCode.Success; } diff --git a/Assets/URS/YooAsset/Editor/BuildTaskAwaitable.cs b/Assets/URS/YooAsset/Editor/BuildTaskAwaitable.cs new file mode 100644 index 0000000..1a7b94c --- /dev/null +++ b/Assets/URS/YooAsset/Editor/BuildTaskAwaitable.cs @@ -0,0 +1,72 @@ + +using UnityEditor; +using System; +using System.IO; +using UnityEngine; +using TagInfo = System.Collections.Generic.Dictionary; +using Context = System.Collections.Generic.Dictionary; +using Debug = UnityEngine.Debug; +using NinjaBeats; + + +namespace URS +{ + public static partial class Build + { + public class BuildTaskAwaitable : System.Runtime.CompilerServices.INotifyCompletion + { + protected Action Continuation; + public object Result { get; protected set; } + public bool IsCompleted { get; protected set; } + + public void OnCompleted(Action continuation) + { + if (IsCompleted) + { + continuation?.Invoke(); + } + else + { + if (continuation != null) + Continuation += continuation; + } + } + + public void SetDone() + { + if (IsCompleted) + return; + Result = null; + IsCompleted = true; + Continuation?.Invoke(); + } + + public object GetResult() => Result; + + public BuildTaskAwaitable GetAwaiter() => this; + } + + public static BuildTaskAwaitable WaitBuildTask() + { + BuildTaskAwaitable r = new(); + EditorApplication.CallbackFunction func = null; + func = () => + { + if (hasTask) + { + if (_buildTaskWorkSpaces[0].hasException) + EditorApplication.Exit(1); + return; + } + + EditorApplication.update -= func; + r.SetDone(); + }; + EditorApplication.update += func; + return r; + } + + + } +} + diff --git a/Assets/URS/YooAsset/Editor/BuildTaskAwaitable.cs.meta b/Assets/URS/YooAsset/Editor/BuildTaskAwaitable.cs.meta new file mode 100644 index 0000000..5d12805 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/BuildTaskAwaitable.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 643e5011f4790a44eae070ead9ef0014 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/BuildTaskProcess.cs b/Assets/URS/YooAsset/Editor/BuildTaskProcess.cs new file mode 100644 index 0000000..180bdfb --- /dev/null +++ b/Assets/URS/YooAsset/Editor/BuildTaskProcess.cs @@ -0,0 +1,42 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +using System; +using System.IO; +using UnityEngine; +using TagInfo = System.Collections.Generic.Dictionary; +using Context = System.Collections.Generic.Dictionary; +using Debug = UnityEngine.Debug; +namespace URS +{ + public static partial class Build + { + public static void UploadCdnSyn(string channel) + { + var context = new Context(); + var buildWS = new BuildTaskWorkSpace(); + buildWS.Init(context); + buildWS.EnqueueTask(GenUploadCdnBuildTask(channel)) ; + Build.AddBuildTaskWorkSpace(buildWS); + } + + public class BuildTaskExcuteCmd : BuildTask + { + private string mCmd = null; + private string mCmdArg = null; + public BuildTaskExcuteCmd(string cmd, string cmdArg) { + mCmd = cmd; + mCmdArg= cmdArg; + } + public override void BeginTask() + { + base.BeginTask(); + SimpleExec.Command.RunAsync(mCmd, mCmdArg).Wait(); + this.FinishTask(); + } + } + } +} + + diff --git a/Assets/URS/YooAsset/Editor/BuildTaskProcess.cs.meta b/Assets/URS/YooAsset/Editor/BuildTaskProcess.cs.meta new file mode 100644 index 0000000..6d8d745 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/BuildTaskProcess.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: df1ee211181cf3b45aaaab3ed5eeaf76 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/BuildTaskUploadCDN.cs b/Assets/URS/YooAsset/Editor/BuildTaskUploadCDN.cs new file mode 100644 index 0000000..6e5feb5 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/BuildTaskUploadCDN.cs @@ -0,0 +1,30 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; +using System.Threading.Tasks; + +namespace URS +{ + public static partial class Build + { + + public static BuildTaskExcuteCmd GenUploadCdnBuildTask(string channel) + { + string cmd = @"coscmd"; + string cmdString = $" upload -rsy --delete {Application.dataPath}/../{Build.GetChannelRoot()}/{channel} /{channel}"; + // Debug.LogError(""+ cmdString); + return new BuildTaskExcuteCmd(cmd, cmdString); + } + [MenuItem("URS/UploadCDNASyn(非阻塞上传cdn)")] + public static Task GenUploadCdnTask(string channel) + { + string cmd = @"coscmd"; + string cmdString = $" upload -rsy --delete {Application.dataPath}/../{Build.GetChannelRoot()}/{channel} /{channel}"; + // Debug.LogError(""+ cmdString); + var task= SimpleExec.Command.RunAsync(cmd, cmdString); + return task; + } + } +} + diff --git a/Assets/URS/YooAsset/Editor/BuildTaskUploadCDN.cs.meta b/Assets/URS/YooAsset/Editor/BuildTaskUploadCDN.cs.meta new file mode 100644 index 0000000..9da7e97 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/BuildTaskUploadCDN.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6e09c3f730e26e0438e2e1aa174b3dd2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/CommandLine.Build.cs b/Assets/URS/YooAsset/Editor/CommandLine.Build.cs new file mode 100644 index 0000000..dbb91e7 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/CommandLine.Build.cs @@ -0,0 +1,305 @@ + +using System.IO; +using System.Threading.Tasks; +using UnityEditor; +using UnityEngine; + +namespace NinjaBeats +{ + public static partial class CommandLine + { + public enum Enum_Build_CommandLine_Arg + { + IL2CPP, + ENABLE_HE_SDK, + ONLY_EXPORT_PROJECT, + BUILD_CHANNEL, + HESDK_CHANNEL, + BUILD_VERSION, + BUILD_NUMBER, + APP_IDENTIFIER, + } + + + private static bool GetArg(Enum_Build_CommandLine_Arg type, out string arg) + { + arg = EditorUtils.CommandLineGetArgValue(type.ToString()); + if (string.IsNullOrWhiteSpace(arg)) + { + Debug.LogError($"{type.ToString()} is invalid"); + EditorApplication.Exit(1); + return false; + } + return true; + } + + private static bool GetArgInt(Enum_Build_CommandLine_Arg type, out int arg) + { + arg = EditorUtils.CommandLineGetArgValueInt(type.ToString()); + if (arg == 0) + { + Debug.LogError($"{type.ToString()} is invalid"); + EditorApplication.Exit(1); + return false; + } + return true; + } + + // 收集Shader变体 + public static void ExportShader() + { + EditorUtils.RunCommandLineAsync(async () => + { + URS.Build.ExportShaderVariantCollection(); + + await URS.Build.WaitBuildTask(); + + return true; + }); + } + + + private static string GenerateVersion(string channel, string ver) + { + if (!System.Version.TryParse(ver, out var version)) + return ver; + + var build = version.Build; + + var stored_version_path = Path.Combine(Application.dataPath, $"../BuildInfo/{channel}/stored_version.txt"); + if (build == 0) + { + var str = EditorUtils.ReadAllText(stored_version_path); + if (!string.IsNullOrWhiteSpace(str) && System.Version.TryParse(str, out var stored_version)) + { + if (version.Major == stored_version.Major && version.Minor == stored_version.Minor) + { + build = stored_version.Build + 1; + } + } + } + + var r = $"{version.Major}.{version.Minor}.{build}"; + EditorUtils.WriteAllText(stored_version_path, r); + return r; + } + + private static bool PrepareBuildEnvironment(out string channel,out string buildingResourceVersion,out string buildInResourceVersion) + { + channel = null; + buildingResourceVersion= null; + buildInResourceVersion= null; + if (!GetArg(Enum_Build_CommandLine_Arg.APP_IDENTIFIER, out var APP_IDENTIFIER)) + return false; + if (!GetArg(Enum_Build_CommandLine_Arg.BUILD_CHANNEL, out var BUILD_CHANNEL)) + return false; + if (!GetArg(Enum_Build_CommandLine_Arg.HESDK_CHANNEL, out var HESDK_CHANNEL)) + return false; + if (!GetArg(Enum_Build_CommandLine_Arg.BUILD_VERSION, out var BUILD_VERSION)) + return false; + if (!GetArgInt(Enum_Build_CommandLine_Arg.BUILD_NUMBER, out var BUILD_NUMBER)) + return false; + + BUILD_VERSION = GenerateVersion(BUILD_CHANNEL, BUILD_VERSION); + + // [包]的版本号 + PlayerSettings.bundleVersion = BUILD_VERSION; + // [包]的构建号 + PlayerSettings.Android.bundleVersionCode = BUILD_NUMBER; +#if UNITY_EDITOR_OSX || UNITY_IOS + // [包]的构建号 + PlayerSettings.iOS.buildNumber = BUILD_NUMBER.ToString(); +#endif + + // [资源]APP标识 + //URSEditorUserSettings.instance.AppId = APP_IDENTIFIER; + // [资源]渠道 + //URSEditorUserSettings.instance.BuildChannel = BUILD_CHANNEL; + channel= BUILD_CHANNEL; + // [资源]的版本号 + // URSEditorUserSettings.instance.BuildVersionCode = $"{BUILD_VERSION}-{BUILD_NUMBER}"; + buildingResourceVersion= $"{BUILD_VERSION}-{BUILD_NUMBER}"; + // [资源]的版本号(进[包]的) + // URSEditorUserSettings.instance.CopyToStreamTargetVersion = $"{BUILD_VERSION}-{BUILD_NUMBER}"; + buildInResourceVersion= $"{BUILD_VERSION}-{BUILD_NUMBER}"; + + return true; + } + + // 生成资源补丁包 + public static void BuildResourcePatch() + { + EditorUtils.RunCommandLineAsync(async () => + { + // if (!PrepareBuildEnvironment()) + // return false; + // + // URS.Build.BuildChannelRouter(); + // + // await URS.Build.WaitBuildTask(); + + return true; + }); + } + + // 准备cdn的资源 + public static void BuildResource() + { + EditorUtils.RunCommandLineAsync(async () => + { + if (!PrepareBuildEnvironment(out var channel, out var buildingResourceVersion, out var buildInResourceVersion)) + { + return false; + } + + Debug.Log("BuildResource HybridBuild 开始: channel " + channel+" " + UnityMacro.Instance.MAINTENANCE_VERSION_COUNT); + + URS.Build.HybridBuild(buildingResourceVersion, buildInResourceVersion, channel,true,true,false,false,false); + + await URS.Build.WaitBuildTask(); + + Debug.Log("BuildResource BuildAutoChannelVersionsAndUploadCDN 开始: channel " + channel + " " + UnityMacro.Instance.MAINTENANCE_VERSION_COUNT); + + URS.Build.BuildAutoChannelVersionsAndUploadCDN( + channel, + null, + UnityMacro.Instance.MAINTENANCE_VERSION_COUNT, + true); + + await URS.Build.WaitBuildTask(); + return true; + }); + } + public static void UploadCdn() + { + EditorUtils.RunCommandLineAsync(async () => + { + if (!PrepareBuildEnvironment(out var channel, out var buildingResourceVersion, out var buildInResourceVersion)) + return false; + + URS.Build.UploadCdnSyn(channel); + + await URS.Build.WaitBuildTask(); + + return true; + }); + } + public static void ClearBundleCache() + { + EditorUtils.RunCommandLineAsync(async () => + { + if (!PrepareBuildEnvironment(out var channel, out var buildingResourceVersion, out var buildInResourceVersion)) + return false; + + URS.Build.ClearBundleCache(); + + await URS.Build.WaitBuildTask(); + + return true; + }); + } + + public static void ReImportResource() + { + EditorUtils.RunCommandLine(() => + { + if (!PrepareBuildEnvironment(out var channel, out var buildingResourceVersion, out var buildInResourceVersion)) + return false; + + AssetDatabase.ImportAsset("Assets/GameResources/", ImportAssetOptions.ForceUpdate | ImportAssetOptions.ImportRecursive); + + return true; + }); + + } + + // 打资源且打包 + public static void Build() + { + EditorUtils.RunCommandLineAsync(async () => + { + if (!PrepareBuildEnvironment(out var channel, out var buildingResourceVersion, out var buildInResourceVersion)) + return false; + + bool IL2CPP = EditorUtils.CommandLineHasArg(nameof(Enum_Build_CommandLine_Arg.IL2CPP)); + bool ONLY_EXPORT_PROJECT = EditorUtils.CommandLineHasArg(nameof(Enum_Build_CommandLine_Arg.ENABLE_HE_SDK)) || EditorUtils.CommandLineHasArg(nameof(Enum_Build_CommandLine_Arg.ONLY_EXPORT_PROJECT)); + + PlayerSettings.Android.targetSdkVersion = AndroidSdkVersions.AndroidApiLevel30; + + if (UnityMacro.Instance.ENABLE_DEVELOPMENT_BUILD) + { + IL2CPP = false; + } + + if (!UnityMacro.Instance.ENABLE_HESDK) + { + ONLY_EXPORT_PROJECT = false; + } + + if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS) + { + IL2CPP = true; + ONLY_EXPORT_PROJECT = true; + } + + PlayerSettings.SetAdditionalIl2CppArgs(""); + EditorUserBuildSettings.development = UnityMacro.Instance.ENABLE_DEVELOPMENT_BUILD; + EditorUserBuildSettings.buildWithDeepProfilingSupport = UnityMacro.Instance.ENABLE_DEVELOPMENT_BUILD; + EditorUserBuildSettings.allowDebugging = UnityMacro.Instance.ENABLE_DEVELOPMENT_BUILD; + EditorUserBuildSettings.connectProfiler = UnityMacro.Instance.ENABLE_DEVELOPMENT_BUILD; + EditorUserBuildSettings.waitForManagedDebugger = UnityMacro.Instance.ENABLE_DEVELOPMENT_BUILD; + EditorUserBuildSettings.waitForPlayerConnection = UnityMacro.Instance.ENABLE_DEVELOPMENT_BUILD; + + bool configSuccess = false; + if (!ONLY_EXPORT_PROJECT) + { + if (IL2CPP) + configSuccess= URS.Build.BuildResourceAndPlayer_Standard_Config(); + else + configSuccess= URS.Build.BuildResourceAndPlayer_Fast_Config(); + } + else + { + if (IL2CPP) + configSuccess= URS.Build.ExportAndroidProject_IL2CPP_Config(); + else + configSuccess= URS.Build.ExportAndroidProject_Mono_Config(); + } + if (configSuccess) + { + URS.Build.HybridBuild( + buildingResourceVersion, + buildInResourceVersion, + channel, + true, + true, + false, + false, + false); + await URS.Build.WaitBuildTask(); + if (UnityMacro.Instance.ENABLE_HOTUPDATE) + { + URS.Build.BuildAutoChannelVersionsAndUploadCDN( + channel, + buildingResourceVersion, + UnityMacro.Instance.MAINTENANCE_VERSION_COUNT); + } + await URS.Build.WaitBuildTask(); + + Task uploadCdnTask = null; + if (UnityMacro.Instance.ENABLE_HOTUPDATE) + { + uploadCdnTask = URS.Build.GenUploadCdnTask(channel); + } + URS.Build.BuildPlayerWithBuildInResource( + buildInResourceVersion, + channel); + await URS.Build.WaitBuildTask(); + if (uploadCdnTask != null) + await uploadCdnTask; + } + return true; + }); + } + } +} \ No newline at end of file diff --git a/Assets/URS/YooAsset/Editor/CommandLine.Build.cs.meta b/Assets/URS/YooAsset/Editor/CommandLine.Build.cs.meta new file mode 100644 index 0000000..2da6e97 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/CommandLine.Build.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1672e1ed9da491e418567aabc66128c6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/Core/URSCore/VersionBuilder.cs b/Assets/URS/YooAsset/Editor/Core/URSCore/VersionBuilder.cs index 0b710d9..d4f3e62 100644 --- a/Assets/URS/YooAsset/Editor/Core/URSCore/VersionBuilder.cs +++ b/Assets/URS/YooAsset/Editor/Core/URSCore/VersionBuilder.cs @@ -8,12 +8,76 @@ using SemanticVersion = SemanticVersioning.SemanticVersion; using MHLab.Patch.Core.Octodiff; using YooAsset.Utility; +using UnityEditor; +using Context = System.Collections.Generic.Dictionary; namespace URS.Editor { + [Serializable] + public class VersionHistory + { + [SerializeField] + public AssetVersionHistory AssetVersion; + + [SerializeField] + public AssetBundleVersionHistory AssetBundleVersion; + + [SerializeField] + public LayoutLookupTables BundleLayout; + + [SerializeField] + public BundleHash BundleHash; + + [SerializeField] + public string BundleBuildLog; + } + [Serializable] + public class AssetVersionHistory + { + [SerializeField] + public AssetVersionItem[] Assets; + } + [Serializable] + public class AssetBundleVersionHistory + { + [SerializeField] + public AssetBundleVersionItem[] AssetBundles; + } + + [Serializable] + public class AssetVersionItem + { + [SerializeField] + public string AssetPath; + + [SerializeField] + public uint AssetFileHash; + + [SerializeField] + public bool HasAssetBundleName; + + [SerializeField] + public string AssetBundleName; + } + + [Serializable] + public class AssetBundleVersionItem + { + [SerializeField] + public string BundleName; + + [SerializeField] + public string [] AssetPaths; + + public string SelfHash; + + public string CRC; + + public string HashCode; + } public class VersionBuilder { - public static void BuildVersion(string directoryPath, IFileSystem fileSystem,string version,Dictionary additionFileInfo,out string newDirectoryName) + public static void BuildVersion(string channel,string directoryPath, IFileSystem fileSystem,string version,Dictionary additionFileInfo, VersionHistory versionHistrory,out string newDirectoryName,bool debug) { var orignDirectoryName = Path.GetDirectoryName(directoryPath); newDirectoryName = orignDirectoryName; @@ -63,7 +127,7 @@ public static void BuildVersion(string directoryPath, IFileSystem fileSystem,str { return a.RelativePath.CompareTo(b.RelativePath); }); - var fileManifest = new FileManifest(finalAarry); + var fileManifest = new FileManifest(finalAarry, version); var json = JsonUtility.ToJson(fileManifest, true); var setting = URSRuntimeSetting.instance; var jsonPath = fileSystem.CombinePaths(directoryPath, setting.FileManifestFileName); @@ -76,7 +140,10 @@ public static void BuildVersion(string directoryPath, IFileSystem fileSystem,str newDirectoryName = tmpNewDirectoryName; fileSystem.DirectoryRename(directoryPath, newDirectoryName); } - + if (debug) + { + BuildHistory(channel,tmpNewDirectoryName, versionHistrory); + } } else { @@ -85,6 +152,53 @@ public static void BuildVersion(string directoryPath, IFileSystem fileSystem,str } + public static void BuildHistory(string channel,string versionName, VersionHistory versionHistrory) + { + if (versionHistrory == null) return; + var versionDirectory = $"{URS.Build.GetVersionHistoryFolder(channel)}/{versionName}"; + Directory.CreateDirectory(versionDirectory); + + var assetVersionHistoryFilePath = $"{versionDirectory}/AssetVersionHistory.json"; + if (File.Exists(assetVersionHistoryFilePath)) + { + File.Delete(assetVersionHistoryFilePath); + } + + var assetVersionHistoryJson = JsonUtility.ToJson(versionHistrory.AssetVersion, true); + File.WriteAllText(assetVersionHistoryFilePath, assetVersionHistoryJson); + + + var assetBundleVersionHistoryFilePath = $"{versionDirectory}/AssetBundleVersionHistory.json"; + if (File.Exists(assetBundleVersionHistoryFilePath)) + { + File.Delete(assetBundleVersionHistoryFilePath); + } + + var assetBundleVersionHistoryJson = JsonUtility.ToJson(versionHistrory.AssetBundleVersion, true); + File.WriteAllText(assetBundleVersionHistoryFilePath, assetBundleVersionHistoryJson); + + var assetBundleHashHistoryFilePath = $"{versionDirectory}/{ASSET_BUNDLE_HASH_HISTORY_FILE_NAME}"; + if (File.Exists(assetBundleHashHistoryFilePath)) + { + File.Delete(assetBundleHashHistoryFilePath); + } + + var assetBundleHashHistoryJson = JsonUtility.ToJson(versionHistrory.BundleHash, true); + File.WriteAllText(assetBundleHashHistoryFilePath, assetBundleHashHistoryJson); + + var bundleBuildLog = $"{versionDirectory}/{ASSET_BUNDLE_BUNDLE_BUILD_LOG_HISTORY_FILE_NAME}"; + if (File.Exists(bundleBuildLog)) + { + File.Delete(bundleBuildLog); + } + File.WriteAllText(bundleBuildLog, versionHistrory.BundleBuildLog); + + } + + public const string ASSET_BUNDLE_HASH_HISTORY_FILE_NAME = "AssetBundleHashHistory.json"; + + public const string ASSET_BUNDLE_BUNDLE_BUILD_LOG_HISTORY_FILE_NAME = "buildlogtep.json"; + public static void BuildVersions(string versionRootDirectory,IFileSystem fileSystem) { var setting = URSRuntimeSetting.instance; @@ -95,7 +209,7 @@ public static void BuildVersions(string versionRootDirectory,IFileSystem fileSys var di = new DirectoryInfo(versionRootDirectory); foreach (DirectoryInfo subDirectory in di.GetDirectories()) { - Debug.LogError(subDirectory.Name); + //Debug.LogError(subDirectory.Name); var name = subDirectory.Name; var names = name.Split("---"); var versionCode = names[0]; @@ -129,13 +243,59 @@ public static void BuildVersions(string versionRootDirectory,IFileSystem fileSys fileSystem.WriteAllTextToFile(IndexJsonPath, IndexJson); } - public static void BuildPatch(string versionRootDirectory,IFileSystem fileSystem, string targetVersionCode = null) + public static void PurgeVersion(string versionRootDirectory, IFileSystem fileSystem,string targetVersion, int maxVersionCount = 4) + { + var setting = URSRuntimeSetting.instance; + var IndexJsonPath = fileSystem.CombinePaths(versionRootDirectory, setting.FilesVersionIndexFileName); + var jsonText = fileSystem.ReadAllTextFromFile(IndexJsonPath); + var versionIndex = JsonUtility.FromJson(jsonText); + versionIndex.AfterSerialize(); + if (versionIndex.Versions == null || versionIndex.Versions.Length <= maxVersionCount) + { + Debug.Log($"当前的版本数量{versionIndex.Versions.Length},小于目标数量{maxVersionCount},跳过跳过版本裁剪"); + return; + } + else + { + int purgeCount = versionIndex.Versions.Length - maxVersionCount; + for (int i = 0; i < purgeCount; i++) + { + var versionCode = versionIndex.Versions[i].VersionCode; + if (versionCode == targetVersion) + { + break;// 这样情况一般就是出现了版本回退,版本回退的时候,一般保留高版本 + } + var currentDirectoryName = $"{versionCode}---{versionIndex.Versions[i].FilesVersionHash}"; + var versionDirectory = fileSystem.CombinePaths(versionRootDirectory, currentDirectoryName).FullPath; + if (!Directory.Exists(versionDirectory)) + { + Debug.LogError($"在版本裁剪的过程中遇到不可预知的错误:{versionDirectory}不存在这个版本"); + continue; + } + else + { + fileSystem.DeleteDirectory((FilePath)versionDirectory); + } + } + + BuildVersions(versionRootDirectory, fileSystem); + } + } + + + public static void BuildPatch(string channel,string versionRootDirectory,IFileSystem fileSystem, string targetVersionCode = null,bool debug = false) { + var setting = URSRuntimeSetting.instance; var IndexJsonPath = fileSystem.CombinePaths(versionRootDirectory, setting.FilesVersionIndexFileName); var jsonText = fileSystem.ReadAllTextFromFile(IndexJsonPath); var versionIndex = JsonUtility.FromJson(jsonText); versionIndex.AfterSerialize(); + var patchDirecrtory = fileSystem.CombinePaths(versionRootDirectory, setting.PatchDirectory).FullPath; + if (Directory.Exists(patchDirecrtory)) + { + Directory.Delete(patchDirecrtory,true); + } if (versionIndex.Versions == null || versionIndex.Versions.Length <= 1) { Debug.LogWarning("构建补丁失败,因为当前文件夹没有可用版本,或者版本数量少于2个"); @@ -172,20 +332,29 @@ public static void BuildPatch(string versionRootDirectory,IFileSystem fileSystem } else { - var item = versionIndex.Versions[targetIndex]; - var targetVersionDiretoryName = $"{item.VersionCode}---{item.FilesVersionHash}"; - var patchDirecrtory = fileSystem.CombinePaths(versionRootDirectory, setting.PatchDirectory).FullPath; + var targetVersion = versionIndex.Versions[targetIndex]; + var targetVersionDiretoryName = $"{targetVersion.VersionCode}---{targetVersion.FilesVersionHash}"; var tempDirectory = fileSystem.CombinePaths(versionRootDirectory, setting.PatchTempDirectory).FullPath; var patchItemInfos = new Dictionary>(); - + //var versionDifference= new Dictionary(); for (int i = 0; i < versionIndex.Versions.Length; i++) { if (i != targetIndex) { - var currentDirectoryName = $"{versionIndex.Versions[i].VersionCode}---{versionIndex.Versions[i].FilesVersionHash}"; - BinaryDiffVersionDirectroy(versionRootDirectory, patchDirecrtory, tempDirectory, currentDirectoryName, targetVersionDiretoryName, fileSystem, ref patchItemInfos); + var versionCode = versionIndex.Versions[i].VersionCode; + var currentDirectoryName = $"{versionCode}---{versionIndex.Versions[i].FilesVersionHash}"; + HashSet patchs = null ; + HashSet missPaths= null ; + BinaryDiffVersionDirectroy(versionRootDirectory, patchDirecrtory, tempDirectory, currentDirectoryName, targetVersionDiretoryName, fileSystem, ref patchItemInfos,ref patchs, ref missPaths); + Debug.Log($"From Version{versionCode},To Version{targetVersion.VersionCode},PatchCount {patchs.Count} missCount{missPaths.Count}"); + + if (debug) + { + CheckBundleHash(channel, patchs, currentDirectoryName, targetVersionDiretoryName); + } } } + var patchItems = new List(); foreach (var kv in patchItemInfos) { @@ -200,8 +369,10 @@ public static void BuildPatch(string versionRootDirectory,IFileSystem fileSystem return a.RelativePath.CompareTo(b.RelativePath); }); versionIndex.Patches = pathItemArray; - fileSystem.DeleteDirectory((FilePath)tempDirectory); - + if (Directory.Exists(tempDirectory)) + { + fileSystem.DeleteDirectory((FilePath)tempDirectory); + } var IndexJson = JsonUtility.ToJson(versionIndex, true); File.Delete(IndexJsonPath.FullPath); fileSystem.WriteAllTextToFile(IndexJsonPath, IndexJson); @@ -209,8 +380,53 @@ public static void BuildPatch(string versionRootDirectory,IFileSystem fileSystem } } - private static void BinaryDiffVersionDirectroy(string versionRootDirectory,string patchDirectory,string patchSigDirectory, string fromDirectoryName, string toDirectoryName, IFileSystem fileSystem,ref Dictionary> collector) + private static void CheckBundleHash(string channel,HashSet DifferentPaths, string versionDirectoryName1, string versionDirectoryName2) { + if (DifferentPaths == null || DifferentPaths.Count==0) return; + var historyDirectoryRoot = Build.GetVersionHistoryFolder(channel); + var bundleHashHistory1 = $"{historyDirectoryRoot}/{versionDirectoryName1}/{ASSET_BUNDLE_HASH_HISTORY_FILE_NAME}"; + var bundleHashHistory2 = $"{historyDirectoryRoot}/{versionDirectoryName2}/{ASSET_BUNDLE_HASH_HISTORY_FILE_NAME}"; + if (!File.Exists(bundleHashHistory1)) + { + Debug.LogWarning($"do exist bundle hash history file,path:{bundleHashHistory1}"); + return; + } + if (!File.Exists(bundleHashHistory2)) + { + Debug.LogWarning($"do exist bundle hash history file,path:{bundleHashHistory2}"); + return; + } + var bundleHash1= JsonUtility.FromJson(File.ReadAllText(bundleHashHistory1)); + bundleHash1.Init(); + var bundleHash2 = JsonUtility.FromJson(File.ReadAllText(bundleHashHistory2)); + bundleHash2.Init(); + + HashSet differentBundle= new HashSet(); + foreach (var relativePath in DifferentPaths) + { + var extension = Path.GetExtension(relativePath); + if (extension == ".bundle") + { + var bundleName = Path.GetFileName(relativePath); + differentBundle.Add(bundleName); + } + } + bundleHash1.Compare(bundleHash2, differentBundle); + } + + private static void BinaryDiffVersionDirectroy( + string versionRootDirectory, + string patchDirectory, + string patchSigDirectory, + string fromDirectoryName, + string toDirectoryName, + IFileSystem fileSystem, + ref Dictionary> collector, + ref HashSet differencePaths, + ref HashSet missPaths) + { + differencePaths = new HashSet(); + missPaths = new HashSet() ; var setting = URSRuntimeSetting.instance; fromDirectoryName = fileSystem.CombinePaths(versionRootDirectory, fromDirectoryName).FullPath; toDirectoryName = fileSystem.CombinePaths(versionRootDirectory, toDirectoryName).FullPath; @@ -262,10 +478,14 @@ private static void BinaryDiffVersionDirectroy(string versionRootDirectory,strin if (!collector.ContainsKey(relativePath)) { var list = new List(); + differencePaths.Add(relativePath); + //Debug.Log($"from {fromDirectoryName} to {toDirectoryName} patched asset path: {relativePath}"); list.Add(new PatchItemVersion() { FromHashCode = fromHashCode, - ToHashCode = toHashCode + ToHashCode = toHashCode, + Hash = Hashing.GetFileXXhash(patchPath), + SizeBytes = FileUtility.GetFileSize(patchPath) }); collector.Add(relativePath, list); } @@ -284,43 +504,70 @@ private static void BinaryDiffVersionDirectroy(string versionRootDirectory,strin } if (!find) { + differencePaths.Add(relativePath); + //Debug.Log($"from {fromDirectoryName} to {toDirectoryName} patched asset path: {relativePath}"); list.Add(new PatchItemVersion() { FromHashCode = fromHashCode, - ToHashCode = toHashCode + ToHashCode = toHashCode, + Hash = Hashing.GetFileXXhash(patchPath), + SizeBytes = FileUtility.GetFileSize(patchPath) }); } } } - + + } + else + { + missPaths.Add(relativePath); + //Debug.Log($"from {fromDirectoryName} to {toDirectoryName} miss asset path: {relativePath}"); + // missCount++; } } } - public static void BuildChannleVersionPatches(string channelRoot) + public static void BuildChannelVersions(string channel,string versionRootDirectory , int purgeVersionCount = 4, string targetVersion = null,bool debug=false) { - var routerFilePath = $"{channelRoot}/{URSRuntimeSetting.instance.RemoteAppToChannelRouterFileName}"; - var jsonText = File.ReadAllText(routerFilePath); - var router = JsonUtility.FromJson(jsonText); var fileSystem = new FileSystem(); - for (int i = 0; i < router.Items.Length; i++) + BuildVersions(versionRootDirectory, fileSystem); + if (purgeVersionCount > 0) { - var item = router.Items[i]; - var channel = item.ChannelId; - var version = item.VersionCode; + PurgeVersion(versionRootDirectory, fileSystem, targetVersion, purgeVersionCount); + } + BuildPatch(channel,versionRootDirectory, fileSystem, targetVersion,debug); + } - var channelDirectoryName= $"{Build.GetChannelRoot()}/{channel}"; - DirectoryInfo directoryInfo = new DirectoryInfo(channelDirectoryName); - foreach (var di in directoryInfo.GetDirectories()) - { - var diName = di.Name;// android,ios,windows... - var versionRootDirectory = $"{channelDirectoryName}/{diName}"; - BuildVersions(versionRootDirectory, fileSystem); - BuildPatch(versionRootDirectory, fileSystem, version); - } + /// + /// 自动是最新版本 + /// + public static void BuildAutoAppVersionRouter(string versionRootDirectory,string targetVersion) + { + var fileSystem = new FileSystem(); + var setting = URSRuntimeSetting.instance; + var IndexJsonPath = fileSystem.CombinePaths(versionRootDirectory, setting.FilesVersionIndexFileName); + var jsonText = fileSystem.ReadAllTextFromFile(IndexJsonPath); + var versionIndex = JsonUtility.FromJson(jsonText); + if (string.IsNullOrEmpty(targetVersion)) { + targetVersion= versionIndex.Versions[versionIndex.Versions.Length - 1].VersionCode; } - + + var routerFilePath = $"{versionRootDirectory}/{URSRuntimeSetting.instance.RemoteAppVersionRouterFileName}"; + Directory.CreateDirectory(System.IO.Path.GetDirectoryName(routerFilePath)); + if (File.Exists(routerFilePath)) + { + File.Delete(routerFilePath); + } + + AppVersionRouter router = new AppVersionRouter(); + router.Items = new AppVersionItem[1]; + router.Items[0] = new AppVersionItem() + { + VersionCode = targetVersion, + ApplicationVersion= @"\d+.\d+.\d+" + }; + router.DefaultVersion = targetVersion; + File.WriteAllText(routerFilePath, JsonUtility.ToJson(router, true)); } - } } diff --git a/Assets/URS/YooAsset/Editor/Menu.meta b/Assets/URS/YooAsset/Editor/Menu.meta new file mode 100644 index 0000000..54e8621 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/Menu.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e100f1ca62caae4408f850ac9682ed76 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndIL2CPPAndroidProject.cs b/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndIL2CPPAndroidProject.cs new file mode 100644 index 0000000..bf3cf1a --- /dev/null +++ b/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndIL2CPPAndroidProject.cs @@ -0,0 +1,27 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +namespace URS +{ + public class BuildResourceAndIL2CPPAndroidProject : ScriptableWizard + { + [SerializeField, Tooltip("正要构建的资源版本")] public string BuildingResVersion; + [SerializeField, Tooltip("要内置资源版本")] public string BuildInResVersion; + [SerializeField, Tooltip("渠道名字")] public string Channel = "default_channel"; + + + [MenuItem("URS/Build(Resource And AndroidProject)-乐元素SDK(IL2CPP)",false,102)] + private static void Open() + { + DisplayWizard(ObjectNames.NicifyVariableName(nameof(BuildResourceAndIL2CPPAndroidProject)),"Build"); + } + + private void OnWizardCreate() + { + Build.ExportAndroidProject_IL2CPP(BuildingResVersion, BuildInResVersion, Channel); + } + } +} + diff --git a/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndIL2CPPAndroidProject.cs.meta b/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndIL2CPPAndroidProject.cs.meta new file mode 100644 index 0000000..014090f --- /dev/null +++ b/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndIL2CPPAndroidProject.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 79ba24a4b1f6c59449076445f06d8bb9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndIL2CPPPlayer.cs b/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndIL2CPPPlayer.cs new file mode 100644 index 0000000..da215d5 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndIL2CPPPlayer.cs @@ -0,0 +1,26 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +namespace URS +{ + public class BuildResourceAndIL2CPPPlayer : ScriptableWizard + { + [SerializeField, Tooltip("正要构建的资源版本")] public string BuildingResVersion; + [SerializeField, Tooltip("要内置资源版本")] public string BuildInResVersion; + [SerializeField, Tooltip("渠道名字")] public string Channel = "default_channel"; + + [MenuItem("URS/Build(Resource And Player)-(IL2CPP)",false,100)] + private static void Open() + { + DisplayWizard(ObjectNames.NicifyVariableName(nameof(BuildResourceAndIL2CPPPlayer)), "Build"); + } + + private void OnWizardCreate() + { + Build.BuildResourceAndPlayer_Standard(BuildingResVersion, BuildInResVersion, Channel); + } + } +} + diff --git a/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndIL2CPPPlayer.cs.meta b/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndIL2CPPPlayer.cs.meta new file mode 100644 index 0000000..a1b5cf1 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndIL2CPPPlayer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9b72699d56920464a980be9810d9208e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndMonoAndroidProject.cs b/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndMonoAndroidProject.cs new file mode 100644 index 0000000..ade3ccd --- /dev/null +++ b/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndMonoAndroidProject.cs @@ -0,0 +1,26 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +namespace URS +{ + public class BuildResourceAndMonoAndroidProject : ScriptableWizard + { + [SerializeField,Tooltip("正要构建的资源版本")] public string BuildingResVersion; + [SerializeField,Tooltip("要内置资源版本")] public string BuildInResVersion; + [SerializeField,Tooltip("渠道名字")] public string Channel="default_channel"; + + [MenuItem("URS/Build(Resource And AndroidProject)-乐元素SDK(Mono)",false,103)] + private static void Open() + { + DisplayWizard(ObjectNames.NicifyVariableName(nameof(BuildResourceAndMonoAndroidProject)),"Build"); + } + + private void OnWizardCreate() + { + Build.ExportAndroidProject_Mono(BuildingResVersion, BuildInResVersion, Channel); + } + } +} + diff --git a/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndMonoAndroidProject.cs.meta b/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndMonoAndroidProject.cs.meta new file mode 100644 index 0000000..e3d29d0 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndMonoAndroidProject.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5aaf541f089fc42438e471441a0d7239 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndMonoPlayer.cs b/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndMonoPlayer.cs new file mode 100644 index 0000000..de9ba9d --- /dev/null +++ b/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndMonoPlayer.cs @@ -0,0 +1,27 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +namespace URS +{ + public class BuildResourceAndMonoPlayer : ScriptableWizard + { + [SerializeField, Tooltip("正要构建的资源版本")] public string BuildingResVersion; + [SerializeField, Tooltip("要内置资源版本")] public string BuildInResVersion; + [SerializeField, Tooltip("渠道名字")] public string Channel = "default_channel"; + + [MenuItem("URS/Build(Resource And Player)-(Mono)",false,101)] + private static void Open() + { + var sw= DisplayWizard(ObjectNames.NicifyVariableName(nameof(BuildResourceAndMonoPlayer)), "Build"); + sw.createButtonName = "Build"; + } + + private void OnWizardCreate() + { + Build.BuildResourceAndPlayer_Fast(BuildingResVersion, BuildInResVersion, Channel); + } + } +} + diff --git a/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndMonoPlayer.cs.meta b/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndMonoPlayer.cs.meta new file mode 100644 index 0000000..1f5c648 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/Menu/BuildResourceAndMonoPlayer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 609e0970f67a26b4c92771a9aab90c79 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/Menu/ExportRuntimeSetting.cs b/Assets/URS/YooAsset/Editor/Menu/ExportRuntimeSetting.cs new file mode 100644 index 0000000..89df7bb --- /dev/null +++ b/Assets/URS/YooAsset/Editor/Menu/ExportRuntimeSetting.cs @@ -0,0 +1,25 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +namespace URS +{ + public class ExportRuntimeSetting : ScriptableWizard + { + + [SerializeField, Tooltip("存放的resource目录")] public string SaveDiretoryPath = @"Assets/Packages/URS/Setting/Resources"; + + [MenuItem("URS/ExportDefaultURSRuntimeSetting")] + private static void Open() + { + var sw = DisplayWizard(ObjectNames.NicifyVariableName(nameof(ExportRuntimeSetting)), "Export"); + } + + private void OnWizardCreate() + { + Build.ExportDefaultURSRuntimeSetting(SaveDiretoryPath); + } + } +} + diff --git a/Assets/URS/YooAsset/Editor/Menu/ExportRuntimeSetting.cs.meta b/Assets/URS/YooAsset/Editor/Menu/ExportRuntimeSetting.cs.meta new file mode 100644 index 0000000..7ffeda4 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/Menu/ExportRuntimeSetting.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8b8cbc93d23f38144afbd9201bbed0aa +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/Menu/HybridBuild.cs b/Assets/URS/YooAsset/Editor/Menu/HybridBuild.cs new file mode 100644 index 0000000..8a96262 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/Menu/HybridBuild.cs @@ -0,0 +1,30 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +namespace URS +{ + public class HybridBuild : ScriptableWizard + { + [SerializeField, Tooltip("正要构建的资源版本")] public string BuildingResVersion; + [SerializeField, Tooltip("要内置资源版本")] public string BuildInResVersion; + [SerializeField, Tooltip("渠道名字")] public string Channel = "default_channel"; + [SerializeField, Tooltip("是不是要buildResource")] public bool BuildResource = true; + [SerializeField, Tooltip("是不是要buildRaw")] public bool BuildRaw= true; + [SerializeField, Tooltip("是不是要copy BuildInRes")] public bool CopyBuildInRes = true; + [SerializeField, Tooltip("是不是要build player")] public bool BuildPlayer = false; + [SerializeField, Tooltip("是不是要build player")] public bool Debug = false; + [MenuItem("URS/CustomBuild(自定义构建)",false,104)] + private static void Open() + { + var sw= DisplayWizard(ObjectNames.NicifyVariableName(nameof(HybridBuild)), "Build"); + } + + private void OnWizardCreate() + { + Build.HybridBuild(BuildingResVersion, BuildInResVersion, Channel, BuildResource, BuildRaw, CopyBuildInRes, BuildPlayer,Debug); + } + } +} + diff --git a/Assets/URS/YooAsset/Editor/Menu/HybridBuild.cs.meta b/Assets/URS/YooAsset/Editor/Menu/HybridBuild.cs.meta new file mode 100644 index 0000000..361aa0e --- /dev/null +++ b/Assets/URS/YooAsset/Editor/Menu/HybridBuild.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a577c2399a68070468f69989d2f06586 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/Menu/ValidateAasset.cs b/Assets/URS/YooAsset/Editor/Menu/ValidateAasset.cs new file mode 100644 index 0000000..cec6642 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/Menu/ValidateAasset.cs @@ -0,0 +1,27 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +namespace URS +{ + public class ValidateAasset : ScriptableWizard + { + [SerializeField, Tooltip("检查并且修复材质球")] public bool Material= false; + [SerializeField, Tooltip("检查并且修复模型的导入")] public bool Model = false; + [SerializeField, Tooltip("检查并且修复粒子系统")] public bool ParticleSystem = false; + [SerializeField, Tooltip("检查并且修复动画系统")] public bool Animation= false; + + [MenuItem("URS/ValidateAsset", false, 104)] + private static void Open() + { + var sw = DisplayWizard(ObjectNames.NicifyVariableName(nameof(ValidateAasset)), "Validate"); + } + + private void OnWizardCreate() + { + Build.ValidateAsset(Material, Model, ParticleSystem, Animation); + } + } +} + diff --git a/Assets/URS/YooAsset/Editor/Menu/ValidateAasset.cs.meta b/Assets/URS/YooAsset/Editor/Menu/ValidateAasset.cs.meta new file mode 100644 index 0000000..7cab485 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/Menu/ValidateAasset.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e5525aa0e0beec84ea280b67fadecd54 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/Menu/VersionAndCDN.cs b/Assets/URS/YooAsset/Editor/Menu/VersionAndCDN.cs new file mode 100644 index 0000000..afa561b --- /dev/null +++ b/Assets/URS/YooAsset/Editor/Menu/VersionAndCDN.cs @@ -0,0 +1,29 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEditor; +using UnityEngine; + +namespace URS +{ + public class VersionAndCDN : ScriptableWizard + { + + [SerializeField, Tooltip("渠道名字")] public string Channel = "default_channel"; + [SerializeField, Tooltip("渠道的目标版本,如果为空,自动为最新的版本")] public string ChannelTargetVersion=""; + [SerializeField, Tooltip("资源版本保留的数量")] public int VersionKeepCount = 4; + [SerializeField, Tooltip("是否上传CDN")] public bool UploadCDN = false; + [SerializeField, Tooltip("Debug")] public bool Debug = false; + + [MenuItem("URS/BuildAutoChannelVersionsAndUploadCDN",false,105)] + private static void Open() + { + var sw= DisplayWizard(ObjectNames.NicifyVariableName(nameof(VersionAndCDN)), "Build"); + } + + private void OnWizardCreate() + { + Build.BuildAutoChannelVersionsAndUploadCDN(Channel, ChannelTargetVersion, VersionKeepCount, UploadCDN,Debug); + } + } +} + diff --git a/Assets/URS/YooAsset/Editor/Menu/VersionAndCDN.cs.meta b/Assets/URS/YooAsset/Editor/Menu/VersionAndCDN.cs.meta new file mode 100644 index 0000000..213138e --- /dev/null +++ b/Assets/URS/YooAsset/Editor/Menu/VersionAndCDN.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 61e93d36489a8f9428fa1736ffc85375 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/PlatformMappingService.cs b/Assets/URS/YooAsset/Editor/PlatformMappingService.cs index 0c1263f..ee4ca82 100644 --- a/Assets/URS/YooAsset/Editor/PlatformMappingService.cs +++ b/Assets/URS/YooAsset/Editor/PlatformMappingService.cs @@ -7,6 +7,7 @@ #if UNITY_EDITOR using UnityEditor; #endif +using URSPlatform = URS.URSPlatform; namespace URS { diff --git a/Assets/URS/YooAsset/Editor/SimpleExec.meta b/Assets/URS/YooAsset/Editor/SimpleExec.meta new file mode 100644 index 0000000..343c9c4 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/SimpleExec.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 697fa42e700292844afdfe4ee71323b1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/SimpleExec/Command.cs b/Assets/URS/YooAsset/Editor/SimpleExec/Command.cs new file mode 100644 index 0000000..ac4763e --- /dev/null +++ b/Assets/URS/YooAsset/Editor/SimpleExec/Command.cs @@ -0,0 +1,430 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace SimpleExec +{ + /// + /// Contains methods for running commands and reading standard output (stdout). + /// + public static class Command + { + private static readonly Action> defaultAction = _ => { }; + private static readonly string defaultEchoPrefix = Assembly.GetEntryAssembly()?.GetName().Name ?? "SimpleExec"; + + /// + /// Runs a command without redirecting standard output (stdout) and standard error (stderr) and without writing to standard input (stdin). + /// By default, the command line is echoed to standard output (stdout). + /// + /// The name of the command. This can be a path to an executable file. + /// The arguments to pass to the command. + /// The working directory in which to run the command. + /// Whether or not to echo the resulting command line and working directory (if specified) to standard output (stdout). + /// The prefix to use when echoing the command line and working directory (if specified) to standard output (stdout). + /// An action which configures environment variables for the command. + /// Whether to run the command in a new window. + /// + /// A delegate which accepts an representing exit code of the command and + /// returns when it has handled the exit code and default exit code handling should be suppressed, and + /// returns otherwise. + /// + /// A to observe while waiting for the command to exit. + /// The command exited with non-zero exit code. + /// + /// By default, the resulting command line and the working directory (if specified) are echoed to standard output (stdout). + /// To suppress this behavior, provide the parameter with a value of true. + /// + public static void Run( + string name, + string args = "", + string workingDirectory = "", + bool noEcho = false, + string? echoPrefix = null, + Action>? configureEnvironment = null, + bool createNoWindow = false, + Func? handleExitCode = null, + CancellationToken cancellationToken = default) => + ProcessStartInfo + .Create( + Resolve(Validate(name)), + args, + Enumerable.Empty(), + workingDirectory, + false, + configureEnvironment ?? defaultAction, + createNoWindow) + .Run(noEcho, echoPrefix ?? defaultEchoPrefix, handleExitCode, cancellationToken); + + /// + /// Runs a command without redirecting standard output (stdout) and standard error (stderr) and without writing to standard input (stdin). + /// By default, the command line is echoed to standard output (stdout). + /// + /// The name of the command. This can be a path to an executable file. + /// + /// The arguments to pass to the command. + /// As with , the strings don't need to be escaped. + /// + /// The working directory in which to run the command. + /// Whether or not to echo the resulting command name, arguments, and working directory (if specified) to standard output (stdout). + /// The prefix to use when echoing the command name, arguments, and working directory (if specified) to standard output (stdout). + /// An action which configures environment variables for the command. + /// Whether to run the command in a new window. + /// + /// A delegate which accepts an representing exit code of the command and + /// returns when it has handled the exit code and default exit code handling should be suppressed, and + /// returns otherwise. + /// + /// A to observe while waiting for the command to exit. + /// The command exited with non-zero exit code. + public static void Run( + string name, + IEnumerable args, + string workingDirectory = "", + bool noEcho = false, + string? echoPrefix = null, + Action>? configureEnvironment = null, + bool createNoWindow = false, + Func? handleExitCode = null, + CancellationToken cancellationToken = default) => + ProcessStartInfo + .Create( + Resolve(Validate(name)), + "", + args ?? throw new ArgumentNullException(nameof(args)), + workingDirectory, + false, + configureEnvironment ?? defaultAction, + createNoWindow) + .Run(noEcho, echoPrefix ?? defaultEchoPrefix, handleExitCode, cancellationToken); + + private static void Run( + this System.Diagnostics.ProcessStartInfo startInfo, + bool noEcho, + string echoPrefix, + Func? handleExitCode, + CancellationToken cancellationToken) + { + using var process = new Process(); + process.StartInfo = startInfo; + + process.Run(noEcho, echoPrefix, cancellationToken); + + if (!(handleExitCode?.Invoke(process.ExitCode) ?? false) && process.ExitCode != 0) + { + throw new ExitCodeException(process.ExitCode); + } + } + + /// + /// Runs a command asynchronously without redirecting standard output (stdout) and standard error (stderr) and without writing to standard input (stdin). + /// By default, the command line is echoed to standard output (stdout). + /// + /// The name of the command. This can be a path to an executable file. + /// The arguments to pass to the command. + /// The working directory in which to run the command. + /// Whether or not to echo the resulting command line and working directory (if specified) to standard output (stdout). + /// The prefix to use when echoing the command line and working directory (if specified) to standard output (stdout). + /// An action which configures environment variables for the command. + /// Whether to run the command in a new window. + /// + /// A delegate which accepts an representing exit code of the command and + /// returns when it has handled the exit code and default exit code handling should be suppressed, and + /// returns otherwise. + /// + /// A to observe while waiting for the command to exit. + /// A that represents the asynchronous running of the command. + /// The command exited with non-zero exit code. + /// + /// By default, the resulting command line and the working directory (if specified) are echoed to standard output (stdout). + /// To suppress this behavior, provide the parameter with a value of true. + /// + public static async Task RunAsync( + string name, + string args = "", + string workingDirectory = "", + bool noEcho = false, + string? echoPrefix = null, + Action>? configureEnvironment = null, + bool createNoWindow = false, + Func? handleExitCode = null, + CancellationToken cancellationToken = default) => + await ProcessStartInfo + .Create( + Resolve(Validate(name)), + args, + Enumerable.Empty(), + workingDirectory, + false, + configureEnvironment ?? defaultAction, + createNoWindow) + .RunAsync(noEcho, echoPrefix ?? defaultEchoPrefix, handleExitCode, cancellationToken) + .ConfigureAwait(false); + + /// + /// Runs a command asynchronously without redirecting standard output (stdout) and standard error (stderr) and without writing to standard input (stdin). + /// By default, the command line is echoed to standard output (stdout). + /// + /// The name of the command. This can be a path to an executable file. + /// + /// The arguments to pass to the command. + /// As with , the strings don't need to be escaped. + /// + /// The working directory in which to run the command. + /// Whether or not to echo the resulting command name, arguments, and working directory (if specified) to standard output (stdout). + /// The prefix to use when echoing the command name, arguments, and working directory (if specified) to standard output (stdout). + /// An action which configures environment variables for the command. + /// Whether to run the command in a new window. + /// + /// A delegate which accepts an representing exit code of the command and + /// returns when it has handled the exit code and default exit code handling should be suppressed, and + /// returns otherwise. + /// + /// A to observe while waiting for the command to exit. + /// A that represents the asynchronous running of the command. + /// The command exited with non-zero exit code. + public static async Task RunAsync( + string name, + IEnumerable args, + string workingDirectory = "", + bool noEcho = false, + string? echoPrefix = null, + Action>? configureEnvironment = null, + bool createNoWindow = false, + Func? handleExitCode = null, + CancellationToken cancellationToken = default) => + await ProcessStartInfo + .Create( + Resolve(Validate(name)), + "", + args ?? throw new ArgumentNullException(nameof(args)), + workingDirectory, + false, + configureEnvironment ?? defaultAction, + createNoWindow) + .RunAsync(noEcho, echoPrefix ?? defaultEchoPrefix, handleExitCode, cancellationToken) + .ConfigureAwait(false); + + private static async Task RunAsync( + this System.Diagnostics.ProcessStartInfo startInfo, + bool noEcho, + string echoPrefix, + Func? handleExitCode, + CancellationToken cancellationToken) + { + using var process = new Process(); + process.StartInfo = startInfo; + + await process.RunAsync(noEcho, echoPrefix, cancellationToken).ConfigureAwait(false); + + if (!(handleExitCode?.Invoke(process.ExitCode) ?? false) && process.ExitCode != 0) + { + throw new ExitCodeException(process.ExitCode); + } + } + + /// + /// Runs a command and reads standard output (stdout) and standard error (stderr) and optionally writes to standard input (stdin). + /// + /// The name of the command. This can be a path to an executable file. + /// The arguments to pass to the command. + /// The working directory in which to run the command. + /// An action which configures environment variables for the command. + /// The preferred for standard output (stdout) and standard output (stdout). + /// + /// A delegate which accepts an representing exit code of the command and + /// returns when it has handled the exit code and default exit code handling should be suppressed, and + /// returns otherwise. + /// + /// The contents of standard input (stdin). + /// A to observe while waiting for the command to exit. + /// + /// A representing the asynchronous running of the command and reading of standard output (stdout) and standard error (stderr). + /// The task result is a representing the contents of standard output (stdout) and standard error (stderr). + /// + /// + /// The command exited with non-zero exit code. The exception contains the contents of standard output (stdout) and standard error (stderr). + /// + public static async Task<(string StandardOutput, string StandardError)> ReadAsync( + string name, + string args = "", + string workingDirectory = "", + Action>? configureEnvironment = null, + Encoding? encoding = null, + Func? handleExitCode = null, + string? standardInput = null, + CancellationToken cancellationToken = default) => + await ProcessStartInfo + .Create( + Resolve(Validate(name)), + args, + Enumerable.Empty(), + workingDirectory, + true, + configureEnvironment ?? defaultAction, + true, + encoding) + .ReadAsync( + handleExitCode, + standardInput, + cancellationToken) + .ConfigureAwait(false); + + /// + /// Runs a command and reads standard output (stdout) and standard error (stderr) and optionally writes to standard input (stdin). + /// + /// The name of the command. This can be a path to an executable file. + /// + /// The arguments to pass to the command. + /// As with , the strings don't need to be escaped. + /// + /// The working directory in which to run the command. + /// An action which configures environment variables for the command. + /// The preferred for standard output (stdout) and standard error (stderr). + /// + /// A delegate which accepts an representing exit code of the command and + /// returns when it has handled the exit code and default exit code handling should be suppressed, and + /// returns otherwise. + /// + /// The contents of standard input (stdin). + /// A to observe while waiting for the command to exit. + /// + /// A representing the asynchronous running of the command and reading of standard output (stdout) and standard error (stderr). + /// The task result is a representing the contents of standard output (stdout) and standard error (stderr). + /// + /// + /// The command exited with non-zero exit code. The exception contains the contents of standard output (stdout) and standard error (stderr). + /// + public static async Task<(string StandardOutput, string StandardError)> ReadAsync( + string name, + IEnumerable args, + string workingDirectory = "", + Action>? configureEnvironment = null, + Encoding? encoding = null, + Func? handleExitCode = null, + string? standardInput = null, + CancellationToken cancellationToken = default) => + await ProcessStartInfo + .Create( + Resolve(Validate(name)), + "", + args ?? throw new ArgumentNullException(nameof(args)), + workingDirectory, + true, + configureEnvironment ?? defaultAction, + true, + encoding) + .ReadAsync( + handleExitCode, + standardInput, + cancellationToken) + .ConfigureAwait(false); + + private static async Task<(string StandardOutput, string StandardError)> ReadAsync( + this System.Diagnostics.ProcessStartInfo startInfo, + Func? handleExitCode, + string? standardInput, + CancellationToken cancellationToken) + { + using var process = new Process(); + process.StartInfo = startInfo; + + var runProcess = process.RunAsync(true, "", cancellationToken); + + Task readOutput; + Task readError; + + try + { + await process.StandardInput.WriteAsync(standardInput).ConfigureAwait(false); + process.StandardInput.Close(); + + readOutput = process.StandardOutput.ReadToEndAsync(); + readError = process.StandardError.ReadToEndAsync(); + } + catch (Exception) + { + await runProcess.ConfigureAwait(false); + throw; + } + + await Task.WhenAll(runProcess, readOutput, readError).ConfigureAwait(false); + +#pragma warning disable CA1849 // Call async methods when in an async method + var output = readOutput.Result; + var error = readError.Result; +#pragma warning restore CA1849 // Call async methods when in an async method + + return (handleExitCode?.Invoke(process.ExitCode) ?? false) || process.ExitCode == 0 + ? (output, error) + : throw new ExitCodeReadException(process.ExitCode, output, error); + } + + private static string Validate(string name) => + string.IsNullOrWhiteSpace(name) ? throw new ArgumentException("The command name is missing.", nameof(name)) : name; + + private static string Resolve(string name) + { + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || Path.IsPathRooted(name)) + { + return name; + } + + var extension = Path.GetExtension(name); + if (!string.IsNullOrEmpty(extension) && extension != ".cmd" && extension != ".bat") + { + return name; + } + + var pathExt = Environment.GetEnvironmentVariable("PATHEXT") ?? ".EXE;.BAT;.CMD"; + + var windowsExecutableExtensions = pathExt.Split(';') + .Select(ext => ext.TrimStart('.')) + .Where(ext => + string.Equals(ext, "exe", StringComparison.OrdinalIgnoreCase) || + string.Equals(ext, "bat", StringComparison.OrdinalIgnoreCase) || + string.Equals(ext, "cmd", StringComparison.OrdinalIgnoreCase)); + + var searchFileNames = string.IsNullOrEmpty(extension) + ? windowsExecutableExtensions.Select(ex => Path.ChangeExtension(name, ex)).ToList() + : new List { name, }; + + var path = GetSearchDirectories().SelectMany(_ => searchFileNames, Path.Combine).FirstOrDefault(File.Exists); + + return path == null || Path.GetExtension(path) == ".exe" ? name : path; + } + + // see https://github.com/dotnet/runtime/blob/14304eb31eea134db58870a6d87312231b1e02b6/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs#L703-L726 + private static IEnumerable GetSearchDirectories() + { + var currentProcessPath = Process.GetCurrentProcess().MainModule?.FileName; + if (!string.IsNullOrEmpty(currentProcessPath)) + { + var currentProcessDirectory = Path.GetDirectoryName(currentProcessPath); + if (!string.IsNullOrEmpty(currentProcessDirectory)) + { + yield return currentProcessDirectory; + } + } + + yield return Directory.GetCurrentDirectory(); + + var path = Environment.GetEnvironmentVariable("PATH"); + if (string.IsNullOrEmpty(path)) + { + yield break; + } + + foreach (var directory in path.Split(Path.PathSeparator)) + { + yield return directory; + } + } + } +} diff --git a/Assets/URS/YooAsset/Editor/SimpleExec/Command.cs.meta b/Assets/URS/YooAsset/Editor/SimpleExec/Command.cs.meta new file mode 100644 index 0000000..ffaa301 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/SimpleExec/Command.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8c2fd56fc5096ca4b8849f078065fd98 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/SimpleExec/ExitCodeException.cs b/Assets/URS/YooAsset/Editor/SimpleExec/ExitCodeException.cs new file mode 100644 index 0000000..1c763af --- /dev/null +++ b/Assets/URS/YooAsset/Editor/SimpleExec/ExitCodeException.cs @@ -0,0 +1,26 @@ +using System; + +namespace SimpleExec +{ + /// + /// The command exited with an unexpected exit code. + /// +#pragma warning disable CA1032 // Implement standard exception constructors + public class ExitCodeException : Exception +#pragma warning restore CA1032 // Implement standard exception constructors + { + /// + /// Constructs an instance of a . + /// + /// The exit code of the command. + public ExitCodeException(int exitCode) => this.ExitCode = exitCode; + + /// + /// Gets the exit code of the command. + /// + public int ExitCode { get; } + + /// + public override string Message => $"The command exited with code {this.ExitCode}."; + } +} diff --git a/Assets/URS/YooAsset/Editor/SimpleExec/ExitCodeException.cs.meta b/Assets/URS/YooAsset/Editor/SimpleExec/ExitCodeException.cs.meta new file mode 100644 index 0000000..b100592 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/SimpleExec/ExitCodeException.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6d0c61f856b7dc44a9d5d833c2fdda33 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/SimpleExec/ExitCodeReadException.cs b/Assets/URS/YooAsset/Editor/SimpleExec/ExitCodeReadException.cs new file mode 100644 index 0000000..c5f2223 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/SimpleExec/ExitCodeReadException.cs @@ -0,0 +1,36 @@ +using System; + +namespace SimpleExec +{ + /// + /// The command being read exited with an unexpected exit code. + /// +#pragma warning disable CA1032 // Implement standard exception constructors + public class ExitCodeReadException : ExitCodeException +#pragma warning restore CA1032 // Implement standard exception constructors + { + private static readonly string twoNewLines = $"{Environment.NewLine}{Environment.NewLine}"; + + /// + /// Constructs an instance of a . + /// + /// The exit code of the command. + /// The contents of standard output (stdout). + /// The contents of standard error (stderr). + public ExitCodeReadException(int exitCode, string standardOutput, string standardError) : base(exitCode) => (this.StandardOutput, this.StandardError) = (standardOutput, standardError); + + /// + /// Gets the contents of standard output (stdout). + /// + public string StandardOutput { get; } + + /// + /// Gets the contents of standard error (stderr). + /// + public string StandardError { get; } + + /// + public override string Message => + $"{base.Message}{twoNewLines}Standard output (stdout):{twoNewLines}{this.StandardOutput}{twoNewLines}Standard error (stderr):{twoNewLines}{this.StandardError}"; + } +} diff --git a/Assets/URS/YooAsset/Editor/SimpleExec/ExitCodeReadException.cs.meta b/Assets/URS/YooAsset/Editor/SimpleExec/ExitCodeReadException.cs.meta new file mode 100644 index 0000000..eb978bc --- /dev/null +++ b/Assets/URS/YooAsset/Editor/SimpleExec/ExitCodeReadException.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e3f5f8286a328e84a82cdee55dbdc1a6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/SimpleExec/ProcessExtensions.cs b/Assets/URS/YooAsset/Editor/SimpleExec/ProcessExtensions.cs new file mode 100644 index 0000000..2b2bf34 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/SimpleExec/ProcessExtensions.cs @@ -0,0 +1,115 @@ +using System; +using System.Diagnostics; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace SimpleExec +{ + internal static class ProcessExtensions + { + public static void Run(this Process process, bool noEcho, string echoPrefix, CancellationToken cancellationToken) + { + var cancelled = 0L; + + if (!noEcho) + { + Console.Out.Write(process.StartInfo.GetEchoLines(echoPrefix)); + } + + _ = process.Start(); + + using (cancellationToken.Register( + () => + { + if (process.TryKill()) + { + _ = Interlocked.Increment(ref cancelled); + } + }, + useSynchronizationContext: false)) + { + process.WaitForExit(); + } + + if (Interlocked.Read(ref cancelled) == 1) + { + cancellationToken.ThrowIfCancellationRequested(); + } + } + + public static async Task RunAsync(this Process process, bool noEcho, string echoPrefix, CancellationToken cancellationToken) + { + // NOTE: can switch to TaskCompletionSource when moving to .NET 5+ + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + process.EnableRaisingEvents = true; + process.Exited += (s, e) => tcs.TrySetResult(0); + + if (!noEcho) + { + await Console.Out.WriteAsync(process.StartInfo.GetEchoLines(echoPrefix)).ConfigureAwait(false); + } + + _ = process.Start(); + + await using (cancellationToken.Register( + () => + { + if (process.TryKill()) + { + _ = tcs.TrySetCanceled(cancellationToken); + } + }, + useSynchronizationContext: false)) + { + _ = await tcs.Task.ConfigureAwait(false); + } + } + + private static string GetEchoLines(this System.Diagnostics.ProcessStartInfo info, string echoPrefix) + { + var builder = new StringBuilder(); + + if (!string.IsNullOrEmpty(info.WorkingDirectory)) + { + _ = builder.AppendLine($"{echoPrefix}: Working directory: {info.WorkingDirectory}"); + } + + if (info.ArgumentList.Count > 0) + { + _ = builder.AppendLine($"{echoPrefix}: {info.FileName}"); + + foreach (var arg in info.ArgumentList) + { + _ = builder.AppendLine($"{echoPrefix}: {arg}"); + } + } + else + { + _ = builder.AppendLine($"{echoPrefix}: {info.FileName}{(string.IsNullOrEmpty(info.Arguments) ? "" : $" {info.Arguments}")}"); + } + + return builder.ToString(); + } + + private static bool TryKill(this Process process) + { + // exceptions may be thrown for all kinds of reasons + // and the _same exception_ may be thrown for all kinds of reasons + // System.Diagnostics.Process is "fine" + try + { + process.Kill(); + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception) +#pragma warning restore CA1031 // Do not catch general exception types + { + return false; + } + + return true; + } + } +} diff --git a/Assets/URS/YooAsset/Editor/SimpleExec/ProcessExtensions.cs.meta b/Assets/URS/YooAsset/Editor/SimpleExec/ProcessExtensions.cs.meta new file mode 100644 index 0000000..664e774 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/SimpleExec/ProcessExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 44ea194012203384cbe99efedd921173 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/SimpleExec/ProcessStartInfo.cs b/Assets/URS/YooAsset/Editor/SimpleExec/ProcessStartInfo.cs new file mode 100644 index 0000000..bdb5860 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/SimpleExec/ProcessStartInfo.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace SimpleExec +{ + internal static class ProcessStartInfo + { + public static System.Diagnostics.ProcessStartInfo Create( + string name, + string args, + IEnumerable argList, + string workingDirectory, + bool redirectStandardStreams, + Action> configureEnvironment, + bool createNoWindow, + Encoding? encoding = null) + { + var startInfo = new System.Diagnostics.ProcessStartInfo + { + FileName = name, + Arguments = args, + WorkingDirectory = workingDirectory, + UseShellExecute = false, + RedirectStandardError = redirectStandardStreams, + RedirectStandardInput = redirectStandardStreams, + RedirectStandardOutput = redirectStandardStreams, + CreateNoWindow = createNoWindow, + StandardErrorEncoding = encoding, + StandardOutputEncoding = encoding, + }; + + foreach (var arg in argList) + { + startInfo.ArgumentList.Add(arg); + } + + configureEnvironment(startInfo.Environment); + + return startInfo; + } + } +} diff --git a/Assets/URS/YooAsset/Editor/SimpleExec/ProcessStartInfo.cs.meta b/Assets/URS/YooAsset/Editor/SimpleExec/ProcessStartInfo.cs.meta new file mode 100644 index 0000000..bf5bff4 --- /dev/null +++ b/Assets/URS/YooAsset/Editor/SimpleExec/ProcessStartInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d8eee768e338a924c899ead077edc0c5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/TagRule.cs b/Assets/URS/YooAsset/Editor/TagRule.cs index 26b6d95..5b41786 100644 --- a/Assets/URS/YooAsset/Editor/TagRule.cs +++ b/Assets/URS/YooAsset/Editor/TagRule.cs @@ -16,6 +16,7 @@ public enum TagRuleType BundleName, BundleCompression, CustomTag, + ExcludeFileNameContains } [SerializeField] private TagRuleType _tagType; diff --git a/Assets/URS/YooAsset/Editor/Utils/EditorUtils.EnumDrawer.cs b/Assets/URS/YooAsset/Editor/Utils/EditorUtils.EnumDrawer.cs deleted file mode 100644 index a200d7b..0000000 --- a/Assets/URS/YooAsset/Editor/Utils/EditorUtils.EnumDrawer.cs +++ /dev/null @@ -1,315 +0,0 @@ - -using System; -using System.Collections.Generic; -using System.Text; -using UnityEditor; -using UnityEngine; - -public partial class EditorUtils -{ - private class MaskBit - { - public long enumValue = 0; - public long maskValue = 0; - public long indexMaskValue = 0; - public string name = ""; - public bool toggle = false; - } - private class Mask - { - public long fullMaskValue = 0; - public long indexFullMaskValue = 0; - public string[] nameArray = { }; - public List bitList = new List(); - - public long MaskValue - { - get - { - long v = 0; - for (int i = 0; i < bitList.Count; ++i) - { - if (bitList[i].toggle) - v |= bitList[i].maskValue; - } - if (v == fullMaskValue) - return -1; - return v; - } - set - { - for (int i = 0; i < bitList.Count; ++i) - { - var bit = bitList[i]; - if ((value & bit.maskValue) != 0) - bit.toggle = true; - else - bit.toggle = false; - } - } - } - public long IndexMaskValue - { - get - { - long v = 0; - for (int i = 0; i < bitList.Count; ++i) - { - if (bitList[i].toggle) - v |= (long)1 << i; - } - if (v == indexFullMaskValue) - return -1; - return v; - } - set - { - for (int i = 0; i < bitList.Count; ++i) - { - var bit = bitList[i]; - if ((value & bit.indexMaskValue) != 0) - bit.toggle = true; - else - bit.toggle = false; - } - } - } - public override string ToString() - { - long value = MaskValue; - - if (value == 0) - return "Nothing"; - if (value == -1) - return "Everything"; - - StringBuilder sb = new StringBuilder(); - sb.Remove(0, sb.Length); - for (int i = 0; i < bitList.Count; ++i) - { - if (bitList[i].toggle) - { - if (sb.Length != 0) - sb.Append("/"); - sb.Append(bitList[i].name); - } - } - - return sb.ToString(); - } - } - private class _EnumValue - { - public string name = ""; - public string upper = ""; - //public string abbr = ""; - public int value = 0; - } - private class _Enum - { - private Type type = null; - private int value = 0; - private string filterText = null; - private string[] displayedOptions = new string[] { }; - private List displayedValues = new List(); - private List<_EnumValue> allValues = new List<_EnumValue>(); - - private void SetAllValues() - { - displayedOptions = new string[allValues.Count]; - displayedValues.Clear(); - for (int i = 0; i < allValues.Count; ++i) - { - displayedOptions[i] = allValues[i].name; - displayedValues.Add(allValues[i].value); - } - } - public string FilterText - { - get { return filterText; } - set - { - if (value.Equals(filterText)) - return; - filterText = value; - if (string.IsNullOrEmpty(filterText)) - { - SetAllValues(); - return; - } - string upper = filterText.ToUpper(); - List displayedOptionsTemp = new List(); - displayedValues.Clear(); - for (int i = 0; i < allValues.Count; ++i) - { - var v = allValues[i]; - if (v.upper.Contains(upper))// || v.abbr.Contains(upper)) - { - displayedOptionsTemp.Add(v.name); - displayedValues.Add(v.value); - } - } - if (displayedValues.Count == 0) - { - SetAllValues(); - } - else - { - displayedOptions = displayedOptionsTemp.ToArray(); - } - } - } - public string[] DisplayedOptions - { - get { return displayedOptions; } - } - public Enum EnumValue - { - get { return (Enum)Enum.ToObject(type, value); } - set { this.value = Convert.ToInt32(value); } - } - public int DisplayedValue - { - get - { - int index = -1; - for (int i = 0; i < displayedValues.Count; ++i) - { - if (displayedValues[i] == value) - { - index = i; - break; - } - } - return index; - } - set - { - if (value >= 0 && value < displayedValues.Count) - this.value = displayedValues[value]; - } - } - public _Enum(Type type) - { - this.type = type; - - allValues.Clear(); - var vs = Enum.GetValues(type); - foreach (var it in vs) - { - _EnumValue v = new _EnumValue(); - v.value = Convert.ToInt32(it); - v.name = v.value.ToString() + "_" + it.ToString(); - v.upper = v.name.ToUpper(); - allValues.Add(v); - } - - FilterText = ""; - } - } - private static Dictionary maskMap = new Dictionary(); - private static Dictionary enumMap = new Dictionary(); - private static byte[] tempByteArray = new byte[1024]; - - private static Mask GetMask(Type type) - { - Mask mask = null; - if (!maskMap.TryGetValue(type, out mask)) - { - mask = new Mask(); - var values = Enum.GetValues(type); - - foreach (var v in values) - { - long enumValue = Convert.ToInt64(v); - if (enumValue > 0) - { - MaskBit bit = new MaskBit(); - bit.enumValue = enumValue; - bit.maskValue = (long)1 << ((int)enumValue - 1); - bit.name = v.ToString(); - bit.toggle = false; - mask.bitList.Add(bit); - - mask.fullMaskValue |= bit.maskValue; - } - } - mask.bitList.Sort((x, y) => - { - if (x.enumValue > y.enumValue) - { - return 1; - } - else if (x.enumValue < y.enumValue) - { - return -1; - } - return 0; - }); - mask.nameArray = new string[mask.bitList.Count]; - for (int i = 0; i < mask.bitList.Count; ++i) - { - var bit = mask.bitList[i]; - bit.indexMaskValue = (long)1 << i; - mask.nameArray[i] = bit.name; - - mask.indexFullMaskValue |= bit.indexMaskValue; - } - - maskMap.Add(type, mask); - } - return mask; - } - - private static _Enum GetEnum(Type type) - { - _Enum _enum = null; - if (!enumMap.TryGetValue(type, out _enum)) - { - _enum = new _Enum(type); - - enumMap.Add(type, _enum); - } - return _enum; - } - - public static string TranslateMask(Type type, long value) - { - Mask mask = GetMask(type); - mask.MaskValue = value; - return mask.ToString(); - } - - public static int MaxEnumValue(Type enumType) - { - int maxValue = 0; - var values = Enum.GetValues(enumType); - foreach (var v in values) - { - int vv = Convert.ToInt32(v); - if (vv > maxValue) - maxValue = vv; - } - return maxValue; - } - - public static void GetCharCount(string info, ref int cnCount, ref int enCount, ref int A2ZCount) - { - for (int i = 0; i <= info.Length - 1; i++) - { - int byteCount = System.Text.Encoding.Default.GetBytes(info, i, 1, tempByteArray, 0); - if (byteCount > 1) - { - cnCount++; - } - else if (byteCount > 0) - { - enCount++; - if (info[0] >= 'A' && info[0] <= 'Z') - { - A2ZCount++; - } - } - } - } -} \ No newline at end of file diff --git a/Assets/URS/YooAsset/Editor/Utils/EditorUtils.EnumDrawer.cs.meta b/Assets/URS/YooAsset/Editor/Utils/EditorUtils.EnumDrawer.cs.meta deleted file mode 100644 index c6dbc1f..0000000 --- a/Assets/URS/YooAsset/Editor/Utils/EditorUtils.EnumDrawer.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 6a934c41bb6cbb6449a787e9873b317a -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/URS/YooAsset/Editor/Utils/EditorUtils.cs b/Assets/URS/YooAsset/Editor/Utils/EditorUtils.cs deleted file mode 100644 index 3953fb9..0000000 --- a/Assets/URS/YooAsset/Editor/Utils/EditorUtils.cs +++ /dev/null @@ -1,674 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using UnityEngine; -using System.Text; -using System.Text.RegularExpressions; -using UnityEditor; -using System.Runtime.InteropServices; - -public static partial class EditorUtils -{ - -#if UNITY_EDITOR_WIN - /// - /// Struct representing a point. - /// - [StructLayout(LayoutKind.Sequential)] - public struct POINT - { - public int X; - public int Y; - } - - /// - /// Retrieves the cursor's position, in screen coordinates. - /// - /// See MSDN documentation for further information. - [DllImport("user32.dll")] - private static extern bool GetCursorPos(out POINT lpPoint); - -#endif - - private static Regex labelRegex = new Regex("[A-Z_]+[a-z_0-9]*"); - - public static Vector2 CursorPosition - { - get - { -#if UNITY_EDITOR_WIN - POINT lpPoint; - bool success = GetCursorPos(out lpPoint); - if (!success) - return Vector2.zero; - return new Vector2(lpPoint.X, lpPoint.Y); -#else - return Vector2.zero; -#endif - } - } - - private static char ToUpper(char value) - { - return (char)((int)value - (int)'a' + (int)'A'); - } - static Dictionary formatLabelDict = new Dictionary(); - public static string FormatLabel(string label) - { - if (!formatLabelDict.TryGetValue(label, out var result)) - { - StringBuilder sb = new StringBuilder(); - var matches = labelRegex.Matches(label); - var newLabel = labelRegex.Replace(label, ""); - if (newLabel.Length > 0) - { - sb.Append(ToUpper(newLabel[0])); - for (int i = 1; i < newLabel.Length; ++i) - { - sb.Append(newLabel[i]); - } - } - for (int i = 0; i < matches.Count; ++i) - { - sb.Append(" "); - sb.Append(matches[i].Value); - } - - result = sb.ToString(); - formatLabelDict.Add(label, result); - } - return result; - } - - - - /// - /// 将指定的自然数转换为26进制表示。映射关系:[1-26] ->[A-Z]。 - /// - /// 自然数(如果无效,则返回空字符串)。 - /// 26进制表示。 - public static string ToNumberSystem26(int n) - { - string s = string.Empty; - while (n > 0) - { - int m = n % 26; - if (m == 0) m = 26; - s = (char)(m + 64) + s; - n = (n - m) / 26; - } - return s; - } - - /// - /// 将指定的26进制表示转换为自然数。映射关系:[A-Z] ->[1-26]。 - /// - /// 26进制表示(如果无效,则返回0)。 - /// 自然数。 - public static int FromNumberSystem26(string s) - { - if (string.IsNullOrEmpty(s)) return 0; - int n = 0; - for (int i = s.Length - 1, j = 1; i >= 0; i--, j *= 26) - { - char c = Char.ToUpper(s[i]); - if (c < 'A' || c > 'Z') return 0; - n += ((int)c - 64) * j; - } - return n; - } - - public static string[] GetAnimStateNames(Animator animator) - { - UnityEditor.Animations.AnimatorController animatorController = animator?.runtimeAnimatorController as UnityEditor.Animations.AnimatorController; - if (animatorController != null) - { - UnityEditor.Animations.AnimatorStateMachine stateMachine = animatorController.layers?[0]?.stateMachine; - if (stateMachine != null) - { - string[] animatorState = new string[stateMachine.states.Length]; - for (int i = 0; i < stateMachine.states.Length; i++) - { - animatorState[i] = stateMachine.states[i].state.name; - } - return animatorState; - } - } - return new string[] { }; - } - - public static GUILayoutOption[] Add(this GUILayoutOption[] self, GUILayoutOption option) - { - int selfCount = self?.Length ?? 0; - GUILayoutOption[] r = new GUILayoutOption[selfCount + 1]; - for (int i = 0; i < selfCount; ++i) - r[i] = self[i]; - r[selfCount] = option; - return r; - } - - public static List GetAllSelectionPrefab() - { - List result = new List(); - foreach (var guid in Selection.assetGUIDs) - { - var path = AssetDatabase.GUIDToAssetPath(guid); - if (Directory.Exists(path)) - GetAllFilesInDir(result, path, ".prefab"); - else if (File.Exists(path)) - CheckFileExtension(result, path, ".prefab"); - - } - return result; - } - - public static List GetAllSectionFiles(string ext) - { - List result = new List(); - foreach (var guid in Selection.assetGUIDs) - { - var path = AssetDatabase.GUIDToAssetPath(guid); - if (Directory.Exists(path)) - GetAllFilesInDir(result, path, ext); - else if (File.Exists(path)) - CheckFileExtension(result, path, ext); - - } - return result; - } - - public static List GetAllSelectionScene() - { - List result = new List(); - foreach (var guid in Selection.assetGUIDs) - { - var path = AssetDatabase.GUIDToAssetPath(guid); - if (Directory.Exists(path)) - GetAllFilesInDir(result, path, ".unity"); - else if (File.Exists(path)) - CheckFileExtension(result, path, ".unity"); - - } - return result; - } - - public static void GetAllFilesInDir(List result, string path, string ext) - { - foreach (var dir in Directory.GetDirectories(path)) - GetAllFilesInDir(result, dir, ext); - - foreach (var dir in Directory.GetFiles(path)) - CheckFileExtension(result, dir, ext); - } - - private static void CheckFileExtension(List result, string path, string ext) - { - if (Path.GetExtension(path).ToLower() == ext) - result.Add(path); - } - - public static List LoadAllAssetsAtPath(string path) where T : UnityEngine.Object - { - List r = new List(); - var list = AssetDatabase.LoadAllAssetsAtPath(path); - foreach(var res in list) - { - if (res is T) - r.Add((T)res); - } - return r; - } - - public static T LoadAssetAtPath(string path, string name) where T : UnityEngine.Object - { - var list = AssetDatabase.LoadAllAssetsAtPath(path); - foreach (var res in list) - { - if (res is T && res.name == name) - return (T)res; - } - return null; - } - - public static bool IdxValid(this IList self, int idx) - { - return idx >= 0 && idx < (self?.Count ?? 0); - } - - public static void TryCopyFile(string src, string dst) - { - try - { - string dir = Path.GetDirectoryName(dst); - if (!Directory.Exists(dir)) - Directory.CreateDirectory(dir); - File.Copy(src, dst, true); - } - catch (Exception e) - { - - } - } - - public static string CalculateMD5(string fileName, params object[] options) - { - try - { - using (var md5 = System.Security.Cryptography.MD5.Create()) - { - byte[] hash = null; - if (options != null && options.Length > 0) - { - var content = ReadAllText(fileName); - foreach (var op in options) - content += "\n" + op.ToString(); - - var bytes = Encoding.UTF8.GetBytes(content); - hash = md5.ComputeHash(bytes); - } - else - { - using (var fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) - hash = md5.ComputeHash(fs); - } - return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); - } - } - catch - { - return ""; - } - } - - public static string ReadFileFirstLine(string fileName) - { - try - { - using (var fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) - { - using (var sr = new StreamReader(fs)) - { - return sr.ReadLine(); - } - } - } - catch - { - return ""; - } - } - - - public static bool ClearPath(string path, Action exceptionCallback) - { - if (!Directory.Exists(path)) - return true; - - return ForEachFiles(path, "*.*", SearchOption.AllDirectories, (value, i, iCount) => - { - File.Delete(value); - }, exceptionCallback); - } - - public static void DeleteFiles(string path, Func callback) - { - if (string.IsNullOrWhiteSpace(path)) - return; - if (!Directory.Exists(path)) - return; - - var files = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly); - foreach (var file in files) - { - if (callback(file)) - { - try - { - if (File.Exists(file)) - File.Delete(file); - } - catch (Exception e) - { - UnityEngine.Debug.LogError(e.Message + "\n" + e.StackTrace); - } - } - } - } - - /// - /// - /// - /// - /// - /// 返回true删除 - public static void DeleteFilesExcept(string path, HashSet exceptNameHashset, Func extraCallback = null) - { - DeleteFiles(path, v => - { - var filename = Path.GetFileName(v); - var dotIdx = filename.IndexOf('.'); - if (dotIdx == -1) - return true; - - var purename = filename.Substring(0, dotIdx); - if (exceptNameHashset.Contains(purename)) - return false; - - if (extraCallback != null) - return extraCallback(filename); - - return true; - }); - } - - - public static bool ForEachFiles(string path, string searchPattern, SearchOption searchOption, Action callback, Action exceptionCallback) - { - var files = Directory.GetFiles(path, "*.*", searchOption); - try - { - int len = files.Length; - for (int i = 0; i < len; ++i) - { - if (!searchPattern.Contains(Path.GetExtension(files[i]).ToLower())) - continue; - if (callback != null) - callback(files[i], i, len); - } - } - catch (Exception e) - { - if (exceptionCallback != null) - exceptionCallback(e); - return false; - } - return true; - } - - - - public static void WriteToFile(string filePath, string content, bool checkSame = true, Encoding encoding = null) - { - string directory = Path.GetDirectoryName(filePath); - if (!Directory.Exists(directory)) - Directory.CreateDirectory(directory); - - if (File.Exists(filePath)) - { - if (checkSame) - { - string oldText = null; - try { oldText = File.ReadAllText(filePath); } - catch { oldText = null; } - - oldText = oldText?.Replace("\r", ""); - var newText = content.Replace("\r", ""); - if (oldText == newText) - return; - } - File.Delete(filePath); - } - - using (var fs = File.Create(filePath)) - { - using (var sw = new StreamWriter(fs, encoding ?? Encoding.Default)) - { - sw.Write(content); - } - } - } - - - public static string ReadAllText(string filePath) - { - if (!File.Exists(filePath)) - return ""; - - try - { - using (var fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) - using (var sr = new StreamReader(fs)) - { - return sr.ReadToEnd(); - } - } - catch - { - return ""; - } - } - - public static void WriteAllText(string filePath, string content) - { - try - { - if (File.Exists(filePath)) - File.Delete(filePath); - - var dir = Path.GetDirectoryName(filePath); - if (!Directory.Exists(dir)) - Directory.CreateDirectory(dir); - - using (var fs = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite)) - using (var sw = new StreamWriter(fs)) - { - sw.Write(content); - } - } - catch - { - - } - } - - - - public static string FormatSelf(this string self, string format) - { - return string.Format(format, self); - } - - static int Indent = 0; - public static void AppendIndentLine(this StringBuilder self, string text) - { - for (int i = 0; i < Indent; ++i) - self.Append('\t'); - self.AppendLine(text); - } - - public static void AppendIndent(this StringBuilder self, string text) - { - for (int i = 0; i < Indent; ++i) - self.Append('\t'); - self.Append(text); - } - - private static void AppendIndentCommentInternal(this StringBuilder self, string comment) - { - if (string.IsNullOrEmpty(comment)) - return; - - using (StringReader sr = new StringReader(comment)) - { - string line; - while ((line = sr.ReadLine()) != null) - { - if (!string.IsNullOrEmpty(line)) - self.AppendIndentLine($"/// {line}"); - } - } - } - - public static void AppendIndentComment(this StringBuilder self, string comment1) - { - if (string.IsNullOrEmpty(comment1)) - return; - - self.AppendIndentLine("/// "); - self.AppendIndentCommentInternal(comment1); - self.AppendIndentLine("/// "); - } - - public static void AppendIndentComment(this StringBuilder self, string comment1, string comment2) - { - if (string.IsNullOrEmpty(comment1) && string.IsNullOrEmpty(comment2)) - return; - - self.AppendIndentLine("/// "); - self.AppendIndentCommentInternal(comment1); - self.AppendIndentCommentInternal(comment2); - self.AppendIndentLine("/// "); - } - - - - public class StringBuilderIndentScope : IDisposable - { - public StringBuilderIndentScope() - { - Indent++; - } - public void Dispose() - { - Indent--; - } - } - - public static bool CommandLineHasArg(string arg) => Environment.GetCommandLineArgs().IndexOf(x => string.Equals(x, arg, StringComparison.OrdinalIgnoreCase)) != -1; - - public static string CommandLineGetArgValue(string arg) - { - var argEquals = arg + "="; - var args = Environment.GetCommandLineArgs(); - var idx = args.IndexOf(x => x.StartsWith(argEquals, StringComparison.OrdinalIgnoreCase)); - if (idx == -1) - return null; - return args[idx].Substring(argEquals.Length); - } - - public static int CommandLineGetArgValueInt(string arg, int defaultValue = 0) - { - try - { - return int.TryParse(CommandLineGetArgValue(arg), out var result) ? result : defaultValue; - } - catch - { - return defaultValue; - } - } - - public static bool CommandLineGetArgValueBool(string arg, bool defaultValue = false) - { - try - { - var str = CommandLineGetArgValue(arg); - if (str == null) - return defaultValue; - if (str.Equals("1") || str.Equals("true", StringComparison.OrdinalIgnoreCase)) - return true; - return false; - } - catch - { - return defaultValue; - } - } - - - private static string s_LogErrorForCommandLinePath = Path.Combine(Application.dataPath, "../Logs/LogErrorForCommandLine.log"); - private static string s_LogErrorForCommandLineAsJsonContentPath = Path.Combine(Application.dataPath, "../Logs/LogErrorForCommandLineAsJsonContent.log"); - - class LogInfo - { - public string msg; - public string trace; - public LogType type; - - public void Append(StringBuilder sb, int index) - { - sb.Append($"[{type}-{index}] {(msg.Length > 500 ? msg.Substring(0, 500) : msg)}\n\n"); - } - } - private static List s_LogErrorForCommandLine = new(); - public static void CommandLineListenError() - { - try - { - if (File.Exists(s_LogErrorForCommandLinePath)) - File.Delete(s_LogErrorForCommandLinePath); - if (File.Exists(s_LogErrorForCommandLineAsJsonContentPath)) - File.Delete(s_LogErrorForCommandLineAsJsonContentPath); - } - catch - { - - } - Application.logMessageReceived += (condition, trace, type) => - { - switch (type) - { - case LogType.Assert: - case LogType.Exception: - case LogType.Error: - { - s_LogErrorForCommandLine.Add(new LogInfo() - { - msg = condition, - trace = trace, - type = type, - }); - break; - } - } - }; - } - - public static string Convert2JsonContent(string text) - { - return text - .Replace("\\", "\\\\") - .Replace("\"", "\\\"") - .Replace("/", "\\/") - .Replace("\b", "\\b") - .Replace("\f", "\\f") - .Replace("\t", "\\t") - .Replace("\n", "\\n") - .Replace("\r", "\\r"); - } - - public static void CommandLineSaveError() - { - StringBuilder sb = new(); - if (s_LogErrorForCommandLine.Count > 4) - { - s_LogErrorForCommandLine[0].Append(sb, 0); - s_LogErrorForCommandLine[1].Append(sb, 1); - - sb.Append("\n......\n\n"); - - s_LogErrorForCommandLine[s_LogErrorForCommandLine.Count - 2].Append(sb, s_LogErrorForCommandLine.Count - 2); - s_LogErrorForCommandLine[s_LogErrorForCommandLine.Count - 1].Append(sb, s_LogErrorForCommandLine.Count - 1); - } - else - { - for (int i = 0; i < s_LogErrorForCommandLine.Count; ++ i) - s_LogErrorForCommandLine[i].Append(sb, i); - } - var text = sb.ToString(); - File.WriteAllText(s_LogErrorForCommandLinePath, text); - - File.WriteAllText(s_LogErrorForCommandLineAsJsonContentPath, Convert2JsonContent(text)); - } - public static int IndexOf(this T[] self, Predicate match) - { - for (int i = 0; i < self.Length; ++i) - { - if (match(self[i])) - return i; - } - return -1; - } -} diff --git a/Assets/URS/YooAsset/Runtime/AssetSystem/AppToChannelRouter.cs b/Assets/URS/YooAsset/Runtime/AssetSystem/AppToChannelRouter.cs deleted file mode 100644 index eef12dc..0000000 --- a/Assets/URS/YooAsset/Runtime/AssetSystem/AppToChannelRouter.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using UnityEngine; -using URS; -using YooAsset.Utility; - - -[Serializable] -public class AppToChannelRouter -{ - [SerializeField] - public AppToChannelItem[] Items; - - [NonSerialized] - private Dictionary _itemMap = new Dictionary(); - - public AppToChannelItem GetChanel(string appId) - { - if (_itemMap.TryGetValue(appId, out var result)) - { - return result; - } - UnityEngine.Debug.LogError("Can not find AppToChannel appid " + appId); - return null; - - } - /// - /// л - /// - public static void Serialize(string savePath, AppToChannelRouter router, bool pretty = false) - { - string json = JsonUtility.ToJson(router, pretty); - FileUtility.CreateFile(savePath, json); - } - /// - /// л - /// - public static AppToChannelRouter Deserialize(string jsonData) - { - AppToChannelRouter router = JsonUtility.FromJson(jsonData); - if (router != null) - { - router.AfterDeserialize(); - } - return router; - } - public void AfterDeserialize() - { - if (Items == null) - { - Items = new AppToChannelItem[0]; - } - if (_itemMap == null) - { - _itemMap = new Dictionary(); - } - for (int i = 0; i < Items.Length; i++) - { - var item = Items[i]; - if (item != null) - { - if (!string.IsNullOrEmpty(item.AppId)) - { - if (!_itemMap.ContainsKey(item.AppId)) - { - _itemMap[item.AppId] = item; - } - } - else - { - Debug.LogError($"{item.AppId} AppId is null"); - } - } - else - { - Debug.LogError($"{i} filemeta is null"); - } - } - } -} -[Serializable] -public class AppToChannelItem -{ - [SerializeField] - public string AppId; - - [SerializeField] - public string ChannelId; - - [SerializeField] - public string VersionCode; -} diff --git a/Assets/URS/YooAsset/Runtime/AssetSystem/AppVersionRouter.cs b/Assets/URS/YooAsset/Runtime/AssetSystem/AppVersionRouter.cs new file mode 100644 index 0000000..609287e --- /dev/null +++ b/Assets/URS/YooAsset/Runtime/AssetSystem/AppVersionRouter.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using URS; +using YooAsset.Utility; +using System.Text; +using System.Text.RegularExpressions; + +[Serializable] +public class AppVersionRouter +{ + [SerializeField] + public AppVersionItem[] Items; + + [SerializeField] + + public string DefaultVersion; + + [NonSerialized] + private Dictionary _itemMap = new Dictionary(); + + public string GetChannel(string applicationVersion) + { + foreach (var key in _itemMap.Keys) + { + Regex regex= new Regex(key); + bool match = regex.IsMatch(applicationVersion); + if (match) + { + return _itemMap[key].VersionCode; + } + } + return DefaultVersion; + } + /// + /// л + /// + public static void Serialize(string savePath, AppVersionRouter router, bool pretty = false) + { + string json = JsonUtility.ToJson(router, pretty); + FileUtility.CreateFile(savePath, json); + } + /// + /// л + /// + public static AppVersionRouter Deserialize(string jsonData) + { + AppVersionRouter router = JsonUtility.FromJson(jsonData); + if (router != null) + { + router.AfterDeserialize(); + } + return router; + } + public void AfterDeserialize() + { + if (Items == null) + { + Items = new AppVersionItem[0]; + } + if (_itemMap == null) + { + _itemMap = new Dictionary(); + } + for (int i = 0; i < Items.Length; i++) + { + var item = Items[i]; + if (item != null) + { + if (!string.IsNullOrEmpty(item.ApplicationVersion)) + { + if (!_itemMap.ContainsKey(item.ApplicationVersion)) + { + _itemMap[item.ApplicationVersion] = item; + } + } + else + { + Debug.LogError($"{item.ApplicationVersion} AppId is null"); + } + } + else + { + Debug.LogError($"{i} filemeta is null"); + } + } + } +} +[Serializable] +public class AppVersionItem +{ + [SerializeField] + public string ApplicationVersion; + + [SerializeField] + public string VersionCode; +} diff --git a/Assets/URS/YooAsset/Runtime/AssetSystem/AppToChannelRouter.cs.meta b/Assets/URS/YooAsset/Runtime/AssetSystem/AppVersionRouter.cs.meta similarity index 100% rename from Assets/URS/YooAsset/Runtime/AssetSystem/AppToChannelRouter.cs.meta rename to Assets/URS/YooAsset/Runtime/AssetSystem/AppVersionRouter.cs.meta diff --git a/Assets/URS/YooAsset/Runtime/AssetSystem/AssetPathHelper.cs b/Assets/URS/YooAsset/Runtime/AssetSystem/AssetPathHelper.cs index 434d08f..aa2d148 100644 --- a/Assets/URS/YooAsset/Runtime/AssetSystem/AssetPathHelper.cs +++ b/Assets/URS/YooAsset/Runtime/AssetSystem/AssetPathHelper.cs @@ -29,22 +29,13 @@ public static string MakeStreamingLoadPath(string path) { return StringUtility.Format("{0}/{1}", UnityEngine.Application.streamingAssetsPath, path); } - public static string sStreamingSandboxDirectory = null; - - public static string GetStreamingSandboxDirectory() + public static string GetBuildInChannelFilePath() { - if (sStreamingSandboxDirectory == null) - { - sStreamingSandboxDirectory= StringUtility.Format("{0}/{1}", UnityEngine.Application.streamingAssetsPath,"sandbox"); - } - return sStreamingSandboxDirectory; + return MakeStreamingLoadPath(URSRuntimeSetting.instance.ChannelFileName); } - /// - /// 获取基于流文件夹的加载路径 - /// - public static string MakeStreamingSandboxLoadPath(string path) + public static string MakeURSBuildInResourcePath(string path) { - return StringUtility.Format("{0}/{1}", GetStreamingSandboxDirectory(), path); + return StringUtility.Format("{0}/{1}", GetURSBuildInResourceFolder(), path); } /// /// 获取基于沙盒文件夹的加载路径 @@ -117,10 +108,53 @@ public static string ConvertToWWWPath(string path) #endif } - /// - /// 合并资源路径 - /// - internal static string CombineAssetPath(string root, string location) + + public static string sPersistentDownloadFolder = null; + public static string GetPersistentDownloadFolder() + { + if (sPersistentDownloadFolder == null) + { + sPersistentDownloadFolder = $"{AssetPathHelper.GetPersistentRootPath()}/download"; + } + return sPersistentDownloadFolder; + } + + public static string sPersistentReadOnlyFolder = null; + public static string GetPersistentReadonlyFolder() + { + if (sPersistentReadOnlyFolder == null) + { + sPersistentReadOnlyFolder = $"{AssetPathHelper.GetPersistentRootPath()}/readonly"; + } + return sPersistentReadOnlyFolder; + } + + public static string sURSBuildInResourceFolder = null; + public static string GetURSBuildInResourceFolder() + { + if (sURSBuildInResourceFolder == null) + { + sURSBuildInResourceFolder = $"{UnityEngine.Application.streamingAssetsPath}/{GetURSBuildInResourceFolderName()}"; + } + return sURSBuildInResourceFolder; + } + public static string GetURSBuildInResourceFolderName() + { + return "urs_buildin_resources"; + } + public static string sDownloadTempFolder = null; + public static string GetDownloadTempFolder() + { + if (sDownloadTempFolder == null) + { + sDownloadTempFolder = $"{AssetPathHelper.GetPersistentRootPath()}/download_temp"; + } + return sDownloadTempFolder; + } + /// + /// 合并资源路径 + /// + internal static string CombineAssetPath(string root, string location) { if (string.IsNullOrEmpty(root)) return location; diff --git a/Assets/URS/YooAsset/Runtime/AssetSystem/AssetSystem.cs b/Assets/URS/YooAsset/Runtime/AssetSystem/AssetSystem.cs index fa6c74e..25a1158 100644 --- a/Assets/URS/YooAsset/Runtime/AssetSystem/AssetSystem.cs +++ b/Assets/URS/YooAsset/Runtime/AssetSystem/AssetSystem.cs @@ -1,15 +1,158 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Runtime.CompilerServices; +using NinjaBeats; using UnityEngine; +using UnityEngine.Pool; using UnityEngine.SceneManagement; using URS; + namespace YooAsset { internal static class AssetSystem { - private static readonly List _loaders = new List(1000); - private static readonly List _providers = new List(1000); + private static readonly Dictionary _loaders = new (1000); + private static readonly Dictionary _providers = new (1000); + + internal static readonly Updater updater = new Updater(); + internal static readonly Unloader unloader = new Unloader(); + + internal class Updater + { + public Dictionary loaders = new(100); + public Dictionary providers = new(100); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() + { + loaders.Clear(); + providers.Clear(); + } + + public void Update() + { + // 更新加载器 + if (loaders.Count > 0) + { + using (ListPool.Get(out var tempList)) + { + tempList.AddValues(loaders); + foreach (var loader in tempList) + { + if (loader.IsDone) + continue; + + loader.Update(); + + if (FpsHelper.instance.needWait) + break; + } + } + } + + // 更新资源提供者 + // 注意:循环更新的时候,可能会扩展列表 + // 注意:不能限制场景对象的加载 + if (providers.Count > 0) + { + using (ListPool.Get(out var tempList)) + { + tempList.AddValues(providers); + foreach (var provider in tempList) + { + if (provider.IsDone) + continue; + + provider.Update(); + + if (FpsHelper.instance.needWait) + break; + } + } + } + } + } + + internal class Unloader + { + public Dictionary destroyProviderLoaders = new(100); + public Dictionary destroyLoaders = new(100); + public Dictionary destroyProviders = new(100); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Clear() + { + destroyProviderLoaders.Clear(); + destroyLoaders.Clear(); + destroyProviders.Clear(); + } + + public void UnloadUnusedAssets() + { + if (SimulationOnEditor) + { + UnityEngine.Profiling.Profiler.BeginSample("AssetSystem.UnloadUnusedAssets TryDestroyAllProviders"); + if (destroyProviders.Count > 0) + { + using (ListPool.Get(out var tempList)) + { + tempList.AddValues(destroyProviders); + foreach (var provider in tempList) + { + if (!provider.CanDestroy) + continue; + + provider.Destroy(); + updater.providers.Remove(provider.Iid); + this.destroyProviders.Remove(provider.Iid); + _providers.Remove(provider.Iid); + } + } + } + UnityEngine.Profiling.Profiler.EndSample(); + } + else + { + UnityEngine.Profiling.Profiler.BeginSample("AssetSystem.UnloadUnusedAssets TryDestroyAllProviders"); + if (destroyProviderLoaders.Count > 0) + { + using (ListPool.Get(out var tempList)) + { + tempList.AddValues(destroyProviderLoaders); + foreach (var loader in tempList) + { + if (!loader.CanDestroyProvider) + continue; + + loader.TryDestroyAllProviders(); + } + } + } + UnityEngine.Profiling.Profiler.EndSample(); + UnityEngine.Profiling.Profiler.BeginSample("AssetSystem.UnloadUnusedAssets TryDestroyAllLoader"); + if (destroyLoaders.Count > 0) + { + using (ListPool.Get(out var tempList)) + { + tempList.AddValues(destroyLoaders); + foreach (var loader in tempList) + { + if (!loader.CanDestroy) + continue; + + loader.Destroy(false); + updater.loaders.Remove(loader.Iid); + this.destroyLoaders.Remove(loader.Iid); + _loaders.Remove(loader.Iid); + } + } + } + UnityEngine.Profiling.Profiler.EndSample(); + } + } + } + /// /// 在编辑器下模拟运行 @@ -36,73 +179,25 @@ public static void Initialize(bool simulationOnEditor, int assetLoadingMaxNumber DecryptionServices = decryptServices; BundleServices = bundleServices; } + + /// /// 轮询更新 /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Update() { - // 更新加载器 - foreach (var loader in _loaders) - { - loader.Update(); - } - - // 更新资源提供者 - // 注意:循环更新的时候,可能会扩展列表 - // 注意:不能限制场景对象的加载 - int loadingCount = 0; - for (int i = 0; i < _providers.Count; i++) - { - var provider = _providers[i]; - if (provider.IsSceneProvider()) - { - provider.Update(); - } - else - { - if (loadingCount < AssetLoadingMaxNumber) - provider.Update(); - - if (provider.IsDone == false) - loadingCount++; - } - } + updater.Update(); } /// /// 资源回收(卸载引用计数为零的资源) /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void UnloadUnusedAssets() { - if (SimulationOnEditor) - { - for (int i = _providers.Count - 1; i >= 0; i--) - { - if (_providers[i].CanDestroy()) - { - _providers[i].Destory(); - _providers.RemoveAt(i); - } - } - } - else - { - for (int i = _loaders.Count - 1; i >= 0; i--) - { - AssetBundleLoader loader = _loaders[i]; - loader.TryDestroyAllProviders(); - } - for (int i = _loaders.Count - 1; i >= 0; i--) - { - AssetBundleLoader loader = _loaders[i]; - if (loader.CanDestroy()) - { - loader.Destroy(false); - _loaders.RemoveAt(i); - } - } - } + unloader.UnloadUnusedAssets(); } /// @@ -110,21 +205,59 @@ public static void UnloadUnusedAssets() /// public static void ForceUnloadAllAssets() { - foreach (var provider in _providers) + foreach (var pair in _providers) { - provider.Destory(); + var provider = pair.Value; + provider.Destroy(); } _providers.Clear(); - foreach (var loader in _loaders) + foreach (var pair in _loaders) { + var loader = pair.Value; loader.Destroy(true); } _loaders.Clear(); + updater.Clear(); + unloader.Clear(); + // 注意:调用底层接口释放所有资源 Resources.UnloadUnusedAssets(); } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AddNewProvider(ProviderBase provider) + { + provider.InitSpawnDebugInfo(); + provider.OnIsDoneChanged += static x => updater.providers.Update(x.Iid, x, !x.IsDone); + if (SimulationOnEditor) + provider.OnCanDestroyChanged += static x => unloader.destroyProviders.Update(x.Iid, x, x.CanDestroy); + + updater.providers.Add(provider.Iid, provider); + _providers.Add(provider.Iid, provider); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void RemoveBundleProviders(Dictionary providers) + { + foreach (var pair in providers) + { + updater.providers.Remove(pair.Key); + _providers.Remove(pair.Key); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void AddNewLoader(AssetBundleLoader loader) + { + loader.OnIsDoneChanged += static x => updater.loaders.Update(x.Iid, x, !x.IsDone); + loader.OnCanDestroyChanged += static x => unloader.destroyLoaders.Update(x.Iid, x, x.CanDestroy); + loader.OnCanDestroyProviderChanged += static x => unloader.destroyProviderLoaders.Update(x.Iid, x, x.CanDestroyProvider); + + updater.loaders.Add(loader.Iid, loader); + _loaders.Add(loader.Iid, loader); + } /// /// 异步加载场景 @@ -138,8 +271,7 @@ public static SceneOperationHandle LoadSceneAsync(string scenePath, LoadSceneMod provider = new DatabaseSceneProvider(scenePath, sceneMode, activateOnLoad, priority); else provider = new BundledSceneProvider(scenePath, sceneMode, activateOnLoad, priority); - provider.InitSpawnDebugInfo(); - _providers.Add(provider); + AddNewProvider(provider); } return provider.CreateHandle() as SceneOperationHandle; } @@ -149,7 +281,7 @@ public static SceneOperationHandle LoadSceneAsync(string scenePath, LoadSceneMod /// /// 资源路径 /// 资源类型 - public static AssetOperationHandle LoadAssetAsync(string assetPath, System.Type assetType) + public static AssetOperationHandle LoadAssetAsync(string assetPath, System.Type assetType,bool requireLocalSecurity=false, bool skipDownloadFolder = true) { ProviderBase provider = TryGetProvider(assetPath); if (provider == null) @@ -157,9 +289,8 @@ public static AssetOperationHandle LoadAssetAsync(string assetPath, System.Type if (SimulationOnEditor) provider = new DatabaseAssetProvider(assetPath, assetType); else - provider = new BundledAssetProvider(assetPath, assetType); - provider.InitSpawnDebugInfo(); - _providers.Add(provider); + provider = new BundledAssetProvider(assetPath, assetType, requireLocalSecurity, skipDownloadFolder); + AddNewProvider(provider); } return provider.CreateHandle() as AssetOperationHandle; } @@ -178,8 +309,7 @@ public static SubAssetsOperationHandle LoadSubAssetsAsync(string assetPath, Syst provider = new DatabaseSubAssetsProvider(assetPath, assetType); else provider = new BundledSubAssetsProvider(assetPath, assetType); - provider.InitSpawnDebugInfo(); - _providers.Add(provider); + AddNewProvider(provider); } return provider.CreateHandle() as SubAssetsOperationHandle; } @@ -206,18 +336,29 @@ internal static List CreateDependAssetBundleLoaders(string as } return result; } + internal static void CreateLocalSecurityAssetBundleLoader( + string assetPath, + out AssetBundleLoader mainloader, + out List dependencyLoaders, + bool skipDownloadFolder= true) + { + BundleServices.SearchLocalSecurityBundleHardDiskFileByPath(assetPath, out var mainHardiskFileSearchResult,out var dependencyHardiskFileSearchResults, skipDownloadFolder); + mainloader = CreateAssetBundleLoaderInternal(mainHardiskFileSearchResult); + dependencyLoaders = new List(); + if (dependencyHardiskFileSearchResults != null) + { + foreach (var dp in dependencyHardiskFileSearchResults) + { + AssetBundleLoader dependLoader = CreateAssetBundleLoaderInternal(dp); + dependencyLoaders.Add(dependLoader); + } + } + } public static HardiskFileSearchResult SearchFile(string fileRelativePath) { var searchResult = BundleServices.SearchHardiskFileByPath(fileRelativePath); return searchResult; } - internal static void RemoveBundleProviders(List providers) - { - foreach (var provider in providers) - { - _providers.Remove(provider); - } - } private static AssetBundleLoader CreateAssetBundleLoaderInternal(HardiskFileSearchResult localFileSearchResult) { @@ -227,15 +368,15 @@ private static AssetBundleLoader CreateAssetBundleLoaderInternal(HardiskFileSear return loader; // 新增下载需求 loader = new AssetBundleLoader(localFileSearchResult); - _loaders.Add(loader); + AddNewLoader(loader); return loader; } private static AssetBundleLoader TryGetAssetBundleLoader(string relativePath) { AssetBundleLoader loader = null; - for (int i = 0; i < _loaders.Count; i++) + foreach (var pair in _loaders) { - AssetBundleLoader temp = _loaders[i]; + AssetBundleLoader temp = pair.Value; if (temp.HardiskFileSearchResult.OrignRelativePath.Equals(relativePath)) { loader = temp; @@ -247,9 +388,9 @@ private static AssetBundleLoader TryGetAssetBundleLoader(string relativePath) private static ProviderBase TryGetProvider(string assetPath) { ProviderBase provider = null; - for (int i = 0; i < _providers.Count; i++) + foreach (var pair in _providers) { - ProviderBase temp = _providers[i]; + ProviderBase temp = pair.Value; if (temp.AssetPath.Equals(assetPath)) { provider = temp; @@ -266,8 +407,9 @@ internal static void GetDebugReport(DebugReport report) report.BundleCount = _loaders.Count; report.AssetCount = _providers.Count; - foreach (var provider in _providers) + foreach (var pair in _providers) { + var provider = pair.Value; DebugProviderInfo providerInfo = new DebugProviderInfo(); providerInfo.AssetPath = provider.AssetPath; providerInfo.SpawnScene = provider.SpawnScene; diff --git a/Assets/URS/YooAsset/Runtime/AssetSystem/Handles/SceneOperationHandle.cs b/Assets/URS/YooAsset/Runtime/AssetSystem/Handles/SceneOperationHandle.cs index 8aa0259..44b850c 100644 --- a/Assets/URS/YooAsset/Runtime/AssetSystem/Handles/SceneOperationHandle.cs +++ b/Assets/URS/YooAsset/Runtime/AssetSystem/Handles/SceneOperationHandle.cs @@ -13,8 +13,11 @@ internal override void InvokeCallback() { if (IsValid) { + UnityEngine.Profiling.Profiler.BeginSample(" SceneOperationHandle "+ this.AssetPath); _callback?.Invoke(this); - } + UnityEngine.Profiling.Profiler.EndSample(); + + } } /// diff --git a/Assets/URS/YooAsset/Runtime/AssetSystem/IBundleServices.cs b/Assets/URS/YooAsset/Runtime/AssetSystem/IBundleServices.cs index e9d3bf9..a1ad8ed 100644 --- a/Assets/URS/YooAsset/Runtime/AssetSystem/IBundleServices.cs +++ b/Assets/URS/YooAsset/Runtime/AssetSystem/IBundleServices.cs @@ -17,5 +17,7 @@ public interface IFileSystemServices /// 获取资源依赖的所有AssetBundle列表 /// List GetAllDependencieBundleRelativePaths(string assetPath); - } + + void SearchLocalSecurityBundleHardDiskFileByPath(string relativePath,out HardiskFileSearchResult mainResult,out List dependency, bool skipDownloadFolder = true); + } } \ No newline at end of file diff --git a/Assets/URS/YooAsset/Runtime/AssetSystem/Loader/AssetBundleLoader.cs b/Assets/URS/YooAsset/Runtime/AssetSystem/Loader/AssetBundleLoader.cs index 54dac38..842cf12 100644 --- a/Assets/URS/YooAsset/Runtime/AssetSystem/Loader/AssetBundleLoader.cs +++ b/Assets/URS/YooAsset/Runtime/AssetSystem/Loader/AssetBundleLoader.cs @@ -1,6 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Runtime.CompilerServices; using UnityEngine; using URS; namespace YooAsset @@ -17,28 +18,154 @@ public enum EStatus Success, Fail, } + + public delegate void OnValueChanged(AssetBundleLoader loader); + private static int s_IidAllocator = 0; + public int Iid { get; } + /// /// 资源包文件信息 /// - public HardiskFileSearchResult HardiskFileSearchResult { private set; get; } + public HardiskFileSearchResult HardiskFileSearchResult { private set; get; } + + private int _refCount = 0; /// /// 引用计数 /// - public int RefCount { private set; get; } + public int RefCount + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private set + { + var old = _refCount; + _refCount = value; + if (old != value) + { + RefreshCanDestroyProvider(); + RefreshCanDestroy(); + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _refCount; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void RefreshCanDestroy() + { + CanDestroy = IsDone && RefCount <= 0; + } + + public OnValueChanged OnCanDestroyChanged = null; + private bool _canDestroy = false; + /// + /// 是否可以销毁 + /// + public bool CanDestroy + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private set + { + var old = _canDestroy; + _canDestroy = value; + if (old != value) + OnCanDestroyChanged?.Invoke(this); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _canDestroy; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private bool CalcCanDestroyProvider() + { + if (IsDone == false) + return false; + + // 注意:必须等待所有Provider可以销毁的时候,才可以释放Bundle文件。 + foreach (var pair in _providers) + { + var provider = pair.Value; + if (provider.CanDestroy == false) + return false; + } + + // 除了自己没有其它引用 + if (RefCount > _providers.Count) + return false; + + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void RefreshCanDestroyProvider() + { + CanDestroyProvider = CalcCanDestroyProvider(); + } + + public OnValueChanged OnCanDestroyProviderChanged = null; + private bool _canDestroyProvider; + public bool CanDestroyProvider + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private set + { + var old = _canDestroyProvider; + _canDestroyProvider = value; + if (old != value) + OnCanDestroyProviderChanged?.Invoke(this); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _canDestroyProvider; + } + + protected EStatus _status = EStatus.None; /// /// 加载状态 /// - public EStatus Status { private set; get; } + public EStatus Status + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected set + { + _status = value; + IsDone = _status == EStatus.Success || _status == EStatus.Fail; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _status; + } + + public OnValueChanged OnIsDoneChanged = null; + private bool _isDone = false; + + /// + /// 是否完毕(无论成功或失败) + /// + public bool IsDone + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private set + { + var old = _isDone; + _isDone = value; + if (old != value) + { + OnIsDoneChanged?.Invoke(this); + RefreshCanDestroyProvider(); + RefreshCanDestroy(); + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _isDone; + } /// /// 是否已经销毁 /// public bool IsDestroyed { private set; get; } = false; - private readonly List _providers = new List(100); + private readonly Dictionary _providers = new Dictionary(100); private bool _isWaitForAsyncComplete = false; private bool _isShowWaitForAsyncError = false; private RemoteDownloader _fileDownloader; @@ -48,6 +175,7 @@ public enum EStatus public AssetBundleLoader(HardiskFileSearchResult hardiskFileSearchResult) { + Iid = ++s_IidAllocator; HardiskFileSearchResult = hardiskFileSearchResult; RefCount = 0; Status = EStatus.None; @@ -58,8 +186,11 @@ public AssetBundleLoader(HardiskFileSearchResult hardiskFileSearchResult) /// public void AddProvider(ProviderBase provider) { - if (_providers.Contains(provider) == false) - _providers.Add(provider); + if (_providers.TryAdd(provider.Iid, provider)) + { + provider.OnCanDestroyChanged += _ => RefreshCanDestroyProvider(); + RefreshCanDestroyProvider(); + } } /// @@ -84,7 +215,7 @@ public void Release() public void Update() { // 如果资源文件加载完毕 - if (IsDone()) + if (IsDone) return; if (Status == EStatus.None) @@ -189,6 +320,7 @@ public void Update() } else { + AssetBundleOccupyPersistentFileTraceManager.Instance.Register(this); Status = EStatus.Success; } } @@ -200,70 +332,46 @@ public void Update() public void Destroy(bool forceDestroy) { IsDestroyed = true; + OnIsDoneChanged = null; + OnCanDestroyChanged = null; + OnCanDestroyProviderChanged = null; // Check fatal if (forceDestroy == false) { if (RefCount > 0) throw new Exception($"Bundle file loader ref is not zero : {HardiskFileSearchResult.OrignRelativePath}"); - if (IsDone() == false) + if (IsDone == false) throw new Exception($"Bundle file loader is not done : {HardiskFileSearchResult.OrignRelativePath}"); } if (CacheBundle != null) { - CacheBundle.Unload(true); + AssetBundleOccupyPersistentFileTraceManager.Instance.Unregister(this); + CacheBundle.Unload(true); CacheBundle = null; } } - /// - /// 是否完毕(无论成功或失败) - /// - public bool IsDone() - { - return Status == EStatus.Success || Status == EStatus.Fail; - } - - /// - /// 是否可以销毁 - /// - public bool CanDestroy() - { - if (IsDone() == false) - return false; - - return RefCount <= 0; - } - /// /// 在满足条件的前提下,销毁所有资源提供者 /// public void TryDestroyAllProviders() { - if (IsDone() == false) - return; - - // 注意:必须等待所有Provider可以销毁的时候,才可以释放Bundle文件。 - foreach (var provider in _providers) - { - if (provider.CanDestroy() == false) - return; - } - - // 除了自己没有其它引用 - if (RefCount > _providers.Count) + if (!CanDestroyProvider) return; // 销毁所有Providers - foreach (var provider in _providers) + foreach (var pair in _providers) { - provider.Destory(); + var provider = pair.Value; + provider.Destroy(); } // 从列表里移除Providers AssetSystem.RemoveBundleProviders(_providers); _providers.Clear(); + RefreshCanDestroyProvider(); } /// @@ -293,7 +401,7 @@ public void WaitForAsyncComplete() Update(); // 完成后退出 - if (IsDone()) + if (IsDone) break; } } diff --git a/Assets/URS/YooAsset/Runtime/AssetSystem/Loader/AssetBundleOccupyPersistentFileTraceManager.cs b/Assets/URS/YooAsset/Runtime/AssetSystem/Loader/AssetBundleOccupyPersistentFileTraceManager.cs new file mode 100644 index 0000000..3db41a2 --- /dev/null +++ b/Assets/URS/YooAsset/Runtime/AssetSystem/Loader/AssetBundleOccupyPersistentFileTraceManager.cs @@ -0,0 +1,46 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using YooAsset; + +public class AssetBundleOccupyPersistentFileTraceManager +{ + public static AssetBundleOccupyPersistentFileTraceManager Instance = new AssetBundleOccupyPersistentFileTraceManager(); + + public HashSet _workingAssetBundleLoaders = new HashSet(); + + public HashSet _filePaths= new HashSet(); + + private bool enable = false; + + public void Register(AssetBundleLoader assetBundleLoader) + { + if (!enable) return; + _workingAssetBundleLoaders.Add(assetBundleLoader); + _filePaths.Add(assetBundleLoader.HardiskFileSearchResult.HardiskPath); + } + + public void Unregister(AssetBundleLoader assetBundleLoader) + { + if (!enable) return; + _workingAssetBundleLoaders.Remove(assetBundleLoader); + _filePaths.Remove(assetBundleLoader.HardiskFileSearchResult.HardiskPath); + } + + + + public bool IsFileOccupy(string filePath) + { + return _filePaths.Contains(filePath); + } + + public void BeginTrace() + { + enable = true; + } + + public void EndTrace() + { + enable = false; + } +} diff --git a/Assets/URS/YooAsset/Runtime/AssetSystem/Loader/AssetBundleOccupyPersistentFileTraceManager.cs.meta b/Assets/URS/YooAsset/Runtime/AssetSystem/Loader/AssetBundleOccupyPersistentFileTraceManager.cs.meta new file mode 100644 index 0000000..9e72746 --- /dev/null +++ b/Assets/URS/YooAsset/Runtime/AssetSystem/Loader/AssetBundleOccupyPersistentFileTraceManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 510648eb4ac3e2043b5105e5fbfd227d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Runtime/AssetSystem/Loader/DependAssetBundleGrouper.cs b/Assets/URS/YooAsset/Runtime/AssetSystem/Loader/DependAssetBundleGrouper.cs index 4643f7c..ff7a3b5 100644 --- a/Assets/URS/YooAsset/Runtime/AssetSystem/Loader/DependAssetBundleGrouper.cs +++ b/Assets/URS/YooAsset/Runtime/AssetSystem/Loader/DependAssetBundleGrouper.cs @@ -15,15 +15,18 @@ public DependAssetBundleGrouper(string assetPath) { _dependBundles = AssetSystem.CreateDependAssetBundleLoaders(assetPath); } - - /// - /// 是否已经完成(无论成功或失败) - /// - public bool IsDone() + public DependAssetBundleGrouper(List dependBundles) + { + _dependBundles = dependBundles; + } + /// + /// 是否已经完成(无论成功或失败) + /// + public bool IsDone() { foreach (var loader in _dependBundles) { - if (loader.IsDone() == false) + if (loader.IsDone == false) return false; } return true; @@ -36,7 +39,7 @@ public void WaitForAsyncComplete() { foreach (var loader in _dependBundles) { - if (loader.IsDone() == false) + if (loader.IsDone == false) loader.WaitForAsyncComplete(); } } diff --git a/Assets/URS/YooAsset/Runtime/AssetSystem/LocalFileInfo.cs b/Assets/URS/YooAsset/Runtime/AssetSystem/LocalFileInfo.cs index beea692..e4a37fa 100644 --- a/Assets/URS/YooAsset/Runtime/AssetSystem/LocalFileInfo.cs +++ b/Assets/URS/YooAsset/Runtime/AssetSystem/LocalFileInfo.cs @@ -1,3 +1,4 @@ +using System; using System.Collections; using System.Collections.Generic; using UnityEngine; @@ -5,12 +6,7 @@ namespace URS { - public enum EnumHardiskDirectoryType - { - Invalid = 0, - Persistent = 1, - StreamAsset = 2 - } + public class UpdateEntry { public FileMeta RemoteFileMeta { get; private set; } @@ -18,21 +14,28 @@ public class UpdateEntry public string _remoteDownloadURL; public PatchItemVersion PatchItemVersion { get; private set; } + private EnumHardiskDirectoryType _patchDirectoryType = EnumHardiskDirectoryType.Invalid; + private FileMeta _patchFileMetaCandidate = null; private string _targetSaveFilePath; - private string _patchSavePath; + private string _downloadTempSavePath; public bool IsPatch() { return PatchItemVersion != null; } + public bool NeedUnzip() + { + return _patchDirectoryType == EnumHardiskDirectoryType.BuildIn; + } + public string GetRemoteDownloadURL() { return _remoteDownloadURL; } - public string GetPatchTargetPath() + public string GetFinalPersistentDownloadSavePath() { return _targetSaveFilePath; } @@ -40,7 +43,7 @@ public string GetPatchTargetPath() public string GetPatchTemp() { var pathRelativePath = $"{GetRelativePath()}---{PatchItemVersion.FromHashCode}---{PatchItemVersion.ToHashCode}.patch.temp"; - return SandboxFileSystem.MakeSandboxFilePath(pathRelativePath); + return URSFileSystem.GetDownloadFolderPath(pathRelativePath); } public uint GetRemoteDownloadFileHash() @@ -70,31 +73,33 @@ public string GetRelativePath() { return RemoteFileMeta.RelativePath; } - public string GetLocalSaveFilePath() + public string GetDownloadTempSaveFilePath() { - if (PatchItemVersion != null) - { - return _patchSavePath; - } - else - { - return _targetSaveFilePath; - } + return _downloadTempSavePath; } - public UpdateEntry(FileMeta remoteFileMeta, string remoteVersionRoot, PatchItemVersion patchItem =null,string remotePatchRoot=null) + public FileMeta GetPatchFileMetaCandidate() + { + return _patchFileMetaCandidate; + } + + public UpdateEntry(FileMeta remoteFileMeta, string remoteVersionRoot, PatchItemVersion patchItem =null,string remotePatchRoot=null,FileMeta patchFileMetaCandidate=null, EnumHardiskDirectoryType patchDirectoryType= EnumHardiskDirectoryType.Invalid + ) { RemoteFileMeta = remoteFileMeta; PatchItemVersion = patchItem; - _targetSaveFilePath = SandboxFileSystem.MakeSandboxFilePath(GetRelativePath()); + _patchDirectoryType = patchDirectoryType; + _targetSaveFilePath = URSFileSystem.GetDownloadFolderPath(GetRelativePath()); + _patchFileMetaCandidate = patchFileMetaCandidate; if (PatchItemVersion != null) { var pathRelativePath = $"{GetRelativePath()}---{PatchItemVersion.FromHashCode}---{PatchItemVersion.ToHashCode}.patch"; - _patchSavePath = SandboxFileSystem.MakeSandboxPatchFilePath(pathRelativePath); + _downloadTempSavePath = URSFileSystem.GetDownloadTempPath(pathRelativePath); _remoteDownloadURL = $"{remotePatchRoot}/{pathRelativePath}"; } else { + _downloadTempSavePath = URSFileSystem.GetDownloadTempPath(GetRelativePath()); _remoteDownloadURL = $"{remoteVersionRoot}/{GetRelativePath()}"; } } @@ -135,10 +140,12 @@ public string GetRelativePath() public UnzipEntry(FileMeta streamFileMeta) { StreamFileMeta = streamFileMeta; - HardiskSavePath = SandboxFileSystem.MakeSandboxFilePath(StreamFileMeta.RelativePath); - HardiskSourcePath = AssetPathHelper.MakeStreamingSandboxLoadPath(StreamFileMeta.RelativePath); + HardiskSavePath = URSFileSystem.PersistentDownloadFolder.GetFileHardiskPath(StreamFileMeta.RelativePath); + HardiskSourcePath = URSFileSystem.BuildInFolder.GetFileHardiskPath(StreamFileMeta.RelativePath); HardiskSourcePath = AssetPathHelper.ConvertToWWWPath(HardiskSourcePath); } + + public Action OnFinish = null; } @@ -273,7 +280,7 @@ UpdateEntry updateEntry { this.FileMeta = fileMeta; OrignRelativePath = fileMeta.RelativePath; - HardiskPath = SandboxFileSystem.MakeSandboxFilePath(OrignRelativePath); + HardiskPath = URSFileSystem.GetDownloadFolderPath(OrignRelativePath); UpdateEntry= updateEntry; HardiskDirectoryType = EnumHardiskDirectoryType.Invalid; } diff --git a/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/BundledAssetProvider.cs b/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/BundledAssetProvider.cs index ebe4c1f..f7f213e 100644 --- a/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/BundledAssetProvider.cs +++ b/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/BundledAssetProvider.cs @@ -17,8 +17,8 @@ public override float Progress } } - public BundledAssetProvider(string assetPath, System.Type assetType) - : base(assetPath, assetType) + public BundledAssetProvider(string assetPath, System.Type assetType, bool requireLocalSecurity, bool skipDownloadFolder = true) + : base(assetPath, assetType, requireLocalSecurity, skipDownloadFolder) { } public override void Update() @@ -42,7 +42,7 @@ public override void Update() if (DependBundles.IsDone() == false) return; - if (OwnerBundle.IsDone() == false) + if (OwnerBundle.IsDone == false) return; if (OwnerBundle.CacheBundle == null) diff --git a/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/BundledProvider.cs b/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/BundledProvider.cs index 9088e44..038bc59 100644 --- a/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/BundledProvider.cs +++ b/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/BundledProvider.cs @@ -8,17 +8,30 @@ internal abstract class BundledProvider : ProviderBase protected AssetBundleLoader OwnerBundle { private set; get; } protected DependAssetBundleGrouper DependBundles { private set; get; } - public BundledProvider(string assetPath, System.Type assetType) : base(assetPath, assetType) + public BundledProvider(string assetPath, System.Type assetType,bool requireLocalSecurity=false, bool skipDownloadFolder = true) : base(assetPath, assetType) { - OwnerBundle = AssetSystem.CreateOwnerAssetBundleLoader(assetPath); - OwnerBundle.Reference(); - OwnerBundle.AddProvider(this); - DependBundles = new DependAssetBundleGrouper(assetPath); - DependBundles.Reference(); + if (requireLocalSecurity) + { + AssetSystem.CreateLocalSecurityAssetBundleLoader(assetPath, out var ownerBundle, out var dependencyLoaders, skipDownloadFolder); + OwnerBundle= ownerBundle; + OwnerBundle.Reference(); + OwnerBundle.AddProvider(this); + DependBundles = new DependAssetBundleGrouper(dependencyLoaders); + DependBundles.Reference(); + } + else + { + OwnerBundle = AssetSystem.CreateOwnerAssetBundleLoader(assetPath); + OwnerBundle.Reference(); + OwnerBundle.AddProvider(this); + DependBundles = new DependAssetBundleGrouper(assetPath); + DependBundles.Reference(); + } + } - public override void Destory() + public override void Destroy() { - base.Destory(); + base.Destroy(); // 释放资源包 if (OwnerBundle != null) diff --git a/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/BundledSceneProvider.cs b/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/BundledSceneProvider.cs index a1c5e5d..e53f950 100644 --- a/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/BundledSceneProvider.cs +++ b/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/BundledSceneProvider.cs @@ -44,7 +44,7 @@ public override void Update() { if (DependBundles.IsDone() == false) return; - if (OwnerBundle.IsDone() == false) + if (OwnerBundle.IsDone == false) return; if (OwnerBundle.CacheBundle == null) @@ -81,14 +81,17 @@ public override void Update() { if (_asyncOp.isDone) { - SceneObject = SceneManager.GetSceneByName(System.IO.Path.GetFileNameWithoutExtension(AssetName)); + UnityEngine.Profiling.Profiler.BeginSample("_asyncOp.isDone"); + SceneObject = SceneManager.GetSceneByName(System.IO.Path.GetFileNameWithoutExtension(AssetName)); if (SceneObject.IsValid() && _activateOnLoad) { SceneManager.SetActiveScene(SceneObject); } - + UnityEngine.Profiling.Profiler.EndSample(); Status = SceneObject.IsValid() ? EStatus.Success : EStatus.Fail; - InvokeCompletion(); - } + UnityEngine.Profiling.Profiler.BeginSample("InvokeCompletion"); + InvokeCompletion(); + UnityEngine.Profiling.Profiler.EndSample(); + } } } } diff --git a/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/BundledSubAssetsProvider.cs b/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/BundledSubAssetsProvider.cs index 808ce08..7df2ddd 100644 --- a/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/BundledSubAssetsProvider.cs +++ b/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/BundledSubAssetsProvider.cs @@ -42,7 +42,7 @@ public override void Update() if (DependBundles.IsDone() == false) return; - if (OwnerBundle.IsDone() == false) + if (OwnerBundle.IsDone == false) return; if (OwnerBundle.CacheBundle == null) diff --git a/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/DatabaseAssetProvider.cs b/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/DatabaseAssetProvider.cs index e6e8fce..9dcabc0 100644 --- a/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/DatabaseAssetProvider.cs +++ b/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/DatabaseAssetProvider.cs @@ -1,4 +1,5 @@ -using System.Collections; +using System; +using System.Collections; using System.Collections.Generic; using System.Diagnostics; using UnityEngine; @@ -23,13 +24,6 @@ public DatabaseAssetProvider(string assetPath, System.Type assetType) : base(assetPath, assetType) { } - -#if UNITY_EDITOR - private static int _sThisFrameCount = 0; - private static long _sThisFrameTotalDuration = 0; - private static Stopwatch _sLoadingStopwatch = new Stopwatch(); - private const long FRAME_LIMIT_DURATION = 12; -#endif public override void Update() { @@ -49,10 +43,14 @@ public override void Update() InvokeCompletion(); return; } - else + + // 检测资源文件是否在Library中 + if (!s_SmartLibraryAssetPathHashSet.Contains(guid)) { - Status = EStatus.Loading; + Logger.Error($"URS SmartLibrary 中找不到资源 \'{this.AssetPath}\' Window/SmartLibrary 中添加该资源后重试,如果你是资源的制作者,那么这条信息非常重要!!!!!如果不是可以当作没看见" ); } + + Status = EStatus.Loading; // 注意:模拟异步加载效果提前返回 if (IsWaitForAsyncComplete == false) @@ -63,19 +61,8 @@ public override void Update() if (Status == EStatus.Loading) { _SimulateProgress = Mathf.Lerp(_SimulateProgress, 100.0f, Time.deltaTime * 20.0f); - if (_sThisFrameCount != Time.frameCount) - { - _sThisFrameCount = Time.frameCount; - _sThisFrameTotalDuration = 0; - } - if (_sThisFrameTotalDuration <= FRAME_LIMIT_DURATION) - { - _sLoadingStopwatch.Restart(); - AssetObject = UnityEditor.AssetDatabase.LoadAssetAtPath(AssetPath, AssetType); - _sLoadingStopwatch.Stop(); - _sThisFrameTotalDuration += _sLoadingStopwatch.ElapsedMilliseconds; - Status = EStatus.Checking; - } + AssetObject = UnityEditor.AssetDatabase.LoadAssetAtPath(AssetPath, AssetType); + Status = EStatus.Checking; } // 2. 检测加载结果 diff --git a/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/DatabaseSceneProvider.cs b/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/DatabaseSceneProvider.cs index de9210c..8b12883 100644 --- a/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/DatabaseSceneProvider.cs +++ b/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/DatabaseSceneProvider.cs @@ -40,6 +40,13 @@ public override void Update() // 1. 加载资源对象 if (Status == EStatus.Loading) { + // 检测资源文件是否在Library中 + string guid = UnityEditor.AssetDatabase.AssetPathToGUID(AssetPath); + if (!s_SmartLibraryAssetPathHashSet.Contains(guid)) + { + Logger.Error($"URS SmartLibrary 中找不到资源 \'{this.AssetPath}\' Window/SmartLibrary 中添加该资源后重试,如果你是资源的制作者,那么这条信息非常重要!!!!!如果不是可以当作没看见" ); + } + LoadSceneParameters loadSceneParameters = new LoadSceneParameters(); loadSceneParameters.loadSceneMode = SceneMode; _asyncOp = UnityEditor.SceneManagement.EditorSceneManager.LoadSceneAsyncInPlayMode(AssetPath, loadSceneParameters); diff --git a/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/ProviderBase.cs b/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/ProviderBase.cs index 14a6ab8..cbb2d60 100644 --- a/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/ProviderBase.cs +++ b/Assets/URS/YooAsset/Runtime/AssetSystem/Provider/ProviderBase.cs @@ -1,9 +1,13 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; +using System.Runtime.CompilerServices; +using UnityEngine.Pool; +using NinjaBeats; + namespace YooAsset { - public abstract class ProviderBase + public abstract class ProviderBase { public enum EStatus { @@ -14,7 +18,12 @@ public enum EStatus Success, Fail, } + + public delegate void OnValueChanged(ProviderBase provider); + private static int s_IidAllocator = 0; + public int Iid { get; } + /// /// 资源路径 /// @@ -45,33 +54,97 @@ public enum EStatus /// public UnityEngine.SceneManagement.Scene SceneObject { protected set; get; } - + protected EStatus _status = EStatus.None; + /// /// 当前的加载状态 /// - public EStatus Status { protected set; get; } = EStatus.None; - + public EStatus Status + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected set + { + _status = value; + IsDone = _status == EStatus.Success || _status == EStatus.Fail; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _status; + } + + private bool _isDone = false; + public OnValueChanged OnIsDoneChanged = null; /// - /// 引用计数 + /// 是否完毕(成功或失败) /// - public int RefCount { private set; get; } = 0; + public bool IsDone + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private set + { + var old = _isDone; + _isDone = value; + if (old != value) + { + OnIsDoneChanged?.Invoke(this); + RefreshCanDestroy(); + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _isDone; + } + + private int _refCount = 0; /// - /// 是否已经销毁 + /// 引用计数 /// - public bool IsDestroyed { private set; get; } = false; + public int RefCount + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private set + { + var old = _refCount; + _refCount = value; + if (old != value) + { + RefreshCanDestroy(); + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _refCount; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void RefreshCanDestroy() + { + CanDestroy = IsDone && RefCount <= 0; + } + public OnValueChanged OnCanDestroyChanged = null; + private bool _canDestroy = false; /// - /// 是否完毕(成功或失败) + /// 是否可以销毁 /// - public bool IsDone + public bool CanDestroy { - get + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private set { - return Status == EStatus.Success || Status == EStatus.Fail; + var old = _canDestroy; + _canDestroy = value; + if (old != value) + OnCanDestroyChanged?.Invoke(this); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => _canDestroy; } + /// + /// 是否已经销毁 + /// + public bool IsDestroyed { private set; get; } = false; + + /// /// 加载进度 /// @@ -90,6 +163,7 @@ public virtual float Progress public ProviderBase(string assetPath, System.Type assetType) { + Iid = ++s_IidAllocator; AssetPath = assetPath; AssetName = assetPath; AssetType = assetType; @@ -103,20 +177,11 @@ public ProviderBase(string assetPath, System.Type assetType) /// /// 销毁资源对象 /// - public virtual void Destory() + public virtual void Destroy() { IsDestroyed = true; - } - - /// - /// 是否可以销毁 - /// - public bool CanDestroy() - { - if (IsDone == false) - return false; - - return RefCount <= 0; + OnIsDoneChanged = null; + OnCanDestroyChanged = null; } /// @@ -224,7 +289,8 @@ private System.Threading.WaitHandle WaitHandle } protected void InvokeCompletion() { - List tempers = new List(_handles); + var tempers = ListPool.Get(); + tempers.AddRange(_handles); foreach (var hande in tempers) { if (hande.IsValid) @@ -233,6 +299,7 @@ protected void InvokeCompletion() } } _waitHandle?.Set(); + ListPool.Release(tempers); } #endregion #region 调试信息相关 @@ -246,11 +313,16 @@ protected void InvokeCompletion() /// public string SpawnTime = string.Empty; + public bool PERFORMANCE = true; + [Conditional("DEBUG")] public void InitSpawnDebugInfo() { - SpawnScene = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name; ; - SpawnTime = SpawnTimeToString(UnityEngine.Time.realtimeSinceStartup); + if (PERFORMANCE) + { + SpawnScene = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name; ; + SpawnTime = SpawnTimeToString(UnityEngine.Time.realtimeSinceStartup); + } } private string SpawnTimeToString(float spawnTime) { @@ -260,5 +332,67 @@ private string SpawnTimeToString(float spawnTime) return h.ToString("00") + ":" + m.ToString("00") + ":" + s.ToString("00"); } #endregion + + +#if UNITY_EDITOR + private static HashSet _s_SmartLibraryAssetPathHashSet = null; + public static HashSet s_SmartLibraryAssetPathHashSet + { + get + { + if (_s_SmartLibraryAssetPathHashSet == null) + InitSmartLibrary(); + return _s_SmartLibraryAssetPathHashSet; + } + } + private static void InitSmartLibrary() + { + _s_SmartLibraryAssetPathHashSet = new(); + try + { + var TypeLibraryDatabase = NinjaBeats.EditorUtils.GetTypeByFullName("Bewildered.SmartLibrary.LibraryDatabase"); + var PropertyRootCollection = TypeLibraryDatabase.GetProperty("RootCollection", (System.Reflection.BindingFlags)(-1)); + var RootCollection = PropertyRootCollection.GetValue(null); + + var TypeLibraryCollection = NinjaBeats.EditorUtils.GetTypeByFullName("Bewildered.SmartLibrary.RootLibraryCollection"); + var Field_subcollections = TypeLibraryCollection.GetField("_subcollections", (System.Reflection.BindingFlags)(-1)); + var Field_items = TypeLibraryCollection.GetField("_items", (System.Reflection.BindingFlags)(-1)); + + static void _DeepCollect(object rootCollection, System.Reflection.FieldInfo Field_subcollections, System.Reflection.FieldInfo Field_items, HashSet result) + { + if (rootCollection == null) + return; + + var TypeLibraryCollection2 = NinjaBeats.EditorUtils.GetTypeByFullName("Bewildered.SmartLibrary.LibraryCollection"); + var Field_subcollections2 = TypeLibraryCollection2.GetField("_subcollections", (System.Reflection.BindingFlags)(-1)); + if (Field_subcollections2.GetValue(rootCollection) is IList subcollections) + { + foreach (var subcollection in subcollections) + { + + var subCollectionType = subcollection.GetType(); + var subCollectionItems = subCollectionType.GetField("_items", (System.Reflection.BindingFlags)(-1)); + var method = subCollectionType.GetMethod("UpdateItems", (System.Reflection.BindingFlags)(-1)); + method.Invoke(subcollection, new object[] { true }); + + if (subCollectionItems.GetValue(subcollection) is ISet items) + { + foreach (var item in items) + { + result.Add(item); + } + } + } + } + } + _DeepCollect(RootCollection, Field_subcollections, Field_items, _s_SmartLibraryAssetPathHashSet); + } + catch (System.Exception e) + { + Logger.Error("读取 URS SmartLibrary 失败: " + e.Message + "\n" + e.StackTrace); + _s_SmartLibraryAssetPathHashSet = new(); + } + } +#endif } } \ No newline at end of file diff --git a/Assets/URS/YooAsset/Runtime/Logger/Logger.cs b/Assets/URS/YooAsset/Runtime/Logger/Logger.cs index ae27c91..05b4112 100644 --- a/Assets/URS/YooAsset/Runtime/Logger/Logger.cs +++ b/Assets/URS/YooAsset/Runtime/Logger/Logger.cs @@ -2,7 +2,7 @@ namespace YooAsset { - internal static class Logger + public static class Logger { /// /// 日志 diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/BundleMeta.cs b/Assets/URS/YooAsset/Runtime/PatchSystem/BundleMeta.cs index 785ec8f..17e912f 100644 --- a/Assets/URS/YooAsset/Runtime/PatchSystem/BundleMeta.cs +++ b/Assets/URS/YooAsset/Runtime/PatchSystem/BundleMeta.cs @@ -4,6 +4,7 @@ using System; using YooAsset.Utility; using System.IO; +using YooAsset; namespace URS { @@ -11,58 +12,64 @@ namespace URS public class AssetMeta { /// - /// Դ· + /// 资源路径 /// public string AssetPath; /// - /// ԴID + /// 所属资源包ID /// public int BundleID; /// - /// ԴIDб + /// 依赖的资源包ID列表 /// public int[] DependIDs; } /// - /// Bundle + /// Bundle依赖 /// [Serializable] public class BundleManifest { /// - /// ԴбռԴб + /// 资源列表(主动收集的资源列表) /// public AssetMeta[] AssetList; /// - /// Դб + /// 资源包列表 /// public FileMeta[] BundleList; /// - /// ԴϣṩBundleNameȡPatchBundle + /// 资源包集合(提供BundleName获取PatchBundle) /// [NonSerialized] private Dictionary BundleMap = new Dictionary(); /// - /// Դӳ伯ϣṩAssetPathȡPatchAsset + /// 资源映射集合(提供AssetPath获取PatchAsset) /// [NonSerialized] private Dictionary AssetMap = new Dictionary(); /// - /// ȡԴб + /// 资源映射集合(提供AssetPath获取PatchAsset) + /// + [NonSerialized] + private Dictionary> BundleLayout = new Dictionary>(); + + /// + /// 获取资源依赖列表 /// public List GetAllDependenciesRelativePath(string assetPath) { if (AssetMap.TryGetValue(assetPath, out AssetMeta patchAsset)) { - List result = new List(patchAsset.DependIDs.Length); // TODO:Żgc + List result = new List(patchAsset.DependIDs.Length); // TODO:优化gc foreach (var dependID in patchAsset.DependIDs) { if (dependID >= 0 && dependID < BundleList.Length) @@ -79,13 +86,21 @@ public List GetAllDependenciesRelativePath(string assetPath) } else { - Debug.LogWarning($"Not found asset path in patch manifest : {assetPath}"); + Debug.LogError($"Not found asset path in patch manifest : {assetPath}"); return null; } } + public List GetBundleAssets(string bundleRelativePath) + { + if (BundleLayout.ContainsKey(bundleRelativePath)) + { + return BundleLayout[bundleRelativePath]; + } + return null; + } /// - /// ȡԴ + /// 获取资源包名称 /// public FileMeta GetBundleFileMeta(string assetPath) { @@ -130,11 +145,34 @@ public void AfterDeserialize() { AssetMap.Add(asset.AssetPath, asset); } + int bundleID = asset.BundleID; + if (bundleID >= 0 && bundleID < BundleList.Length) + { + var bundle = BundleList[bundleID]; + var bundleRelativePath = bundle.RelativePath; + if (BundleLayout.ContainsKey(bundleRelativePath)) + { + List assetList = BundleLayout[bundleRelativePath]; + if (!assetList.Contains(asset.AssetPath)) + { + assetList.Add(asset.AssetPath); + } + } + else + { + List assetList = new List { asset.AssetPath }; + BundleLayout[bundleRelativePath] = assetList; + } + } + else + { + throw new Exception($"Invalid depend id : {bundleID} Asset path : {asset.AssetPath}"); + } } } } /// - /// л + /// 序列化 /// public static void Serialize(string savePath, BundleManifest patchManifest,bool pretty=false) { @@ -143,7 +181,7 @@ public static void Serialize(string savePath, BundleManifest patchManifest,bool } /// - /// л + /// 反序列化 /// public static BundleManifest Deserialize(string jsonData) { diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/Download/HttpDownloader.cs b/Assets/URS/YooAsset/Runtime/PatchSystem/Download/HttpDownloader.cs index 8167ea0..fdd2723 100644 --- a/Assets/URS/YooAsset/Runtime/PatchSystem/Download/HttpDownloader.cs +++ b/Assets/URS/YooAsset/Runtime/PatchSystem/Download/HttpDownloader.cs @@ -106,7 +106,7 @@ internal void Update() _downloadError = _threadError; if (_threadResult) { - SandboxFileSystem.RegisterVerifyFile(_hardiskFileSearchResult.FileMeta); + URSFileSystem.DownloadFolderRegisterVerifyFile(_hardiskFileSearchResult.FileMeta); _steps = ESteps.Succeed; } else @@ -208,7 +208,7 @@ private void ThreadRun() } // 验证下载文件完整性 - bool verfiyResult = SandboxFileSystem.CheckContentIntegrity(savePath, _hardiskFileSearchResult.SizeBytes, _hardiskFileSearchResult.Hash); + bool verfiyResult = URSFileSystem.DownloadFolderCheckContentIntegrity(savePath, _hardiskFileSearchResult.SizeBytes, _hardiskFileSearchResult.Hash); if(verfiyResult) { _threadResult = true; diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/Download/RemoteDownloadSystem.cs b/Assets/URS/YooAsset/Runtime/PatchSystem/Download/RemoteDownloadSystem.cs index 3195734..083a356 100644 --- a/Assets/URS/YooAsset/Runtime/PatchSystem/Download/RemoteDownloadSystem.cs +++ b/Assets/URS/YooAsset/Runtime/PatchSystem/Download/RemoteDownloadSystem.cs @@ -45,7 +45,7 @@ public static void Update() /// 开始下载资源文件 /// 注意:只有第一次请求的参数才是有效的 /// - public static RemoteDownloader BeginDownload(UpdateEntry updateEntry, int failedTryAgain, int timeout = 60) + public static RemoteDownloader BeginDownload(UpdateEntry updateEntry, int failedTryAgain, int timeout = 700) { // 查询存在的下载器 if (_downloaderDic.TryGetValue(updateEntry.GetRemoteDownloadURL(), out var downloader)) diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/Download/RemoteDownloader.cs b/Assets/URS/YooAsset/Runtime/PatchSystem/Download/RemoteDownloader.cs index f7b5f8f..8a7b6ae 100644 --- a/Assets/URS/YooAsset/Runtime/PatchSystem/Download/RemoteDownloader.cs +++ b/Assets/URS/YooAsset/Runtime/PatchSystem/Download/RemoteDownloader.cs @@ -11,6 +11,7 @@ using System.Net; using MHLab.Patch.Core.Octodiff; using BestHTTP.SecureProtocol.Org.BouncyCastle.Ocsp; +using YooAsset.Utility; namespace YooAsset { @@ -28,6 +29,11 @@ private enum ESteps // private readonly HardiskFileSearchResult _hardiskFileSearchResult; private readonly UpdateEntry _updateEntry; + private UnzipEntry _unzipEntry; + private bool _isUnzipFinish = false; + private bool _isUnizipError = false; + + // private UnityWebRequest _webRequest; // private UnityWebRequestAsyncOperation _operationHandle; private HTTPRequest _request; @@ -71,7 +77,7 @@ internal RemoteDownloader(UpdateEntry info) internal void SendRequest(int failedTryAgain, int timeout) { - if (string.IsNullOrEmpty(_updateEntry.GetLocalSaveFilePath())) + if (string.IsNullOrEmpty(_updateEntry.GetDownloadTempSaveFilePath())) throw new ArgumentNullException(); if (_steps == ESteps.None) @@ -81,6 +87,16 @@ internal void SendRequest(int failedTryAgain, int timeout) _steps = ESteps.CreateDownload; } } + private void OnUnzipFinish(Unziper unziper) + { + _isUnzipFinish = true; + _isUnizipError = unziper.HasError(); + if (!_isUnizipError) + { + // Debug.LogError("..."+ _updateEntry.GetPatchFileMetaCandidate().RelativePath); + URSFileSystem.DownloadFolderRegisterVerifyFile(_updateEntry.GetPatchFileMetaCandidate()); + } + } internal void Update() { if (_steps == ESteps.None) @@ -117,6 +133,14 @@ internal void Update() } _response = null; _request.Send(); + + if (_updateEntry.IsPatch()&& _updateEntry.NeedUnzip()) + { + this._unzipEntry = new UnzipEntry(_updateEntry.GetPatchFileMetaCandidate()); + _unzipEntry.OnFinish = this.OnUnzipFinish; + UnzipSystem.EnqueueUnzip(_unzipEntry); + } + //_request.OnRequestFinishedDelegate _steps = ESteps.CheckDownload; } @@ -128,6 +152,18 @@ internal void Update() // DownloadedBytes = _webRequest.downloadedBytes; // DownloadProgress= _request.progr + if (this._unzipEntry != null) { + if (!_isUnzipFinish) { + return; + } + if (_isUnizipError) + { + DisposeRequest(); + ClearLocalSaveFile(); + _lastError = $"fail to unzip file {_unzipEntry.GetRelativePath()}"; + _steps = ESteps.Failed; + } + } if (_response == null) { CheckTimeout(); @@ -170,13 +206,25 @@ internal void Update() EnsureDirectory(); try { - File.WriteAllBytes(_updateEntry.GetLocalSaveFilePath(), _response.Data); + File.WriteAllBytes(_updateEntry.GetDownloadTempSaveFilePath(), _response.Data); + } catch (Exception e) { + _lastError = $" File.WriteAllBytes failed {_updateEntry.GetDownloadTempSaveFilePath()} message : {e.Message}"; isError = true; } } + try + { + isError = !CheckDownLoadedFileIntegrity(_updateEntry.GetDownloadTempSaveFilePath(), _updateEntry.GetRemoteDownloadFileHash(), _updateEntry.GetRemoteDownloadFileSize()); + } + catch (Exception e) + { + _lastError = $"CheckDownLoadedFileIntegrity failed {_updateEntry.GetDownloadTempSaveFilePath()} message : {e.Message}"; + isError = true; + } + if (!isError) { if (_updateEntry.IsPatch()) @@ -186,13 +234,15 @@ internal void Update() { File.Delete(patchTargetTemp); } - File.Move(_updateEntry.GetPatchTargetPath(), patchTargetTemp); + var targetPath = _updateEntry.GetFinalPersistentDownloadSavePath(); + File.Move(targetPath, patchTargetTemp); try { - DeltaFileApplier.Apply(patchTargetTemp, _updateEntry.GetLocalSaveFilePath(), _updateEntry.GetPatchTargetPath()); - if (SandboxFileSystem.CheckContentIntegrity(_updateEntry.RemoteFileMeta, _updateEntry.GetPatchTargetPath())) + DeltaFileApplier.Apply(patchTargetTemp, _updateEntry.GetDownloadTempSaveFilePath(), targetPath); + if (URSFileSystem.DownloadFolderCheckContentIntegrity(_updateEntry.RemoteFileMeta, targetPath)) { - SandboxFileSystem.RegisterVerifyFile(_updateEntry.RemoteFileMeta); + // Debug.Log("ɹ " + _updateEntry.RemoteFileMeta.RelativePath); + URSFileSystem.DownloadFolderRegisterVerifyFile(_updateEntry.RemoteFileMeta); } else { @@ -203,27 +253,36 @@ internal void Update() } catch (Exception e) + { + URSFileSystem.DownloadFolderDeleteFile(_updateEntry.GetRelativePath()); + _lastError = $"patch failed message : {e.Message}"; + isError = true; + } + finally { if (File.Exists(patchTargetTemp)) { File.Delete(patchTargetTemp); } - SandboxFileSystem.DeleteSandboxFile(_updateEntry.GetRelativePath()); - _lastError = $"patch failed message : {e.Message}"; - isError = true; } } else { - if (SandboxFileSystem.CheckContentIntegrity(_updateEntry.RemoteFileMeta, _updateEntry.GetLocalSaveFilePath())) - { - SandboxFileSystem.RegisterVerifyFile(_updateEntry.RemoteFileMeta); - } - else - { - isError = true; - _lastError = $"Verification failed"; - } + var tempDownLoadPath = _updateEntry.GetDownloadTempSaveFilePath(); + var targetPath = _updateEntry.GetFinalPersistentDownloadSavePath(); + Directory.CreateDirectory(Path.GetDirectoryName(targetPath)); + File.Move(tempDownLoadPath, targetPath); + URSFileSystem.DownloadFolderRegisterVerifyFile(_updateEntry.RemoteFileMeta); + //if (URSFileSystem.DownloadFolderCheckContentIntegrity(_updateEntry.RemoteFileMeta, _updateEntry.GetLocalSaveFilePath())) + //{ + // Debug.Log("ȫļسɹ " + _updateEntry.RemoteFileMeta.RelativePath); + // URSFileSystem.DownloadFolderRegisterVerifyFile(_updateEntry.RemoteFileMeta); + //} + //else + //{ + // isError = true; + // _lastError = $"Verification failed"; + //} } } } @@ -237,8 +296,7 @@ internal void Update() else { _steps = ESteps.Succeed; - Logger.Log($"{_requestURL} "); - // SandboxFileSystem.RegisterVerifyFile(_downloadInfo.FileMeta); + //Logger.Log($"{_requestURL} "); } // ͷ @@ -262,17 +320,34 @@ internal void SetDone() _steps = ESteps.Succeed; } + public bool CheckDownLoadedFileIntegrity(string filePath, uint hash,long size) + { + if (File.Exists(filePath)) + { + var currentFileHash = Hashing.GetFileXXhash(filePath); + if (currentFileHash == hash) + { + long fileSize = FileUtility.GetFileSize(filePath); + if (fileSize == size) + { + //Logger.Error($"֤ʧܣļСͨ ĿС {size} ǰļС{fileSize}"); + return true; + } + } + } + return false; + } public void ClearLocalSaveFile() { - if (File.Exists(_updateEntry.GetLocalSaveFilePath())) + if (File.Exists(_updateEntry.GetDownloadTempSaveFilePath())) { - File.Delete(_updateEntry.GetLocalSaveFilePath()); + File.Delete(_updateEntry.GetDownloadTempSaveFilePath()); } } private void OnRequestFinish(HTTPRequest originalRequest, HTTPResponse response) { - // Debug.LogError("on OnRequestFinish" + _requestURL + " " + response.IsSuccess); + //Debug.LogError("on OnRequestFinish" + _requestURL + " " + response.IsSuccess); _response = response; var fs = _request.Tag as System.IO.FileStream; @@ -294,7 +369,7 @@ private string GetRequestURL() private void CheckTimeout() { // ע⣺ʱݼжΪʱ - if (_response == null) + if (_response == null&& _request!=null) { if (_latestDownloadBytes != DownloadedBytes) { @@ -373,7 +448,7 @@ private bool OnData(HTTPRequest req, HTTPResponse resp, byte[] dataFragment, int if (fs == null) { EnsureDirectory(); - req.Tag = fs = new System.IO.FileStream(_updateEntry.GetLocalSaveFilePath(), System.IO.FileMode.Create); + req.Tag = fs = new System.IO.FileStream(_updateEntry.GetDownloadTempSaveFilePath(), System.IO.FileMode.Create); } fs.Write(dataFragment, 0, dataFragmentLength); } @@ -384,7 +459,7 @@ private bool OnData(HTTPRequest req, HTTPResponse resp, byte[] dataFragment, int private void EnsureDirectory() { - var directoryName = Path.GetDirectoryName(_updateEntry.GetLocalSaveFilePath()); + var directoryName = Path.GetDirectoryName(_updateEntry.GetDownloadTempSaveFilePath()); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); @@ -393,6 +468,11 @@ private void EnsureDirectory() private void OnDownloadProgress(HTTPRequest request, long downloaded, long length) { DownloadedBytes = downloaded; + //Debug.LogError( + // "path "+ + // _updateEntry.RemoteFileMeta.RelativePath+ + // " totalSize"+ _updateEntry.GetRemoteDownloadFileSize()+ + // "downloaded "+ downloaded); DownloadProgress = (downloaded / (float)length) * 100.0f; } diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/Download/UnzipSystem.cs b/Assets/URS/YooAsset/Runtime/PatchSystem/Download/UnzipSystem.cs index 48f07e2..65c5ab3 100644 --- a/Assets/URS/YooAsset/Runtime/PatchSystem/Download/UnzipSystem.cs +++ b/Assets/URS/YooAsset/Runtime/PatchSystem/Download/UnzipSystem.cs @@ -1,11 +1,9 @@ -using System; -using System.IO; +using System.IO; using System.Collections; using System.Collections.Generic; using YooAsset.Utility; using URS; -using MHLab.Patch.Core.Utilities; - +using YooAsset; namespace YooAsset { /// @@ -18,6 +16,15 @@ internal static class UnzipSystem private static readonly Dictionary _downloaderDic = new Dictionary(); private static readonly List _removeList = new List(100); + private static Queue _waitQueue = new Queue(); + + public static int BatchCount = 20; + + + public static void EnqueueUnzip(UnzipEntry unzipEntry) + { + _waitQueue.Enqueue(unzipEntry); + } /// /// 更新所有下载器 @@ -39,6 +46,23 @@ public static void Update() { _downloaderDic.Remove(key); } + + int waitingCount = _waitQueue.Count; + int currentDownloadingCount = _downloaderDic.Count; + if (waitingCount > 0&& currentDownloadingCount < BatchCount) + { + int maxDownloadCount = BatchCount - currentDownloadingCount; + + List batch = new List(); + int count = waitingCount < maxDownloadCount ? waitingCount : maxDownloadCount; + while (count > 0) + { + batch.Add(_waitQueue.Dequeue()); + count--; + } + var operation = new UnzipOperation(batch, count, 1); + YooAsset.OperationSystem.ProcessOperaiton(operation); + } } /// @@ -54,7 +78,7 @@ public static Unziper BeginDownload(UnzipEntry hardiskFileSearchResult, int fail } // 如果资源已经缓存 - if(SandboxFileSystem.ContainsFile(hardiskFileSearchResult.GetRelativePath())) + if(URSFileSystem.PersistentDownloadFolder.ContainsFile(hardiskFileSearchResult.GetRelativePath())) { var newDownloader = new Unziper(hardiskFileSearchResult); newDownloader.SetDone(); @@ -63,7 +87,7 @@ public static Unziper BeginDownload(UnzipEntry hardiskFileSearchResult, int fail // 创建新的下载器 { - Logger.Log($"Beginning to download file : {hardiskFileSearchResult.GetRelativePath()} URL : {hardiskFileSearchResult.HardiskSourcePath} SavePath: {hardiskFileSearchResult.HardiskSavePath}"); + //Logger.Log($"Beginning to download file : {hardiskFileSearchResult.GetRelativePath()} URL : {hardiskFileSearchResult.HardiskSourcePath} SavePath: {hardiskFileSearchResult.HardiskSavePath}"); FileUtility.CreateFileDirectory(hardiskFileSearchResult.HardiskSavePath); var newDownloader = new Unziper(hardiskFileSearchResult); newDownloader.SendRequest(failedTryAgain, timeout); diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/Download/Unziper.cs b/Assets/URS/YooAsset/Runtime/PatchSystem/Download/Unziper.cs index 4f1c375..3a0394a 100644 --- a/Assets/URS/YooAsset/Runtime/PatchSystem/Download/Unziper.cs +++ b/Assets/URS/YooAsset/Runtime/PatchSystem/Download/Unziper.cs @@ -8,7 +8,7 @@ namespace YooAsset { - internal class Unziper + public class Unziper { private enum ESteps { @@ -125,7 +125,7 @@ internal void Update() if (isError == false) { // 注意:如果文件验证失败需要删除文件 - if (SandboxFileSystem.CheckContentIntegrity(_unzipEntry.StreamFileMeta, _unzipEntry.HardiskSavePath) == false) + if (URSFileSystem.DownloadFolderCheckContentIntegrity(_unzipEntry.StreamFileMeta, _unzipEntry.HardiskSavePath) == false) { isError = true; _lastError = $"Verification failed"; @@ -138,16 +138,24 @@ internal void Update() { ReportError(); if (_failedTryAgain > 0) + { _steps = ESteps.TryAgain; - else - _steps = ESteps.Failed; + } + else + { + _steps = ESteps.Failed; + OnFinish(); + } + } else { - _steps = ESteps.Succeed; - Logger.Log($"下载完毕{_unzipEntry.HardiskSavePath} "); - SandboxFileSystem.RegisterVerifyFile(_unzipEntry.StreamFileMeta); - } + + //Logger.Log($"unzip 下载完毕{_unzipEntry.HardiskSavePath} "); + URSFileSystem.DownloadFolderRegisterVerifyFile(_unzipEntry.StreamFileMeta); + _steps = ESteps.Succeed; + OnFinish(); + } // 释放下载器 DisposeWebRequest(); @@ -168,7 +176,17 @@ internal void Update() internal void SetDone() { _steps = ESteps.Succeed; - } + OnFinish(); + + } + private void OnFinish() + { + var callback = _unzipEntry.OnFinish; + if (callback != null) + { + callback(this); + } + } private string GetRequestURL() { diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/FileMeta.cs b/Assets/URS/YooAsset/Runtime/PatchSystem/FileMeta.cs index 60b5f6b..45d1a3e 100644 --- a/Assets/URS/YooAsset/Runtime/PatchSystem/FileMeta.cs +++ b/Assets/URS/YooAsset/Runtime/PatchSystem/FileMeta.cs @@ -9,6 +9,10 @@ namespace URS [Serializable] public class FileManifest { + [SerializeField] + public string BuildVersion; + + [SerializeField] public FileMeta[] FileMetas; [NonSerialized] @@ -18,9 +22,15 @@ public Dictionary GetFileMetaMap() { return _fileMetaMap; } - public FileManifest(FileMeta[] fileMetas) + + public void ClearMetaMap() + { + _fileMetaMap = new Dictionary(); + } + public FileManifest(FileMeta[] fileMetas,string buildVersion) { FileMetas = fileMetas; + BuildVersion = buildVersion; } public void GetFileMetaByTag(string[] tags, ref List result) { diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/Operations/InitializationOperation.cs b/Assets/URS/YooAsset/Runtime/PatchSystem/Operations/InitializationOperation.cs index 08d931b..059268e 100644 --- a/Assets/URS/YooAsset/Runtime/PatchSystem/Operations/InitializationOperation.cs +++ b/Assets/URS/YooAsset/Runtime/PatchSystem/Operations/InitializationOperation.cs @@ -36,11 +36,12 @@ internal class OfflinePlayModeInitializationOperation : InitializationOperation private enum ESteps { None, - LoadAppFileManifest, - CheckAppFileManifest, - LoadAppBundleManifest, - CheckAppBundleManifest, - InitSandbox, + CheckAppFootPrint, + LoadBuildInFileManifest, + CheckBuildInFileManifest, + LoadBuildInBundleManifest, + CheckBuildInBundleManifest, + InitPersistentFolders, Done, } @@ -56,23 +57,44 @@ internal OfflinePlayModeInitializationOperation(OfflinePlayModeImpl impl) } internal override void Start() { - _steps = ESteps.LoadAppFileManifest; + _steps = ESteps.CheckAppFootPrint; } internal override void Update() { if (_steps == ESteps.None || _steps == ESteps.Done) return; - - if (_steps == ESteps.LoadAppFileManifest) + if (_steps == ESteps.CheckAppFootPrint) + { + // 每次启动时比对APP版本号是否一致 + AppFootPrint fp = AppFootPrint.Load(); + if (fp == null) + { + AppFootPrint.Create(); + } + else + { + if (fp.IsDirty()) + { + if (_impl.ClearCacheWhenDirty) + { + Logger.Warning("Clear cache files."); + URSFileSystem.DeletePersistentRootFolder(); + AppFootPrint.Create(); + } + } + } + _steps = ESteps.LoadBuildInFileManifest; + } + if (_steps == ESteps.LoadBuildInFileManifest) { - string filePath = AssetPathHelper.MakeStreamingSandboxLoadPath(URSRuntimeSetting.instance.FileManifestFileName); + string filePath = AssetPathHelper.MakeURSBuildInResourcePath(URSRuntimeSetting.instance.FileManifestFileName); _downloadURL = AssetPathHelper.ConvertToWWWPath(filePath); _fileManifestDownloader = new UnityWebRequester(); _fileManifestDownloader.SendRequest(_downloadURL); - _steps = ESteps.CheckAppFileManifest; + _steps = ESteps.CheckBuildInFileManifest; } - if (_steps == ESteps.CheckAppFileManifest) + if (_steps == ESteps.CheckBuildInFileManifest) { if (_fileManifestDownloader.IsDone() == false) return; @@ -85,24 +107,24 @@ internal override void Update() } else { - _impl.AppFileManifest = FileManifest.Deserialize(_fileManifestDownloader.GetText()); + URSFileSystem.BuildInFolder.FileManifest = FileManifest.Deserialize(_fileManifestDownloader.GetText()); } // 解析APP里的补丁清单 _fileManifestDownloader.Dispose(); - _steps = ESteps.LoadAppBundleManifest; + _steps = ESteps.LoadBuildInBundleManifest; } - if (_steps == ESteps.LoadAppBundleManifest) + if (_steps == ESteps.LoadBuildInBundleManifest) { - string filePath = AssetPathHelper.MakeStreamingSandboxLoadPath(URSRuntimeSetting.instance.BundleManifestFileName); + string filePath = AssetPathHelper.MakeURSBuildInResourcePath(URSRuntimeSetting.instance.BundleManifestFileRelativePath); _downloadURL = AssetPathHelper.ConvertToWWWPath(filePath); _BunleManifestDownloader = new UnityWebRequester(); _BunleManifestDownloader.SendRequest(_downloadURL); - _steps = ESteps.CheckAppBundleManifest; + _steps = ESteps.CheckBuildInBundleManifest; } - if (_steps == ESteps.CheckAppBundleManifest) + if (_steps == ESteps.CheckBuildInBundleManifest) { if (_BunleManifestDownloader.IsDone() == false) return; @@ -113,16 +135,15 @@ internal override void Update() } else { - _impl.AppBundleManifest = BundleManifest.Deserialize(_BunleManifestDownloader.GetText()); - + URSFileSystem.BuildInFolder.BundleManifest = BundleManifest.Deserialize(_BunleManifestDownloader.GetText()); } _BunleManifestDownloader.Dispose(); - _steps = ESteps.InitSandbox; + _steps = ESteps.InitPersistentFolders; } - if(_steps == ESteps.InitSandbox) + if(_steps == ESteps.InitPersistentFolders) { - SandboxFileSystem.InitSandboxFileAndBundle(); + URSFileSystem.InitPersistentFolders(); _steps = ESteps.Done; Status = EOperationStatus.Succeed; } @@ -138,23 +159,17 @@ internal class HostPlayModeInitializationOperation : InitializationOperation private enum ESteps { None, - LoadAppId, - CheckAppId, - LoadChannelRouter, - CheckChannelRouter, - - LoadFilesVersionIndex, - CheckFilesVersionIndex, + CheckAppFootPrint, - LoadAppFileManifest, - CheckAppFileManifest, - LoadAppBundleManifest, - CheckAppBundleManifest, + LoadBuildInFileManifest, + CheckBuildInFileManifest, + LoadBuildInBundleManifest, + CheckBuildInBundleManifest, - InitSandbox, + InitPersistentFolders, Done, } @@ -163,9 +178,7 @@ private enum ESteps private ESteps _steps = ESteps.None; - private UnityWebRequester _appIdDownloader; - private UnityWebRequester _remoteAppToChannelRouterFileDownloader; - private UnityWebRequester _remoteFilesVersionIndexDownloader; + private UnityWebRequester _appFileManifestDownloader; private UnityWebRequester _appBundleManifestDownloader; @@ -174,112 +187,17 @@ private enum ESteps internal HostPlayModeInitializationOperation(HostPlayModeImpl impl) { _impl = impl; + URSFileSystem.InitRemoteFolder(impl); } internal override void Start() { - _steps = ESteps.LoadAppId; + _steps = ESteps.CheckAppFootPrint; } internal override void Update() { if (_steps == ESteps.None || _steps == ESteps.Done) return; - if (_steps == ESteps.LoadAppId) - { - - _impl.AppId = null; - string filePath = AssetPathHelper.MakeStreamingSandboxLoadPath(URSRuntimeSetting.instance.AppIdFileName); - // 加载APP内的补丁清单 - Logger.Log($"Load application file manifest.{filePath}"); - var downloadURL = AssetPathHelper.ConvertToWWWPath(filePath); - _appIdDownloader = new UnityWebRequester(); - _appIdDownloader.SendRequest(downloadURL); - _steps = ESteps.CheckAppId; - } - if (_steps == ESteps.CheckAppId) - { - - if (_appIdDownloader.IsDone() == false) - return; - - if (_appIdDownloader.HasError()) - { - Error = _appIdDownloader.GetError(); - Logger.Warning($"can not Load _appId.error {Error}"); - } - else - { - // 解析补丁清单 - string appid = _appIdDownloader.GetText(); - _impl.AppId = appid; - } - //_impl.LocalPatchManifest = _impl.AppPatchManifest; - _appIdDownloader.Dispose(); - _steps = ESteps.LoadChannelRouter; - } - if (_steps == ESteps.LoadChannelRouter) - { - // 加载APP内的补丁清单 - string filePath =_impl.RemoteAppToChannelRouterFileUrl; - var downloadURL = (filePath); - _remoteAppToChannelRouterFileDownloader = new UnityWebRequester(); - _remoteAppToChannelRouterFileDownloader.SendRequest(downloadURL); - _steps = ESteps.CheckChannelRouter; - } - if (_steps == ESteps.CheckChannelRouter) - { - - if (_remoteAppToChannelRouterFileDownloader.IsDone() == false) - return; - - if (_remoteAppToChannelRouterFileDownloader.HasError()) - { - Error = _remoteAppToChannelRouterFileDownloader.GetError(); - Logger.Warning($"can not Load _remoteAppToChannelRouterFile.error {Error}"); - } - else - { - // 解析补丁清单 - string jsonText = _remoteAppToChannelRouterFileDownloader.GetText(); - var router = AppToChannelRouter.Deserialize(jsonText); - var item = router.GetChanel(_impl.AppId); - _impl.InitVersion(item); - } - //_impl.LocalPatchManifest = _impl.AppPatchManifest; - _remoteAppToChannelRouterFileDownloader.Dispose(); - _steps = ESteps.LoadFilesVersionIndex; - } - if (_steps == ESteps.LoadFilesVersionIndex) - { - // 加载APP内的补丁清单 - string filePath = _impl.GetRemoteFilesVersionIndexUrl(); - var downloadURL = filePath; - _remoteFilesVersionIndexDownloader = new UnityWebRequester(); - _remoteFilesVersionIndexDownloader.SendRequest(downloadURL); - _steps = ESteps.CheckFilesVersionIndex; - } - if (_steps == ESteps.CheckFilesVersionIndex) - { - - if (_remoteFilesVersionIndexDownloader.IsDone() == false) - return; - - if (_remoteFilesVersionIndexDownloader.HasError()) - { - // Error = _appIdDownloader.GetError(); - Logger.Warning($"can not Load _remoteFilesVersionIndex .error {Error}"); - } - else - { - // 解析补丁清单 - string jsonText = _remoteFilesVersionIndexDownloader.GetText(); - var versionIndex = JsonUtility.FromJson(jsonText); - versionIndex.AfterSerialize(); - _impl.InitFilesVersion(versionIndex); - } - //_impl.LocalPatchManifest = _impl.AppPatchManifest; - _remoteFilesVersionIndexDownloader.Dispose(); - _steps = ESteps.CheckAppFootPrint; - } + if (_steps == ESteps.CheckAppFootPrint) { // 每次启动时比对APP版本号是否一致 @@ -295,26 +213,26 @@ internal override void Update() if (_impl.ClearCacheWhenDirty) { Logger.Warning("Clear cache files."); - SandboxFileSystem.DeleteSandboxFolder(); + URSFileSystem.DeletePersistentRootFolder(); AppFootPrint.Create(); } } } - _steps = ESteps.LoadAppFileManifest; + _steps = ESteps.LoadBuildInFileManifest; } - if (_steps == ESteps.LoadAppFileManifest) + if (_steps == ESteps.LoadBuildInFileManifest) { // 加载APP内的补丁清单 Logger.Log($"Load application file manifest."); - string filePath = AssetPathHelper.MakeStreamingSandboxLoadPath(URSRuntimeSetting.instance.FileManifestFileName); + string filePath = AssetPathHelper.MakeURSBuildInResourcePath(URSRuntimeSetting.instance.FileManifestFileName); _downloadURL = AssetPathHelper.ConvertToWWWPath(filePath); _appFileManifestDownloader = new UnityWebRequester(); _appFileManifestDownloader.SendRequest(_downloadURL); - _steps = ESteps.CheckAppFileManifest; + _steps = ESteps.CheckBuildInFileManifest; } - if (_steps == ESteps.CheckAppFileManifest) + if (_steps == ESteps.CheckBuildInFileManifest) { if (_appFileManifestDownloader.IsDone() == false) return; @@ -328,23 +246,23 @@ internal override void Update() { // 解析补丁清单 string jsonData = _appFileManifestDownloader.GetText(); - _impl.AppFileManifest = FileManifest.Deserialize(jsonData); + URSFileSystem.BuildInFolder.FileManifest = FileManifest.Deserialize(jsonData); } //_impl.LocalPatchManifest = _impl.AppPatchManifest; _appFileManifestDownloader.Dispose(); - _steps = ESteps.LoadAppBundleManifest; + _steps = ESteps.LoadBuildInBundleManifest; } - if (_steps == ESteps.LoadAppBundleManifest) + if (_steps == ESteps.LoadBuildInBundleManifest) { // 加载APP内的补丁清单 Logger.Log($"Load application bundle manifest."); - string filePath = AssetPathHelper.MakeStreamingSandboxLoadPath(URSRuntimeSetting.instance.BundleManifestFileName); + string filePath = AssetPathHelper.MakeURSBuildInResourcePath(URSRuntimeSetting.instance.BundleManifestFileRelativePath); _downloadURL = AssetPathHelper.ConvertToWWWPath(filePath); _appBundleManifestDownloader = new UnityWebRequester(); _appBundleManifestDownloader.SendRequest(_downloadURL); - _steps = ESteps.CheckAppBundleManifest; + _steps = ESteps.CheckBuildInBundleManifest; } - if (_steps == ESteps.CheckAppBundleManifest) + if (_steps == ESteps.CheckBuildInBundleManifest) { if (_appBundleManifestDownloader.IsDone() == false) return; @@ -357,17 +275,17 @@ internal override void Update() else { string jsonData = _appBundleManifestDownloader.GetText(); - _impl.AppBundleManifest = BundleManifest.Deserialize(jsonData); + URSFileSystem.BuildInFolder.BundleManifest = BundleManifest.Deserialize(jsonData); } // 解析补丁清单 //_impl.LocalPatchManifest = _impl.AppPatchManifest; _appBundleManifestDownloader.Dispose(); - _steps = ESteps.InitSandbox; + _steps = ESteps.InitPersistentFolders; } - if (_steps == ESteps.InitSandbox) + if (_steps == ESteps.InitPersistentFolders) { - SandboxFileSystem.InitSandboxFileAndBundle(); + URSFileSystem.InitPersistentFolders(); _steps = ESteps.Done; Status = EOperationStatus.Succeed; } diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/Operations/RemoteUpdateOperation.cs b/Assets/URS/YooAsset/Runtime/PatchSystem/Operations/RemoteUpdateOperation.cs index 14da209..0dc1c60 100644 --- a/Assets/URS/YooAsset/Runtime/PatchSystem/Operations/RemoteUpdateOperation.cs +++ b/Assets/URS/YooAsset/Runtime/PatchSystem/Operations/RemoteUpdateOperation.cs @@ -13,7 +13,7 @@ private enum ESteps Done, } - private const int MAX_LOADER_COUNT = 64; + private const int MAX_LOADER_COUNT = 30; public delegate void OnDownloadOver(bool isSucceed); public delegate void OnDownloadProgress(int totalDownloadCount, int currentDownloadCount, long totalDownloadBytes, long currentDownloadBytes); diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/Operations/UnzipOperation.cs b/Assets/URS/YooAsset/Runtime/PatchSystem/Operations/UnzipOperation.cs index c8dd2e2..c484c0b 100644 --- a/Assets/URS/YooAsset/Runtime/PatchSystem/Operations/UnzipOperation.cs +++ b/Assets/URS/YooAsset/Runtime/PatchSystem/Operations/UnzipOperation.cs @@ -82,7 +82,7 @@ internal UnzipOperation(List downloadList, int fileLoadingMaxNumber, } internal override void Start() { - Logger.Log($"Begine to download : {TotalDownloadCount} files and {TotalDownloadBytes} bytes"); + //Logger.Log($"Begine to download : {TotalDownloadCount} files and {TotalDownloadBytes} bytes"); _steps = ESteps.Loading; } internal override void Update() diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/Operations/UpdateManifestOperation.cs b/Assets/URS/YooAsset/Runtime/PatchSystem/Operations/UpdateManifestOperation.cs index d9e8af3..3d78f60 100644 --- a/Assets/URS/YooAsset/Runtime/PatchSystem/Operations/UpdateManifestOperation.cs +++ b/Assets/URS/YooAsset/Runtime/PatchSystem/Operations/UpdateManifestOperation.cs @@ -51,56 +51,159 @@ internal class HostPlayModeUpdateManifestOperation : UpdateManifestOperation private enum ESteps { None, - LoadWebFileManifest, + + LoadAppChannel, + CheckAppChannel, + + LoadChannelRouter, + CheckChannelRouter, + + LoadFilesVersionIndex, + CheckFilesVersionIndex, + + LoadWebFileManifest, CheckWebFileManifest, + LoadWebBundleManifest, CheckWebBundelManifest, - LoadLocalFilePaths, - CheckLocalFileSystemIntegrity, + BeginCheckDownloadFolder, + CheckDownloadFolder, + + BeginCheckReadOnlyFolder, + CheckReadOnlyFolder, - Done, + Done, } private static int RequestCount = 0; private readonly HostPlayModeImpl _impl; - private readonly int _updateResourceVersion; private readonly int _timeout; private ESteps _steps = ESteps.None; - private UnityWebRequester _webFileManifestDownloader; + + private UnityWebRequester _appChannelDownloader; + private UnityWebRequester _remoteAppToChannelRouterFileDownloader; + private UnityWebRequester _remoteFilesVersionIndexDownloader; + private UnityWebRequester _webFileManifestDownloader; private UnityWebRequester _webBundleManifestDownloader; - private float _verifyTime; + private List<(string,string)> _relativePaths = new List<(string, string)>(); private int _currentCheckIndex = 0; private const int MAX_STEP = 20; - public HostPlayModeUpdateManifestOperation(HostPlayModeImpl impl, int updateResourceVersion, int timeout) + public HostPlayModeUpdateManifestOperation(HostPlayModeImpl impl , int timeout) { _impl = impl; - _updateResourceVersion = updateResourceVersion; _timeout = timeout; + } internal override void Start() { RequestCount++; - _steps = ESteps.LoadWebFileManifest; - - if (_impl.IgnoreResourceVersion && _updateResourceVersion > 0) - { - Logger.Warning($"Update resource version {_updateResourceVersion} is invalid when ignore resource version."); - } - else - { - Logger.Log($"Update patch manifest : update resource version is {_updateResourceVersion}"); - } + _steps = ESteps.LoadAppChannel; } internal override void Update() { if (_steps == ESteps.None || _steps == ESteps.Done) return; + if (_steps == ESteps.LoadAppChannel) + { + + _impl.channel = null; + string filePath = AssetPathHelper.GetBuildInChannelFilePath(); + // 加载APP内的补丁清单 + Logger.Log($"Load application file manifest.{filePath}"); + var downloadURL = AssetPathHelper.ConvertToWWWPath(filePath); + _appChannelDownloader = new UnityWebRequester(); + _appChannelDownloader.SendRequest(downloadURL); + _steps = ESteps.CheckAppChannel; + } + if (_steps == ESteps.CheckAppChannel) + { + + if (_appChannelDownloader.IsDone() == false) + return; + + if (_appChannelDownloader.HasError()) + { + Error = _appChannelDownloader.GetError(); + Logger.Warning($"can not Load _appId.error {Error}"); + } + else + { + // 解析补丁清单 + string channel = _appChannelDownloader.GetText(); + _impl.InitChannel(channel); + } + //_impl.LocalPatchManifest = _impl.AppPatchManifest; + _appChannelDownloader.Dispose(); + _steps = ESteps.LoadChannelRouter; + } + if (_steps == ESteps.LoadChannelRouter) + { + // 加载APP内的补丁清单 + var downloadURL = AppendSeedToFreshCDN(_impl.RemoteAppToChannelRouterFileUrl); + _remoteAppToChannelRouterFileDownloader = new UnityWebRequester(); + _remoteAppToChannelRouterFileDownloader.SendRequest(downloadURL); + _steps = ESteps.CheckChannelRouter; + } + if (_steps == ESteps.CheckChannelRouter) + { + + if (_remoteAppToChannelRouterFileDownloader.IsDone() == false) + return; - if (_steps == ESteps.LoadWebFileManifest) + if (_remoteAppToChannelRouterFileDownloader.HasError()) + { + Error = _remoteAppToChannelRouterFileDownloader.GetError(); + Logger.Warning($"can not Load _remoteAppToChannelRouterFile.error {Error}"); + } + else + { + // 解析补丁清单 + string jsonText = _remoteAppToChannelRouterFileDownloader.GetText(); + var router = AppVersionRouter.Deserialize(jsonText); + var targetVersion = router.GetChannel(Application.version); + _impl.InitVersion(targetVersion); + } + //_impl.LocalPatchManifest = _impl.AppPatchManifest; + _remoteAppToChannelRouterFileDownloader.Dispose(); + _steps = ESteps.LoadFilesVersionIndex; + } + if (_steps == ESteps.LoadFilesVersionIndex) + { + // 加载APP内的补丁清单 + string downloadURL = AppendSeedToFreshCDN(_impl.GetRemoteFilesVersionIndexUrl()); + _remoteFilesVersionIndexDownloader = new UnityWebRequester(); + _remoteFilesVersionIndexDownloader.SendRequest(downloadURL); + _steps = ESteps.CheckFilesVersionIndex; + } + if (_steps == ESteps.CheckFilesVersionIndex) + { + + if (_remoteFilesVersionIndexDownloader.IsDone() == false) + return; + + if (_remoteFilesVersionIndexDownloader.HasError()) + { + // Error = _appIdDownloader.GetError(); + Logger.Warning($"can not Load _remoteFilesVersionIndex .error {Error}"); + } + else + { + // 解析补丁清单 + string jsonText = _remoteFilesVersionIndexDownloader.GetText(); + var versionIndex = JsonUtility.FromJson(jsonText); + versionIndex.AfterSerialize(); + _impl.InitFilesVersion(versionIndex); + } + //_impl.LocalPatchManifest = _impl.AppPatchManifest; + _remoteFilesVersionIndexDownloader.Dispose(); + _steps = ESteps.LoadWebFileManifest; + } + + if (_steps == ESteps.LoadWebFileManifest) { string webURL = GetWebRequestURL(URSRuntimeSetting.instance.FileManifestFileName, false); _webFileManifestDownloader = new UnityWebRequester(); @@ -116,10 +219,9 @@ internal override void Update() // Check fatal if (_webFileManifestDownloader.HasError()) { - _impl.WebFileManifest = null; + URSFileSystem.RemoteFolder.FileManifest = null; Error = _webFileManifestDownloader.GetError(); _webFileManifestDownloader.Dispose(); - Debug.LogError(Error+" url "+ _webFileManifestDownloader.URL); _steps = ESteps.Done; Status = EOperationStatus.Failed; return; @@ -127,14 +229,14 @@ internal override void Update() // 获取补丁清单文件的哈希值 string webManifestHash = _webFileManifestDownloader.GetText(); - _impl.WebFileManifest = FileManifest.Deserialize(webManifestHash); + URSFileSystem.RemoteFolder.FileManifest = FileManifest.Deserialize(webManifestHash); _webFileManifestDownloader.Dispose(); _steps = ESteps.LoadWebBundleManifest; } if (_steps == ESteps.LoadWebBundleManifest) { - string webURL = GetWebRequestURL(URSRuntimeSetting.instance.BundleManifestFileName,false); + string webURL = GetWebRequestURL(URSRuntimeSetting.instance.BundleManifestFileRelativePath,false); Logger.Log($"Beginning to request web bundle manifest : {webURL}"); _webBundleManifestDownloader = new UnityWebRequester(); _webBundleManifestDownloader.SendRequest(webURL, _timeout); @@ -157,70 +259,42 @@ internal override void Update() else { string text = _webBundleManifestDownloader.GetText(); - _impl.WebBundleManifest = BundleManifest.Deserialize(text); + URSFileSystem.RemoteFolder.BundleManifest = BundleManifest.Deserialize(text); } _webFileManifestDownloader.Dispose(); - _steps = ESteps.LoadLocalFilePaths; + _steps = ESteps.BeginCheckDownloadFolder; } - if (_steps == ESteps.LoadLocalFilePaths) + if (_steps == ESteps.BeginCheckDownloadFolder) { - _relativePaths.Clear(); - string sandboxPath = SandboxFileSystem.GetSandboxDirectory(); - Directory.CreateDirectory(sandboxPath); - var sandboxPathLength = sandboxPath.Length; - var paths = Directory.GetFiles(sandboxPath,"*", SearchOption.AllDirectories); - if (paths != null && paths.Length > 0) - { - for (int i = 0; i < paths.Length; i++) - { - var fullPath = paths[i]; - var relativePath = paths[i].Substring(sandboxPathLength + 1); - var pure = relativePath.Replace('\\', '/').Replace("//", "/"); - _relativePaths.Add((pure, fullPath)); - } + URSFileSystem.PersistentDownloadFolder.BeginCheckLocalFile(); + _steps = ESteps.CheckDownloadFolder; + } + if (_steps == ESteps.CheckDownloadFolder) { + // 遍历所有文件然后验证并缓存合法文件 + bool isEnd= URSFileSystem.PersistentDownloadFolder.CheckLocalFile(URSFileSystem.RemoteFolder.FileManifest); + if (isEnd) { + URSFileSystem.PersistentDownloadFolder.EndCheck(); + _steps = ESteps.BeginCheckReadOnlyFolder; } - _currentCheckIndex = 0; - _steps = ESteps.CheckLocalFileSystemIntegrity; + + } + if (_steps == ESteps.BeginCheckReadOnlyFolder) + { + URSFileSystem.PersistentReadOnlyFolder.BeginCheckLocalFile(); + _steps = ESteps.CheckReadOnlyFolder; } - if (_steps == ESteps.CheckLocalFileSystemIntegrity) { + if (_steps == ESteps.CheckReadOnlyFolder) + { // 遍历所有文件然后验证并缓存合法文件 - - for (int i = 0; i < MAX_STEP; i++) + bool isEnd = URSFileSystem.PersistentReadOnlyFolder.CheckLocalFile(URSFileSystem.RemoteFolder.FileManifest); + if (isEnd) { - _currentCheckIndex++; - if (_currentCheckIndex < _relativePaths.Count) - { - var relativePath = _relativePaths[_currentCheckIndex].Item1; - var fullPath= _relativePaths[_currentCheckIndex].Item2; - if (relativePath == URSRuntimeSetting.instance.FileManifestFileName) - { - continue; - } - var webFileManifest = _impl.WebFileManifest; - var fileMap = webFileManifest.GetFileMetaMap(); - if (fileMap.ContainsKey(relativePath)) - { - var fileMeta = fileMap[relativePath]; - if (SandboxFileSystem.CheckContentIntegrity(fullPath, fileMeta.SizeBytes, fileMeta.Hash)) - { - SandboxFileSystem.RegisterVerifyFile(fileMeta); - } - } - else - { - SandboxFileSystem.DeleteSandboxFile(relativePath); - } - } - else - { - SandboxFileSystem.FlushSandboxFileManifestToHardisk(); - _steps = ESteps.Done; - Status = EOperationStatus.Succeed; - } + URSFileSystem.PersistentReadOnlyFolder.EndCheck(); + _steps = ESteps.Done; + Status = EOperationStatus.Succeed; } } - - } + } private string GetWebRequestURL(string fileName,bool freshCDN) { @@ -230,10 +304,15 @@ private string GetWebRequestURL(string fileName,bool freshCDN) // 注意:在URL末尾添加时间戳 if (freshCDN) - url = $"{url}?{System.DateTime.UtcNow.Ticks}"; + url = AppendSeedToFreshCDN(url); return url; } + + public string AppendSeedToFreshCDN(string url) + { + return $"{url}?{System.DateTime.UtcNow.Ticks}"; + } /* private void ParseAndSaveRemotePatchManifest(string content) { diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/PlayMode/EditorPlayModeImpl.cs b/Assets/URS/YooAsset/Runtime/PatchSystem/PlayMode/EditorPlayModeImpl.cs index b434d85..fe979cd 100644 --- a/Assets/URS/YooAsset/Runtime/PatchSystem/PlayMode/EditorPlayModeImpl.cs +++ b/Assets/URS/YooAsset/Runtime/PatchSystem/PlayMode/EditorPlayModeImpl.cs @@ -46,6 +46,12 @@ List IFileSystemServices.GetAllDependencieBundleRelativePaths(string a { return null; } - #endregion - } + + public void SearchLocalSecurityBundleHardDiskFileByPath(string relativePath, out HardiskFileSearchResult mainResult, out List dependency,bool skipDownloadFolder= true) { + + mainResult= new HardiskFileSearchResult(relativePath); + dependency = null; + } + #endregion + } } \ No newline at end of file diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/PlayMode/HostPlayModeImpl.cs b/Assets/URS/YooAsset/Runtime/PatchSystem/PlayMode/HostPlayModeImpl.cs index da6262f..a6292b4 100644 --- a/Assets/URS/YooAsset/Runtime/PatchSystem/PlayMode/HostPlayModeImpl.cs +++ b/Assets/URS/YooAsset/Runtime/PatchSystem/PlayMode/HostPlayModeImpl.cs @@ -5,53 +5,27 @@ using URS; namespace YooAsset { - internal class HostPlayModeImpl : IFileSystemServices + public class HostPlayModeImpl : IFileSystemServices { // 补丁清单 //internal PatchManifest AppPatchManifest; //internal PatchManifest LocalPatchManifest; - internal FileManifest WebFileManifest; - internal BundleManifest WebBundleManifest; + // internal FileManifest WebFileManifest; + // internal BundleManifest WebBundleManifest; - internal FileManifest AppFileManifest; - internal BundleManifest AppBundleManifest; - internal string AppId; + // internal FileManifest AppFileManifest; + // internal BundleManifest AppBundleManifest; + internal string channel; - public BundleManifest GetJudgedBundleManifest() - { - if (WebBundleManifest != null) - { - return WebBundleManifest; - } - var sanboxBundleManifest = SandboxFileSystem.GetBundleManifest(); - if (sanboxBundleManifest != null) - { - return sanboxBundleManifest; - } - return AppBundleManifest; - } - public FileManifest GetJudgedFileManifest() - { - if (WebFileManifest != null) - { - return WebFileManifest; - } - var sanboxFileManifest = SandboxFileSystem.GetFileManifest(); - if (sanboxFileManifest != null) - { - return sanboxFileManifest; - } - return AppFileManifest; - } + // 参数相关 internal bool ClearCacheWhenDirty { private set; get; } - internal bool IgnoreResourceVersion { private set; get; } internal string RemoteAppToChannelRouterFileUrl { get; set; } internal string RemoteVersionsRootUrl { get; set; } internal string RemoteVersionRootUrl { get; set; } internal string RemoteVersionPatchUrl { get; set; } - internal AppToChannelItem AppChannel {get;set;} + internal string TargetVersion {get;set;} internal URSFilesVersionIndex FilesVersionIndex { get; set; } @@ -61,28 +35,37 @@ public FileManifest GetJudgedFileManifest() public InitializationOperation InitializeAsync() { ClearCacheWhenDirty = true; - IgnoreResourceVersion = true; - RemoteAppToChannelRouterFileUrl = $"{URSRuntimeSetting.instance.RemoteChannelRootUrl}/{URSRuntimeSetting.instance.RemoteAppToChannelRouterFileName}"; ; + var operation = new HostPlayModeInitializationOperation(this); OperationSystem.ProcessOperaiton(operation); return operation; } - - public void InitVersion(AppToChannelItem item) - { - AppChannel= item; - RemoteVersionsRootUrl = $"{URSRuntimeSetting.instance.RemoteChannelRootUrl}/{item.ChannelId}/{URS.PlatformMappingService.GetPlatformPathSubFolder()}"; + public void InitChannel(string channel) + { + this.channel= channel; + RemoteVersionsRootUrl = $"{URSRuntimeSetting.instance.RemoteChannelRootUrl}/{this.channel}/{URS.PlatformMappingService.GetPlatformPathSubFolder()}"; RemoteVersionPatchUrl = $"{RemoteVersionsRootUrl}/{URSRuntimeSetting.instance.PatchDirectory}"; + RemoteAppToChannelRouterFileUrl = $"{RemoteVersionsRootUrl}/{URSRuntimeSetting.instance.RemoteAppVersionRouterFileName}"; + } + public void InitVersion(string targetVersion) + { + TargetVersion = targetVersion; + } + + public string GetResourceVersion() + { + return URSFileSystem.RemoteFolder?.FileManifest?.BuildVersion; } - public string GetRemoteFilesVersionIndexUrl() + + public string GetRemoteFilesVersionIndexUrl() { return $"{RemoteVersionsRootUrl}/{URSRuntimeSetting.instance.FilesVersionIndexFileName}"; } public void InitFilesVersion(URSFilesVersionIndex versions) { FilesVersionIndex = versions; - var item = FilesVersionIndex.GetVersion(AppChannel.VersionCode); + var item = FilesVersionIndex.GetVersion(TargetVersion); RemoteVersionRootUrl = $"{RemoteVersionsRootUrl}/{item.VersionCode}---{item.FilesVersionHash}"; } @@ -94,9 +77,9 @@ public PatchItemVersion GetPatch(FileMeta localfileMeta, FileMeta remoteFileMeta /// /// 异步更新补丁清单 /// - public UpdateManifestOperation UpdatePatchManifestAsync(int updateResourceVersion, int timeout) + public UpdateManifestOperation UpdatePatchManifestAsync(int timeout) { - var operation = new HostPlayModeUpdateManifestOperation(this, updateResourceVersion, timeout); + var operation = new HostPlayModeUpdateManifestOperation(this, timeout); OperationSystem.ProcessOperaiton(operation); return operation; } @@ -110,50 +93,39 @@ public RemoteUpdateOperation CreateDownloaderByTags(string[] tags, int fileLoadi { List downloadList = GetDownloadListByTags(tags); var operation = new RemoteUpdateOperation(downloadList, fileLoadingMaxNumber, failedTryAgain); - return operation; + Action callback = (AsyncOperationBase ab) => { + Logger.Log($"下载完毕 {operation.Status}"); + if (operation.Status == EOperationStatus.Succeed) + { + URSFileSystem.PersistentDownloadFolder.FlushFileManifestToHardisk(); + } + }; + operation.Completed += callback; + return operation; } private List GetDownloadListByTags(string[] tags) { List downloadList = new List(1000); - if (WebFileManifest != null) + var patchCount = 0; + if (URSFileSystem.RemoteFolder.FileManifest != null) { - foreach (var kv in WebFileManifest.GetFileMetaMap()) + foreach (var kv in URSFileSystem.RemoteFolder.FileManifest.GetFileMetaMap()) { var remoteFileMeta = kv.Value; if (!remoteFileMeta.HasAnyTag(tags)) continue; - var relativePath = kv.Key; - - FileMeta sandboxCandicate = null; - // 忽略缓存文件 - if (SandboxFileSystem.TryGetHardiskFilePath(relativePath, out var __, out var sandboxFileMeta)) + + var searchResult = URSFileSystem.SearchHardiskFile(remoteFileMeta); + + if (searchResult != null && searchResult.UpdateEntry!=null) { - - if (sandboxFileMeta.Hash == remoteFileMeta.Hash) - { - continue; + if (searchResult.UpdateEntry.IsPatch()){ + patchCount++; } - else - { - sandboxCandicate = sandboxFileMeta; - } - } - else - { - //UnityEngine.Debug.LogError("can not find relativePath" + relativePath); - } - - // 忽略APP资源 - // 注意:如果是APP资源并且哈希值相同,则不需要下载 - - if (AppFileManifest != null && AppFileManifest.ContainFile(relativePath, remoteFileMeta.Hash)) - { - continue; + downloadList.Add(searchResult.UpdateEntry); } - UpdateEntry updateEntry = GetUpdateEntry(remoteFileMeta, sandboxCandicate); - downloadList.Add(updateEntry); } } - + Debug.Log($"总共需要下载 {downloadList.Count}个 其中patch的数量 {patchCount}"); return downloadList; } @@ -171,13 +143,14 @@ public RemoteUpdateOperation CreateDownloaderByPaths(List assetPaths, in private List GetDownloadListByPaths(List assetPaths) { // 获取资源对象的资源包和所有依赖资源包 - var bundleManifest = GetJudgedBundleManifest(); + var bundleManifest = URSFileSystem.RemoteFolder.BundleManifest; Dictionary all= new Dictionary(); //List dependency = new List(); foreach (var assetPath in assetPaths) { - var mainFileMeta = bundleManifest.GetBundleFileMeta(assetPath); - if (mainFileMeta!=null&& !all.ContainsKey(mainFileMeta.RelativePath)) + var mainFileMeta = bundleManifest.GetBundleFileMeta(assetPath); + + if (mainFileMeta!=null&& !all.ContainsKey(mainFileMeta.RelativePath)) { all.Add(mainFileMeta.RelativePath,mainFileMeta); } @@ -201,23 +174,11 @@ private List GetDownloadListByPaths(List assetPaths) foreach (var kv in all) { var remoteFileMeta = kv.Value; - FileMeta sanboxCandicate = null; - if (SandboxFileSystem.TryGetHardiskFilePath(remoteFileMeta.RelativePath, out var hardiskPath, out var sanboxFileMeta)) + var searchResult = URSFileSystem.SearchHardiskFile(remoteFileMeta); + if (searchResult != null&& searchResult.UpdateEntry!=null) { - if (sanboxFileMeta.Hash == remoteFileMeta.Hash) - { - continue; - } - else - { - sanboxCandicate = sanboxFileMeta; - } + results.Add(searchResult.UpdateEntry); } - if (AppFileManifest.ContainFile(remoteFileMeta)) - { - continue; - } - results.Add(GetUpdateEntry(remoteFileMeta, sanboxCandicate)); } return results; @@ -232,34 +193,33 @@ internal string GetRemoterPatchDownloadURL(string fileName) } internal string GetRemoteVersionDownloadURL(string fileName) { - return $"{RemoteVersionRootUrl}/{fileName}"; + return WWW.UnEscapeURL($"{RemoteVersionRootUrl}/{fileName}"); } // 下载相关 - private HardiskFileSearchResult ConvertToDownloadInfo(FileMeta webFileMeta,FileMeta patchSandboxFileMetaCandidate) + public HardiskFileSearchResult ConvertToDownloadInfo(FileMeta webFileMeta,FileMeta patchFileMetaCandidate, EnumHardiskDirectoryType patchFileMetaCandidateDirectoryType) { // 注意:资源版本号只用于确定下载路径 //string sandboxPath = SandboxFileSystem.MakeSandboxFilePath(fileMeta.RelativePath); //string remoteMainURL = GetPatchDownloadMainURL(fileMeta.RelativePath); /// string remoteFallbackURL = GetPatchDownloadFallbackURL(fileMeta.RelativePath); - var result = new HardiskFileSearchResult(webFileMeta, GetUpdateEntry(webFileMeta, patchSandboxFileMetaCandidate)); + var result = new HardiskFileSearchResult(webFileMeta, GetUpdateEntry(webFileMeta, patchFileMetaCandidate, patchFileMetaCandidateDirectoryType)); return result; } - private UpdateEntry GetUpdateEntry(FileMeta webFileMeta, FileMeta patchSandboxFileMetaCandidate) + private UpdateEntry GetUpdateEntry(FileMeta webFileMeta, FileMeta patchFileMetaCandidate, EnumHardiskDirectoryType patchFileMetaCandidateDirectoryType) { UpdateEntry result = null; - if (patchSandboxFileMetaCandidate == null) + if (patchFileMetaCandidate == null) { result = new UpdateEntry(webFileMeta, RemoteVersionRootUrl); return result; } else { - var patch = GetPatch(patchSandboxFileMetaCandidate, webFileMeta); - Debug.LogError("patch "+(patch==null)+" relative Path "+ webFileMeta.RelativePath); + var patch = GetPatch(patchFileMetaCandidate, webFileMeta); if (patch != null) { - result = new UpdateEntry(webFileMeta, RemoteVersionRootUrl,patch,RemoteVersionPatchUrl); + result = new UpdateEntry(webFileMeta, RemoteVersionRootUrl,patch,RemoteVersionPatchUrl, patchFileMetaCandidate, patchFileMetaCandidateDirectoryType); } else { @@ -293,7 +253,7 @@ public UnzipOperation CreateUnpackerByTags(string[] tags, int fileUpackingMaxNum Logger.Log($"解压完毕 {operation.Status}"); if (operation.Status == EOperationStatus.Succeed) { - SandboxFileSystem.FlushSandboxFileManifestToHardisk(); + URSFileSystem.PersistentDownloadFolder.FlushFileManifestToHardisk(); } }; operation.Completed += callback; @@ -302,15 +262,15 @@ public UnzipOperation CreateUnpackerByTags(string[] tags, int fileUpackingMaxNum private List GetUnpackListByTags(string[] tags) { List unzipEntries = new List(); - if (AppFileManifest != null) + if (URSFileSystem.BuildInFolder.FileManifest != null) { List downloadList = new List(); - AppFileManifest.GetFileMetaByTag(tags, ref downloadList); + URSFileSystem.BuildInFolder.FileManifest.GetFileMetaByTag(tags, ref downloadList); for (int i = downloadList.Count - 1; i >= 0; i--) { var streamFileMeta = downloadList[i]; - if (!SandboxFileSystem.ContainsFile(streamFileMeta.RelativePath)) + if (!URSFileSystem.PersistentDownloadFolder.ContainsFile(streamFileMeta.RelativePath)) { unzipEntries.Add(new UnzipEntry(streamFileMeta)); } @@ -341,60 +301,30 @@ private HardiskFileSearchResult ConvertToUnpackInfo(FileMeta FileMeta) #region IBundleServices接口 public HardiskFileSearchResult SearchHardiskFile(FileMeta fileMeta) { - if (!fileMeta.IsValid()) - return HardiskFileSearchResult.EMPTY; - return this.SearchHardiskFileByPath(fileMeta.RelativePath); + return URSFileSystem.SearchHardiskFile(fileMeta); } public HardiskFileSearchResult SearchHardiskFileByPath(string relativePath) { - if (WebFileManifest.GetFileMetaMap().TryGetValue(relativePath, out var webFileMeta)) - { - FileMeta patchSandboxFileMetaCandidate = null; - // 查询沙盒资源 - if (SandboxFileSystem.TryGetHardiskFilePath(relativePath, out var hardiskPath, out var sandboxFileMeta)) - { - if (sandboxFileMeta.Hash == webFileMeta.Hash) - { - var result = new HardiskFileSearchResult(sandboxFileMeta, hardiskPath, EnumHardiskDirectoryType.Persistent); - return result; - } - else - { - patchSandboxFileMetaCandidate = sandboxFileMeta; - } - - } - - // 查询APP资源 - if (AppFileManifest!=null&&AppFileManifest.GetFileMetaMap().TryGetValue(relativePath, out var appFileMeta)) - { - if (webFileMeta.Hash == appFileMeta.Hash) - { - string appLoadPath = AssetPathHelper.MakeStreamingSandboxLoadPath(relativePath); - var result = new HardiskFileSearchResult(appFileMeta, appLoadPath, EnumHardiskDirectoryType.StreamAsset); - return result; - } - } - - // 从服务端下载 - return ConvertToDownloadInfo(webFileMeta, patchSandboxFileMetaCandidate); - } - else - { - Logger.Warning($"Not found bundle in patch manifest : {relativePath}"); - HardiskFileSearchResult result = new HardiskFileSearchResult(relativePath); - return result; - } + return URSFileSystem.SearchHardiskFileByPath(relativePath); } public FileMeta GetBundleRelativePath(string assetPath) { - return WebBundleManifest.GetBundleFileMeta(assetPath); + return URSFileSystem.GetBundleRelativePath(assetPath); } public List GetAllDependencieBundleRelativePaths(string assetPath) { - return WebBundleManifest.GetAllDependenciesRelativePath(assetPath); + return URSFileSystem.GetAllDependencieBundleRelativePaths(assetPath); } - #endregion - } + public void SearchLocalSecurityBundleHardDiskFileByPath( + string relativePath, + out HardiskFileSearchResult mainResult, + out List dependency, + bool skipDownloadFolder = true) + { + URSFileSystem.SearchLocalSecurityBundleHardDiskFileByPath(relativePath, out mainResult, out dependency, skipDownloadFolder); + } + + #endregion + } } \ No newline at end of file diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/PlayMode/OfflinePlayModeImpl.cs b/Assets/URS/YooAsset/Runtime/PatchSystem/PlayMode/OfflinePlayModeImpl.cs index aeb1f73..77c1b1d 100644 --- a/Assets/URS/YooAsset/Runtime/PatchSystem/PlayMode/OfflinePlayModeImpl.cs +++ b/Assets/URS/YooAsset/Runtime/PatchSystem/PlayMode/OfflinePlayModeImpl.cs @@ -6,85 +6,53 @@ namespace YooAsset { internal class OfflinePlayModeImpl : IFileSystemServices { - internal FileManifest AppFileManifest; - internal BundleManifest AppBundleManifest; - - public FileManifest GetJudgedFileManifest() - { - var sanboxFileManifest = SandboxFileSystem.GetFileManifest(); - if (sanboxFileManifest != null) - { - UnityEngine.Debug.Log("use sanboxFileManifest"); - return sanboxFileManifest; - } - UnityEngine.Debug.Log("use AppFileManifest"); - return AppFileManifest; - } + //internal FileManifest AppFileManifest; + //internal BundleManifest AppBundleManifest; + internal bool ClearCacheWhenDirty { private set; get; } + /// /// 异步初始化 /// public InitializationOperation InitializeAsync() { - var operation = new OfflinePlayModeInitializationOperation(this); + ClearCacheWhenDirty = true; + var operation = new OfflinePlayModeInitializationOperation(this); OperationSystem.ProcessOperaiton(operation); return operation; } + public string GetResourceVersion() + { + return URSFileSystem.BuildInFolder?.FileManifest?.BuildVersion; + } + #region IBundleServices接口 public HardiskFileSearchResult SearchHardiskFile(FileMeta fileMeta) { - if (!fileMeta.IsValid()) - return HardiskFileSearchResult.EMPTY; - - return this.SearchHardiskFileByPath(fileMeta.RelativePath); + return URSFileSystem.SearchHardiskFile(fileMeta); } + public HardiskFileSearchResult SearchHardiskFileByPath(string relativePath) { - var initedSanboxFileManifest = SandboxFileSystem.GetFileManifest(); - if (initedSanboxFileManifest != null && initedSanboxFileManifest.GetFileMetaMap().TryGetValue(relativePath, out var sandboxFileMeta)) - { - string hardiskPath = SandboxFileSystem.MakeSandboxFilePath(relativePath); - return new HardiskFileSearchResult(sandboxFileMeta, hardiskPath,EnumHardiskDirectoryType.Persistent); - } - else if (AppFileManifest != null && AppFileManifest.GetFileMetaMap().TryGetValue(relativePath, out var appFileMeta)) - { - string localPath = AssetPathHelper.MakeStreamingSandboxLoadPath(relativePath); - HardiskFileSearchResult result = new HardiskFileSearchResult(appFileMeta, localPath,EnumHardiskDirectoryType.StreamAsset); - return result; - } - else - { - Logger.Error($"Not found bundle in patch manifest : {relativePath}"); - HardiskFileSearchResult result = new HardiskFileSearchResult(relativePath); - return result; - } + return URSFileSystem.SearchHardiskFileByPath(relativePath); } public FileMeta GetBundleRelativePath(string assetPath) { - var sandboxBundleManifest = SandboxFileSystem.GetBundleManifest(); - if (sandboxBundleManifest != null) - { - return sandboxBundleManifest.GetBundleFileMeta(assetPath); - } - if (AppBundleManifest != null) - { - return AppBundleManifest.GetBundleFileMeta(assetPath); - } - return FileMeta.ERROR_FILE_META; - } + return URSFileSystem.GetBundleRelativePath(assetPath); + } public List GetAllDependencieBundleRelativePaths(string assetPath) { - var sandboxBundleManifest = SandboxFileSystem.GetBundleManifest(); - if (sandboxBundleManifest != null) - { - return sandboxBundleManifest.GetAllDependenciesRelativePath(assetPath); - } - if (AppBundleManifest != null) { - return AppBundleManifest.GetAllDependenciesRelativePath(assetPath); - } - return null; + return URSFileSystem.GetAllDependencieBundleRelativePaths(assetPath); + } + public void SearchLocalSecurityBundleHardDiskFileByPath( + string relativePath, + out HardiskFileSearchResult mainResult, + out List dependency, + bool skipDownloadFolder = true) + { + URSFileSystem.SearchLocalSecurityBundleHardDiskFileByPath(relativePath, out mainResult, out dependency, skipDownloadFolder); } // 解压相关 /// @@ -98,7 +66,7 @@ public UnzipOperation CreateUnpackerByTags(string[] tags, int fileUpackingMaxNum Logger.Log($"解压完毕 {operation.Status}"); if (operation.Status == EOperationStatus.Succeed) { - SandboxFileSystem.FlushSandboxFileManifestToHardisk(); + URSFileSystem.PersistentDownloadFolder.FlushFileManifestToHardisk(); } }; operation.Completed += callback; @@ -107,15 +75,15 @@ public UnzipOperation CreateUnpackerByTags(string[] tags, int fileUpackingMaxNum private List GetUnpackListByTags(string[] tags) { List unzipEntries = new List(); - if (AppFileManifest != null) + if (URSFileSystem.BuildInFolder.FileManifest != null) { List downloadList = new List(); - AppFileManifest.GetFileMetaByTag(tags, ref downloadList); + URSFileSystem.BuildInFolder.FileManifest.GetFileMetaByTag(tags, ref downloadList); for (int i = downloadList.Count - 1; i >= 0; i--) { var streamFileMeta = downloadList[i]; - if (!SandboxFileSystem.ContainsFile(streamFileMeta.RelativePath)) + if (!URSFileSystem.PersistentDownloadFolder.ContainsFile(streamFileMeta.RelativePath)) { unzipEntries.Add(new UnzipEntry(streamFileMeta)); } diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/PlayMode/ShareUtil.cs b/Assets/URS/YooAsset/Runtime/PatchSystem/PlayMode/ShareUtil.cs new file mode 100644 index 0000000..78ad757 --- /dev/null +++ b/Assets/URS/YooAsset/Runtime/PatchSystem/PlayMode/ShareUtil.cs @@ -0,0 +1,127 @@ +/* +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using YooAsset; + +namespace URS { + public class ShareUtil + { + public static void SearchLocalSecurityBundleHardDiskFileByPath(FileManifest appFileManifest, BundleManifest appBundleManifest, string relativePath, out HardiskFileSearchResult mainResult, out List dependency) + { + bool valid = false; + var sandboxBundleManifest = SandboxFileSystem.GetBundleManifest(); + + string mainHardDiskFilePath = ""; + var mainHardiskDirectoryType = EnumHardiskDirectoryType.Invalid; + FileMeta mainFileMeta=null; + List<(FileMeta, string, EnumHardiskDirectoryType)> deps = new List<(FileMeta, string, EnumHardiskDirectoryType)>(); + if (sandboxBundleManifest != null) + { + var fileMeta = sandboxBundleManifest.GetBundleFileMeta(relativePath); + var dependencyFileMetas = sandboxBundleManifest.GetAllDependenciesRelativePath(relativePath); + if (fileMeta != FileMeta.ERROR_FILE_META && dependencyFileMetas != null) + { + bool mainIsOK = SandboxFileSystem.CheckContentIntegrity(fileMeta); + if (!mainIsOK) + { + if (appFileManifest != null) + { + var exist = appFileManifest.ContainFile(fileMeta); + if (exist) + { + mainFileMeta = fileMeta; + mainHardiskDirectoryType = EnumHardiskDirectoryType.StreamAsset; + mainHardDiskFilePath = AssetPathHelper.MakeStreamingSandboxLoadPath(fileMeta.RelativePath); + } + mainIsOK = exist; + } + + } + else + { + mainFileMeta = fileMeta; + mainHardiskDirectoryType = EnumHardiskDirectoryType.PersistentDownload; + mainHardDiskFilePath = SandboxFileSystem.MakeSandboxFilePath(mainFileMeta.RelativePath); + } + if (mainIsOK) + { + + bool dependencyIsOK = true; + if (dependencyFileMetas.Count > 0) + { + foreach (var fm in dependencyFileMetas) + { + bool dpIsOK = SandboxFileSystem.CheckContentIntegrity(fm); + if (!dpIsOK) + { + if (appFileManifest != null) + { + var exist = appFileManifest.ContainFile(fm); + if (exist) + { + var dpInfo = (fm, AssetPathHelper.MakeStreamingSandboxLoadPath(fm.RelativePath), EnumHardiskDirectoryType.StreamAsset); + deps.Add(dpInfo); + } + dpIsOK = exist; + } + + } + else + { + var dpInfo = (fm, SandboxFileSystem.MakeSandboxFilePath(fm.RelativePath), EnumHardiskDirectoryType.PersistentDownload); + deps.Add(dpInfo); + } + if (!dpIsOK) + { + dependencyIsOK = false; + break; + } + } + } + if (dependencyIsOK) + { + valid = true; + } + } + } + } + if (!valid && appBundleManifest != null) + { + var fileMeta = appBundleManifest.GetBundleFileMeta(relativePath); + valid = (fileMeta != FileMeta.ERROR_FILE_META); + if (valid) + { + mainFileMeta = fileMeta; + mainHardiskDirectoryType = EnumHardiskDirectoryType.StreamAsset; + mainHardDiskFilePath = AssetPathHelper.MakeStreamingSandboxLoadPath(fileMeta.RelativePath); + + var appDps = appBundleManifest.GetAllDependenciesRelativePath(relativePath); + if (appDps != null) + { + foreach (var appDp in appDps) + { + deps.Add((appDp, AssetPathHelper.MakeStreamingSandboxLoadPath(appDp.RelativePath) ,EnumHardiskDirectoryType.StreamAsset)); + } + } + } + } + if (valid) + { + mainResult = new HardiskFileSearchResult(mainFileMeta, mainHardDiskFilePath, mainHardiskDirectoryType ); + dependency = new List(); + foreach (var dpInfo in deps) + { + dependency.Add(new HardiskFileSearchResult(dpInfo.Item1, dpInfo.Item2, dpInfo.Item3)); + } + } + else + { + mainResult = new HardiskFileSearchResult(relativePath); + dependency = new List(); + } + + } + } +} +*/ diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/PlayMode/ShareUtil.cs.meta b/Assets/URS/YooAsset/Runtime/PatchSystem/PlayMode/ShareUtil.cs.meta new file mode 100644 index 0000000..57da3ea --- /dev/null +++ b/Assets/URS/YooAsset/Runtime/PatchSystem/PlayMode/ShareUtil.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: aac46f7011f54b544b8e56f2797c364d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/SandboxFileSystem.cs b/Assets/URS/YooAsset/Runtime/PatchSystem/SandboxFileSystem.cs deleted file mode 100644 index 4a67431..0000000 --- a/Assets/URS/YooAsset/Runtime/PatchSystem/SandboxFileSystem.cs +++ /dev/null @@ -1,268 +0,0 @@ -using System; -using System.IO; -using System.Collections; -using System.Collections.Generic; -using YooAsset.Utility; -using URS; -using MHLab.Patch.Core.Utilities; - -namespace YooAsset -{ - public static class SandboxFileSystem - { - // private static Dictionary _cachedFileMap = new Dictionary(1000); - - private static FileManifest _sandboxFileManifest = null; - private static BundleManifest _sandboxBundleManifest = null; - - public static FileManifest GetFileManifest() - { - return _sandboxFileManifest; - } - - public static Dictionary GetFileMap() - { - if (_sandboxFileManifest != null) - { - return _sandboxFileManifest.GetFileMetaMap(); - } - return null; - } - public static BundleManifest GetBundleManifest() - { - return _sandboxBundleManifest; - } - public static bool TryGetHardiskFilePath(string relativePath, out string hardiskPath, out FileMeta fileMeta) - { - hardiskPath = null; - fileMeta = null; - var filemap = GetFileMap(); - if (filemap == null) - { - return false; - } - if (filemap.ContainsKey(relativePath)) - { - var fm = filemap[relativePath]; - string filePath = MakeSandboxFilePath(relativePath); - if (File.Exists(filePath)) - { - hardiskPath = filePath; - fileMeta = fm; - return true; - } - else - { - _sandboxFileManifest.RemoveFile(relativePath); - Logger.Error($"Cache file is missing : {fm.RelativePath} Hash : {fm.Hash}"); - } - } - return false; - } - /// - /// ѯǷΪ֤ļ - /// ע⣺¼ļǾЧ - /// - public static bool ContainsFile(string relativePath) - { - var filemap = GetFileMap(); - if (filemap == null) - { - return false; - } - if (filemap.ContainsKey(relativePath)) - { - string filePath = MakeSandboxFilePath(relativePath); - if (File.Exists(filePath)) - { - return true; - } - else - { - var fileMeta = filemap[relativePath]; - _sandboxFileManifest.RemoveFile(relativePath); - Logger.Error($"Cache file is missing : {fileMeta.RelativePath} Hash : {fileMeta.Hash}"); - return false; - } - } - else - { - return false; - } - } - public static bool ContainsFile(FileMeta fileMeta) - { - return ContainsFile(fileMeta.RelativePath); - } - /// - /// ֤ļ - /// - public static void RegisterVerifyFile(FileMeta fileMeta) - { - if (_sandboxFileManifest == null) - { - _sandboxFileManifest = new FileManifest(null); - } - _sandboxFileManifest.ReplaceFile(fileMeta); - - } - public static void GetFileMetaByTag(string[] tags, ref List result) - { - _sandboxFileManifest.GetFileMetaByTag(tags, ref result); - } - public static void FlushSandboxFileManifestToHardisk() - { - if (_sandboxFileManifest != null) - { - var fileMap = _sandboxFileManifest.GetFileMetaMap(); - if (fileMap != null) - { - _sandboxFileManifest.FileMetas = new List(fileMap.Values).ToArray(); - var savePath = MakeSandboxFilePath(URSRuntimeSetting.instance.FileManifestFileName); - FileManifest.Serialize(savePath, _sandboxFileManifest, true); - } - } - } - - // ֤ļ - public static bool CheckContentIntegrity(FileMeta fileMeta, string hardiskFilePath) - { - return CheckContentIntegrity(hardiskFilePath, fileMeta.SizeBytes, fileMeta.Hash); - } - public static bool CheckContentIntegrity(FileMeta fileMeta) - { - string filePath = MakeSandboxFilePath(fileMeta.RelativePath); - return CheckContentIntegrity(filePath, fileMeta.SizeBytes, fileMeta.Hash); - } - public static bool CheckContentIntegrity(string filePath, long size, uint fileHash) - { - if (File.Exists(filePath) == false) - return false; - - // ֤ļС - long fileSize = FileUtility.GetFileSize(filePath); - if (fileSize != size) - return false; - - // ֤ļCRC - var currentFileHash = Hashing.GetFileXXhash(filePath); - return fileHash == currentFileHash; - } - private static string sSandboxDirectoryName = null; - - public static string GetSandboxDirectory() - { - if (sSandboxDirectoryName == null) - { - var forceSandboxDirectory = URSRuntimeSetting.instance.ForceSandboxDirectory; - if (string.IsNullOrEmpty(forceSandboxDirectory)) - { - sSandboxDirectoryName = $"{AssetPathHelper.GetPersistentRootPath()}/sandbox"; - } - else - { - sSandboxDirectoryName = forceSandboxDirectory; - } - } - return sSandboxDirectoryName; - } - - private static string _sanboxPatchDirectory = null; - public static string GetSanboxPatchDirectory() - { - - if (_sanboxPatchDirectory == null) - { - _sanboxPatchDirectory = $"{AssetPathHelper.GetPersistentRootPath()}/sandbox_patch"; - } - return _sanboxPatchDirectory; - } - - /// - /// ȡļĴ洢· - /// - public static string MakeSandboxPatchFilePath(string fileName) - { - return $"{GetSanboxPatchDirectory()}/{fileName}"; - } - /// - /// ɾɳڵĻļ - /// - public static void DeleteSandboxFolder() - { - string directoryPath = GetSandboxDirectory(); - if (Directory.Exists(directoryPath)) - Directory.Delete(directoryPath, true); - } - - /// - /// ɾɳڵĻļ - /// - public static void DeleteSandboxFile(string fileRelativePath) - { - string filePath = MakeSandboxFilePath(fileRelativePath); - if (File.Exists(filePath)) - File.Delete(filePath); - _sandboxFileManifest.RemoveFile(fileRelativePath); - } - /// - /// ɳڲ嵥ļǷ - /// - public static bool CheckSandboxPatchManifestFileExist() - { - string filePath = MakeSandboxFilePath(URSRuntimeSetting.instance.FileManifestFileName); - return File.Exists(filePath); - } - - - public static void InitSandboxFileAndBundle() - { - string filePath = MakeSandboxFilePath(URSRuntimeSetting.instance.FileManifestFileName); - if (File.Exists(filePath)) - { - Logger.Log($"Load sandbox FileManifest manifest." + filePath); - string jsonData = File.ReadAllText(filePath); - _sandboxFileManifest = FileManifest.Deserialize(jsonData); - // _cachedFileMap = sInitSandboxFileManifest.GetFileMetaMap(); - } - filePath = MakeSandboxFilePath(URSRuntimeSetting.instance.BundleManifestFileName); - if (File.Exists(filePath)) - { - Logger.Log($"Load sandbox BundleManifest manifest." + filePath); - string jsonData = File.ReadAllText(filePath); - _sandboxBundleManifest = BundleManifest.Deserialize(jsonData); - } - } - - /// - /// ɳڲ嵥ļǷ - /// - public static bool CheckSandboxBundleManifestFileExist() - { - string filePath = MakeSandboxFilePath(URSRuntimeSetting.instance.BundleManifestFileName); - return File.Exists(filePath); - } - /// - /// ȡɳڲ嵥ļĹϣֵ - /// ע⣺ɳڲ嵥ļڣؿַ - /// - /// - public static string GetSandboxPatchManifestFileHash() - { - string filePath = MakeSandboxFilePath(URSRuntimeSetting.instance.FileManifestFileName); - if (File.Exists(filePath)) - return HashUtility.FileMD5(filePath); - else - return string.Empty; - } - - /// - /// ȡļĴ洢· - /// - public static string MakeSandboxFilePath(string fileName) - { - return $"{GetSandboxDirectory()}/{fileName}"; - } - } -} - diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/SandboxFileSystem.cs.meta b/Assets/URS/YooAsset/Runtime/PatchSystem/SandboxFileSystem.cs.meta deleted file mode 100644 index a9bd585..0000000 --- a/Assets/URS/YooAsset/Runtime/PatchSystem/SandboxFileSystem.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: eb77f83295a776b4cbc48050a4526ac5 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/URSFileSystem.cs b/Assets/URS/YooAsset/Runtime/PatchSystem/URSFileSystem.cs new file mode 100644 index 0000000..33eabfd --- /dev/null +++ b/Assets/URS/YooAsset/Runtime/PatchSystem/URSFileSystem.cs @@ -0,0 +1,826 @@ +using System; +using System.IO; +using System.Collections; +using System.Collections.Generic; +using YooAsset.Utility; +using URS; +using MHLab.Patch.Core.Utilities; +using YooAsset; + +namespace URS +{ + public enum EnumHardiskDirectoryType + { + Invalid = 0, + PersistentDownload = 1, + PersistentReadonly = 2, + BuildIn = 3, + } + public class URSFileSystem + { + public static PersistentDownloadFolder PersistentDownloadFolder; + + public static PersistentReadOnlyFolder PersistentReadOnlyFolder; + + public static BuildInFolder BuildInFolder; + + public static RemoteFolder RemoteFolder; + + public static List _localFolders= new List(); + + private static string _downloadTempFolder; + + public static void Init() + { + PersistentDownloadFolder = new PersistentDownloadFolder(AssetPathHelper.GetPersistentDownloadFolder()); + PersistentReadOnlyFolder = new PersistentReadOnlyFolder(AssetPathHelper.GetPersistentReadonlyFolder()); + BuildInFolder = new BuildInFolder(AssetPathHelper.GetURSBuildInResourceFolder()); + + /// 在离线模式下的固定资源优先级 + _localFolders.Add(PersistentDownloadFolder); + _localFolders.Add(PersistentReadOnlyFolder); + _localFolders.Add(BuildInFolder); + + _downloadTempFolder = AssetPathHelper.GetDownloadTempFolder(); + if (Directory.Exists(_downloadTempFolder)) + { + Directory.Delete(_downloadTempFolder,true); + } + } + + public static void InitPersistentFolders() + { + PersistentDownloadFolder.InitManifest(); + PersistentReadOnlyFolder.InitManifest(); + } + public static void InitRemoteFolder(HostPlayModeImpl hostPlayModeImpl) + { + RemoteFolder = new RemoteFolder(hostPlayModeImpl); + } + + public static void MoveAssetFromDownloadToReadOnly(string relativePath) + { + var bundleManifest= GetTrustBundleManifest(); + if (bundleManifest != null) { + var fileMetas = new List(); + var mainFileMeta= bundleManifest.GetBundleFileMeta(relativePath); + if (mainFileMeta.IsValid()) + { + fileMetas.Add(mainFileMeta); + } + var dps = bundleManifest.GetAllDependenciesRelativePath(relativePath); + fileMetas.AddRange(dps); + if (fileMetas.Count > 0) + { + bool anyChange = false; + foreach (var fm in fileMetas) + { + if (PersistentDownloadFolder.SafeContainsFile(fm)) + { + if (!PersistentReadOnlyFolder.SafeContainsFile(fm)) + { + var src = PersistentDownloadFolder.GetFileHardiskPath(fm); + var dest = PersistentReadOnlyFolder.GetFileHardiskPath(fm); + var directory = Path.GetDirectoryName(dest); + Directory.CreateDirectory(directory); + File.Move(src, dest); + anyChange = true; + PersistentDownloadFolder.DeleteFile(fm.RelativePath); + PersistentReadOnlyFolder.RegisterVerifyFile(fm); + } + } + else if (BuildInFolder.ContainsFile(fm)) + { + // Logger.Error("存在于build中,跳过检查"); + } + } + if (anyChange) + { + PersistentReadOnlyFolder.FlushFileManifestToHardisk(); + PersistentDownloadFolder.FlushFileManifestToHardisk(); + } + } + } + } + + public static BundleManifest GetTrustBundleManifest() + { + if (RemoteFolder != null&& RemoteFolder.BundleManifest!=null) + { + return RemoteFolder.BundleManifest; + } + + for (int i = 0; i < _localFolders.Count; i++) + { + var folder = _localFolders[i]; + if (folder.BundleManifest != null) + { + return folder.BundleManifest; + } + } + Logger.Error("没有找到值得信赖的bundleManifest"); + return null; + } + public static string GetDownloadTempPath(string relativePath) + { + return $"{_downloadTempFolder}/{relativePath}"; + } + + public static string GetDownloadFolderPath(string relativePath) + { + return PersistentDownloadFolder.GetFileHardiskPath(relativePath); + } + + public static bool ConfirmDownload(FileMeta fileMeta,string hardiskFilePath) + { + bool result = DownloadFolderCheckContentIntegrity(fileMeta, hardiskFilePath); + if (result) + { + DownloadFolderRegisterVerifyFile(fileMeta); + } + return result; + } + + public static bool DownloadFolderCheckContentIntegrity(FileMeta fileMeta, string hardiskFilePath) + { + return PersistentDownloadFolder.CheckContentIntegrity(fileMeta, hardiskFilePath); + } + public static bool DownloadFolderCheckContentIntegrity(string filePath, long size, uint fileHash) + { + return PersistentDownloadFolder.CheckContentIntegrity(filePath,size,fileHash); + } + public static void DownloadFolderRegisterVerifyFile(FileMeta fileMeta) + { + PersistentDownloadFolder.RegisterVerifyFile(fileMeta); + } + public static void DownloadFolderDeleteFile(string fileRelativePath) + { + PersistentDownloadFolder.DeleteFile(fileRelativePath); + } + public static void DeletePersistentRootFolder() + { + string directoryPath = AssetPathHelper.GetPersistentRootPath(); + if (Directory.Exists(directoryPath)) + Directory.Delete(directoryPath, true); + } + public static HardiskFileSearchResult SearchHardiskFileByPath(string relativePath) + { + HardiskFileSearchResult result = null; + FileMeta trustFileMeta = null; + if (RemoteFolder != null) + { + var find= RemoteFolder.ContainsFile(relativePath,out var remoteFileMeta); + if (find) + { + trustFileMeta = remoteFileMeta; + } + } + if (trustFileMeta != null) + { + return SearchHardiskFile(trustFileMeta); + } + else + { + for (int i = 0; i < _localFolders.Count; i++) + { + var folder = _localFolders[i]; + if (folder.ContainsFile(relativePath,out var localFileMeta)) + { + result = new HardiskFileSearchResult(localFileMeta, folder.GetFileHardiskPath(localFileMeta.RelativePath), folder.GetDiretoryType()); + return result; + } + } + } + Logger.Error($"Not found bundle in patch manifest : {relativePath}"); + result = new HardiskFileSearchResult(relativePath); + return result; + } + public static HardiskFileSearchResult SearchHardiskFile(FileMeta fileMeta) + { + if (!fileMeta.IsValid()) + return HardiskFileSearchResult.EMPTY; + HardiskFileSearchResult result = null; + Folder currentLocalFolder = null; + FileMeta currentFileMeta= null; + for (int i = 0; i < _localFolders.Count; i++) + { + var folder= _localFolders[i]; + if (folder.ContainsFile(fileMeta)) + { + currentLocalFolder = folder; + currentFileMeta= fileMeta; + break; + } + } + if (currentLocalFolder != null) + { + result = new HardiskFileSearchResult(currentFileMeta, currentLocalFolder.GetFileHardiskPath(fileMeta.RelativePath), currentLocalFolder.GetDiretoryType()); + return result; + } + else + { + if (RemoteFolder != null) + { + var find= RemoteFolder.SearchFile(PersistentDownloadFolder,BuildInFolder, fileMeta,out var hardiskFileSearchResult); + if (find) + { + result = hardiskFileSearchResult; + return result; + } + } + } + Logger.Error($"Not found bundle in patch manifest : {fileMeta.RelativePath}"); + result = new HardiskFileSearchResult(fileMeta.RelativePath); + return result; + } + + public static bool CheckBundleManifestValid(BundleManifest bundleManifest, + string mainRelativePath, + out HardiskFileSearchResult mainResult, + out List dependency, + bool skipDownloadFolder = true + ) + { + + if (bundleManifest == null) + { + mainResult = new HardiskFileSearchResult(mainRelativePath); + dependency = new List(); + return false; + } + + var mainFileMeta = bundleManifest.GetBundleFileMeta(mainRelativePath); + var dependencyFileMetas = bundleManifest.GetAllDependenciesRelativePath(mainRelativePath); + + if (mainFileMeta == FileMeta.ERROR_FILE_META) + { + mainResult = new HardiskFileSearchResult(mainRelativePath); + dependency = new List(); + return false; + } + string mainHardDiskFilePath = ""; + var mainHardiskDirectoryType = EnumHardiskDirectoryType.Invalid; + List<(FileMeta, string, EnumHardiskDirectoryType)> deps = new List<(FileMeta, string, EnumHardiskDirectoryType)>(); + + bool valid = false; + for (int i = 0; i <_localFolders.Count; i++) + { + var folder = _localFolders[i]; + if (skipDownloadFolder && folder == PersistentDownloadFolder) + { + continue; + } + if (folder.SafeContainsFile(mainFileMeta)) + { + mainHardDiskFilePath = folder.GetFileHardiskPath(mainFileMeta.RelativePath); + mainHardiskDirectoryType = folder.GetDiretoryType(); + valid = true; + break; + } + } + if (valid && dependencyFileMetas != null && dependencyFileMetas.Count > 0) + { + for (int i = 0; i < dependencyFileMetas.Count; i++) + { + var dp = dependencyFileMetas[i]; + var dpValid = false; + for (int j = 0; j < _localFolders.Count; j++) + { + var folder = _localFolders[j]; + if (skipDownloadFolder && folder == PersistentDownloadFolder) + { + continue; + } + if (folder.SafeContainsFile(dp)) + { + deps.Add((dp,folder.GetFileHardiskPath(dp.RelativePath),folder.GetDiretoryType())) ; + dpValid = true; + break; + } + } + if (!dpValid) + { + valid = false; + } + } + } + if (valid) + { + mainResult = new HardiskFileSearchResult(mainFileMeta, mainHardDiskFilePath, mainHardiskDirectoryType); + dependency = new List(); + foreach (var dpInfo in deps) + { + dependency.Add(new HardiskFileSearchResult(dpInfo.Item1, dpInfo.Item2, dpInfo.Item3)); + } + } + else + { + mainResult = new HardiskFileSearchResult(mainRelativePath); + dependency = new List(); + } + return valid; + } + + public static FileMeta GetBundleRelativePath(string assetPath) + { + var trustBundleManifest = GetTrustBundleManifest(); + return trustBundleManifest.GetBundleFileMeta(assetPath); + } + public static List GetAllDependencieBundleRelativePaths(string assetPath) + { + var trustBundleManifest = GetTrustBundleManifest(); + return trustBundleManifest.GetAllDependenciesRelativePath(assetPath); + } + public static void SearchLocalSecurityBundleHardDiskFileByPath( + string relativePath, + out HardiskFileSearchResult mainResult, + out List dependency, + bool skipDownloadFolder= true) + { + for (int i = 0; i <_localFolders.Count; i++) + { + var localFolder = _localFolders[i]; + bool isValid = CheckBundleManifestValid(localFolder.BundleManifest, relativePath,out mainResult,out dependency, skipDownloadFolder); + if (isValid) + { + return; + } + } + Logger.Error("没有找到"+ relativePath); + mainResult = new HardiskFileSearchResult(relativePath); + dependency = new List(); + } + } + public class RemoteFolder : Folder + { + private HostPlayModeImpl _hostPlayModeImpl= null; + public RemoteFolder(HostPlayModeImpl hostPlayModeImpl) : base(hostPlayModeImpl.RemoteVersionRootUrl) + { + _hostPlayModeImpl= hostPlayModeImpl; + } + + public bool SearchFile(PersistentDownloadFolder downloadFolder,BuildInFolder buildInFolder, FileMeta fileMeta, out HardiskFileSearchResult hardiskFileSearchResult) + { + hardiskFileSearchResult = null; + if (ContainsFile(fileMeta)) + { + FileMeta patchFileMetaCandidate = null; + EnumHardiskDirectoryType directoryType = EnumHardiskDirectoryType.Invalid; + if (downloadFolder.ContainsFile(fileMeta.RelativePath, out var downloadFileMeta)) + { + if (downloadFileMeta.Hash != fileMeta.Hash) + { + patchFileMetaCandidate = downloadFileMeta; + directoryType = EnumHardiskDirectoryType.PersistentDownload; + } + } + if (patchFileMetaCandidate == null) + { + if (buildInFolder.ContainsFile(fileMeta.RelativePath, out var buildInFileMeta)) + { + if (buildInFileMeta.Hash != fileMeta.Hash) + { + patchFileMetaCandidate = buildInFileMeta; + directoryType = EnumHardiskDirectoryType.BuildIn; + } + } + } + hardiskFileSearchResult = this._hostPlayModeImpl.ConvertToDownloadInfo(fileMeta, patchFileMetaCandidate, directoryType); + return true; + } + return false; + } + + + public override bool IsWriteable() + { + return false; + } + } + public class PersistentDownloadFolder : Folder + { + private List<(string, string)> _relativePaths = new List<(string, string)>(); + private int _currentCheckIndex = 0; + private const int MAX_STEP = 20; + + public PersistentDownloadFolder(string basePath):base(basePath) + { + + } + + public void InitManifest() + { + string filePath = GetFileHardiskPath(URSRuntimeSetting.instance.FileManifestFileName); + if (File.Exists(filePath)) + { + Logger.Log($"Load FileManifest manifest." + filePath); + string jsonData = File.ReadAllText(filePath); + _fileManifest = FileManifest.Deserialize(jsonData); + // _cachedFileMap = sInitSandboxFileManifest.GetFileMetaMap(); + } + filePath = GetFileHardiskPath(URSRuntimeSetting.instance.BundleManifestFileRelativePath); + if (File.Exists(filePath)) + { + Logger.Log($"Load BundleManifest manifest." + filePath); + string jsonData = File.ReadAllText(filePath); + _bundleManifest = BundleManifest.Deserialize(jsonData); + } + } + + public void BeginCheckLocalFile() + { + _relativePaths.Clear(); + HashSet relativePathSet = new HashSet(); + string directoryRoot = _basePath; + Directory.CreateDirectory(directoryRoot); + var pathLength = directoryRoot.Length; + var paths = Directory.GetFiles(directoryRoot, "*", SearchOption.AllDirectories); + if (paths != null && paths.Length > 0) + { + for (int i = 0; i < paths.Length; i++) + { + var fullPath = paths[i]; + var relativePath = paths[i].Substring(pathLength + 1); + var pure = relativePath.Replace('\\', '/').Replace("//", "/"); + _relativePaths.Add((pure, fullPath)); + relativePathSet.Add(pure); + } + } + RemoveFileMetaMissed( relativePathSet); + _currentCheckIndex = 0; + } + + private void RemoveFileMetaMissed(HashSet rPaths) + { + if (_fileManifest != null) + { + var fileMap = _fileManifest.GetFileMetaMap(); + List removes = null; + foreach (var rPath in fileMap.Keys) + { + + if (!rPaths.Contains(rPath)) + { + if (removes == null) + { + removes = new List(); + } + + removes.Add(rPath); + } + } + if (removes != null) + { + for (int i = 0; i < removes.Count; i++) + { + var rPath = removes[i]; + DeleteFile(rPath); + } + } + } + } + + public bool CheckLocalFile(FileManifest fileManifest) + { + if (fileManifest == null) return true; + for (int i = 0; i < MAX_STEP; i++) + { + var currentIndex= _currentCheckIndex++; + if (currentIndex < _relativePaths.Count) + { + var relativePath = _relativePaths[currentIndex].Item1; + var fullPath = _relativePaths[currentIndex].Item2; + if (relativePath == URSRuntimeSetting.instance.FileManifestFileName) + { + continue; + } + // var webFileManifest = _impl.WebFileManifest; + var fileMap = fileManifest.GetFileMetaMap(); + if (fileMap.ContainsKey(relativePath)) + { + var fileMeta = fileMap[relativePath]; + + if (CheckContentSize(fullPath, fileMeta.SizeBytes)) // 不检测hash啦,任何资源进去这个文件夹的时候,检测hash就可以了, + { + RegisterVerifyFile(fileMeta); + } + else + { + DeleteFile(relativePath); + } + } + } + else + { + FlushFileManifestToHardisk(); + return true; + } + } + return false; + } + + public void EndCheck() + { + _relativePaths.Clear(); + _currentCheckIndex = 0; + } + /// + /// 缓存验证过的文件 + /// + public void RegisterVerifyFile(FileMeta fileMeta) + { + if (_fileManifest == null) + { + _fileManifest = new FileManifest(null,null); + } + _fileManifest.ReplaceFile(fileMeta); + } + + public void DeleteFile(string fileRelativePath) + { + string filePath = GetFileHardiskPath(fileRelativePath); + if (File.Exists(filePath)) + File.Delete(filePath); + _fileManifest.RemoveFile(fileRelativePath); + } + // 验证文件完整性 + public bool CheckContentIntegrity(FileMeta fileMeta, string hardiskFilePath) + { + return CheckContentIntegrity(hardiskFilePath, fileMeta.SizeBytes, fileMeta.Hash); + } + public bool CheckContentIntegrity(FileMeta fileMeta) + { + string filePath = GetFileHardiskPath(fileMeta.RelativePath); + return CheckContentIntegrity(filePath, fileMeta.SizeBytes, fileMeta.Hash); + } + public virtual bool CheckContentIntegrity(string filePath, long size, uint fileHash) + { + if (File.Exists(filePath) == false) + { + //Logger.Error($"验证失败,文件不存在{filePath}"); + return false; + } + + + // 先验证文件大小 + long fileSize = FileUtility.GetFileSize(filePath); + if (fileSize != size) + { + //Logger.Error($"验证失败,文件大小不通过 目标大小 {size} ,当前文件大小{fileSize}"); + return false; + } + + + // 再验证文件CRC + var currentFileHash = Hashing.GetFileXXhash(filePath); + var success = fileHash == currentFileHash; + if (!success) + { + //Logger.Error($"验证失败,文件大小不通过 目标hash {fileHash} ,当前文件大小{currentFileHash}"); + return false; + } + return success; + } + public virtual bool CheckContentSize(string filePath, long size) + { + if (File.Exists(filePath) == false) + { + //Logger.Error($"验证失败,文件不存在{filePath}"); + return false; + } + + + // 先验证文件大小 + long fileSize = FileUtility.GetFileSize(filePath); + if (fileSize != size) + { + //Logger.Error($"验证失败,文件大小不通过 目标大小 {size} ,当前文件大小{fileSize}"); + return false; + } + + return true; + } + + public override bool SafeContainsFile(FileMeta fileMeta) + { + var selfContains = ContainsFile(fileMeta); + if (selfContains) + { + var check= CheckContentIntegrity(fileMeta); + if (check) + { + return true; + } + } + return false; + + } + public void FlushFileManifestToHardisk() + { + if (_fileManifest != null) + { + var fileMap = _fileManifest.GetFileMetaMap(); + if (fileMap != null) + { + _fileManifest.FileMetas = new List(fileMap.Values).ToArray(); + System.Array.Sort(_fileManifest.FileMetas, (a, b) => + { + return a.RelativePath.CompareTo(b.RelativePath); + }); + var savePath = GetFileHardiskPath(URSRuntimeSetting.instance.FileManifestFileName); + FileManifest.Serialize(savePath, _fileManifest, true); + } + } + } + + public override bool IsWriteable() + { + return true; + } + } + + public class PersistentReadOnlyFolder : PersistentDownloadFolder + { + public PersistentReadOnlyFolder(string basePath) : base(basePath) + { + + } + + public override bool IsWriteable() + { + return false; + } + } + + public class BuildInFolder : Folder + { + public BuildInFolder(string basePath) : base(basePath) + { + + } + public override bool IsWriteable() + { + return false; + } + + public override bool SafeContainsFile(FileMeta fileMeta) + { + return ContainsFile(fileMeta); + } + } + + + public class Folder + { + public string _basePath; + + public FileManifest _fileManifest; + + public BundleManifest _bundleManifest; + + + public virtual void InitFolder() + { + + } + + public virtual EnumHardiskDirectoryType GetDiretoryType() + { + return EnumHardiskDirectoryType.Invalid; + } + public Folder(string basePath) + { + _basePath = basePath; + } + + public FileManifest FileManifest + { + get + { + return _fileManifest; + } + set + { + _fileManifest = value; + } + } + + public BundleManifest BundleManifest + { + get + { + return _bundleManifest; + } + set + { + _bundleManifest = value; + } + } + + public Dictionary GetFileMap() + { + if (_fileManifest != null) + { + return _fileManifest.GetFileMetaMap(); + } + return null; + } + + public virtual bool TryGetHardiskFilePath(string relativePath, out string hardiskPath, out FileMeta fileMeta) + { + hardiskPath = null; + fileMeta = null; + var filemap = GetFileMap(); + if (filemap == null) + { + return false; + } + if (filemap.ContainsKey(relativePath)) + { + var fm = filemap[relativePath]; + hardiskPath = GetFileHardiskPath(relativePath); + fileMeta = fm; + } + return false; + } + + public virtual string GetFileHardiskPath(string relativePath) + { + return $"{_basePath}/{relativePath}"; + } + public virtual string GetFileHardiskPath(FileMeta fileMeta) + { + return $"{_basePath}/{fileMeta.RelativePath}"; + } + /// + /// 查询是否为验证文件 + /// 注意:被收录的文件完整性是绝对有效的 + /// + public bool ContainsFile(string relativePath) + { + var filemap = GetFileMap(); + if (filemap == null) + { + return false; + } + if (filemap.ContainsKey(relativePath)) + { + return true; + } + else + { + return false; + } + } + public bool ContainsFile(string relativePath,out FileMeta fileMeta) + { + var filemap = GetFileMap(); + fileMeta = null; + if (filemap == null) + { + return false; + } + if (filemap.ContainsKey(relativePath)) + { + fileMeta = filemap[relativePath]; + return true; + } + else + { + return false; + } + } + public bool ContainsFile(FileMeta fileMeta) + { + var selfContains= ContainsFile(fileMeta.RelativePath,out var selfFileMeta); + if (!selfContains) return false; + if (selfFileMeta.Hash != fileMeta.Hash) return false; + if (selfFileMeta.SizeBytes != fileMeta.SizeBytes) return false; + return true; + } + + public virtual bool SafeContainsFile(FileMeta fileMeta) + { + return false; + } + + + + public void GetFileMetaByTag(string[] tags, ref List result) + { + if (_fileManifest != null) + { + _fileManifest.GetFileMetaByTag(tags, ref result); + } + } + + public virtual bool IsWriteable() + { + return true; + } + + } +} + + + diff --git a/Assets/URS/YooAsset/Runtime/PatchSystem/URSFileSystem.cs.meta b/Assets/URS/YooAsset/Runtime/PatchSystem/URSFileSystem.cs.meta new file mode 100644 index 0000000..eeea0dc --- /dev/null +++ b/Assets/URS/YooAsset/Runtime/PatchSystem/URSFileSystem.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7b238443ae2b2224fa5eef18d47633e6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Runtime/ShaderVariantCollection.cs b/Assets/URS/YooAsset/Runtime/ShaderVariantCollection.cs new file mode 100644 index 0000000..c2184b4 --- /dev/null +++ b/Assets/URS/YooAsset/Runtime/ShaderVariantCollection.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace URS +{ + public static class URSShaderVariantConstant + { + public const string SHADER_VARIANT_SAVE_PATH = "Assets/GameResources/ShaderVarians/ShaderVariantCollection.shadervariants"; + public const string BLACK_SHADER_VARIANT_STRIPPER_SAVE_PATH = "Assets/GameResources/ShaderVarians/BlackShaderVariantCollection.shadervariants"; + + public const int WARM_ONE_SHADER_VARIANT_COUNT = 7; + public const string WARM_SHADER_FILE_FORMAT = "Assets/GameResources/ShaderVarians/WarmShaderVariantCollection_{0}.shadervariants"; + public const string WARM_SHADER_JSON_FILE = "Assets/GameResources/ShaderVarians/WarmShaderVariantCollections.json"; + + public const string BUILD_IN_WARM_SHADER_SAVE_PATH_FORMAT = "Assets/GameResources/ShaderVarians/BuildIn/BuildInWarmShaderVariantCollection_{0}.shadervariants"; + } + + + public class WarmShaderVariants + { + [SerializeField] + public string[] paths; + } +} + diff --git a/Assets/URS/YooAsset/Runtime/ShaderVariantCollection.cs.meta b/Assets/URS/YooAsset/Runtime/ShaderVariantCollection.cs.meta new file mode 100644 index 0000000..bb77f45 --- /dev/null +++ b/Assets/URS/YooAsset/Runtime/ShaderVariantCollection.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 078c7e0d4c084ac46bb33d273b3111cb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/URS/YooAsset/Runtime/YooAssets.cs b/Assets/URS/YooAsset/Runtime/YooAssets.cs index eee2b34..4f5c34f 100644 --- a/Assets/URS/YooAsset/Runtime/YooAssets.cs +++ b/Assets/URS/YooAsset/Runtime/YooAssets.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using URS; using UnityEngine.SceneManagement; +using UnityEngine; namespace YooAsset { public static class YooAssets @@ -51,7 +52,7 @@ public class InitParameters /// /// 资源加载的最大数量 /// - public int AssetLoadingMaxNumber = int.MaxValue; + public int AssetLoadingMaxNumber =5; } @@ -68,6 +69,27 @@ public class InitParameters private static float _releaseCD = -1f; + public static EPlayMode GetPlayMode() { + return _playMode; + } + + public static string GetResourceVersion() + { + if (_playMode == EPlayMode.EditorPlayMode) + { + return Application.version; + } + else if (_playMode == EPlayMode.OfflinePlayMode) + { + return _offlinePlayModeImpl.GetResourceVersion(); + } + else if (_playMode == EPlayMode.HostPlayMode) + { + return _hostPlayModeImpl.GetResourceVersion(); + } + return null; + } + /// /// 异步初始化 /// @@ -79,7 +101,10 @@ public static InitializationOperation InitializeAsync(InitParameters parameters) #if !UNITY_EDITOR if (_playMode == EPlayMode.EditorPlayMode) { - _playMode = EPlayMode.OfflinePlayMode; // 防止犯错 + if (UnityMacro.Instance.ENABLE_HOTUPDATE) + _playMode = EPlayMode.HostPlayMode; // 防止犯错 + else + _playMode = EPlayMode.OfflinePlayMode; } #endif if (parameters == null) @@ -113,7 +138,7 @@ public static InitializationOperation InitializeAsync(InitParameters parameters) _releaseCD = parameters.AutoReleaseInterval; } - + URSFileSystem.Init(); // 初始化 if (_playMode == EPlayMode.EditorPlayMode) { @@ -147,7 +172,7 @@ public static InitializationOperation InitializeAsync(InitParameters parameters) /// /// 更新的资源版本号 /// 超时时间(默认值:60秒) - public static UpdateManifestOperation UpdateManifestAsync(int updateResourceVersion, int timeout = 60) + public static UpdateManifestOperation UpdateManifestAsync(int timeout = 60) { if (_playMode == EPlayMode.EditorPlayMode) { @@ -165,7 +190,7 @@ public static UpdateManifestOperation UpdateManifestAsync(int updateResourceVers { if (_hostPlayModeImpl == null) throw new Exception("YooAsset is not initialized."); - return _hostPlayModeImpl.UpdatePatchManifestAsync(updateResourceVersion, timeout); + return _hostPlayModeImpl.UpdatePatchManifestAsync(timeout); } else { @@ -399,6 +424,15 @@ public static RemoteUpdateOperation CreateBundleDownloader(string[] locations, i throw new NotImplementedException(); } } + + public static BundleManifest GetBundleManifest() + { + if (_playMode == EPlayMode.EditorPlayMode) + { + return null; + } + return URSFileSystem.GetTrustBundleManifest(); + } #endregion #region 资源解压接口 @@ -459,8 +493,8 @@ public static UnzipOperation CreatePatchUnpacker(string[] tags, int unpackingMax public static void ClearSandbox() { Logger.Warning("Clear sandbox."); - SandboxFileSystem.DeleteSandboxFolder(); - } + URSFileSystem.DeletePersistentRootFolder(); + } #endregion @@ -471,27 +505,39 @@ public static void ClearSandbox() /// internal static void InternalUpdate() { - // 更新异步请求操作 - OperationSystem.Update(); + //UnityEngine.Profiling.Profiler.BeginSample("OperationSystem.Update()"); + // 更新异步请求操作 + OperationSystem.Update(); - // 解压管理系统 - UnzipSystem.Update(); + //UnityEngine.Profiling.Profiler.EndSample(); - // 下载模块 - RemoteDownloadSystem.Update(); + //UnityEngine.Profiling.Profiler.BeginSample(" UnzipSystem.Update()"); + // 解压管理系统 + UnzipSystem.Update(); - // 轮询更新资源系统 - AssetSystem.Update(); + // UnityEngine.Profiling.Profiler.EndSample(); + + // UnityEngine.Profiling.Profiler.BeginSample(" RemoteDownloadSystem.Update()"); + // 下载模块 + RemoteDownloadSystem.Update(); + + // UnityEngine.Profiling.Profiler.EndSample(); - // 自动释放零引用资源 - if (_releaseCD > 0) + //UnityEngine.Profiling.Profiler.BeginSample("AssetSystem.Update"); + // 轮询更新资源系统 + AssetSystem.Update(); + //UnityEngine.Profiling.Profiler.EndSample(); + // 自动释放零引用资源 + if (_releaseCD > 0) { _releaseTimer += UnityEngine.Time.unscaledDeltaTime; if (_releaseTimer >= _releaseCD) { _releaseTimer = 0f; + // UnityEngine.Profiling.Profiler.BeginSample("UnloadUnusedAssets"); AssetSystem.UnloadUnusedAssets(); - } + // UnityEngine.Profiling.Profiler.EndSample(); + } } } diff --git a/Assets/URS/xxHash/xxHash64.cs b/Assets/URS/xxHash/xxHash64.cs index 08c31dc..671a3bc 100644 --- a/Assets/URS/xxHash/xxHash64.cs +++ b/Assets/URS/xxHash/xxHash64.cs @@ -147,9 +147,9 @@ await stream.ReadAsync(buffer, offset, bufferSize, cancellationToken).ConfigureA /// hash public static unsafe ulong ComputeHash(Span data, int length, ulong seed = 0) { - Debug.Assert(data != null); - Debug.Assert(length >= 0); - Debug.Assert(length <= data.Length); + //Debug.Assert(data != null); + //Debug.Assert(length >= 0); + //Debug.Assert(length <= data.Length); fixed (byte* pData = &MemoryMarshal.GetReference(data)) { diff --git a/Assets/UniversalRenderPipelineGlobalSettings.asset b/Assets/UniversalRenderPipelineGlobalSettings.asset deleted file mode 100644 index a996a2e..0000000 --- a/Assets/UniversalRenderPipelineGlobalSettings.asset +++ /dev/null @@ -1,27 +0,0 @@ -%YAML 1.1 -%TAG !u! tag:unity3d.com,2011: ---- !u!114 &11400000 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 0} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: 2ec995e51a6e251468d2a3fd8a686257, type: 3} - m_Name: UniversalRenderPipelineGlobalSettings - m_EditorClassIdentifier: - k_AssetVersion: 2 - lightLayerName0: Light Layer default - lightLayerName1: Light Layer 1 - lightLayerName2: Light Layer 2 - lightLayerName3: Light Layer 3 - lightLayerName4: Light Layer 4 - lightLayerName5: Light Layer 5 - lightLayerName6: Light Layer 6 - lightLayerName7: Light Layer 7 - m_StripDebugVariants: 1 - m_StripUnusedPostProcessingVariants: 0 - m_StripUnusedVariants: 1 - supportRuntimeDebugDisplay: 0 diff --git a/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/Tasks/ArchiveAndCompressBundles.cs b/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/Tasks/ArchiveAndCompressBundles.cs index 7f6ca06..7249bad 100644 --- a/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/Tasks/ArchiveAndCompressBundles.cs +++ b/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/Tasks/ArchiveAndCompressBundles.cs @@ -85,7 +85,7 @@ internal static void CopyFileWithTimestampIfDifferent(string srcPath, string des } } - static CacheEntry GetCacheEntry(IBuildCache cache, string bundleName, IEnumerable resources, BuildCompression compression, List hashes) + static CacheEntry GetCacheEntry(IBuildCache cache, string bundleName, IEnumerable resources, BuildCompression compression, List hashes,ArchiveWorkItem item) { var entry = new CacheEntry(); entry.Type = CacheEntry.EntryType.Data; @@ -99,6 +99,13 @@ static CacheEntry GetCacheEntry(IBuildCache cache, string bundleName, IEnumerabl toHash.AddRange(hashes.Select(x => (object)x.RawFileHash)); entry.Hash = HashingMethods.Calculate(toHash).ToHash128(); entry.Version = kVersion; + + item.ResourceFilesRawHash = entry.Hash.ToString(); + List contentHashs = new List { kVersion }; + contentHashs.AddRange(hashes.Select(x => (object)x.ContentHash)); + item.ResourceFilesContentHash= HashingMethods.Calculate(contentHashs).ToHash128().ToString(); + + return entry; } @@ -119,7 +126,14 @@ internal static Hash128 CalculateHashVersion(ArchiveWorkItem item, string[] depe return HashingMethods.Calculate(hashes, dependencies).ToHash128(); } + internal static Hash128 CalculateContentHashVersion(ArchiveWorkItem item) + { + List hashes = new List(); + hashes.AddRange(item.SeriliazedFileMetaDatas.Select(x => x.ContentHash)); + + return HashingMethods.Calculate(hashes).ToHash128(); + } internal class ArchiveWorkItem { public int Index; @@ -130,6 +144,9 @@ internal class ArchiveWorkItem public BuildCompression Compression; public BundleDetails ResultDetails; public List SeriliazedFileMetaDatas = new List(); + + public string ResourceFilesRawHash; + public string ResourceFilesContentHash; } internal struct TaskInput @@ -255,6 +272,7 @@ static void PostArchiveProcessing(List items, List // apply bundle dependencies item.ResultDetails.Dependencies = bundleDependencies.ContainsKey(item.BundleName) ? bundleDependencies[item.BundleName] : new string[0]; item.ResultDetails.Hash = CalculateHashVersion(item, item.ResultDetails.Dependencies); + item.ResultDetails.ContentHash = CalculateContentHashVersion(item); } } } @@ -326,7 +344,7 @@ static internal ReturnCode Run(TaskInput input, out TaskOutput output) if (input.BuildCache != null) { using (input.Log.ScopedStep(LogLevel.Info, "Creating Cache Entries")) - cacheEntries = allItems.Select(x => GetCacheEntry(input.BuildCache, x.BundleName, x.ResourceFiles, x.Compression, x.SeriliazedFileMetaDatas)).ToList(); + cacheEntries = allItems.Select(x => GetCacheEntry(input.BuildCache, x.BundleName, x.ResourceFiles, x.Compression, x.SeriliazedFileMetaDatas, x)).ToList(); using (input.Log.ScopedStep(LogLevel.Info, "Load Cached Data")) input.BuildCache.LoadCachedData(cacheEntries, out cachedInfo); diff --git a/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/Tasks/CalculateAssetDependencyData.cs b/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/Tasks/CalculateAssetDependencyData.cs index 08d44fa..bd89064 100644 --- a/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/Tasks/CalculateAssetDependencyData.cs +++ b/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/Tasks/CalculateAssetDependencyData.cs @@ -275,7 +275,7 @@ static internal ReturnCode RunInternal(TaskInput input, out TaskOutput output) assetResult.objectTypes = objectTypes; output.AssetResults[i] = assetResult; output.CachedAssetCount++; - input.Logger.AddEntrySafe(LogLevel.Info, $"{assetResult.asset} (cached)"); + input.Logger.AddEntrySafe(LogLevel.Info, $"Path:{AssetDatabase.GUIDToAssetPath(assetInfos.asset)} Guid :{assetResult.asset} (cached)"); continue; } } @@ -286,7 +286,7 @@ static internal ReturnCode RunInternal(TaskInput input, out TaskOutput output) if (!input.ProgressTracker.UpdateInfoUnchecked(assetPath)) return ReturnCode.Canceled; - input.Logger.AddEntrySafe(LogLevel.Info, $"{assetResult.asset}"); + input.Logger.AddEntrySafe(LogLevel.Info, $"Path:{assetPath} Guid :{assetResult.asset} (not cached)"); assetResult.assetInfo = new AssetLoadInfo(); assetResult.usageTags = new BuildUsageTagSet(); diff --git a/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/Tasks/WriteSerializedFiles.cs b/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/Tasks/WriteSerializedFiles.cs index 6469565..0a43ada 100644 --- a/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/Tasks/WriteSerializedFiles.cs +++ b/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/Tasks/WriteSerializedFiles.cs @@ -165,7 +165,7 @@ void IRunCachedCallbacks.ProcessUncached(WorkItem item) string targetDir = m_UseCache != null ? m_UseCache.GetCachedArtifactsDirectory(item.entry) : m_Parameters.TempOutputFolder; Directory.CreateDirectory(targetDir); - using (m_Log.ScopedStep(LogLevel.Info, $"Writing {op.GetType().Name}", op.Command.fileName)) + using (m_Log.ScopedStep(LogLevel.Info, $"ProcessUncached Writing {op.GetType().Name}", op.Command.fileName)) { #if UNITY_2020_2_OR_NEWER || ENABLE_DETAILED_PROFILE_CAPTURING using (new ProfileCaptureScope(m_Log, ProfileCaptureOptions.None)) diff --git a/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/WriteTypes/AssetBundleWriteOperation.cs b/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/WriteTypes/AssetBundleWriteOperation.cs index 31257ed..39d1772 100644 --- a/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/WriteTypes/AssetBundleWriteOperation.cs +++ b/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/WriteTypes/AssetBundleWriteOperation.cs @@ -1,10 +1,12 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Security.Policy; using UnityEditor.Build.Content; using UnityEditor.Build.Pipeline.Interfaces; using UnityEditor.Build.Pipeline.Utilities; using UnityEngine; +using System.Reflection; namespace UnityEditor.Build.Pipeline.WriteTypes { @@ -14,6 +16,13 @@ namespace UnityEditor.Build.Pipeline.WriteTypes [Serializable] public class AssetBundleWriteOperation : IWriteOperation { + static MethodInfo BuildReferenceMapSerializeToJson = null; + static AssetBundleWriteOperation() { + + BuildReferenceMap BM= new BuildReferenceMap(); + var type= BM.GetType(); + BuildReferenceMapSerializeToJson = type.GetMethod("SerializeToJson",BindingFlags.Instance| BindingFlags.NonPublic | BindingFlags.Public); + } /// public WriteCommand Command { get; set; } /// @@ -51,24 +60,56 @@ public WriteResult Write(string outputFolder, BuildSettings settings, BuildUsage public Hash128 GetHash128(IBuildLogger log) { HashSet hashObjects = new HashSet(); - using (log.ScopedStep(LogLevel.Verbose, $"Gather Objects {GetType().Name}", Command.fileName)) + var bundleNameAndFileName = $"{Info.bundleName} ,fileName {Command.fileName}"; + using (log.ScopedStep(LogLevel.Verbose, $"Gather Objects {GetType().Name}", bundleNameAndFileName)) { Command.GatherSerializedObjectCacheEntries(hashObjects); - + } List hashes = new List(); - using (log.ScopedStep(LogLevel.Verbose, $"Hashing Command", Command.fileName)) - hashes.Add(Command.GetHash128()); - using (log.ScopedStep(LogLevel.Verbose, $"Hashing UsageSet", Command.fileName)) - hashes.Add(UsageSet.GetHash128()); - using (log.ScopedStep(LogLevel.Verbose, $"Hashing ReferenceMap", Command.fileName)) - hashes.Add(ReferenceMap.GetHash128()); - using (log.ScopedStep(LogLevel.Verbose, $"Hashing Info", Command.fileName)) - hashes.Add(Info.GetHash128()); - using (log.ScopedStep(LogLevel.Verbose, $"Hashing Objects", Command.fileName)) - hashes.Add(HashingMethods.Calculate(hashObjects).ToHash128()); + using (log.ScopedStep(LogLevel.Verbose, $"Hashing Command", bundleNameAndFileName)) + { + var hash = Command.GetHash128(); + log.AddEntry(LogLevel.Verbose, $"Hashing Command hash {hash}"); + hashes.Add(hash); + } + + using (log.ScopedStep(LogLevel.Verbose, $"Hashing UsageSet", bundleNameAndFileName)) + { + var hash = UsageSet.GetHash128(); + log.AddEntry(LogLevel.Verbose, $" Hashing UsageSet {hash}"); + hashes.Add(hash); + } + + using (log.ScopedStep(LogLevel.Verbose, $"Hashing ReferenceMap", bundleNameAndFileName)) { + + var hash = ReferenceMap.GetHash128(); + var json = (string)(BuildReferenceMapSerializeToJson.Invoke(ReferenceMap,new object[] { })); + log.AddEntry(LogLevel.Verbose, $" Hashing ReferenceMap {hash} json: {json}"); + hashes.Add(hash); + } + + using (log.ScopedStep(LogLevel.Verbose, $"Hashing Info", bundleNameAndFileName)) + { + var hash = Info.GetHash128(); + log.AddEntry(LogLevel.Verbose, $" Hashing Info {hash}"); + hashes.Add(hash); + } + + using (log.ScopedStep(LogLevel.Verbose, $"Hashing Objects", bundleNameAndFileName)) + { + var hash = HashingMethods.Calculate(hashObjects).ToHash128(); + log.AddEntry(LogLevel.Verbose, $" Hashing Objects {hash}"); + hashes.Add(hash); + } + hashes.Add(DependencyHash); hashes.Add(BuildInterfacesWrapper.ShaderCallbackVersionHash); - return HashingMethods.Calculate(hashes).ToHash128(); + var finalHash = HashingMethods.Calculate(hashes).ToHash128(); + using (log.ScopedStep(LogLevel.Verbose, $" Hashing {GetType().Name} bundleName {bundleNameAndFileName},finalHash {finalHash}")) + { + return finalHash; + } + } /// diff --git a/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/WriteTypes/RawWriteOperation.cs b/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/WriteTypes/RawWriteOperation.cs index 9e599d2..4d9bf8f 100644 --- a/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/WriteTypes/RawWriteOperation.cs +++ b/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/WriteTypes/RawWriteOperation.cs @@ -53,8 +53,8 @@ public Hash128 GetHash128(IBuildLogger log) hashes.Add(Command.GetHash128()); using (log.ScopedStep(LogLevel.Verbose, $"Hashing UsageSet", Command.fileName)) hashes.Add(UsageSet.GetHash128()); - using (log.ScopedStep(LogLevel.Verbose, $"Hashing ReferenceMap", Command.fileName)) - hashes.Add(ReferenceMap.GetHash128()); + using (log.ScopedStep(LogLevel.Verbose, $"Hashing ReferenceMap", Command.fileName)) + hashes.Add(ReferenceMap.GetHash128()); using (log.ScopedStep(LogLevel.Verbose, $"Hashing Objects", Command.fileName)) hashes.Add(HashingMethods.Calculate(hashObjects).ToHash128()); hashes.Add(DependencyHash); diff --git a/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/WriteTypes/SceneBundleWriteOperation.cs b/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/WriteTypes/SceneBundleWriteOperation.cs index 5d1b790..faf8d31 100644 --- a/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/WriteTypes/SceneBundleWriteOperation.cs +++ b/Packages/com.unity.scriptablebuildpipeline@1.20.2/Editor/WriteTypes/SceneBundleWriteOperation.cs @@ -86,8 +86,8 @@ public Hash128 GetHash128(IBuildLogger log) hashes.Add(Command.GetHash128()); using (log.ScopedStep(LogLevel.Verbose, $"Hashing UsageSet", Command.fileName)) hashes.Add(UsageSet.GetHash128()); - using (log.ScopedStep(LogLevel.Verbose, $"Hashing ReferenceMap", Command.fileName)) - hashes.Add(ReferenceMap.GetHash128()); + using (log.ScopedStep(LogLevel.Verbose, $"Hashing ReferenceMap", Command.fileName)) + hashes.Add(ReferenceMap.GetHash128()); using (log.ScopedStep(LogLevel.Verbose, $"Hashing PreloadInfo", Command.fileName)) hashes.Add(PreloadInfo.GetHash128()); using (log.ScopedStep(LogLevel.Verbose, $"Hashing Info", Command.fileName)) diff --git a/Packages/com.unity.scriptablebuildpipeline@1.20.2/Runtime/Shared/BundleDetails.cs b/Packages/com.unity.scriptablebuildpipeline@1.20.2/Runtime/Shared/BundleDetails.cs index 3ee4c21..0bcd03f 100644 --- a/Packages/com.unity.scriptablebuildpipeline@1.20.2/Runtime/Shared/BundleDetails.cs +++ b/Packages/com.unity.scriptablebuildpipeline@1.20.2/Runtime/Shared/BundleDetails.cs @@ -17,6 +17,9 @@ public struct BundleDetails : IEquatable [SerializeField] string m_Hash; + [SerializeField] + string m_ContentHash; + [SerializeField] string[] m_Dependencies; @@ -49,6 +52,13 @@ public Hash128 Hash set { m_Hash = value.ToString(); } } + + public Hash128 ContentHash + { + get { return Hash128.Parse(m_Hash); } + set { m_Hash = value.ToString(); } + } + /// /// The array of all dependent asset bundles for this asset bundle. /// diff --git a/README.md b/README.md index f47c088..e0fdba6 100644 --- a/README.md +++ b/README.md @@ -28,4 +28,29 @@ ## 交流 - 如果遇到任何问题:进qq群讨论:1067123079 ## 免责声明 -里面用的收费插件,仅仅用做学习的目的,鼓励大家购买正版,不要随便传播收费插件 \ No newline at end of file +里面用的收费插件,仅仅用做学习的目的,鼓励大家购买正版,不要随便传播收费插件 + +## 变更历史 +#### 2023-11-13 +- 优化:在不同图片的后处理的时候,代码会跳过 原来图片size小于预设size的 +- 优化:shader 预热 shader variant collection的导出(全网唯一支持 mutil_compiler 关键字预热的方案) + +#### 2023-7-26 +- 功能:所有的远程下载操作,都会放到临时目录,只要通过验证的,才可以进最终目录 +- 功能:Share 资源的包名,会自动根据历史记录,固定下来,保证了 binary diff 的命中率 +- 功能:包名固定下来之后,sbp的hash的命中率百分百命中 +- 功能:增加版本日志功能,跟踪每次打包每个hash的命中情况 +- 功能:在用assetdatabase加载资源的时候,也会检查资源的有效性,保证和手机端一样的加载流程,把找不到资源的bug,彻底堵死 +- 优化:不在使用基于ScriptObject的配置方式,而是使用json的方式 +- BUG:修复了运行时下载过程中 断了之后,第二次启动游戏重复下载的问题(运行时bug只此一个) + +#### 2023-4-18 +- 功能:版本管理增加数量限制,多余的版本会被删除 +- 功能:第一个热更新界面,也可以做到更新自己了,全网只此URS支持,这一个特性 +- 功能:重构了虚拟文件夹系统 +- 功能:用户手机上任意删除本地文件的时候,更新系统通过开机自检保证资源数据的正确性 +- 功能:一个渠道里面可以根据app-version-number定制自己的版本号 +- 功能:增加CI脚本接口 +- 优化:urs的帧率控制 +- 优化:urs的在游戏重装下的策略:删除老旧的资源 +- BUG:修正了多个bug \ No newline at end of file